source
stringlengths 3
92
| c
stringlengths 26
2.25M
|
|---|---|
2mm.c
|
/**
* 2mm.c: This file was adapted from PolyBench/GPU 1.0 test suite
* to run on GPU with OpenMP 4.0 pragmas and OpenCL driver.
*
* http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU
*
* Contacts: Marcio M Pereira <[email protected]>
* Rafael Cardoso F Sousa <[email protected]>
* Luís Felipe Mattos <[email protected]>
*/
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "BenchmarksUtil.h"
#define NI SIZE
#define NJ SIZE
#define NK SIZE
#define NL SIZE
#pragma GCC diagnostic ignored "-Wbuiltin-macro-redefined"
#pragma clang diagnostic ignored "-Wmacro-redefined"
#define ERROR_THRESHOLD 1.5
/* Can switch DATA_TYPE between float and double */
typedef float DATA_TYPE;
/**
* @brief Initialize operand matrices
*
* @param A
* @param B
* @param D
*/
void init_array(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *D) {
int i, j;
for (i = 0; i < NI; i++) {
for (j = 0; j < NK; j++) {
A[i * NI + j] = ((DATA_TYPE)i * j) / NI;
}
}
for (i = 0; i < NK; i++) {
for (j = 0; j < NJ; j++) {
B[i * NK + j] = ((DATA_TYPE)i * (j + 1)) / NJ;
}
}
for (i = 0; i < NI; i++) {
for (j = 0; j < NL; j++) {
D[i * NL + j] = ((DATA_TYPE)i * (j + 2)) / NK;
}
}
}
/**
* @brief
*
* @param E Expected result matrix
* @param E_OMP Obtained matrix
* @return int Number of detected fails
*/
int compareResults(DATA_TYPE *E, DATA_TYPE *E_OMP) {
int i, j, fail;
fail = 0;
for (i = 0; i < NL; i++) {
for (j = 0; j < NI; j++) {
if (percentDiff(E[i * NI + j], E_OMP[i * NI + j]) > ERROR_THRESHOLD) {
fail++;
}
}
}
return fail;
}
/**
* @brief Sequential CPU version to compute A.B.D matrixes
*
* @param A Input
* @param B Input
* @param C Auxiliar
* @param D Input
* @param E Output
*/
void mm2(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C, DATA_TYPE *D,
DATA_TYPE *E) {
int i, j, k;
for (i = 0; i < NI; i++) {
for (j = 0; j < NJ; j++) {
C[i * NJ + j] = 0.0;
for (k = 0; k < NK; ++k) {
C[i * NJ + j] += A[i * NK + k] * B[k * NJ + j];
}
}
}
for (i = 0; i < NI; i++) {
for (j = 0; j < NL; j++) {
E[i * NL + j] = 0.0;
for (k = 0; k < NJ; ++k) {
E[i * NL + j] += C[i * NJ + k] * D[k * NL + j];
}
}
}
}
/**
* @brief OMP version to compute A.B.D matrixes
*
* @param A Input
* @param B Input
* @param C Auxiliar
* @param D Input
* @param E Output
*/
void mm2_OMP(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C, DATA_TYPE *D, DATA_TYPE *E) {
#pragma omp target teams map(from: E[:NI*NL], C[:NI*NJ]) map(to: A[:NI*NK], B[:NK*NJ], D[:NJ*NL]) device(OMP_DEVICE_ID)
{
#pragma omp distribute parallel for collapse(2)
for (int i = 0; i < NI; i++) {
for (int j = 0; j < NJ; j++) {
LLVM_MCA_BEGIN("kernel");
C[i * NJ + j] = 0.0;
for (int k = 0; k < NK; ++k) {
C[i * NJ + j] += A[i * NK + k] * B[k * NJ + j];
}
LLVM_MCA_END("kernel");
}
}
#pragma omp distribute parallel for collapse(2)
for (int i = 0; i < NI; i++) {
for (int j = 0; j < NL; j++) {
E[i * NL + j] = 0.0;
for (int k = 0; k < NJ; ++k) {
E[i * NL + j] += C[i * NJ + k] * D[k * NL + j];
}
}
}
}
}
int main(int argc, char **argv) {
fprintf(stdout,
"<< Linear Algebra: 2 Matrix Multiplications (C=A.B; E=C.D) >>\n");
// declare arrays and allocate memory
DATA_TYPE *A = (DATA_TYPE *)malloc(NI * NK * sizeof(DATA_TYPE));
DATA_TYPE *B = (DATA_TYPE *)malloc(NK * NJ * sizeof(DATA_TYPE));
DATA_TYPE *D = (DATA_TYPE *)malloc(NJ * NL * sizeof(DATA_TYPE));
DATA_TYPE *C = NULL;
DATA_TYPE *C_OMP = NULL;
DATA_TYPE *E = NULL;
DATA_TYPE *E_OMP = NULL;
// init operand matrices
init_array(A, B, D);
// run OMP on GPU or CPU if enabled
#if defined(RUN_OMP_GPU) || defined(RUN_OMP_CPU)
C_OMP = (DATA_TYPE *)calloc(NI * NJ, sizeof(DATA_TYPE));
E_OMP = (DATA_TYPE *)calloc(NI * NL, sizeof(DATA_TYPE));
BENCHMARK_OMP(mm2_OMP(A, B, C_OMP, D, E_OMP));
// prevent dead code elimination
DCE_PREVENT(E_OMP, NI*NL);
#endif
// run sequential version if enabled
#ifdef RUN_CPU_SEQ
C = (DATA_TYPE *)calloc(NI * NJ, sizeof(DATA_TYPE));
E = (DATA_TYPE *)calloc(NI * NL, sizeof(DATA_TYPE));
BENCHMARK_CPU(mm2(A, B, C, D, E));
// prevent dead code elimination
DCE_PREVENT(E, NI*NL);
#endif
// if TEST is enabled, then compare OMP results against sequential mode
int fail = 0;
#ifdef RUN_TEST
fail += compareResults(C, C_OMP);
fail += compareResults(E, E_OMP);
printf("Errors on OMP (threshold %4.2lf): %d\n", ERROR_THRESHOLD, fail);
#endif
/** Release memory */
free(A);
free(B);
free(D);
free(C_OMP);
free(E_OMP);
free(C);
free(E);
return fail;
}
|
convolution_sgemm_pack4to1_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 im2col_sgemm_pack4to1_bf16s_neon(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
// Mat bottom_im2col(size, maxk, inch, 8u, 4, opt.workspace_allocator);
const int size = bottom_im2col.w;
const int maxk = bottom_im2col.h;
const int inch = bottom_im2col.c;
const int outch = top_blob.c;
const float* bias = _bias;
// permute
Mat tmp;
#if __aarch64__
if (size >= 12)
tmp.create(12 * maxk, inch, size / 12 + (size % 12) / 8 + (size % 12 % 8) / 4 + size % 12 % 4, 8u, 4, opt.workspace_allocator);
else if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + size % 4, 8u, 4, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + size % 4, 8u, 4, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 8u, 4, opt.workspace_allocator);
#else
if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + size % 4, 8u, 4, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + size % 4, 8u, 4, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 8u, 4, opt.workspace_allocator);
#endif
{
#if __aarch64__
int nn_size = size / 12;
int remain_size_start = 0;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 12;
unsigned short* tmpptr = tmp.channel(i / 12);
for (int q = 0; q < inch; q++)
{
const unsigned short* img0 = (const unsigned short*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
// transpose 4x12
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n"
"ld4 {v4.4h, v5.4h, v6.4h, v7.4h}, [%0] \n"
"st1 {v0.8h}, [%1], #16 \n"
"st1 {v4.4h}, [%1], #8 \n"
"st1 {v1.8h}, [%1], #16 \n"
"st1 {v5.4h}, [%1], #8 \n"
"sub %0, %0, #64 \n"
"st1 {v2.8h}, [%1], #16 \n"
"st1 {v6.4h}, [%1], #8 \n"
"st1 {v3.8h}, [%1], #16 \n"
"st1 {v7.4h}, [%1], #8 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7");
img0 += size * 4;
}
}
}
remain_size_start += nn_size * 12;
nn_size = (size - remain_size_start) >> 3;
#else
int nn_size = size >> 3;
int remain_size_start = 0;
#endif
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
#else
unsigned short* tmpptr = tmp.channel(i / 8);
#endif
for (int q = 0; q < inch; q++)
{
const unsigned short* img0 = (const unsigned short*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
// transpose 4x8
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n"
"st1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3");
#else
asm volatile(
"pld [%0, #256] \n"
"vld4.u16 {d0-d3}, [%0]! \n"
"pld [%0, #256] \n"
"vld4.u16 {d4-d7}, [%0] \n"
"sub %0, %0, #32 \n"
"vst1.u16 {d0}, [%1 :64]! \n"
"vst1.u16 {d4}, [%1 :64]! \n"
"vst1.u16 {d1}, [%1 :64]! \n"
"vst1.u16 {d5}, [%1 :64]! \n"
"vst1.u16 {d2}, [%1 :64]! \n"
"vst1.u16 {d6}, [%1 :64]! \n"
"vst1.u16 {d3}, [%1 :64]! \n"
"vst1.u16 {d7}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1", "q2", "q3");
#endif // __aarch64__
img0 += size * 4;
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
#endif
for (int q = 0; q < inch; q++)
{
const unsigned short* img0 = (const unsigned short*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
// transpose 4x4
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld4 {v0.4h, v1.4h, v2.4h, v3.4h}, [%0] \n"
"st1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#else
asm volatile(
"pld [%0, #256] \n"
"vld4.u16 {d0-d3}, [%0 :64] \n"
"vst1.u16 {d0-d3}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1");
#endif // __aarch64__
img0 += size * 4;
}
}
}
remain_size_start += nn_size << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
#endif
for (int q = 0; q < inch; q++)
{
const unsigned short* img0 = (const unsigned short*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #64] \n"
"ld1 {v0.4h}, [%0] \n"
"st1 {v0.4h}, [%1], #8 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
#else
asm volatile(
"pld [%0, #64] \n"
"vld1.u16 {d0}, [%0 :64] \n"
"vst1.u16 {d0}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0");
#endif // __aarch64__
img0 += size * 4;
}
}
}
}
int nn_outch = 0;
int remain_outch_start = 0;
#if __aarch64__
nn_outch = outch >> 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 8;
unsigned short* outptr0 = top_blob.channel(p);
unsigned short* outptr1 = top_blob.channel(p + 1);
unsigned short* outptr2 = top_blob.channel(p + 2);
unsigned short* outptr3 = top_blob.channel(p + 3);
unsigned short* outptr4 = top_blob.channel(p + 4);
unsigned short* outptr5 = top_blob.channel(p + 5);
unsigned short* outptr6 = top_blob.channel(p + 6);
unsigned short* outptr7 = top_blob.channel(p + 7);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p : zeros;
int i = 0;
for (; i + 11 < size; i += 12)
{
unsigned short* tmpptr = tmp.channel(i / 12);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v30.4s, v31.4s}, [%22] \n"
"dup v8.4s, v30.s[0] \n"
"dup v9.4s, v30.s[0] \n"
"dup v10.4s, v30.s[0] \n"
"dup v11.4s, v30.s[1] \n"
"dup v12.4s, v30.s[1] \n"
"dup v13.4s, v30.s[1] \n"
"dup v14.4s, v30.s[2] \n"
"dup v15.4s, v30.s[2] \n"
"dup v16.4s, v30.s[2] \n"
"dup v17.4s, v30.s[3] \n"
"dup v18.4s, v30.s[3] \n"
"dup v19.4s, v30.s[3] \n"
"dup v20.4s, v31.s[0] \n"
"dup v21.4s, v31.s[0] \n"
"dup v22.4s, v31.s[0] \n"
"dup v23.4s, v31.s[1] \n"
"dup v24.4s, v31.s[1] \n"
"dup v25.4s, v31.s[1] \n"
"dup v26.4s, v31.s[2] \n"
"dup v27.4s, v31.s[2] \n"
"dup v28.4s, v31.s[2] \n"
"dup v29.4s, v31.s[3] \n"
"dup v30.4s, v31.s[3] \n"
"dup v31.4s, v31.s[3] \n"
"0: \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%10], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v11.4s, v0.4s, v4.s[1] \n"
"fmla v14.4s, v0.4s, v4.s[2] \n"
"fmla v17.4s, v0.4s, v4.s[3] \n"
"fmla v20.4s, v0.4s, v5.s[0] \n"
"fmla v23.4s, v0.4s, v5.s[1] \n"
"fmla v26.4s, v0.4s, v5.s[2] \n"
"fmla v29.4s, v0.4s, v5.s[3] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v12.4s, v1.4s, v4.s[1] \n"
"fmla v15.4s, v1.4s, v4.s[2] \n"
"fmla v18.4s, v1.4s, v4.s[3] \n"
"fmla v21.4s, v1.4s, v5.s[0] \n"
"fmla v24.4s, v1.4s, v5.s[1] \n"
"fmla v27.4s, v1.4s, v5.s[2] \n"
"fmla v30.4s, v1.4s, v5.s[3] \n"
"fmla v10.4s, v2.4s, v4.s[0] \n"
"fmla v13.4s, v2.4s, v4.s[1] \n"
"fmla v16.4s, v2.4s, v4.s[2] \n"
"fmla v19.4s, v2.4s, v4.s[3] \n"
"fmla v22.4s, v2.4s, v5.s[0] \n"
"fmla v25.4s, v2.4s, v5.s[1] \n"
"fmla v28.4s, v2.4s, v5.s[2] \n"
"fmla v31.4s, v2.4s, v5.s[3] \n"
"fmla v8.4s, v3.4s, v6.s[0] \n"
"fmla v11.4s, v3.4s, v6.s[1] \n"
"fmla v14.4s, v3.4s, v6.s[2] \n"
"fmla v17.4s, v3.4s, v6.s[3] \n"
"fmla v20.4s, v3.4s, v7.s[0] \n"
"fmla v23.4s, v3.4s, v7.s[1] \n"
"fmla v26.4s, v3.4s, v7.s[2] \n"
"fmla v29.4s, v3.4s, v7.s[3] \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v9.4s, v0.4s, v6.s[0] \n"
"fmla v12.4s, v0.4s, v6.s[1] \n"
"fmla v15.4s, v0.4s, v6.s[2] \n"
"fmla v18.4s, v0.4s, v6.s[3] \n"
"fmla v21.4s, v0.4s, v7.s[0] \n"
"fmla v24.4s, v0.4s, v7.s[1] \n"
"fmla v27.4s, v0.4s, v7.s[2] \n"
"fmla v30.4s, v0.4s, v7.s[3] \n"
"fmla v10.4s, v1.4s, v6.s[0] \n"
"fmla v13.4s, v1.4s, v6.s[1] \n"
"fmla v16.4s, v1.4s, v6.s[2] \n"
"fmla v19.4s, v1.4s, v6.s[3] \n"
"fmla v22.4s, v1.4s, v7.s[0] \n"
"fmla v25.4s, v1.4s, v7.s[1] \n"
"fmla v28.4s, v1.4s, v7.s[2] \n"
"fmla v31.4s, v1.4s, v7.s[3] \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%10], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v8.4s, v2.4s, v4.s[0] \n"
"fmla v11.4s, v2.4s, v4.s[1] \n"
"fmla v14.4s, v2.4s, v4.s[2] \n"
"fmla v17.4s, v2.4s, v4.s[3] \n"
"fmla v20.4s, v2.4s, v5.s[0] \n"
"fmla v23.4s, v2.4s, v5.s[1] \n"
"fmla v26.4s, v2.4s, v5.s[2] \n"
"fmla v29.4s, v2.4s, v5.s[3] \n"
"fmla v9.4s, v3.4s, v4.s[0] \n"
"fmla v12.4s, v3.4s, v4.s[1] \n"
"fmla v15.4s, v3.4s, v4.s[2] \n"
"fmla v18.4s, v3.4s, v4.s[3] \n"
"fmla v21.4s, v3.4s, v5.s[0] \n"
"fmla v24.4s, v3.4s, v5.s[1] \n"
"fmla v27.4s, v3.4s, v5.s[2] \n"
"fmla v30.4s, v3.4s, v5.s[3] \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v10.4s, v0.4s, v4.s[0] \n"
"fmla v13.4s, v0.4s, v4.s[1] \n"
"fmla v16.4s, v0.4s, v4.s[2] \n"
"fmla v19.4s, v0.4s, v4.s[3] \n"
"fmla v22.4s, v0.4s, v5.s[0] \n"
"fmla v25.4s, v0.4s, v5.s[1] \n"
"fmla v28.4s, v0.4s, v5.s[2] \n"
"fmla v31.4s, v0.4s, v5.s[3] \n"
"fmla v8.4s, v1.4s, v6.s[0] \n"
"fmla v11.4s, v1.4s, v6.s[1] \n"
"fmla v14.4s, v1.4s, v6.s[2] \n"
"fmla v17.4s, v1.4s, v6.s[3] \n"
"fmla v20.4s, v1.4s, v7.s[0] \n"
"fmla v23.4s, v1.4s, v7.s[1] \n"
"fmla v26.4s, v1.4s, v7.s[2] \n"
"fmla v29.4s, v1.4s, v7.s[3] \n"
"fmla v9.4s, v2.4s, v6.s[0] \n"
"fmla v12.4s, v2.4s, v6.s[1] \n"
"fmla v15.4s, v2.4s, v6.s[2] \n"
"fmla v18.4s, v2.4s, v6.s[3] \n"
"fmla v21.4s, v2.4s, v7.s[0] \n"
"fmla v24.4s, v2.4s, v7.s[1] \n"
"fmla v27.4s, v2.4s, v7.s[2] \n"
"fmla v30.4s, v2.4s, v7.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v10.4s, v3.4s, v6.s[0] \n"
"fmla v13.4s, v3.4s, v6.s[1] \n"
"fmla v16.4s, v3.4s, v6.s[2] \n"
"fmla v19.4s, v3.4s, v6.s[3] \n"
"fmla v22.4s, v3.4s, v7.s[0] \n"
"fmla v25.4s, v3.4s, v7.s[1] \n"
"fmla v28.4s, v3.4s, v7.s[2] \n"
"fmla v31.4s, v3.4s, v7.s[3] \n"
"bne 0b \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"shrn v12.4h, v12.4s, #16 \n"
"shrn v13.4h, v13.4s, #16 \n"
"shrn v14.4h, v14.4s, #16 \n"
"shrn v15.4h, v15.4s, #16 \n"
"shrn v16.4h, v16.4s, #16 \n"
"shrn v17.4h, v17.4s, #16 \n"
"shrn v18.4h, v18.4s, #16 \n"
"shrn v19.4h, v19.4s, #16 \n"
"shrn v20.4h, v20.4s, #16 \n"
"shrn v21.4h, v21.4s, #16 \n"
"shrn v22.4h, v22.4s, #16 \n"
"shrn v23.4h, v23.4s, #16 \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"shrn v26.4h, v26.4s, #16 \n"
"shrn v27.4h, v27.4s, #16 \n"
"shrn v28.4h, v28.4s, #16 \n"
"shrn v29.4h, v29.4s, #16 \n"
"shrn v30.4h, v30.4s, #16 \n"
"shrn v31.4h, v31.4s, #16 \n"
"st1 {v8.4h, v9.4h, v10.4h}, [%1], #24 \n"
"st1 {v11.4h, v12.4h, v13.4h}, [%2], #24 \n"
"st1 {v14.4h, v15.4h, v16.4h}, [%3], #24 \n"
"st1 {v17.4h, v18.4h, v19.4h}, [%4], #24 \n"
"st1 {v20.4h, v21.4h, v22.4h}, [%5], #24 \n"
"st1 {v23.4h, v24.4h, v25.4h}, [%6], #24 \n"
"st1 {v26.4h, v27.4h, v28.4h}, [%7], #24 \n"
"st1 {v29.4h, v30.4h, v31.4h}, [%8], #24 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(tmpptr), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(tmpptr),
"10"(kptr),
"r"(biasptr) // %22
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 7 < size; i += 8)
{
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v30.4s, v31.4s}, [%22] \n"
"dup v16.4s, v30.s[0] \n"
"dup v17.4s, v30.s[0] \n"
"dup v18.4s, v30.s[1] \n"
"dup v19.4s, v30.s[1] \n"
"dup v20.4s, v30.s[2] \n"
"dup v21.4s, v30.s[2] \n"
"dup v22.4s, v30.s[3] \n"
"dup v23.4s, v30.s[3] \n"
"dup v24.4s, v31.s[0] \n"
"dup v25.4s, v31.s[0] \n"
"dup v26.4s, v31.s[1] \n"
"dup v27.4s, v31.s[1] \n"
"dup v28.4s, v31.s[2] \n"
"dup v29.4s, v31.s[2] \n"
"dup v30.4s, v31.s[3] \n"
"dup v31.4s, v31.s[3] \n"
"0: \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%10], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v16.4s, v0.4s, v4.s[0] \n"
"fmla v18.4s, v0.4s, v4.s[1] \n"
"fmla v20.4s, v0.4s, v4.s[2] \n"
"fmla v22.4s, v0.4s, v4.s[3] \n"
"fmla v24.4s, v0.4s, v5.s[0] \n"
"fmla v26.4s, v0.4s, v5.s[1] \n"
"fmla v28.4s, v0.4s, v5.s[2] \n"
"fmla v30.4s, v0.4s, v5.s[3] \n"
"fmla v17.4s, v1.4s, v4.s[0] \n"
"fmla v19.4s, v1.4s, v4.s[1] \n"
"fmla v21.4s, v1.4s, v4.s[2] \n"
"fmla v23.4s, v1.4s, v4.s[3] \n"
"fmla v25.4s, v1.4s, v5.s[0] \n"
"fmla v27.4s, v1.4s, v5.s[1] \n"
"fmla v29.4s, v1.4s, v5.s[2] \n"
"fmla v31.4s, v1.4s, v5.s[3] \n"
"fmla v16.4s, v2.4s, v6.s[0] \n"
"fmla v18.4s, v2.4s, v6.s[1] \n"
"fmla v20.4s, v2.4s, v6.s[2] \n"
"fmla v22.4s, v2.4s, v6.s[3] \n"
"fmla v24.4s, v2.4s, v7.s[0] \n"
"fmla v26.4s, v2.4s, v7.s[1] \n"
"fmla v28.4s, v2.4s, v7.s[2] \n"
"fmla v30.4s, v2.4s, v7.s[3] \n"
"fmla v17.4s, v3.4s, v6.s[0] \n"
"fmla v19.4s, v3.4s, v6.s[1] \n"
"fmla v21.4s, v3.4s, v6.s[2] \n"
"fmla v23.4s, v3.4s, v6.s[3] \n"
"fmla v25.4s, v3.4s, v7.s[0] \n"
"fmla v27.4s, v3.4s, v7.s[1] \n"
"fmla v29.4s, v3.4s, v7.s[2] \n"
"fmla v31.4s, v3.4s, v7.s[3] \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v12.4h, v13.4h, v14.4h, v15.4h}, [%9], #32 \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v8.4h, v9.4h, v10.4h, v11.4h}, [%10], #32 \n"
"shll v12.4s, v12.4h, #16 \n"
"shll v13.4s, v13.4h, #16 \n"
"shll v14.4s, v14.4h, #16 \n"
"shll v15.4s, v15.4h, #16 \n"
"shll v8.4s, v8.4h, #16 \n"
"shll v9.4s, v9.4h, #16 \n"
"shll v10.4s, v10.4h, #16 \n"
"shll v11.4s, v11.4h, #16 \n"
"fmla v16.4s, v12.4s, v8.s[0] \n"
"fmla v18.4s, v12.4s, v8.s[1] \n"
"fmla v20.4s, v12.4s, v8.s[2] \n"
"fmla v22.4s, v12.4s, v8.s[3] \n"
"fmla v24.4s, v12.4s, v9.s[0] \n"
"fmla v26.4s, v12.4s, v9.s[1] \n"
"fmla v28.4s, v12.4s, v9.s[2] \n"
"fmla v30.4s, v12.4s, v9.s[3] \n"
"fmla v17.4s, v13.4s, v8.s[0] \n"
"fmla v19.4s, v13.4s, v8.s[1] \n"
"fmla v21.4s, v13.4s, v8.s[2] \n"
"fmla v23.4s, v13.4s, v8.s[3] \n"
"fmla v25.4s, v13.4s, v9.s[0] \n"
"fmla v27.4s, v13.4s, v9.s[1] \n"
"fmla v29.4s, v13.4s, v9.s[2] \n"
"fmla v31.4s, v13.4s, v9.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v14.4s, v10.s[0] \n"
"fmla v18.4s, v14.4s, v10.s[1] \n"
"fmla v20.4s, v14.4s, v10.s[2] \n"
"fmla v22.4s, v14.4s, v10.s[3] \n"
"fmla v24.4s, v14.4s, v11.s[0] \n"
"fmla v26.4s, v14.4s, v11.s[1] \n"
"fmla v28.4s, v14.4s, v11.s[2] \n"
"fmla v30.4s, v14.4s, v11.s[3] \n"
"fmla v17.4s, v15.4s, v10.s[0] \n"
"fmla v19.4s, v15.4s, v10.s[1] \n"
"fmla v21.4s, v15.4s, v10.s[2] \n"
"fmla v23.4s, v15.4s, v10.s[3] \n"
"fmla v25.4s, v15.4s, v11.s[0] \n"
"fmla v27.4s, v15.4s, v11.s[1] \n"
"fmla v29.4s, v15.4s, v11.s[2] \n"
"fmla v31.4s, v15.4s, v11.s[3] \n"
"bne 0b \n"
"shrn v16.4h, v16.4s, #16 \n"
"shrn v17.4h, v17.4s, #16 \n"
"shrn v18.4h, v18.4s, #16 \n"
"shrn v19.4h, v19.4s, #16 \n"
"shrn v20.4h, v20.4s, #16 \n"
"shrn v21.4h, v21.4s, #16 \n"
"shrn v22.4h, v22.4s, #16 \n"
"shrn v23.4h, v23.4s, #16 \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"shrn v26.4h, v26.4s, #16 \n"
"shrn v27.4h, v27.4s, #16 \n"
"shrn v28.4h, v28.4s, #16 \n"
"shrn v29.4h, v29.4s, #16 \n"
"shrn v30.4h, v30.4s, #16 \n"
"shrn v31.4h, v31.4s, #16 \n"
"st1 {v16.4h, v17.4h}, [%1], #16 \n"
"st1 {v18.4h, v19.4h}, [%2], #16 \n"
"st1 {v20.4h, v21.4h}, [%3], #16 \n"
"st1 {v22.4h, v23.4h}, [%4], #16 \n"
"st1 {v24.4h, v25.4h}, [%5], #16 \n"
"st1 {v26.4h, v27.4h}, [%6], #16 \n"
"st1 {v28.4h, v29.4h}, [%7], #16 \n"
"st1 {v30.4h, v31.4h}, [%8], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(tmpptr), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(tmpptr),
"10"(kptr),
"r"(biasptr) // %22
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 3 < size; i += 4)
{
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v22.4s, v23.4s}, [%22] \n"
"dup v16.4s, v22.s[0] \n"
"dup v17.4s, v22.s[1] \n"
"dup v18.4s, v22.s[2] \n"
"dup v19.4s, v22.s[3] \n"
"dup v20.4s, v23.s[0] \n"
"dup v21.4s, v23.s[1] \n"
"dup v22.4s, v23.s[2] \n"
"dup v23.4s, v23.s[3] \n"
"0: \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%10], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v16.4s, v0.4s, v4.s[0] \n"
"fmla v17.4s, v0.4s, v4.s[1] \n"
"fmla v18.4s, v0.4s, v4.s[2] \n"
"fmla v19.4s, v0.4s, v4.s[3] \n"
"fmla v20.4s, v0.4s, v5.s[0] \n"
"fmla v21.4s, v0.4s, v5.s[1] \n"
"fmla v22.4s, v0.4s, v5.s[2] \n"
"fmla v23.4s, v0.4s, v5.s[3] \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v8.4h, v9.4h, v10.4h, v11.4h}, [%10], #32 \n"
"shll v8.4s, v8.4h, #16 \n"
"shll v9.4s, v9.4h, #16 \n"
"shll v10.4s, v10.4h, #16 \n"
"shll v11.4s, v11.4h, #16 \n"
"fmla v16.4s, v1.4s, v6.s[0] \n"
"fmla v17.4s, v1.4s, v6.s[1] \n"
"fmla v18.4s, v1.4s, v6.s[2] \n"
"fmla v19.4s, v1.4s, v6.s[3] \n"
"fmla v20.4s, v1.4s, v7.s[0] \n"
"fmla v21.4s, v1.4s, v7.s[1] \n"
"fmla v22.4s, v1.4s, v7.s[2] \n"
"fmla v23.4s, v1.4s, v7.s[3] \n"
"fmla v16.4s, v2.4s, v8.s[0] \n"
"fmla v17.4s, v2.4s, v8.s[1] \n"
"fmla v18.4s, v2.4s, v8.s[2] \n"
"fmla v19.4s, v2.4s, v8.s[3] \n"
"fmla v20.4s, v2.4s, v9.s[0] \n"
"fmla v21.4s, v2.4s, v9.s[1] \n"
"fmla v22.4s, v2.4s, v9.s[2] \n"
"fmla v23.4s, v2.4s, v9.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v3.4s, v10.s[0] \n"
"fmla v17.4s, v3.4s, v10.s[1] \n"
"fmla v18.4s, v3.4s, v10.s[2] \n"
"fmla v19.4s, v3.4s, v10.s[3] \n"
"fmla v20.4s, v3.4s, v11.s[0] \n"
"fmla v21.4s, v3.4s, v11.s[1] \n"
"fmla v22.4s, v3.4s, v11.s[2] \n"
"fmla v23.4s, v3.4s, v11.s[3] \n"
"bne 0b \n"
"shrn v16.4h, v16.4s, #16 \n"
"shrn v17.4h, v17.4s, #16 \n"
"shrn v18.4h, v18.4s, #16 \n"
"shrn v19.4h, v19.4s, #16 \n"
"shrn v20.4h, v20.4s, #16 \n"
"shrn v21.4h, v21.4s, #16 \n"
"shrn v22.4h, v22.4s, #16 \n"
"shrn v23.4h, v23.4s, #16 \n"
"st1 {v16.4h}, [%1], #8 \n"
"st1 {v17.4h}, [%2], #8 \n"
"st1 {v18.4h}, [%3], #8 \n"
"st1 {v19.4h}, [%4], #8 \n"
"st1 {v20.4h}, [%5], #8 \n"
"st1 {v21.4h}, [%6], #8 \n"
"st1 {v22.4h}, [%7], #8 \n"
"st1 {v23.4h}, [%8], #8 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(tmpptr), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(tmpptr),
"10"(kptr),
"r"(biasptr) // %22
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
}
for (; i < size; i++)
{
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v16.4s, v17.4s}, [%22] \n"
"eor v18.16b, v18.16b, v18.16b \n"
"eor v19.16b, v19.16b, v19.16b \n"
"0: \n"
"prfm pldl1keep, [%9, #64] \n"
"ld1 {v0.4h}, [%9], #8 \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%10], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v16.4s, v4.4s, v0.s[0] \n"
"fmla v17.4s, v5.4s, v0.s[0] \n"
"fmla v18.4s, v6.4s, v0.s[1] \n"
"fmla v19.4s, v7.4s, v0.s[1] \n"
"prfm pldl1keep, [%10, #256] \n"
"ld1 {v8.4h, v9.4h, v10.4h, v11.4h}, [%10], #32 \n"
"shll v8.4s, v8.4h, #16 \n"
"shll v9.4s, v9.4h, #16 \n"
"shll v10.4s, v10.4h, #16 \n"
"shll v11.4s, v11.4h, #16 \n"
"fmla v16.4s, v8.4s, v0.s[2] \n"
"fmla v17.4s, v9.4s, v0.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v18.4s, v10.4s, v0.s[3] \n"
"fmla v19.4s, v11.4s, v0.s[3] \n"
"bne 0b \n"
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"shrn v16.4h, v16.4s, #16 \n"
"shrn v17.4h, v17.4s, #16 \n"
"st1 {v16.h}[0], [%1], #2 \n"
"st1 {v16.h}[1], [%2], #2 \n"
"st1 {v16.h}[2], [%3], #2 \n"
"st1 {v16.h}[3], [%4], #2 \n"
"st1 {v17.h}[0], [%5], #2 \n"
"st1 {v17.h}[1], [%6], #2 \n"
"st1 {v17.h}[2], [%7], #2 \n"
"st1 {v17.h}[3], [%8], #2 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(tmpptr), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(tmpptr),
"10"(kptr),
"r"(biasptr) // %22
: "cc", "memory", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19");
}
}
remain_outch_start += nn_outch << 3;
nn_outch = (outch - remain_outch_start) >> 2;
#else // __aarch64__
nn_outch = outch >> 2;
#endif // __aarch64__
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
unsigned short* outptr0 = top_blob.channel(p);
unsigned short* outptr1 = top_blob.channel(p + 1);
unsigned short* outptr2 = top_blob.channel(p + 2);
unsigned short* outptr3 = top_blob.channel(p + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p : zeros;
int i = 0;
#if __aarch64__
for (; i + 11 < size; i += 12)
{
unsigned short* tmpptr = tmp.channel(i / 12);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v19.4s}, [%14] \n"
"dup v8.4s, v19.s[0] \n"
"dup v9.4s, v19.s[0] \n"
"dup v10.4s, v19.s[0] \n"
"dup v11.4s, v19.s[1] \n"
"dup v12.4s, v19.s[1] \n"
"dup v13.4s, v19.s[1] \n"
"dup v14.4s, v19.s[2] \n"
"dup v15.4s, v19.s[2] \n"
"dup v16.4s, v19.s[2] \n"
"dup v17.4s, v19.s[3] \n"
"dup v18.4s, v19.s[3] \n"
"dup v19.4s, v19.s[3] \n"
"0: \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%5], #32 \n"
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%6], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v11.4s, v0.4s, v4.s[1] \n"
"fmla v14.4s, v0.4s, v4.s[2] \n"
"fmla v17.4s, v0.4s, v4.s[3] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v12.4s, v1.4s, v4.s[1] \n"
"fmla v15.4s, v1.4s, v4.s[2] \n"
"fmla v18.4s, v1.4s, v4.s[3] \n"
"fmla v10.4s, v2.4s, v4.s[0] \n"
"fmla v13.4s, v2.4s, v4.s[1] \n"
"fmla v16.4s, v2.4s, v4.s[2] \n"
"fmla v19.4s, v2.4s, v4.s[3] \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v20.4h, v21.4h, v22.4h, v23.4h}, [%5], #32 \n"
"shll v20.4s, v20.4h, #16 \n"
"shll v21.4s, v21.4h, #16 \n"
"shll v22.4s, v22.4h, #16 \n"
"shll v23.4s, v23.4h, #16 \n"
"fmla v8.4s, v3.4s, v5.s[0] \n"
"fmla v11.4s, v3.4s, v5.s[1] \n"
"fmla v14.4s, v3.4s, v5.s[2] \n"
"fmla v17.4s, v3.4s, v5.s[3] \n"
"fmla v9.4s, v20.4s, v5.s[0] \n"
"fmla v12.4s, v20.4s, v5.s[1] \n"
"fmla v15.4s, v20.4s, v5.s[2] \n"
"fmla v18.4s, v20.4s, v5.s[3] \n"
"fmla v10.4s, v21.4s, v5.s[0] \n"
"fmla v13.4s, v21.4s, v5.s[1] \n"
"fmla v16.4s, v21.4s, v5.s[2] \n"
"fmla v19.4s, v21.4s, v5.s[3] \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%5], #32 \n"
"shll v24.4s, v24.4h, #16 \n"
"shll v25.4s, v25.4h, #16 \n"
"shll v26.4s, v26.4h, #16 \n"
"shll v27.4s, v27.4h, #16 \n"
"fmla v8.4s, v22.4s, v6.s[0] \n"
"fmla v11.4s, v22.4s, v6.s[1] \n"
"fmla v14.4s, v22.4s, v6.s[2] \n"
"fmla v17.4s, v22.4s, v6.s[3] \n"
"fmla v9.4s, v23.4s, v6.s[0] \n"
"fmla v12.4s, v23.4s, v6.s[1] \n"
"fmla v15.4s, v23.4s, v6.s[2] \n"
"fmla v18.4s, v23.4s, v6.s[3] \n"
"fmla v10.4s, v24.4s, v6.s[0] \n"
"fmla v13.4s, v24.4s, v6.s[1] \n"
"fmla v16.4s, v24.4s, v6.s[2] \n"
"fmla v19.4s, v24.4s, v6.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v25.4s, v7.s[0] \n"
"fmla v11.4s, v25.4s, v7.s[1] \n"
"fmla v14.4s, v25.4s, v7.s[2] \n"
"fmla v17.4s, v25.4s, v7.s[3] \n"
"fmla v9.4s, v26.4s, v7.s[0] \n"
"fmla v12.4s, v26.4s, v7.s[1] \n"
"fmla v15.4s, v26.4s, v7.s[2] \n"
"fmla v18.4s, v26.4s, v7.s[3] \n"
"fmla v10.4s, v27.4s, v7.s[0] \n"
"fmla v13.4s, v27.4s, v7.s[1] \n"
"fmla v16.4s, v27.4s, v7.s[2] \n"
"fmla v19.4s, v27.4s, v7.s[3] \n"
"bne 0b \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"shrn v12.4h, v12.4s, #16 \n"
"shrn v13.4h, v13.4s, #16 \n"
"shrn v14.4h, v14.4s, #16 \n"
"shrn v15.4h, v15.4s, #16 \n"
"shrn v16.4h, v16.4s, #16 \n"
"shrn v17.4h, v17.4s, #16 \n"
"shrn v18.4h, v18.4s, #16 \n"
"shrn v19.4h, v19.4s, #16 \n"
"st1 {v8.4h, v9.4h, v10.4h}, [%1], #24 \n"
"st1 {v11.4h, v12.4h, v13.4h}, [%2], #24 \n"
"st1 {v14.4h, v15.4h, v16.4h}, [%3], #24 \n"
"st1 {v17.4h, v18.4h, v19.4h}, [%4], #24 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(tmpptr), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(tmpptr),
"6"(kptr),
"r"(biasptr) // %14
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27");
}
#endif // __aarch64__
for (; i + 7 < size; i += 8)
{
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v15.4s}, [%14] \n"
"dup v8.4s, v15.s[0] \n"
"dup v9.4s, v15.s[0] \n"
"dup v10.4s, v15.s[1] \n"
"dup v11.4s, v15.s[1] \n"
"dup v12.4s, v15.s[2] \n"
"dup v13.4s, v15.s[2] \n"
"dup v14.4s, v15.s[3] \n"
"dup v15.4s, v15.s[3] \n"
"0: \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%5], #32 \n"
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%6], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v10.4s, v0.4s, v4.s[1] \n"
"fmla v12.4s, v0.4s, v4.s[2] \n"
"fmla v14.4s, v0.4s, v4.s[3] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v11.4s, v1.4s, v4.s[1] \n"
"fmla v13.4s, v1.4s, v4.s[2] \n"
"fmla v15.4s, v1.4s, v4.s[3] \n"
"fmla v8.4s, v2.4s, v5.s[0] \n"
"fmla v10.4s, v2.4s, v5.s[1] \n"
"fmla v12.4s, v2.4s, v5.s[2] \n"
"fmla v14.4s, v2.4s, v5.s[3] \n"
"fmla v9.4s, v3.4s, v5.s[0] \n"
"fmla v11.4s, v3.4s, v5.s[1] \n"
"fmla v13.4s, v3.4s, v5.s[2] \n"
"fmla v15.4s, v3.4s, v5.s[3] \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v16.4h, v17.4h, v18.4h, v19.4h}, [%5], #32 \n"
"shll v16.4s, v16.4h, #16 \n"
"shll v17.4s, v17.4h, #16 \n"
"shll v18.4s, v18.4h, #16 \n"
"shll v19.4s, v19.4h, #16 \n"
"fmla v8.4s, v16.4s, v6.s[0] \n"
"fmla v10.4s, v16.4s, v6.s[1] \n"
"fmla v12.4s, v16.4s, v6.s[2] \n"
"fmla v14.4s, v16.4s, v6.s[3] \n"
"fmla v9.4s, v17.4s, v6.s[0] \n"
"fmla v11.4s, v17.4s, v6.s[1] \n"
"fmla v13.4s, v17.4s, v6.s[2] \n"
"fmla v15.4s, v17.4s, v6.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v18.4s, v7.s[0] \n"
"fmla v10.4s, v18.4s, v7.s[1] \n"
"fmla v12.4s, v18.4s, v7.s[2] \n"
"fmla v14.4s, v18.4s, v7.s[3] \n"
"fmla v9.4s, v19.4s, v7.s[0] \n"
"fmla v11.4s, v19.4s, v7.s[1] \n"
"fmla v13.4s, v19.4s, v7.s[2] \n"
"fmla v15.4s, v19.4s, v7.s[3] \n"
"bne 0b \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"shrn v12.4h, v12.4s, #16 \n"
"shrn v13.4h, v13.4s, #16 \n"
"shrn v14.4h, v14.4s, #16 \n"
"shrn v15.4h, v15.4s, #16 \n"
"st1 {v8.4h, v9.4h}, [%1], #16 \n"
"st1 {v10.4h, v11.4h}, [%2], #16 \n"
"st1 {v12.4h, v13.4h}, [%3], #16 \n"
"st1 {v14.4h, v15.4h}, [%4], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(tmpptr), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(tmpptr),
"6"(kptr),
"r"(biasptr) // %14
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
#else // __aarch64__
asm volatile(
"vld1.f32 {d30-d31}, [%14] \n"
"vdup.f32 q8, d30[0] \n"
"vdup.f32 q9, d30[0] \n"
"vdup.f32 q10, d30[1] \n"
"vdup.f32 q11, d30[1] \n"
"vdup.f32 q12, d31[0] \n"
"vdup.f32 q13, d31[0] \n"
"vdup.f32 q14, d31[1] \n"
"vdup.f32 q15, d31[1] \n"
"0: \n"
"pld [%5, #256] \n"
"vld1.u16 {d4-d7}, [%5]! \n"
"pld [%6, #256] \n"
"vld1.u16 {d12-d15}, [%6]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q10, q0, d8[1] \n"
"vmla.f32 q12, q0, d9[0] \n"
"vmla.f32 q14, q0, d9[1] \n"
"vmla.f32 q9, q1, d8[0] \n"
"vmla.f32 q11, q1, d8[1] \n"
"vmla.f32 q13, q1, d9[0] \n"
"vmla.f32 q15, q1, d9[1] \n"
"vmla.f32 q8, q2, d10[0] \n"
"vmla.f32 q10, q2, d10[1] \n"
"vmla.f32 q12, q2, d11[0] \n"
"vmla.f32 q14, q2, d11[1] \n"
"vmla.f32 q9, q3, d10[0] \n"
"vmla.f32 q11, q3, d10[1] \n"
"vmla.f32 q13, q3, d11[0] \n"
"vmla.f32 q15, q3, d11[1] \n"
"pld [%5, #256] \n"
"vld1.u16 {d4-d7}, [%5]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"vmla.f32 q8, q0, d12[0] \n"
"vmla.f32 q10, q0, d12[1] \n"
"vmla.f32 q12, q0, d13[0] \n"
"vmla.f32 q14, q0, d13[1] \n"
"vmla.f32 q9, q1, d12[0] \n"
"vmla.f32 q11, q1, d12[1] \n"
"vmla.f32 q13, q1, d13[0] \n"
"vmla.f32 q15, q1, d13[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q2, d14[0] \n"
"vmla.f32 q10, q2, d14[1] \n"
"vmla.f32 q12, q2, d15[0] \n"
"vmla.f32 q14, q2, d15[1] \n"
"vmla.f32 q9, q3, d14[0] \n"
"vmla.f32 q11, q3, d14[1] \n"
"vmla.f32 q13, q3, d15[0] \n"
"vmla.f32 q15, q3, d15[1] \n"
"bne 0b \n"
"vshrn.u32 d16, q8, #16 \n"
"vshrn.u32 d17, q9, #16 \n"
"vshrn.u32 d20, q10, #16 \n"
"vshrn.u32 d21, q11, #16 \n"
"vshrn.u32 d24, q12, #16 \n"
"vshrn.u32 d25, q13, #16 \n"
"vshrn.u32 d28, q14, #16 \n"
"vshrn.u32 d29, q15, #16 \n"
"vst1.u16 {d16-d17}, [%1 :64]! \n"
"vst1.u16 {d20-d21}, [%2 :64]! \n"
"vst1.u16 {d24-d25}, [%3 :64]! \n"
"vst1.u16 {d28-d29}, [%4 :64]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(tmpptr), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(tmpptr),
"6"(kptr),
"r"(biasptr) // %14
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
}
for (; i + 3 < size; i += 4)
{
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v11.4s}, [%14] \n"
"dup v8.4s, v11.s[0] \n"
"dup v9.4s, v11.s[1] \n"
"dup v10.4s, v11.s[2] \n"
"dup v11.4s, v11.s[3] \n"
"0: \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%5], #32 \n"
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%6], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v0.4s, v4.s[1] \n"
"fmla v10.4s, v0.4s, v4.s[2] \n"
"fmla v11.4s, v0.4s, v4.s[3] \n"
"fmla v8.4s, v1.4s, v5.s[0] \n"
"fmla v9.4s, v1.4s, v5.s[1] \n"
"fmla v10.4s, v1.4s, v5.s[2] \n"
"fmla v11.4s, v1.4s, v5.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v2.4s, v6.s[0] \n"
"fmla v9.4s, v2.4s, v6.s[1] \n"
"fmla v10.4s, v2.4s, v6.s[2] \n"
"fmla v11.4s, v2.4s, v6.s[3] \n"
"fmla v8.4s, v3.4s, v7.s[0] \n"
"fmla v9.4s, v3.4s, v7.s[1] \n"
"fmla v10.4s, v3.4s, v7.s[2] \n"
"fmla v11.4s, v3.4s, v7.s[3] \n"
"bne 0b \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"st1 {v8.4h}, [%1], #8 \n"
"st1 {v9.4h}, [%2], #8 \n"
"st1 {v10.4h}, [%3], #8 \n"
"st1 {v11.4h}, [%4], #8 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(tmpptr), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(tmpptr),
"6"(kptr),
"r"(biasptr) // %14
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else // __aarch64__
asm volatile(
"vld1.f32 {d22-d23}, [%14] \n"
"vdup.f32 q8, d22[0] \n"
"vdup.f32 q9, d22[1] \n"
"vdup.f32 q10, d23[0] \n"
"vdup.f32 q11, d23[1] \n"
"0: \n"
"pld [%5, #256] \n"
"vld1.u16 {d4-d7}, [%5]! \n"
"pld [%6, #256] \n"
"vld1.u16 {d12-d15}, [%6]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q9, q0, d8[1] \n"
"vmla.f32 q10, q0, d9[0] \n"
"vmla.f32 q11, q0, d9[1] \n"
"vmla.f32 q8, q1, d10[0] \n"
"vmla.f32 q9, q1, d10[1] \n"
"vmla.f32 q10, q1, d11[0] \n"
"vmla.f32 q11, q1, d11[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q2, d12[0] \n"
"vmla.f32 q9, q2, d12[1] \n"
"vmla.f32 q10, q2, d13[0] \n"
"vmla.f32 q11, q2, d13[1] \n"
"vmla.f32 q8, q3, d14[0] \n"
"vmla.f32 q9, q3, d14[1] \n"
"vmla.f32 q10, q3, d15[0] \n"
"vmla.f32 q11, q3, d15[1] \n"
"bne 0b \n"
"vshrn.u32 d16, q8, #16 \n"
"vshrn.u32 d18, q9, #16 \n"
"vshrn.u32 d20, q10, #16 \n"
"vshrn.u32 d22, q11, #16 \n"
"vst1.u16 {d16}, [%1 :64]! \n"
"vst1.u16 {d18}, [%2 :64]! \n"
"vst1.u16 {d20}, [%3 :64]! \n"
"vst1.u16 {d22}, [%4 :64]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(tmpptr), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(tmpptr),
"6"(kptr),
"r"(biasptr) // %14
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif // __aarch64__
}
for (; i < size; i++)
{
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v8.4s}, [%14] \n"
"eor v9.16b, v9.16b, v9.16b \n"
"eor v10.16b, v10.16b, v10.16b \n"
"eor v11.16b, v11.16b, v11.16b \n"
"0: \n"
"prfm pldl1keep, [%5, #64] \n"
"ld1 {v0.4h}, [%5], #8 \n"
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%6], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[1] \n"
"subs %w0, %w0, #1 \n"
"fmla v10.4s, v6.4s, v0.s[2] \n"
"fmla v11.4s, v7.4s, v0.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v9.4s \n"
"fadd v10.4s, v10.4s, v11.4s \n"
"fadd v8.4s, v8.4s, v10.4s \n"
"shrn v8.4h, v8.4s, #16 \n"
"st1 {v8.h}[0], [%1], #2 \n"
"st1 {v8.h}[1], [%2], #2 \n"
"st1 {v8.h}[2], [%3], #2 \n"
"st1 {v8.h}[3], [%4], #2 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(tmpptr), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(tmpptr),
"6"(kptr),
"r"(biasptr) // %14
: "cc", "memory", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else // __aarch64__
asm volatile(
"vld1.f32 {d16-d17}, [%14] \n"
"veor q9, q9 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"0: \n"
"pld [%5, #64] \n"
"vld1.u16 {d1}, [%5]! \n"
"pld [%6, #256] \n"
"vld1.u16 {d12-d15}, [%6]! \n"
"vshll.u16 q0, d1, #16 \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q10, q6, d1[0] \n"
"vmla.f32 q11, q7, d1[1] \n"
"bne 0b \n"
"vadd.f32 q8, q8, q9 \n"
"vadd.f32 q10, q10, q11 \n"
"vadd.f32 q8, q8, q10 \n"
"vshrn.u32 d16, q8, #16 \n"
"vst1.u16 {d16[0]}, [%1]! \n"
"vst1.u16 {d16[1]}, [%2]! \n"
"vst1.u16 {d16[2]}, [%3]! \n"
"vst1.u16 {d16[3]}, [%4]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(tmpptr), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(tmpptr),
"6"(kptr),
"r"(biasptr) // %14
: "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif // __aarch64__
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
unsigned short* outptr0 = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
int i = 0;
#if __aarch64__
for (; i + 11 < size; i += 12)
{
unsigned short* tmpptr = tmp.channel(i / 12);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
asm volatile(
"dup v8.4s, %w8 \n"
"dup v9.4s, %w8 \n"
"dup v10.4s, %w8 \n"
"eor v5.16b, v5.16b, v5.16b \n"
"eor v6.16b, v6.16b, v6.16b \n"
"eor v7.16b, v7.16b, v7.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%2], #32 \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v4.4h}, [%3], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v10.4s, v2.4s, v4.s[0] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v12.4h, v13.4h, v14.4h, v15.4h}, [%2], #32 \n"
"shll v12.4s, v12.4h, #16 \n"
"shll v13.4s, v13.4h, #16 \n"
"shll v14.4s, v14.4h, #16 \n"
"shll v15.4s, v15.4h, #16 \n"
"fmla v5.4s, v3.4s, v4.s[1] \n"
"fmla v6.4s, v12.4s, v4.s[1] \n"
"fmla v7.4s, v13.4s, v4.s[1] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v16.4h, v17.4h, v18.4h, v19.4h}, [%2], #32 \n"
"shll v16.4s, v16.4h, #16 \n"
"shll v17.4s, v17.4h, #16 \n"
"shll v18.4s, v18.4h, #16 \n"
"shll v19.4s, v19.4h, #16 \n"
"fmla v8.4s, v14.4s, v4.s[2] \n"
"fmla v9.4s, v15.4s, v4.s[2] \n"
"fmla v10.4s, v16.4s, v4.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v5.4s, v17.4s, v4.s[3] \n"
"fmla v6.4s, v18.4s, v4.s[3] \n"
"fmla v7.4s, v19.4s, v4.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v5.4s \n"
"fadd v9.4s, v9.4s, v6.4s \n"
"fadd v10.4s, v10.4s, v7.4s \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"st1 {v8.4h, v9.4h, v10.4h}, [%1], #24 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr),
"r"(bias0) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
}
#endif // __aarch64__
for (; i + 7 < size; i += 8)
{
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 4 + p % 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"dup v8.4s, %w8 \n"
"dup v9.4s, %w8 \n"
"eor v10.16b, v10.16b, v10.16b \n"
"eor v11.16b, v11.16b, v11.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%2], #32 \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v4.4h}, [%3], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v10.4s, v2.4s, v4.s[1] \n"
"fmla v11.4s, v3.4s, v4.s[1] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v12.4h, v13.4h, v14.4h, v15.4h}, [%2], #32 \n"
"shll v12.4s, v12.4h, #16 \n"
"shll v13.4s, v13.4h, #16 \n"
"shll v14.4s, v14.4h, #16 \n"
"shll v15.4s, v15.4h, #16 \n"
"fmla v8.4s, v12.4s, v4.s[2] \n"
"fmla v9.4s, v13.4s, v4.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v10.4s, v14.4s, v4.s[3] \n"
"fmla v11.4s, v15.4s, v4.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v10.4s \n"
"fadd v9.4s, v9.4s, v11.4s \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"st1 {v8.4h, v9.4h}, [%1], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr),
"r"(bias0) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
#else // __aarch64__
asm volatile(
"vdup.f32 q8, %8 \n"
"vdup.f32 q9, %8 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"0: \n"
"pld [%2, #256] \n"
"vld1.u16 {d4-d7}, [%2]! \n"
"pld [%3, #64] \n"
"vld1.u16 {d9}, [%3]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"vshll.u16 q4, d9, #16 \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q9, q1, d8[0] \n"
"vmla.f32 q10, q2, d8[1] \n"
"vmla.f32 q11, q3, d8[1] \n"
"pld [%2, #256] \n"
"vld1.u16 {d28-d31}, [%2]! \n"
"vshll.u16 q12, d28, #16 \n"
"vshll.u16 q13, d29, #16 \n"
"vshll.u16 q14, d30, #16 \n"
"vshll.u16 q15, d31, #16 \n"
"vmla.f32 q8, q12, d9[0] \n"
"vmla.f32 q9, q13, d9[0] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q10, q14, d9[1] \n"
"vmla.f32 q11, q15, d9[1] \n"
"bne 0b \n"
"vadd.f32 q8, q8, q10 \n"
"vadd.f32 q9, q9, q11 \n"
"vshrn.u32 d16, q8, #16 \n"
"vshrn.u32 d17, q9, #16 \n"
"vst1.u16 {d16-d17}, [%1 :64]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr),
"r"(bias0) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
}
for (; i + 3 < size; i += 4)
{
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 4 + p % 4);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"dup v8.4s, %w8 \n"
"eor v9.16b, v9.16b, v9.16b \n"
"eor v10.16b, v10.16b, v10.16b \n"
"eor v11.16b, v11.16b, v11.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%2], #32 \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v4.4h}, [%3], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v1.4s, v4.s[1] \n"
"subs %w0, %w0, #1 \n"
"fmla v10.4s, v2.4s, v4.s[2] \n"
"fmla v11.4s, v3.4s, v4.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v9.4s \n"
"fadd v10.4s, v10.4s, v11.4s \n"
"fadd v8.4s, v8.4s, v10.4s \n"
"shrn v8.4h, v8.4s, #16 \n"
"st1 {v8.4h}, [%1], #8 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr),
"r"(bias0) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11");
#else // __aarch64__
asm volatile(
"vdup.f32 q8, %8 \n"
"veor q9, q9 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"0: \n"
"pld [%2, #256] \n"
"vld1.u16 {d4-d7}, [%2]! \n"
"pld [%3, #64] \n"
"vld1.u16 {d9}, [%3]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"vshll.u16 q4, d9, #16 \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q9, q1, d8[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q10, q2, d9[0] \n"
"vmla.f32 q11, q3, d9[1] \n"
"bne 0b \n"
"vadd.f32 q8, q8, q9 \n"
"vadd.f32 q10, q10, q11 \n"
"vadd.f32 q8, q8, q10 \n"
"vshrn.u32 d16, q8, #16 \n"
"vst1.u16 {d16}, [%1]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr),
"r"(bias0) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11");
#endif // __aarch64__
}
for (; i < size; i++)
{
#if __aarch64__
unsigned short* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + i % 12 % 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
const unsigned short* kptr = (const unsigned short*)kernel.channel(p / 4 + p % 4);
#endif
int nn = inch * maxk; // inch always > 0
float32x4_t _sum0 = vdupq_n_f32(0.f);
for (int q = 0; q < nn; q++)
{
float32x4_t _r0 = vcvt_f32_bf16(vld1_u16(tmpptr));
float32x4_t _k0 = vcvt_f32_bf16(vld1_u16(kptr));
_sum0 = vmlaq_f32(_sum0, _r0, _k0);
kptr += 4;
tmpptr += 4;
}
#if __aarch64__
float sum0 = vaddvq_f32(_sum0);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float32x2_t _ss2 = vpadd_f32(_ss, _ss);
float sum0 = vget_lane_f32(_ss2, 0);
#endif
outptr0[0] = float32_to_bfloat16(bias0 + sum0);
outptr0++;
}
}
}
static void convolution_im2col_sgemm_transform_kernel_pack4to1_bf16s_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h)
{
const int maxk = kernel_w * kernel_h;
// interleave
// src = maxk-inch-outch
// dst = 4b-4a-maxk-inch/4a-outch/4b
Mat kernel = _kernel.reshape(maxk, inch, outch);
#if __aarch64__
kernel_tm.create(32 * maxk, inch / 4, outch / 8 + (outch % 8) / 4 + outch % 4, (size_t)2u);
#else
kernel_tm.create(16 * maxk, inch / 4, outch / 4 + outch % 4, (size_t)2u);
#endif
int q = 0;
#if __aarch64__
for (; q + 7 < outch; q += 8)
{
const Mat k0 = kernel.channel(q);
const Mat k1 = kernel.channel(q + 1);
const Mat k2 = kernel.channel(q + 2);
const Mat k3 = kernel.channel(q + 3);
const Mat k4 = kernel.channel(q + 4);
const Mat k5 = kernel.channel(q + 5);
const Mat k6 = kernel.channel(q + 6);
const Mat k7 = kernel.channel(q + 7);
unsigned short* g00 = kernel_tm.channel(q / 8);
for (int p = 0; p + 3 < inch; p += 4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p + 1);
const float* k02 = k0.row(p + 2);
const float* k03 = k0.row(p + 3);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p + 1);
const float* k12 = k1.row(p + 2);
const float* k13 = k1.row(p + 3);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p + 1);
const float* k22 = k2.row(p + 2);
const float* k23 = k2.row(p + 3);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p + 1);
const float* k32 = k3.row(p + 2);
const float* k33 = k3.row(p + 3);
const float* k40 = k4.row(p);
const float* k41 = k4.row(p + 1);
const float* k42 = k4.row(p + 2);
const float* k43 = k4.row(p + 3);
const float* k50 = k5.row(p);
const float* k51 = k5.row(p + 1);
const float* k52 = k5.row(p + 2);
const float* k53 = k5.row(p + 3);
const float* k60 = k6.row(p);
const float* k61 = k6.row(p + 1);
const float* k62 = k6.row(p + 2);
const float* k63 = k6.row(p + 3);
const float* k70 = k7.row(p);
const float* k71 = k7.row(p + 1);
const float* k72 = k7.row(p + 2);
const float* k73 = k7.row(p + 3);
for (int k = 0; k < maxk; k++)
{
g00[0] = float32_to_bfloat16(k00[k]);
g00[1] = float32_to_bfloat16(k10[k]);
g00[2] = float32_to_bfloat16(k20[k]);
g00[3] = float32_to_bfloat16(k30[k]);
g00[4] = float32_to_bfloat16(k40[k]);
g00[5] = float32_to_bfloat16(k50[k]);
g00[6] = float32_to_bfloat16(k60[k]);
g00[7] = float32_to_bfloat16(k70[k]);
g00[8] = float32_to_bfloat16(k01[k]);
g00[9] = float32_to_bfloat16(k11[k]);
g00[10] = float32_to_bfloat16(k21[k]);
g00[11] = float32_to_bfloat16(k31[k]);
g00[12] = float32_to_bfloat16(k41[k]);
g00[13] = float32_to_bfloat16(k51[k]);
g00[14] = float32_to_bfloat16(k61[k]);
g00[15] = float32_to_bfloat16(k71[k]);
g00[16] = float32_to_bfloat16(k02[k]);
g00[17] = float32_to_bfloat16(k12[k]);
g00[18] = float32_to_bfloat16(k22[k]);
g00[19] = float32_to_bfloat16(k32[k]);
g00[20] = float32_to_bfloat16(k42[k]);
g00[21] = float32_to_bfloat16(k52[k]);
g00[22] = float32_to_bfloat16(k62[k]);
g00[23] = float32_to_bfloat16(k72[k]);
g00[24] = float32_to_bfloat16(k03[k]);
g00[25] = float32_to_bfloat16(k13[k]);
g00[26] = float32_to_bfloat16(k23[k]);
g00[27] = float32_to_bfloat16(k33[k]);
g00[28] = float32_to_bfloat16(k43[k]);
g00[29] = float32_to_bfloat16(k53[k]);
g00[30] = float32_to_bfloat16(k63[k]);
g00[31] = float32_to_bfloat16(k73[k]);
g00 += 32;
}
}
}
#endif // __aarch64__
for (; q + 3 < outch; q += 4)
{
const Mat k0 = kernel.channel(q);
const Mat k1 = kernel.channel(q + 1);
const Mat k2 = kernel.channel(q + 2);
const Mat k3 = kernel.channel(q + 3);
#if __aarch64__
unsigned short* g00 = kernel_tm.channel(q / 8 + (q % 8) / 4);
#else
unsigned short* g00 = kernel_tm.channel(q / 4);
#endif
for (int p = 0; p + 3 < inch; p += 4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p + 1);
const float* k02 = k0.row(p + 2);
const float* k03 = k0.row(p + 3);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p + 1);
const float* k12 = k1.row(p + 2);
const float* k13 = k1.row(p + 3);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p + 1);
const float* k22 = k2.row(p + 2);
const float* k23 = k2.row(p + 3);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p + 1);
const float* k32 = k3.row(p + 2);
const float* k33 = k3.row(p + 3);
for (int k = 0; k < maxk; k++)
{
g00[0] = float32_to_bfloat16(k00[k]);
g00[1] = float32_to_bfloat16(k10[k]);
g00[2] = float32_to_bfloat16(k20[k]);
g00[3] = float32_to_bfloat16(k30[k]);
g00[4] = float32_to_bfloat16(k01[k]);
g00[5] = float32_to_bfloat16(k11[k]);
g00[6] = float32_to_bfloat16(k21[k]);
g00[7] = float32_to_bfloat16(k31[k]);
g00[8] = float32_to_bfloat16(k02[k]);
g00[9] = float32_to_bfloat16(k12[k]);
g00[10] = float32_to_bfloat16(k22[k]);
g00[11] = float32_to_bfloat16(k32[k]);
g00[12] = float32_to_bfloat16(k03[k]);
g00[13] = float32_to_bfloat16(k13[k]);
g00[14] = float32_to_bfloat16(k23[k]);
g00[15] = float32_to_bfloat16(k33[k]);
g00 += 16;
}
}
}
for (; q < outch; q++)
{
const Mat k0 = kernel.channel(q);
#if __aarch64__
unsigned short* g00 = kernel_tm.channel(q / 8 + (q % 8) / 4 + q % 4);
#else
unsigned short* g00 = kernel_tm.channel(q / 4 + q % 4);
#endif
for (int p = 0; p + 3 < inch; p += 4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p + 1);
const float* k02 = k0.row(p + 2);
const float* k03 = k0.row(p + 3);
for (int k = 0; k < maxk; k++)
{
g00[0] = float32_to_bfloat16(k00[k]);
g00[1] = float32_to_bfloat16(k01[k]);
g00[2] = float32_to_bfloat16(k02[k]);
g00[3] = float32_to_bfloat16(k03[k]);
g00 += 4;
}
}
}
}
static void convolution_im2col_sgemm_pack4to1_bf16s_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
const int size = outw * outh;
const int maxk = kernel_w * kernel_h;
// im2col
Mat bottom_im2col(size, maxk, inch, 8u, 4, opt.workspace_allocator);
{
const int gap = (w * stride_h - outw * stride_w) * 4;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
unsigned short* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const unsigned short* sptr = img.row<const unsigned short>(dilation_h * u) + dilation_w * v * 4;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
uint16x4_t _val0 = vld1_u16(sptr);
uint16x4_t _val1 = vld1_u16(sptr + stride_w * 4);
uint16x4_t _val2 = vld1_u16(sptr + stride_w * 8);
uint16x4_t _val3 = vld1_u16(sptr + stride_w * 12);
vst1_u16(ptr, _val0);
vst1_u16(ptr + 4, _val1);
vst1_u16(ptr + 8, _val2);
vst1_u16(ptr + 12, _val3);
sptr += stride_w * 16;
ptr += 16;
}
for (; j + 1 < outw; j += 2)
{
uint16x4_t _val0 = vld1_u16(sptr);
uint16x4_t _val1 = vld1_u16(sptr + stride_w * 4);
vst1_u16(ptr, _val0);
vst1_u16(ptr + 4, _val1);
sptr += stride_w * 8;
ptr += 8;
}
for (; j < outw; j++)
{
uint16x4_t _val = vld1_u16(sptr);
vst1_u16(ptr, _val);
sptr += stride_w * 4;
ptr += 4;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_pack4to1_bf16s_neon(bottom_im2col, top_blob, kernel, _bias, opt);
}
|
GB_unaryop__identity_uint64_uint64.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__identity_uint64_uint64
// op(A') function: GB_tran__identity_uint64_uint64
// C type: uint64_t
// A type: uint64_t
// cast: uint64_t cij = (uint64_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, aij) \
uint64_t z = (uint64_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_uint64_uint64
(
uint64_t *Cx, // Cx and Ax may be aliased
uint64_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__identity_uint64_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
sms4speed.c
|
/* crypto/sms4/sms4speed.c */
/* ====================================================================
* Copyright (c) 2014 - 2016 The GmSSL Project. 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.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include <openmp.h>
#include "sms4.h"
int main(int argc, char **argv)
{
sms4_key_t sms4_key;
unsigned char user_key[16] = {
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
};
size_t buflen = SMS4_BLOCK_SIZE * 8 * 3 * 1000 * 1000;
unsigned char *buf = NULL;
unsigned char *p;
int i;
if (!(buf = (unsigned char *)malloc(buflen))) {
fprintf(stderr, "malloc failed\n");
return -1;
}
sms4_set_encrypt_key(&sms4_key, user_key);
#pragma omp parallel for
for (i = 0, p = buf; i < buflen/(SMS4_BLOCK_SIZE * 16); i++, p += SMS4_BLOCK_SIZE * 16) {
sms4_encrypt_16blocks(&sms4_key, p, p);
}
return 0;
}
|
GB_transpose_bucket.c
|
//------------------------------------------------------------------------------
// GB_transpose_bucket: transpose and optionally typecast and/or apply operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// C = A' or op(A'). Optionally typecasts from A->type to the new type ctype,
// and/or optionally applies a unary operator.
// If an operator z=op(x) is provided, the type of z must be the same as the
// type of C. The type of A must be compatible with the type of of x (A is
// typecasted into the type of x). These conditions must be checked in the
// caller.
// This function is agnostic for the CSR/CSC format of C and A. C_is_csc is
// defined by the caller and assigned to C->is_csc, but otherwise unused.
// A->is_csc is ignored.
// The input can be hypersparse or non-hypersparse. The output C is always
// non-hypersparse, and never shallow. On input, C is a static header.
// If A is m-by-n in CSC format, with e nonzeros, the time and memory taken is
// O(m+n+e) if A is non-hypersparse, or O(m+e) if hypersparse. This is fine if
// most rows and columns of A are non-empty, but can be very costly if A or A'
// is hypersparse. In particular, if A is a non-hypersparse column vector with
// m >> e, the time and memory is O(m), which can be huge. Thus, for
// hypersparse matrices, or for very sparse matrices, the qsort method should
// be used instead (see GB_transpose).
// This method is parallel, but not highly scalable. At most O(e/m) threads
// are used.
#include "GB_transpose.h"
#define GB_FREE_WORK \
{ \
if (Workspaces != NULL && Workspaces_size != NULL) \
{ \
for (int tid = 0 ; tid < nworkspaces ; tid++) \
{ \
GB_FREE_WERK (&(Workspaces [tid]), Workspaces_size [tid]) ; \
} \
} \
GB_WERK_POP (A_slice, int64_t) ; \
GB_WERK_POP (Workspaces_size, size_t) ; \
GB_WERK_POP (Workspaces, int64_t *) ; \
}
#define GB_FREE_ALL \
{ \
GB_phbix_free (C) ; \
GB_FREE_WORK ; \
}
GrB_Info GB_transpose_bucket // bucket transpose; typecast and apply op
(
GrB_Matrix C, // output matrix (static header)
const GB_iso_code C_code_iso, // iso code for C
const GrB_Type ctype, // type of output matrix C
const bool C_is_csc, // format of output matrix C
const GrB_Matrix A, // input matrix
// no operator is applied if both op1 and op2 are NULL
const GrB_UnaryOp op1, // unary operator to apply
const GrB_BinaryOp op2, // binary operator to apply
const GxB_Scalar scalar, // scalar to bind to binary operator
bool binop_bind1st, // if true, binop(x,A) else binop(A,y)
const int nworkspaces, // # of workspaces to use (1, or nthreads)
const int nthreads, // # of threads to use
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (C != NULL) ;
ASSERT (C->static_header) ;
ASSERT_TYPE_OK (ctype, "ctype for transpose", GB0) ;
ASSERT_MATRIX_OK (A, "A input for transpose_bucket", GB0) ;
ASSERT (!GB_PENDING (A)) ;
ASSERT (!GB_ZOMBIES (A)) ;
ASSERT (GB_JUMBLED_OK (A)) ;
// if op1 and op2 are NULL, then no operator is applied
// This method is only be used when A is sparse or hypersparse.
// The full and bitmap cases are handled in GB_transpose.
ASSERT (!GB_IS_FULL (A)) ;
ASSERT (!GB_IS_BITMAP (A)) ;
ASSERT (GB_IS_SPARSE (A) || GB_IS_HYPERSPARSE (A)) ;
GB_WERK_DECLARE (A_slice, int64_t) ; // size nthreads+1
GB_WERK_DECLARE (Workspaces, int64_t *) ; // size nworkspaces
GB_WERK_DECLARE (Workspaces_size, size_t) ; // size nworkspaces
//--------------------------------------------------------------------------
// get A
//--------------------------------------------------------------------------
int64_t anz = GB_nnz (A) ;
int64_t vlen = A->vlen ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
// # of threads to use in the O(vlen) loops below
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nth = GB_nthreads (vlen, chunk, nthreads_max) ;
//--------------------------------------------------------------------------
// allocate C: always sparse
//--------------------------------------------------------------------------
// The bucket transpose only works when C is sparse.
// A can be sparse or hypersparse.
// C->p is allocated but not initialized.
GrB_Info info ;
// set C->iso = C_iso OK
bool C_iso = (C_code_iso != GB_NON_ISO) ;
GB_OK (GB_new_bix (&C, true, // sparse, static header
ctype, A->vdim, vlen, GB_Ap_malloc, C_is_csc,
GxB_SPARSE, true, A->hyper_switch, vlen, anz, true, C_iso, Context)) ;
int64_t *restrict Cp = C->p ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
GB_WERK_PUSH (Workspaces, nworkspaces, int64_t *) ;
GB_WERK_PUSH (Workspaces_size, nworkspaces, size_t) ;
if (Workspaces == NULL || Workspaces_size == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
bool ok = true ;
for (int tid = 0 ; tid < nworkspaces ; tid++)
{
Workspaces [tid] = GB_MALLOC_WERK (vlen + 1, int64_t,
&Workspaces_size [tid]) ;
ok = ok && (Workspaces [tid] != NULL) ;
}
if (!ok)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
//==========================================================================
// phase1: symbolic analysis
//==========================================================================
// slice the A matrix, perfectly balanced for one task per thread
GB_WERK_PUSH (A_slice, nthreads + 1, int64_t) ;
if (A_slice == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
GB_pslice (A_slice, A->p, A->nvec, nthreads, true) ;
// sum up the row counts and find C->p
if (nthreads == 1)
{
//----------------------------------------------------------------------
// sequential method: A is not sliced
//----------------------------------------------------------------------
// Only requires a single int64 workspace of size vlen for a single
// thread. The resulting C matrix is not jumbled.
// compute the row counts of A. No need to scan the A->p pointers
ASSERT (nworkspaces == 1) ;
int64_t *restrict workspace = Workspaces [0] ;
memset (workspace, 0, (vlen + 1) * sizeof (int64_t)) ;
const int64_t *restrict Ai = A->i ;
for (int64_t p = 0 ; p < anz ; p++)
{
int64_t i = Ai [p] ;
workspace [i]++ ;
}
// cumulative sum of the workspace, and copy back into C->p
GB_cumsum (workspace, vlen, &(C->nvec_nonempty), 1, NULL) ;
memcpy (Cp, workspace, (vlen + 1) * sizeof (int64_t)) ;
}
else if (nworkspaces == 1)
{
//----------------------------------------------------------------------
// atomic method: A is sliced but workspace is shared
//----------------------------------------------------------------------
// Only requires a single int64 workspace of size vlen, shared by all
// threads. Scales well, but requires atomics. If the # of rows is
// very small and the average row degree is high, this can be very slow
// because of contention on the atomic workspace. Otherwise, it is
// typically faster than the non-atomic method. The resulting C matrix
// is jumbled.
// compute the row counts of A. No need to scan the A->p pointers
int64_t *restrict workspace = Workspaces [0] ;
GB_memset (workspace, 0, (vlen + 1) * sizeof (int64_t), nth) ;
const int64_t *restrict Ai = A->i ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t i = Ai [p] ;
// update workspace [i]++ automically:
GB_ATOMIC_UPDATE
workspace [i]++ ;
}
C->jumbled = true ; // atomic transpose leaves C jumbled
// cumulative sum of the workspace, and copy back into C->p
GB_cumsum (workspace, vlen, &(C->nvec_nonempty), nth, Context) ;
GB_memcpy (Cp, workspace, (vlen+ 1) * sizeof (int64_t), nth) ;
}
else
{
//----------------------------------------------------------------------
// non-atomic method
//----------------------------------------------------------------------
// compute the row counts of A for each slice, one per thread; This
// method is parallel, but not highly scalable. Each thread requires
// int64 workspace of size vlen, but no atomics are required. The
// resulting C matrix is not jumbled, so this can save work if C needs
// to be unjumbled later.
ASSERT (nworkspaces == nthreads) ;
const int64_t *restrict Ap = A->p ;
const int64_t *restrict Ah = A->h ;
const int64_t *restrict Ai = A->i ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < nthreads ; tid++)
{
// get the row counts for this slice, of size A->vlen
int64_t *restrict workspace = Workspaces [tid] ;
memset (workspace, 0, (vlen + 1) * sizeof (int64_t)) ;
for (int64_t k = A_slice [tid] ; k < A_slice [tid+1] ; k++)
{
// iterate over the entries in A(:,j)
int64_t j = GBH (Ah, k) ;
int64_t pA_start = Ap [k] ;
int64_t pA_end = Ap [k+1] ;
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
// count one more entry in C(i,:) for this slice
int64_t i = Ai [pA] ;
workspace [i]++ ;
}
}
}
// cumulative sum of the workspaces across the slices
int64_t i ;
#pragma omp parallel for num_threads(nth) schedule(static)
for (i = 0 ; i < vlen ; i++)
{
int64_t s = 0 ;
for (int tid = 0 ; tid < nthreads ; tid++)
{
int64_t *restrict workspace = Workspaces [tid] ;
int64_t c = workspace [i] ;
workspace [i] = s ;
s += c ;
}
Cp [i] = s ;
}
Cp [vlen] = 0 ;
// compute the vector pointers for C
GB_cumsum (Cp, vlen, &(C->nvec_nonempty), nth, Context) ;
// add Cp back to all Workspaces
#pragma omp parallel for num_threads(nth) schedule(static)
for (i = 0 ; i < vlen ; i++)
{
int64_t s = Cp [i] ;
int64_t *restrict workspace = Workspaces [0] ;
workspace [i] = s ;
for (int tid = 1 ; tid < nthreads ; tid++)
{
int64_t *restrict workspace = Workspaces [tid] ;
workspace [i] += s ;
}
}
}
C->magic = GB_MAGIC ;
//==========================================================================
// phase2: transpose A into C
//==========================================================================
// transpose both the pattern and the values
if (op1 == NULL && op2 == NULL)
{
// do not apply an operator; optional typecast to C->type
GB_transpose_ix (C, A, Workspaces, A_slice, nworkspaces, nthreads) ;
}
else
{
// apply an operator, C has type op->ztype
GB_transpose_op (C, C_code_iso, op1, op2, scalar, binop_bind1st, A,
Workspaces, A_slice, nworkspaces, nthreads) ;
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
GB_FREE_WORK ;
ASSERT_MATRIX_OK (C, "C transpose of A", GB0) ;
ASSERT (C->h == NULL) ;
return (GrB_SUCCESS) ;
}
|
kmp_stats.h
|
#ifndef KMP_STATS_H
#define KMP_STATS_H
/** @file kmp_stats.h
* Functions for collecting statistics.
*/
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "kmp_config.h"
#include "kmp_debug.h"
#if KMP_STATS_ENABLED
/* Statistics accumulator.
Accumulates number of samples and computes min, max, mean, standard deviation
on the fly.
Online variance calculation algorithm from
http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm
*/
#include "kmp_stats_timing.h"
#include <limits>
#include <math.h>
#include <new> // placement new
#include <stdint.h>
#include <string>
#include <vector>
/* Enable developer statistics here if you want them. They are more detailed
than is useful for application characterisation and are intended for the
runtime library developer. */
#define KMP_DEVELOPER_STATS 0
/* Enable/Disable histogram output */
#define KMP_STATS_HIST 0
/*!
* @ingroup STATS_GATHERING
* \brief flags to describe the statistic (timer or counter)
*
*/
enum stats_flags_e {
noTotal = 1 << 0, //!< do not show a TOTAL_aggregation for this statistic
onlyInMaster = 1 << 1, //!< statistic is valid only for primary thread
noUnits = 1 << 2, //!< statistic doesn't need units printed next to it
notInMaster = 1 << 3, //!< statistic is valid only for non-primary threads
logEvent = 1 << 4 //!< statistic can be logged on the event timeline when
//! KMP_STATS_EVENTS is on (valid only for timers)
};
/*!
* @ingroup STATS_GATHERING
* \brief the states which a thread can be in
*
*/
enum stats_state_e {
IDLE,
SERIAL_REGION,
FORK_JOIN_BARRIER,
PLAIN_BARRIER,
TASKWAIT,
TASKYIELD,
TASKGROUP,
IMPLICIT_TASK,
EXPLICIT_TASK,
TEAMS_REGION
};
/*!
* \brief Add new counters under KMP_FOREACH_COUNTER() macro in kmp_stats.h
*
* @param macro a user defined macro that takes three arguments -
* macro(COUNTER_NAME, flags, arg)
* @param arg a user defined argument to send to the user defined macro
*
* \details A counter counts the occurrence of some event. Each thread
* accumulates its own count, at the end of execution the counts are aggregated
* treating each thread as a separate measurement. (Unless onlyInMaster is set,
* in which case there's only a single measurement). The min,mean,max are
* therefore the values for the threads. Adding the counter here and then
* putting a KMP_BLOCK_COUNTER(name) at the point you want to count is all you
* need to do. All of the tables and printing is generated from this macro.
* Format is "macro(name, flags, arg)"
*
* @ingroup STATS_GATHERING
*/
// clang-format off
#define KMP_FOREACH_COUNTER(macro, arg) \
macro(OMP_PARALLEL,stats_flags_e::onlyInMaster|stats_flags_e::noTotal,arg) \
macro(OMP_NESTED_PARALLEL, 0, arg) \
macro(OMP_LOOP_STATIC, 0, arg) \
macro(OMP_LOOP_STATIC_STEAL, 0, arg) \
macro(OMP_LOOP_DYNAMIC, 0, arg) \
macro(OMP_DISTRIBUTE, 0, arg) \
macro(OMP_BARRIER, 0, arg) \
macro(OMP_CRITICAL, 0, arg) \
macro(OMP_SINGLE, 0, arg) \
macro(OMP_MASTER, 0, arg) \
macro(OMP_MASKED, 0, arg) \
macro(OMP_TEAMS, 0, arg) \
macro(OMP_set_lock, 0, arg) \
macro(OMP_test_lock, 0, arg) \
macro(REDUCE_wait, 0, arg) \
macro(REDUCE_nowait, 0, arg) \
macro(OMP_TASKYIELD, 0, arg) \
macro(OMP_TASKLOOP, 0, arg) \
macro(TASK_executed, 0, arg) \
macro(TASK_cancelled, 0, arg) \
macro(TASK_stolen, 0, arg)
// clang-format on
/*!
* \brief Add new timers under KMP_FOREACH_TIMER() macro in kmp_stats.h
*
* @param macro a user defined macro that takes three arguments -
* macro(TIMER_NAME, flags, arg)
* @param arg a user defined argument to send to the user defined macro
*
* \details A timer collects multiple samples of some count in each thread and
* then finally aggregates all of the samples from all of the threads. For most
* timers the printing code also provides an aggregation over the thread totals.
* These are printed as TOTAL_foo. The count is normally a time (in ticks),
* hence the name "timer". (But can be any value, so we use this for "number of
* arguments passed to fork" as well). For timers the threads are not
* significant, it's the individual observations that count, so the statistics
* are at that level. Format is "macro(name, flags, arg)"
*
* @ingroup STATS_GATHERING2
*/
// clang-format off
#define KMP_FOREACH_TIMER(macro, arg) \
macro (OMP_worker_thread_life, stats_flags_e::logEvent, arg) \
macro (OMP_parallel, stats_flags_e::logEvent, arg) \
macro (OMP_parallel_overhead, stats_flags_e::logEvent, arg) \
macro (OMP_teams, stats_flags_e::logEvent, arg) \
macro (OMP_teams_overhead, stats_flags_e::logEvent, arg) \
macro (OMP_loop_static, 0, arg) \
macro (OMP_loop_static_scheduling, 0, arg) \
macro (OMP_loop_dynamic, 0, arg) \
macro (OMP_loop_dynamic_scheduling, 0, arg) \
macro (OMP_distribute, 0, arg) \
macro (OMP_distribute_scheduling, 0, arg) \
macro (OMP_critical, 0, arg) \
macro (OMP_critical_wait, 0, arg) \
macro (OMP_single, 0, arg) \
macro (OMP_master, 0, arg) \
macro (OMP_masked, 0, arg) \
macro (OMP_task_immediate, 0, arg) \
macro (OMP_task_taskwait, 0, arg) \
macro (OMP_task_taskyield, 0, arg) \
macro (OMP_task_taskgroup, 0, arg) \
macro (OMP_task_join_bar, 0, arg) \
macro (OMP_task_plain_bar, 0, arg) \
macro (OMP_taskloop_scheduling, 0, arg) \
macro (OMP_plain_barrier, stats_flags_e::logEvent, arg) \
macro (OMP_idle, stats_flags_e::logEvent, arg) \
macro (OMP_fork_barrier, stats_flags_e::logEvent, arg) \
macro (OMP_join_barrier, stats_flags_e::logEvent, arg) \
macro (OMP_serial, stats_flags_e::logEvent, arg) \
macro (OMP_set_numthreads, stats_flags_e::noUnits | stats_flags_e::noTotal, \
arg) \
macro (OMP_PARALLEL_args, stats_flags_e::noUnits | stats_flags_e::noTotal, \
arg) \
macro (OMP_loop_static_iterations, \
stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
macro (OMP_loop_static_total_iterations, \
stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
macro (OMP_loop_dynamic_iterations, \
stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
macro (OMP_loop_dynamic_total_iterations, \
stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
macro (OMP_distribute_iterations, \
stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
KMP_FOREACH_DEVELOPER_TIMER(macro, arg)
// clang-format on
// OMP_worker_thread_life -- Time from thread becoming an OpenMP thread (either
// initializing OpenMP or being created by a primary
// thread) until the thread is destroyed
// OMP_parallel -- Time thread spends executing work directly
// within a #pragma omp parallel
// OMP_parallel_overhead -- Time thread spends setting up a parallel region
// OMP_loop_static -- Time thread spends executing loop iterations from
// a statically scheduled loop
// OMP_loop_static_scheduling -- Time thread spends scheduling loop iterations
// from a statically scheduled loop
// OMP_loop_dynamic -- Time thread spends executing loop iterations from
// a dynamically scheduled loop
// OMP_loop_dynamic_scheduling -- Time thread spends scheduling loop iterations
// from a dynamically scheduled loop
// OMP_critical -- Time thread spends executing critical section
// OMP_critical_wait -- Time thread spends waiting to enter
// a critical section
// OMP_single -- Time spent executing a "single" region
// OMP_master -- Time spent executing a "master" region
// OMP_masked -- Time spent executing a "masked" region
// OMP_task_immediate -- Time spent executing non-deferred tasks
// OMP_task_taskwait -- Time spent executing tasks inside a taskwait
// construct
// OMP_task_taskyield -- Time spent executing tasks inside a taskyield
// construct
// OMP_task_taskgroup -- Time spent executing tasks inside a taskygroup
// construct
// OMP_task_join_bar -- Time spent executing tasks inside a join barrier
// OMP_task_plain_bar -- Time spent executing tasks inside a barrier
// construct
// OMP_taskloop_scheduling -- Time spent scheduling tasks inside a taskloop
// construct
// OMP_plain_barrier -- Time spent in a #pragma omp barrier construct or
// inside implicit barrier at end of worksharing
// construct
// OMP_idle -- Time worker threads spend waiting for next
// parallel region
// OMP_fork_barrier -- Time spent in a the fork barrier surrounding a
// parallel region
// OMP_join_barrier -- Time spent in a the join barrier surrounding a
// parallel region
// OMP_serial -- Time thread zero spends executing serial code
// OMP_set_numthreads -- Values passed to omp_set_num_threads
// OMP_PARALLEL_args -- Number of arguments passed to a parallel region
// OMP_loop_static_iterations -- Number of iterations thread is assigned for
// statically scheduled loops
// OMP_loop_dynamic_iterations -- Number of iterations thread is assigned for
// dynamically scheduled loops
#if (KMP_DEVELOPER_STATS)
// Timers which are of interest to runtime library developers, not end users.
// These have to be explicitly enabled in addition to the other stats.
// KMP_fork_barrier -- time in __kmp_fork_barrier
// KMP_join_barrier -- time in __kmp_join_barrier
// KMP_barrier -- time in __kmp_barrier
// KMP_end_split_barrier -- time in __kmp_end_split_barrier
// KMP_setup_icv_copy -- time in __kmp_setup_icv_copy
// KMP_icv_copy -- start/stop timer for any ICV copying
// KMP_linear_gather -- time in __kmp_linear_barrier_gather
// KMP_linear_release -- time in __kmp_linear_barrier_release
// KMP_tree_gather -- time in __kmp_tree_barrier_gather
// KMP_tree_release -- time in __kmp_tree_barrier_release
// KMP_hyper_gather -- time in __kmp_hyper_barrier_gather
// KMP_hyper_release -- time in __kmp_hyper_barrier_release
// KMP_dist_gather -- time in __kmp_dist_barrier_gather
// KMP_dist_release -- time in __kmp_dist_barrier_release
// clang-format off
#define KMP_FOREACH_DEVELOPER_TIMER(macro, arg) \
macro(KMP_fork_call, 0, arg) \
macro(KMP_join_call, 0, arg) \
macro(KMP_end_split_barrier, 0, arg) \
macro(KMP_hier_gather, 0, arg) \
macro(KMP_hier_release, 0, arg) \
macro(KMP_hyper_gather, 0, arg) \
macro(KMP_hyper_release, 0, arg) \
macro(KMP_dist_gather, 0, arg) \
macro(KMP_dist_release, 0, arg) \
macro(KMP_linear_gather, 0, arg) \
macro(KMP_linear_release, 0, arg) \
macro(KMP_tree_gather, 0, arg) \
macro(KMP_tree_release, 0, arg) \
macro(USER_resume, 0, arg) \
macro(USER_suspend, 0, arg) \
macro(USER_mwait, 0, arg) \
macro(KMP_allocate_team, 0, arg) \
macro(KMP_setup_icv_copy, 0, arg) \
macro(USER_icv_copy, 0, arg) \
macro (FOR_static_steal_stolen, \
stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
macro (FOR_static_steal_chunks, \
stats_flags_e::noUnits | stats_flags_e::noTotal, arg)
#else
#define KMP_FOREACH_DEVELOPER_TIMER(macro, arg)
#endif
// clang-format on
/*!
* \brief Add new explicit timers under KMP_FOREACH_EXPLICIT_TIMER() macro.
*
* @param macro a user defined macro that takes three arguments -
* macro(TIMER_NAME, flags, arg)
* @param arg a user defined argument to send to the user defined macro
*
* \warning YOU MUST HAVE THE SAME NAMED TIMER UNDER KMP_FOREACH_TIMER() OR ELSE
* BAD THINGS WILL HAPPEN!
*
* \details Explicit timers are ones where we need to allocate a timer itself
* (as well as the accumulated timing statistics). We allocate these on a
* per-thread basis, and explicitly start and stop them. Block timers just
* allocate the timer itself on the stack, and use the destructor to notice
* block exit; they don't need to be defined here. The name here should be the
* same as that of a timer above.
*
* @ingroup STATS_GATHERING
*/
#define KMP_FOREACH_EXPLICIT_TIMER(macro, arg) KMP_FOREACH_TIMER(macro, arg)
#define ENUMERATE(name, ignore, prefix) prefix##name,
enum timer_e { KMP_FOREACH_TIMER(ENUMERATE, TIMER_) TIMER_LAST };
enum explicit_timer_e {
KMP_FOREACH_EXPLICIT_TIMER(ENUMERATE, EXPLICIT_TIMER_) EXPLICIT_TIMER_LAST
};
enum counter_e { KMP_FOREACH_COUNTER(ENUMERATE, COUNTER_) COUNTER_LAST };
#undef ENUMERATE
/*
* A logarithmic histogram. It accumulates the number of values in each power of
* ten bin. So 1<=x<10, 10<=x<100, ...
* Mostly useful where we have some big outliers and want to see information
* about them.
*/
class logHistogram {
enum {
numBins = 31, /* Number of powers of 10. If this changes you need to change
* the initializer for binMax */
/*
* If you want to use this to analyse values that may be less than 1, (for
* instance times in s), then the logOffset gives you negative powers.
* In our case here, we're just looking at times in ticks, or counts, so we
* can never see values with magnitude < 1 (other than zero), so we can set
* it to 0. As above change the initializer if you change this.
*/
logOffset = 0
};
uint32_t KMP_ALIGN_CACHE zeroCount;
struct {
uint32_t count;
double total;
} bins[numBins];
static double binMax[numBins];
#ifdef KMP_DEBUG
uint64_t _total;
void check() const {
uint64_t t = zeroCount;
for (int i = 0; i < numBins; i++)
t += bins[i].count;
KMP_DEBUG_ASSERT(t == _total);
}
#else
void check() const {}
#endif
public:
logHistogram() { reset(); }
logHistogram(logHistogram const &o) {
for (int i = 0; i < numBins; i++)
bins[i] = o.bins[i];
#ifdef KMP_DEBUG
_total = o._total;
#endif
}
void reset() {
zeroCount = 0;
for (int i = 0; i < numBins; i++) {
bins[i].count = 0;
bins[i].total = 0;
}
#ifdef KMP_DEBUG
_total = 0;
#endif
}
uint32_t count(int b) const { return bins[b + logOffset].count; }
double total(int b) const { return bins[b + logOffset].total; }
static uint32_t findBin(double sample);
logHistogram &operator+=(logHistogram const &o) {
zeroCount += o.zeroCount;
for (int i = 0; i < numBins; i++) {
bins[i].count += o.bins[i].count;
bins[i].total += o.bins[i].total;
}
#ifdef KMP_DEBUG
_total += o._total;
check();
#endif
return *this;
}
void addSample(double sample);
int minBin() const;
int maxBin() const;
std::string format(char) const;
};
class statistic {
double KMP_ALIGN_CACHE minVal;
double maxVal;
double meanVal;
double m2;
uint64_t sampleCount;
double offset;
bool collectingHist;
logHistogram hist;
public:
statistic(bool doHist = bool(KMP_STATS_HIST)) {
reset();
collectingHist = doHist;
}
statistic(statistic const &o)
: minVal(o.minVal), maxVal(o.maxVal), meanVal(o.meanVal), m2(o.m2),
sampleCount(o.sampleCount), offset(o.offset),
collectingHist(o.collectingHist), hist(o.hist) {}
statistic(double minv, double maxv, double meanv, uint64_t sc, double sd)
: minVal(minv), maxVal(maxv), meanVal(meanv), m2(sd * sd * sc),
sampleCount(sc), offset(0.0), collectingHist(false) {}
bool haveHist() const { return collectingHist; }
double getMin() const { return minVal; }
double getMean() const { return meanVal; }
double getMax() const { return maxVal; }
uint64_t getCount() const { return sampleCount; }
double getSD() const { return sqrt(m2 / sampleCount); }
double getTotal() const { return sampleCount * meanVal; }
logHistogram const *getHist() const { return &hist; }
void setOffset(double d) { offset = d; }
void reset() {
minVal = (std::numeric_limits<double>::max)();
maxVal = -minVal;
meanVal = 0.0;
m2 = 0.0;
sampleCount = 0;
offset = 0.0;
hist.reset();
}
void addSample(double sample);
void scale(double factor);
void scaleDown(double f) { scale(1. / f); }
void forceCount(uint64_t count) { sampleCount = count; }
statistic &operator+=(statistic const &other);
std::string format(char unit, bool total = false) const;
std::string formatHist(char unit) const { return hist.format(unit); }
};
struct statInfo {
const char *name;
uint32_t flags;
};
class timeStat : public statistic {
static statInfo timerInfo[];
public:
timeStat() : statistic() {}
static const char *name(timer_e e) { return timerInfo[e].name; }
static bool noTotal(timer_e e) {
return timerInfo[e].flags & stats_flags_e::noTotal;
}
static bool masterOnly(timer_e e) {
return timerInfo[e].flags & stats_flags_e::onlyInMaster;
}
static bool workerOnly(timer_e e) {
return timerInfo[e].flags & stats_flags_e::notInMaster;
}
static bool noUnits(timer_e e) {
return timerInfo[e].flags & stats_flags_e::noUnits;
}
static bool logEvent(timer_e e) {
return timerInfo[e].flags & stats_flags_e::logEvent;
}
static void clearEventFlags() {
for (int i = 0; i < TIMER_LAST; i++) {
timerInfo[i].flags &= (~(stats_flags_e::logEvent));
}
}
};
// Where we need explicitly to start and end the timer, this version can be used
// Since these timers normally aren't nicely scoped, so don't have a good place
// to live on the stack of the thread, they're more work to use.
class explicitTimer {
timeStat *stat;
timer_e timerEnumValue;
tsc_tick_count startTime;
tsc_tick_count pauseStartTime;
tsc_tick_count::tsc_interval_t totalPauseTime;
public:
explicitTimer(timeStat *s, timer_e te)
: stat(s), timerEnumValue(te), startTime(), pauseStartTime(0),
totalPauseTime() {}
// void setStat(timeStat *s) { stat = s; }
void start(tsc_tick_count tick);
void pause(tsc_tick_count tick) { pauseStartTime = tick; }
void resume(tsc_tick_count tick) {
totalPauseTime += (tick - pauseStartTime);
}
void stop(tsc_tick_count tick, kmp_stats_list *stats_ptr = nullptr);
void reset() {
startTime = 0;
pauseStartTime = 0;
totalPauseTime = 0;
}
timer_e get_type() const { return timerEnumValue; }
};
// Where you need to partition a threads clock ticks into separate states
// e.g., a partitionedTimers class with two timers of EXECUTING_TASK, and
// DOING_NOTHING would render these conditions:
// time(EXECUTING_TASK) + time(DOING_NOTHING) = total time thread is alive
// No clock tick in the EXECUTING_TASK is a member of DOING_NOTHING and vice
// versa
class partitionedTimers {
private:
std::vector<explicitTimer> timer_stack;
public:
partitionedTimers();
void init(explicitTimer timer);
void exchange(explicitTimer timer);
void push(explicitTimer timer);
void pop();
void windup();
};
// Special wrapper around the partitioned timers to aid timing code blocks
// It avoids the need to have an explicit end, leaving the scope suffices.
class blockPartitionedTimer {
partitionedTimers *part_timers;
public:
blockPartitionedTimer(partitionedTimers *pt, explicitTimer timer)
: part_timers(pt) {
part_timers->push(timer);
}
~blockPartitionedTimer() { part_timers->pop(); }
};
// Special wrapper around the thread state to aid in keeping state in code
// blocks It avoids the need to have an explicit end, leaving the scope
// suffices.
class blockThreadState {
stats_state_e *state_pointer;
stats_state_e old_state;
public:
blockThreadState(stats_state_e *thread_state_pointer, stats_state_e new_state)
: state_pointer(thread_state_pointer), old_state(*thread_state_pointer) {
*state_pointer = new_state;
}
~blockThreadState() { *state_pointer = old_state; }
};
// If all you want is a count, then you can use this...
// The individual per-thread counts will be aggregated into a statistic at
// program exit.
class counter {
uint64_t value;
static const statInfo counterInfo[];
public:
counter() : value(0) {}
void increment() { value++; }
uint64_t getValue() const { return value; }
void reset() { value = 0; }
static const char *name(counter_e e) { return counterInfo[e].name; }
static bool masterOnly(counter_e e) {
return counterInfo[e].flags & stats_flags_e::onlyInMaster;
}
};
/* ****************************************************************
Class to implement an event
There are four components to an event: start time, stop time
nest_level, and timer_name.
The start and stop time should be obvious (recorded in clock ticks).
The nest_level relates to the bar width in the timeline graph.
The timer_name is used to determine which timer event triggered this event.
the interface to this class is through four read-only operations:
1) getStart() -- returns the start time as 64 bit integer
2) getStop() -- returns the stop time as 64 bit integer
3) getNestLevel() -- returns the nest level of the event
4) getTimerName() -- returns the timer name that triggered event
*MORE ON NEST_LEVEL*
The nest level is used in the bar graph that represents the timeline.
Its main purpose is for showing how events are nested inside eachother.
For example, say events, A, B, and C are recorded. If the timeline
looks like this:
Begin -------------------------------------------------------------> Time
| | | | | |
A B C C B A
start start start end end end
Then A, B, C will have a nest level of 1, 2, 3 respectively.
These values are then used to calculate the barwidth so you can
see that inside A, B has occurred, and inside B, C has occurred.
Currently, this is shown with A's bar width being larger than B's
bar width, and B's bar width being larger than C's bar width.
**************************************************************** */
class kmp_stats_event {
uint64_t start;
uint64_t stop;
int nest_level;
timer_e timer_name;
public:
kmp_stats_event()
: start(0), stop(0), nest_level(0), timer_name(TIMER_LAST) {}
kmp_stats_event(uint64_t strt, uint64_t stp, int nst, timer_e nme)
: start(strt), stop(stp), nest_level(nst), timer_name(nme) {}
inline uint64_t getStart() const { return start; }
inline uint64_t getStop() const { return stop; }
inline int getNestLevel() const { return nest_level; }
inline timer_e getTimerName() const { return timer_name; }
};
/* ****************************************************************
Class to implement a dynamically expandable array of events
---------------------------------------------------------
| event 1 | event 2 | event 3 | event 4 | ... | event N |
---------------------------------------------------------
An event is pushed onto the back of this array at every
explicitTimer->stop() call. The event records the thread #,
start time, stop time, and nest level related to the bar width.
The event vector starts at size INIT_SIZE and grows (doubles in size)
if needed. An implication of this behavior is that log(N)
reallocations are needed (where N is number of events). If you want
to avoid reallocations, then set INIT_SIZE to a large value.
the interface to this class is through six operations:
1) reset() -- sets the internal_size back to 0 but does not deallocate any
memory
2) size() -- returns the number of valid elements in the vector
3) push_back(start, stop, nest, timer_name) -- pushes an event onto
the back of the array
4) deallocate() -- frees all memory associated with the vector
5) sort() -- sorts the vector by start time
6) operator[index] or at(index) -- returns event reference at that index
**************************************************************** */
class kmp_stats_event_vector {
kmp_stats_event *events;
int internal_size;
int allocated_size;
static const int INIT_SIZE = 1024;
public:
kmp_stats_event_vector() {
events =
(kmp_stats_event *)__kmp_allocate(sizeof(kmp_stats_event) * INIT_SIZE);
internal_size = 0;
allocated_size = INIT_SIZE;
}
~kmp_stats_event_vector() {}
inline void reset() { internal_size = 0; }
inline int size() const { return internal_size; }
void push_back(uint64_t start_time, uint64_t stop_time, int nest_level,
timer_e name) {
int i;
if (internal_size == allocated_size) {
kmp_stats_event *tmp = (kmp_stats_event *)__kmp_allocate(
sizeof(kmp_stats_event) * allocated_size * 2);
for (i = 0; i < internal_size; i++)
tmp[i] = events[i];
__kmp_free(events);
events = tmp;
allocated_size *= 2;
}
events[internal_size] =
kmp_stats_event(start_time, stop_time, nest_level, name);
internal_size++;
return;
}
void deallocate();
void sort();
const kmp_stats_event &operator[](int index) const { return events[index]; }
kmp_stats_event &operator[](int index) { return events[index]; }
const kmp_stats_event &at(int index) const { return events[index]; }
kmp_stats_event &at(int index) { return events[index]; }
};
/* ****************************************************************
Class to implement a doubly-linked, circular, statistics list
|---| ---> |---| ---> |---| ---> |---| ---> ... next
| | | | | | | |
|---| <--- |---| <--- |---| <--- |---| <--- ... prev
Sentinel first second third
Node node node node
The Sentinel Node is the user handle on the list.
The first node corresponds to thread 0's statistics.
The second node corresponds to thread 1's statistics and so on...
Each node has a _timers, _counters, and _explicitTimers array to hold that
thread's statistics. The _explicitTimers point to the correct _timer and
update its statistics at every stop() call. The explicitTimers' pointers are
set up in the constructor. Each node also has an event vector to hold that
thread's timing events. The event vector expands as necessary and records
the start-stop times for each timer.
The nestLevel variable is for plotting events and is related
to the bar width in the timeline graph.
Every thread will have a thread local pointer to its node in
the list. The sentinel node is used by the primary thread to
store "dummy" statistics before __kmp_create_worker() is called.
**************************************************************** */
class kmp_stats_list {
int gtid;
timeStat _timers[TIMER_LAST + 1];
counter _counters[COUNTER_LAST + 1];
explicitTimer thread_life_timer;
partitionedTimers _partitionedTimers;
int _nestLevel; // one per thread
kmp_stats_event_vector _event_vector;
kmp_stats_list *next;
kmp_stats_list *prev;
stats_state_e state;
int thread_is_idle_flag;
public:
kmp_stats_list()
: thread_life_timer(&_timers[TIMER_OMP_worker_thread_life],
TIMER_OMP_worker_thread_life),
_nestLevel(0), _event_vector(), next(this), prev(this), state(IDLE),
thread_is_idle_flag(0) {}
~kmp_stats_list() {}
inline timeStat *getTimer(timer_e idx) { return &_timers[idx]; }
inline counter *getCounter(counter_e idx) { return &_counters[idx]; }
inline partitionedTimers *getPartitionedTimers() {
return &_partitionedTimers;
}
inline timeStat *getTimers() { return _timers; }
inline counter *getCounters() { return _counters; }
inline kmp_stats_event_vector &getEventVector() { return _event_vector; }
inline void startLife() { thread_life_timer.start(tsc_tick_count::now()); }
inline void endLife() { thread_life_timer.stop(tsc_tick_count::now(), this); }
inline void resetEventVector() { _event_vector.reset(); }
inline void incrementNestValue() { _nestLevel++; }
inline int getNestValue() { return _nestLevel; }
inline void decrementNestValue() { _nestLevel--; }
inline int getGtid() const { return gtid; }
inline void setGtid(int newgtid) { gtid = newgtid; }
inline void setState(stats_state_e newstate) { state = newstate; }
inline stats_state_e getState() const { return state; }
inline stats_state_e *getStatePointer() { return &state; }
inline bool isIdle() { return thread_is_idle_flag == 1; }
inline void setIdleFlag() { thread_is_idle_flag = 1; }
inline void resetIdleFlag() { thread_is_idle_flag = 0; }
kmp_stats_list *push_back(int gtid); // returns newly created list node
inline void push_event(uint64_t start_time, uint64_t stop_time,
int nest_level, timer_e name) {
_event_vector.push_back(start_time, stop_time, nest_level, name);
}
void deallocate();
class iterator;
kmp_stats_list::iterator begin();
kmp_stats_list::iterator end();
int size();
class iterator {
kmp_stats_list *ptr;
friend kmp_stats_list::iterator kmp_stats_list::begin();
friend kmp_stats_list::iterator kmp_stats_list::end();
public:
iterator();
~iterator();
iterator operator++();
iterator operator++(int dummy);
iterator operator--();
iterator operator--(int dummy);
bool operator!=(const iterator &rhs);
bool operator==(const iterator &rhs);
kmp_stats_list *operator*() const; // dereference operator
};
};
/* ****************************************************************
Class to encapsulate all output functions and the environment variables
This module holds filenames for various outputs (normal stats, events, plot
file), as well as coloring information for the plot file.
The filenames and flags variables are read from environment variables.
These are read once by the constructor of the global variable
__kmp_stats_output which calls init().
During this init() call, event flags for the timeStat::timerInfo[] global
array are cleared if KMP_STATS_EVENTS is not true (on, 1, yes).
The only interface function that is public is outputStats(heading). This
function should print out everything it needs to, either to files or stderr,
depending on the environment variables described below
ENVIRONMENT VARIABLES:
KMP_STATS_FILE -- if set, all statistics (not events) will be printed to this
file, otherwise, print to stderr
KMP_STATS_THREADS -- if set to "on", then will print per thread statistics to
either KMP_STATS_FILE or stderr
KMP_STATS_PLOT_FILE -- if set, print the ploticus plot file to this filename,
otherwise, the plot file is sent to "events.plt"
KMP_STATS_EVENTS -- if set to "on", then log events, otherwise, don't log
events
KMP_STATS_EVENTS_FILE -- if set, all events are outputted to this file,
otherwise, output is sent to "events.dat"
**************************************************************** */
class kmp_stats_output_module {
public:
struct rgb_color {
float r;
float g;
float b;
};
private:
std::string outputFileName;
static const char *eventsFileName;
static const char *plotFileName;
static int printPerThreadFlag;
static int printPerThreadEventsFlag;
static const rgb_color globalColorArray[];
static rgb_color timerColorInfo[];
void init();
static void setupEventColors();
static void printPloticusFile();
static void printHeaderInfo(FILE *statsOut);
static void printTimerStats(FILE *statsOut, statistic const *theStats,
statistic const *totalStats);
static void printCounterStats(FILE *statsOut, statistic const *theStats);
static void printCounters(FILE *statsOut, counter const *theCounters);
static void printEvents(FILE *eventsOut, kmp_stats_event_vector *theEvents,
int gtid);
static rgb_color getEventColor(timer_e e) { return timerColorInfo[e]; }
static void windupExplicitTimers();
bool eventPrintingEnabled() const { return printPerThreadEventsFlag; }
public:
kmp_stats_output_module() { init(); }
void outputStats(const char *heading);
};
#ifdef __cplusplus
extern "C" {
#endif
void __kmp_stats_init();
void __kmp_stats_fini();
void __kmp_reset_stats();
void __kmp_output_stats(const char *);
void __kmp_accumulate_stats_at_exit(void);
// thread local pointer to stats node within list
extern KMP_THREAD_LOCAL kmp_stats_list *__kmp_stats_thread_ptr;
// head to stats list.
extern kmp_stats_list *__kmp_stats_list;
// lock for __kmp_stats_list
extern kmp_tas_lock_t __kmp_stats_lock;
// reference start time
extern tsc_tick_count __kmp_stats_start_time;
// interface to output
extern kmp_stats_output_module __kmp_stats_output;
#ifdef __cplusplus
}
#endif
// Simple, standard interfaces that drop out completely if stats aren't enabled
/*!
* \brief Adds value to specified timer (name).
*
* @param name timer name as specified under the KMP_FOREACH_TIMER() macro
* @param value double precision sample value to add to statistics for the timer
*
* \details Use KMP_COUNT_VALUE(name, value) macro to add a particular value to
* a timer statistics.
*
* @ingroup STATS_GATHERING
*/
#define KMP_COUNT_VALUE(name, value) \
__kmp_stats_thread_ptr->getTimer(TIMER_##name)->addSample((double)value)
/*!
* \brief Increments specified counter (name).
*
* @param name counter name as specified under the KMP_FOREACH_COUNTER() macro
*
* \details Use KMP_COUNT_BLOCK(name, value) macro to increment a statistics
* counter for the executing thread.
*
* @ingroup STATS_GATHERING
*/
#define KMP_COUNT_BLOCK(name) \
__kmp_stats_thread_ptr->getCounter(COUNTER_##name)->increment()
/*!
* \brief Outputs the current thread statistics and reset them.
*
* @param heading_string heading put above the final stats output
*
* \details Explicitly stops all timers and outputs all stats. Environment
* variable, `OMPTB_STATSFILE=filename`, can be used to output the stats to a
* filename instead of stderr. Environment variable,
* `OMPTB_STATSTHREADS=true|undefined`, can be used to output thread specific
* stats. For now the `OMPTB_STATSTHREADS` environment variable can either be
* defined with any value, which will print out thread specific stats, or it can
* be undefined (not specified in the environment) and thread specific stats
* won't be printed. It should be noted that all statistics are reset when this
* macro is called.
*
* @ingroup STATS_GATHERING
*/
#define KMP_OUTPUT_STATS(heading_string) __kmp_output_stats(heading_string)
/*!
* \brief Initializes the partitioned timers to begin with name.
*
* @param name timer which you want this thread to begin with
*
* @ingroup STATS_GATHERING
*/
#define KMP_INIT_PARTITIONED_TIMERS(name) \
__kmp_stats_thread_ptr->getPartitionedTimers()->init(explicitTimer( \
__kmp_stats_thread_ptr->getTimer(TIMER_##name), TIMER_##name))
#define KMP_TIME_PARTITIONED_BLOCK(name) \
blockPartitionedTimer __PBLOCKTIME__( \
__kmp_stats_thread_ptr->getPartitionedTimers(), \
explicitTimer(__kmp_stats_thread_ptr->getTimer(TIMER_##name), \
TIMER_##name))
#define KMP_PUSH_PARTITIONED_TIMER(name) \
__kmp_stats_thread_ptr->getPartitionedTimers()->push(explicitTimer( \
__kmp_stats_thread_ptr->getTimer(TIMER_##name), TIMER_##name))
#define KMP_POP_PARTITIONED_TIMER() \
__kmp_stats_thread_ptr->getPartitionedTimers()->pop()
#define KMP_EXCHANGE_PARTITIONED_TIMER(name) \
__kmp_stats_thread_ptr->getPartitionedTimers()->exchange(explicitTimer( \
__kmp_stats_thread_ptr->getTimer(TIMER_##name), TIMER_##name))
#define KMP_SET_THREAD_STATE(state_name) \
__kmp_stats_thread_ptr->setState(state_name)
#define KMP_GET_THREAD_STATE() __kmp_stats_thread_ptr->getState()
#define KMP_SET_THREAD_STATE_BLOCK(state_name) \
blockThreadState __BTHREADSTATE__(__kmp_stats_thread_ptr->getStatePointer(), \
state_name)
/*!
* \brief resets all stats (counters to 0, timers to 0 elapsed ticks)
*
* \details Reset all stats for all threads.
*
* @ingroup STATS_GATHERING
*/
#define KMP_RESET_STATS() __kmp_reset_stats()
#if (KMP_DEVELOPER_STATS)
#define KMP_COUNT_DEVELOPER_VALUE(n, v) KMP_COUNT_VALUE(n, v)
#define KMP_COUNT_DEVELOPER_BLOCK(n) KMP_COUNT_BLOCK(n)
#define KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(n) KMP_TIME_PARTITIONED_BLOCK(n)
#define KMP_PUSH_DEVELOPER_PARTITIONED_TIMER(n) KMP_PUSH_PARTITIONED_TIMER(n)
#define KMP_POP_DEVELOPER_PARTITIONED_TIMER(n) KMP_POP_PARTITIONED_TIMER(n)
#define KMP_EXCHANGE_DEVELOPER_PARTITIONED_TIMER(n) \
KMP_EXCHANGE_PARTITIONED_TIMER(n)
#else
// Null definitions
#define KMP_COUNT_DEVELOPER_VALUE(n, v) ((void)0)
#define KMP_COUNT_DEVELOPER_BLOCK(n) ((void)0)
#define KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(n) ((void)0)
#define KMP_PUSH_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
#define KMP_POP_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
#define KMP_EXCHANGE_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
#endif
#else // KMP_STATS_ENABLED
// Null definitions
#define KMP_COUNT_VALUE(n, v) ((void)0)
#define KMP_COUNT_BLOCK(n) ((void)0)
#define KMP_OUTPUT_STATS(heading_string) ((void)0)
#define KMP_RESET_STATS() ((void)0)
#define KMP_COUNT_DEVELOPER_VALUE(n, v) ((void)0)
#define KMP_COUNT_DEVELOPER_BLOCK(n) ((void)0)
#define KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(n) ((void)0)
#define KMP_PUSH_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
#define KMP_POP_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
#define KMP_EXCHANGE_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
#define KMP_INIT_PARTITIONED_TIMERS(name) ((void)0)
#define KMP_TIME_PARTITIONED_BLOCK(name) ((void)0)
#define KMP_PUSH_PARTITIONED_TIMER(name) ((void)0)
#define KMP_POP_PARTITIONED_TIMER() ((void)0)
#define KMP_SET_THREAD_STATE(state_name) ((void)0)
#define KMP_GET_THREAD_STATE() ((void)0)
#define KMP_SET_THREAD_STATE_BLOCK(state_name) ((void)0)
#endif // KMP_STATS_ENABLED
#endif // KMP_STATS_H
|
GB_unop__identity_uint64_bool.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_uint64_bool
// op(A') function: GB_unop_tran__identity_uint64_bool
// C type: uint64_t
// A type: bool
// cast: uint64_t cij = (uint64_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
bool
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint64_t z = (uint64_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
bool aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint64_t z = (uint64_t) aij ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT64 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_uint64_bool
(
uint64_t *Cx, // Cx and Ax may be aliased
const bool *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 (bool), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
bool aij = Ax [p] ;
uint64_t z = (uint64_t) aij ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
bool aij = Ax [p] ;
uint64_t z = (uint64_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_uint64_bool
(
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
|
eigen.h
|
/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#ifndef VOTCA_XTP_EIGEN_H
#define VOTCA_XTP_EIGEN_H
// CMake Generated file
// clang-format off
// order seems to matter here
#include "votca_xtp_config.h"
#include <votca/tools/votca_tools_config.h>
//clang-format on
// VOTCA includes
#include <votca/tools/eigen.h>
#include <votca/tools/types.h>
typedef Eigen::Matrix<double, 9, 1> Vector9d;
typedef Eigen::Matrix<double, 9, 9> Matrix9d;
typedef Eigen::Array<votca::Index, Eigen::Dynamic, 1> ArrayXl;
namespace votca {
namespace xtp {
inline bool XTP_HAS_MKL_OVERLOAD() {
bool mkl_overload = false;
#ifdef EIGEN_USE_MKL_ALL
mkl_overload = true;
#endif
bool mkl_found = false;
#ifdef MKL_FOUND
mkl_found = true;
#endif
if (mkl_overload && mkl_found) {
return true;
} else {
return false;
}
}
// Stores matrix and energy together
class Mat_p_Energy {
public:
Mat_p_Energy()
: energy_(0.0), matrix_(Eigen::MatrixXd::Zero(0, 0)){};
Mat_p_Energy(Index rows, Index cols)
: energy_(0.0), matrix_(Eigen::MatrixXd::Zero(rows, cols)){};
Mat_p_Energy(double e, const Eigen::MatrixXd& mat)
: energy_(e), matrix_(mat){};
Mat_p_Energy(double e, Eigen::MatrixXd&& mat)
: energy_(e), matrix_(std::move(mat)){};
Mat_p_Energy operator+(const Mat_p_Energy& other) const {
Mat_p_Energy result = *this;
result. energy_ += other. energy_;
result. matrix_ += other. matrix_;
return result;
}
Index rows() const { return matrix_.rows(); }
Index cols() const { return matrix_.cols(); }
Eigen::MatrixXd& matrix() { return matrix_; }
double& energy() { return energy_; }
const Eigen::MatrixXd& matrix() const { return matrix_; }
double energy() const { return energy_; }
private:
double energy_;
Eigen::MatrixXd matrix_;
};
//Stores the diadicProduct of a vector with itself
class AxA {
public:
AxA(const Eigen::Vector3d& a) {
data_.segment<3>(0) = a.x() * a;
data_.segment<2>(3) = a.y() * a.segment<2>(1);
data_[5] = a.z() * a.z();
}
inline const double& xx() const { return data_[0]; }
inline const double& xy() const { return data_[1]; }
inline const double& xz() const { return data_[2]; }
inline const double& yy() const { return data_[3]; }
inline const double& yz() const { return data_[4]; }
inline const double& zz() const { return data_[5]; }
private:
Eigen::Matrix<double, 6, 1> data_;
};
#pragma omp declare reduction (+:Mat_p_Energy: omp_out=omp_out+omp_in)\
initializer(omp_priv=Mat_p_Energy(omp_orig.rows(),omp_orig.cols()))
#pragma omp declare reduction (+: Eigen::VectorXd: omp_out=omp_out+omp_in)\
initializer(omp_priv=Eigen::VectorXd::Zero(omp_orig.size()))
#pragma omp declare reduction (+: Eigen::MatrixXd: omp_out=omp_out+omp_in)\
initializer(omp_priv=Eigen::MatrixXd::Zero(omp_orig.rows(),omp_orig.cols()))
#pragma omp declare reduction (+: Eigen::Matrix3d: omp_out=omp_out+omp_in)\
initializer(omp_priv=Eigen::Matrix3d::Zero())
#pragma omp declare reduction (+: Eigen::Vector3d: omp_out=omp_out+omp_in)\
initializer(omp_priv=Eigen::Vector3d::Zero())
namespace OPENMP {
inline Index getMaxThreads() {
Index nthreads = 1;
#ifdef _OPENMP
nthreads = Index(omp_get_max_threads());
#endif
return nthreads;
}
inline bool InsideActiveParallelRegion(){
#ifdef _OPENMP
return omp_in_parallel();
#endif
return false;
}
inline Index getThreadId() {
Index thread_id = 0;
#ifdef _OPENMP
thread_id = Index(omp_get_thread_num());
#endif
return thread_id;
}
#ifdef _OPENMP
inline void setMaxThreads(Index threads) {
if (threads > 0) {
omp_set_num_threads(int(threads));
}
}
#else
inline void setMaxThreads(Index) {}
#endif
} // namespace OPENMP
} // namespace xtp
} // namespace votca
#endif // VOTCA_XTP_EIGEN_H
|
GrB_Vector_wait.c
|
//------------------------------------------------------------------------------
// GrB_Vector_wait: wait for a vector to complete
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Finishes all work on a vector, followed by an OpenMP flush.
#include "GB.h"
#define GB_FREE_ALL ;
GrB_Info GrB_Vector_wait // finish all work on a vector
(
GrB_Vector *v
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
#pragma omp flush
GB_WHERE ((*v), "GrB_Vector_wait (&v)") ;
GB_RETURN_IF_NULL (v) ;
GB_RETURN_IF_NULL_OR_FAULTY (*v) ;
//--------------------------------------------------------------------------
// finish all pending work on the vector
//--------------------------------------------------------------------------
if (GB_ANY_PENDING_WORK (*v))
{
GrB_Info info ;
GB_BURBLE_START ("GrB_Vector_wait") ;
GB_OK (GB_Matrix_wait ((GrB_Matrix) (*v), "vector", Context)) ;
GB_BURBLE_END ;
}
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
#pragma omp flush
return (GrB_SUCCESS) ;
}
|
ep.c
|
/*******************************************************************************
* Copyright 2021 UChicago Argonne, LLC.
* (c.f. AUTHORS, LICENSE)
*
* This file is part of the NRM Benchmarks project.
* For more info, see https://github.com/anlsys/nrm-benchmarks
*
* SPDX-License-Identifier: BSD-3-Clause
******************************************************************************/
#include "config.h"
#include "nrm-benchmarks.h"
#include <nrm.h>
#include <math.h>
#define MK 16
#define NK (1 << MK)
#define NQ 10
/* utils functions */
double randlc (double *, double);
void vranlc (int, double *, double, double []);
static struct nrm_context *context;
static struct nrm_scope *region_scope, **thread_scope;
static double x[2*NK];
#pragma omp threadprivate(x)
static double q[NQ];
void ep_kernel(double *gc, double *rx, double *ry, double a, double s, double an, size_t nn)
{
int k_offset = -1;
double sx = 0.0, sy = 0.0;
#pragma omp parallel copyin(x)
{
double t1, t2, t3, t4, x1, x2;
int k, kk, i, ik, l;
double qq[NQ]; /* private copy of q[0:NQ-1] */
for (i = 0; i < NQ; i++) qq[i] = 0.0;
#pragma omp for reduction(+:sx,sy) schedule(static)
for (k = 1; k <= (int)nn; k++) {
kk = k_offset + k;
t1 = s;
t2 = an;
/* Find starting seed t1 for this kk. */
for (i = 1; i <= 100; i++) {
ik = kk / 2;
if (2 * ik != kk) t3 = randlc(&t1, t2);
if (ik == 0) break;
t3 = randlc(&t2, t2);
kk = ik;
}
/* Compute uniform pseudorandom numbers. */
vranlc(2*NK, &t1, a, x);
/*
c Compute Gaussian deviates by acceptance-rejection method and
c tally counts in concentric square annuli. This loop is not
c vectorizable.
*/
for ( i = 0; i < NK; i++) {
x1 = 2.0 * x[2*i] - 1.0;
x2 = 2.0 * x[2*i+1] - 1.0;
t1 = pow(x1,2) + pow(x2,2);
if (t1 <= 1.0) {
t2 = sqrt(-2.0 * log(t1) / t1);
t3 = fabs(x1 * t2); /* Xi */
t4 = fabs(x2 * t2); /* Yi */
l = fmax(t3, t4);
qq[l] += 1.0; /* counts */
sx = sx + t3; /* sum of Xi */
sy = sy + t4; /* sum of Yi */
}
}
}
#pragma omp critical
{
for (i = 0; i < NQ; i++) q[i] += qq[i];
}
}
for(size_t i = 0; i < NQ; i++)
*gc = *gc + q[i];
*rx = sx;
*ry = sy;
}
int main(int argc, char **argv)
{
/* configuration parameters:
* - M is the only user-input parameter, it determines the size of the
* problem. All other parameters are derived from it.
* From the NAS NPB documentation:
* - Class: S W A B C D E F
* - M val: 24 25 28 30 32 36 40 44
*/
size_t m;
size_t mm, nn;
double a = 1220703125.0, s = 271828183.0;
double t, an, gc, rx, ry;
long int times;
/* needed for performance measurement */
int64_t sumtime = 0, mintime = INT64_MAX, maxtime = 0;
nrmb_time_t start, end;
int num_threads;
/* retrieve the size of the problem and initialize the rest of the
* configuration from it
*/
assert(argc == 3);
m = strtoull(argv[1], NULL, 0);
assert(!errno);
times = strtol(argv[2], NULL, 0);
assert(!errno);
mm = m - MK;
nn = 1 << mm;
/* ensure that OpenMP is giving us the right number of threads */
#pragma omp parallel
#pragma omp master
num_threads = omp_get_num_threads();
int err = 0;
#pragma omp parallel
#pragma omp atomic
err++;
assert(num_threads == err);
err = 0;
/* initialization: random number generator and private array
* dum arrays are there to avoid dead code elimination
*/
double dum[3] = { 1.0, 1.0, 1.0 };
vranlc(0, &(dum[0]), dum[1], &(dum[2]));
dum[0] = randlc(&(dum[1]), dum[2]);
#pragma omp parallel for default(shared)
for (size_t i = 0; i < 2*NK; i++) x[i] = -1.0e99;
/* the original NAS EP considers this section part of the benchmark, but
* it's single threaded, so we execute it as part of init to make the
* whole benchmark even more parallel.
*/
vranlc(0, &t, a, x);
/* Compute AN = A ^ (2 * NK) (mod 2^46). */
t = a;
for (size_t i = 0; i <= MK; i++) {
randlc(&t, t);
}
for (size_t i = 0; i < NQ; i++) {
q[i] = 0.0;
}
an = t;
gc = 0.0;
/* NRM Context init */
context = nrm_ctxt_create();
nrm_init(context, argv[0], 0, 0);
/* this version of the benchmarks reports one progress each time it goes
* through the entire array.
*/
/* Create scopes */
region_scope = nrm_scope_create();
thread_scope = malloc(num_threads*sizeof(nrm_scope_t*));
for (int i = 0; i < num_threads; i++)
{
thread_scope[i] = nrm_scope_create();
}
for(long int iter = 0; iter < times; iter++)
{
int64_t time;
nrmb_gettime(&start);
/* the actual benchmark is quite involved,
* so we put it in a separate function
*/
ep_kernel(&gc, &rx, &ry, a, s, an, nn);
nrmb_gettime(&end);
/* Get scopes */
nrm_scope_threadshared(region_scope);
nrm_scope_threadprivate(thread_scope[omp_get_thread_num()]);
nrm_send_progress(context, 1, thread_scope[omp_get_thread_num()]);
time = nrmb_timediff(&start, &end);
sumtime += time;
mintime = NRMB_MIN(time, mintime);
maxtime = NRMB_MAX(time, maxtime);
}
nrm_fini(context);
nrm_ctxt_delete(context);
/* Delete scopes */
nrm_scope_delete(region_scope);
for (int i = 0; i < num_threads; i++)
{
nrm_scope_delete(thread_scope[i]);
}
/* report the configuration and timings */
fprintf(stdout, "NRM Benchmarks: %s\n", argv[0]);
fprintf(stdout, "Version: %s\n", PACKAGE_VERSION);
fprintf(stdout, "Description: one progress per iteration, NPB EP benchmark\n");
fprintf(stdout, "Problem size: %zu.\n", m);
fprintf(stdout, "Gaussian Pairs: %15.0f.\n", gc);
fprintf(stdout, "Validation values: %25.15e %25.15e\n", rx, ry);
fprintf(stdout, "Kernel was executed: %ld times.\n", times);
fprintf(stdout, "Number of threads: %d\n", num_threads);
fprintf(stdout, "Time (s): avg: %11.6f min: %11.6f max: %11.6f\n",
1.0E-09 * sumtime/times, 1.0E-09 * mintime, 1.0E-09 * maxtime);
/* validate the benchmark: minimum about of bits should be different.
* Note that NAS does not give us a validation value for all inputs */
err = 0;
switch(m)
{
case 24:
err = err || !nrmb_check_double_prec(1.051299420395306e07, rx, 1e-8);
err = err || !nrmb_check_double_prec(1.051517131857535e07, ry, 1e-8);
break;
case 25:
err = err || !nrmb_check_double_prec(2.102505525182392e07, rx, 1e-8);
err = err || !nrmb_check_double_prec(2.103162209578822e07, ry, 1e-8);
break;
case 28:
err = err || !nrmb_check_double_prec(1.682235632304711e08, rx, 1e-8);
err = err || !nrmb_check_double_prec(1.682195123368299e08, ry, 1e-8);
break;
case 30:
err = err || !nrmb_check_double_prec(6.728927543423024e08, rx, 1e-8);
err = err || !nrmb_check_double_prec(6.728951822504275e08, ry, 1e-8);
break;
case 32:
err = err || !nrmb_check_double_prec(2.691444083862931e09, rx, 1e-8);
err = err || !nrmb_check_double_prec(2.691519118724585e09, ry, 1e-8);
break;
case 36:
err = err || !nrmb_check_double_prec(4.306350280812112e10, rx, 1e-8);
err = err || !nrmb_check_double_prec(4.306347571859157e10, ry, 1e-8);
break;
case 40:
err = err || !nrmb_check_double_prec(6.890169663167274e11, rx, 1e-8);
err = err || !nrmb_check_double_prec(6.890164670688535e11, ry, 1e-8);
break;
case 44:
err = err || !nrmb_check_double_prec(1.102426773788175e13, rx, 1e-8);
err = err || !nrmb_check_double_prec(1.102426773787993e13, ry, 1e-8);
break;
}
if(err)
fprintf(stdout, "VALIDATION FAILED!!!!\n");
else
fprintf(stdout, "VALIDATION PASSED!!!!\n");
return err;
}
|
GB_unaryop__identity_uint8_int8.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__identity_uint8_int8
// op(A') function: GB_tran__identity_uint8_int8
// C type: uint8_t
// A type: int8_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
uint8_t z = (uint8_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_uint8_int8
(
uint8_t *restrict Cx,
const int8_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__identity_uint8_int8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__isfinite_bool_fp32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__isfinite_bool_fp32)
// op(A') function: GB (_unop_tran__isfinite_bool_fp32)
// C type: bool
// A type: float
// cast: float cij = (aij)
// unaryop: cij = isfinite (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = isfinite (x) ;
// casting
#define GB_CAST(z, aij) \
float z = (aij) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = (aij) ; \
Cx [pC] = isfinite (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISFINITE || GxB_NO_BOOL || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__isfinite_bool_fp32)
(
bool *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = (aij) ;
Cx [p] = isfinite (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = (aij) ;
Cx [p] = isfinite (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__isfinite_bool_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
deconvolution_pack4.h
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void deconvolution_pack4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_pack4, 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 h = bottom_blob.h;
int channels = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1;
const int maxk = kernel_w * kernel_h;
const float* bias_data_ptr = bias_data;
// num_output
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
float* outptr = top_blob.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
v4f32 _sum = (v4f32)__msa_fill_w(0);
if (bias_data_ptr)
{
_sum = (v4f32)__msa_ld_w((const float*)bias_data_ptr + p * 4, 0);
}
const float* kptr = (const float*)weight_data_pack4.channel(p);
// channels
for (int q = 0; q < channels; q++)
{
const Mat m = bottom_blob.channel(q);
for (int y = 0; y < kernel_h; y++)
{
int sys = (i + y * dilation_h - (kernel_extent_h - 1));
if (sys < 0 || sys % stride_h != 0)
continue;
int sy = sys / stride_h;
if (sy >= h)
continue;
for (int x = 0; x < kernel_w; x++)
{
int sxs = (j + x * dilation_w - (kernel_extent_w - 1));
if (sxs < 0 || sxs % stride_w != 0)
continue;
int sx = sxs / stride_w;
if (sx >= w)
continue;
const float* sptr = m.row(sy) + sx * 4;
int k = (y * kernel_w + x) * 16;
v4f32 _val0 = (v4f32)__msa_fill_w_f32(*sptr++);
v4f32 _val1 = (v4f32)__msa_fill_w_f32(*sptr++);
v4f32 _val2 = (v4f32)__msa_fill_w_f32(*sptr++);
v4f32 _val3 = (v4f32)__msa_fill_w_f32(*sptr++);
v4f32 _w0 = (v4f32)__msa_ld_w(kptr + k, 0);
v4f32 _w1 = (v4f32)__msa_ld_w(kptr + k + 4, 0);
v4f32 _w2 = (v4f32)__msa_ld_w(kptr + k + 8, 0);
v4f32 _w3 = (v4f32)__msa_ld_w(kptr + k + 12, 0);
_sum = __msa_fmadd_w(_sum, _val0, _w0);
_sum = __msa_fmadd_w(_sum, _val1, _w1);
_sum = __msa_fmadd_w(_sum, _val2, _w2);
_sum = __msa_fmadd_w(_sum, _val3, _w3);
}
}
kptr += maxk * 16;
}
_sum = activation_ps(_sum, activation_type, activation_params);
__msa_st_w((v4i32)_sum, outptr + j * 4, 0);
}
outptr += outw * 4;
}
}
}
|
3d25pt_var.c
|
/*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
tile_size[2] = 24;
tile_size[3] = 256;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] =
coef[0][i][j][k] * A[(t)%2][i ][j ][k ] +
coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ;
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
colormap.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO L OOO RRRR M M AAA PPPP %
% C O O L O O R R MM MM A A P P %
% C O O L O O RRRR M M M AAAAA PPPP %
% C O O L O O R R M M A A P %
% CCCC OOO LLLLL OOO R R M M A A P %
% %
% %
% MagickCore Colormap Methods %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2012 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% We use linked-lists because splay-trees do not currently support duplicate
% key / value pairs (.e.g X11 green compliance and SVG green compliance).
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/cache-view.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/client.h"
#include "magick/configure.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-private.h"
#include "magick/quantize.h"
#include "magick/quantum.h"
#include "magick/semaphore.h"
#include "magick/string_.h"
#include "magick/token.h"
#include "magick/utility.h"
#include "magick/xml-tree.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImageColormap() allocates an image colormap and initializes
% it to a linear gray colorspace. If the image already has a colormap,
% it is replaced. AcquireImageColormap() returns MagickTrue if successful,
% otherwise MagickFalse if there is not enough memory.
%
% The format of the AcquireImageColormap method is:
%
% MagickBooleanType AcquireImageColormap(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.
%
*/
static inline size_t MagickMax(const size_t x,
const size_t y)
{
if (x > y)
return(x);
return(y);
}
static inline size_t MagickMin(const size_t x,
const size_t y)
{
if (x < y)
return(x);
return(y);
}
MagickExport MagickBooleanType AcquireImageColormap(Image *image,
const size_t colors)
{
register ssize_t
i;
size_t
length;
/*
Allocate image colormap.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
image->colors=colors;
length=(size_t) colors;
if (image->colormap == (PixelPacket *) NULL)
image->colormap=(PixelPacket *) AcquireQuantumMemory(length,
sizeof(*image->colormap));
else
image->colormap=(PixelPacket *) ResizeQuantumMemory(image->colormap,length,
sizeof(*image->colormap));
if (image->colormap == (PixelPacket *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
for (i=0; i < (ssize_t) image->colors; i++)
{
size_t
pixel;
pixel=(size_t) (i*(QuantumRange/MagickMax(colors-1,1)));
image->colormap[i].red=(Quantum) pixel;
image->colormap[i].green=(Quantum) pixel;
image->colormap[i].blue=(Quantum) pixel;
image->colormap[i].opacity=OpaqueOpacity;
}
return(SetImageStorageClass(image,PseudoClass));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C y c l e C o l o r m a p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CycleColormap() displaces an image's colormap by a given number of
% positions. If you cycle the colormap a number of times you can produce
% a psychodelic effect.
%
% The format of the CycleColormapImage method is:
%
% MagickBooleanType CycleColormapImage(Image *image,const ssize_t displace)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o displace: displace the colormap this amount.
%
*/
MagickExport MagickBooleanType CycleColormapImage(Image *image,
const ssize_t displace)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == DirectClass)
(void) SetImageType(image,PaletteType);
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
ssize_t
index;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
index=(ssize_t) (GetPixelIndex(indexes+x)+displace) %
image->colors;
if (index < 0)
index+=(ssize_t) image->colors;
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S o r t C o l o r m a p B y I n t e n s i t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SortColormapByIntensity() sorts the colormap of a PseudoClass image by
% decreasing color intensity.
%
% The format of the SortColormapByIntensity method is:
%
% MagickBooleanType SortColormapByIntensity(Image *image)
%
% A description of each parameter follows:
%
% o image: A pointer to an Image structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int IntensityCompare(const void *x,const void *y)
{
const PixelPacket
*color_1,
*color_2;
int
intensity;
color_1=(const PixelPacket *) x;
color_2=(const PixelPacket *) y;
intensity=(int) PixelIntensityToQuantum(color_2)-
(int) PixelIntensityToQuantum(color_1);
return(intensity);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
MagickExport MagickBooleanType SortColormapByIntensity(Image *image)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
y;
unsigned short
*pixels;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
if (image->storage_class != PseudoClass)
return(MagickTrue);
/*
Allocate memory for pixel indexes.
*/
pixels=(unsigned short *) AcquireQuantumMemory((size_t) image->colors,
sizeof(*pixels));
if (pixels == (unsigned short *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Assign index values to colormap entries.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status)
#endif
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].opacity=(IndexPacket) i;
/*
Sort image colormap by decreasing color popularity.
*/
qsort((void *) image->colormap,(size_t) image->colors,
sizeof(*image->colormap),IntensityCompare);
/*
Update image colormap indexes to sorted colormap order.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status)
#endif
for (i=0; i < (ssize_t) image->colors; i++)
pixels[(ssize_t) image->colormap[i].opacity]=(unsigned short) i;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireCacheView(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
IndexPacket
index;
register ssize_t
x;
register IndexPacket
*restrict indexes;
register PixelPacket
*restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
index=(IndexPacket) pixels[(ssize_t) GetPixelIndex(indexes+x)];
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (status == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
pixels=(unsigned short *) RelinquishMagickMemory(pixels);
return(status);
}
|
Questao02.c
|
//Programa que permite o usuario inserir a precisao do PI(versão paralelizada)
//Criado por Gustavo Lopes Rodrigues
#include <stdio.h>
//Função que encapsula o código do cálculo do PI
double calcularPi();
//Função main
int main(void){
int precisao;
scanf("%d", &precisao);
double pi = calcularPi(precisao);
printf("O valor de PI é: %f\n", pi);
}
double calcularPi(int precisao) {
double x = 1, operacao = 0.0,resultado = 4.0;
#pragma omp parallel for private(operacao)
for(int i=0; i < precisao; i++){
#pragma omp critical
x += 2;
if ( i % 2 == 0 ) {
operacao -= 4/x;
}
else {
operacao += 4/x;
}
#pragma omp critical
resultado += operacao;
}
return resultado;
}
|
graph.h
|
// Copyright (c) 2015, The Regents of the University of California (Regents)
// See LICENSE.txt for license details
#ifndef GRAPH_H_
#define GRAPH_H_
#include <algorithm>
#include <cinttypes>
#include <cstddef>
#include <iostream>
#include <type_traits>
#include "pvector.h"
#include "util.h"
/*
GAP Benchmark Suite
Class: CSRGraph
Author: Scott Beamer
Simple container for graph in CSR format
- Intended to be constructed by a Builder
- To make weighted, set DestID_ template type to NodeWeight
- MakeInverse parameter controls whether graph stores its inverse
*/
// Used to hold node & weight, with another node it makes a weighted edge
template <typename NodeID_, typename WeightT_>
struct NodeWeight
{
NodeID_ v;
WeightT_ w;
NodeWeight() {}
NodeWeight(NodeID_ v) : v(v), w(1) {}
NodeWeight(NodeID_ v, WeightT_ w) : v(v), w(w) {}
bool operator<(const NodeWeight &rhs) const
{
return v == rhs.v ? w < rhs.w : v < rhs.v;
}
// doesn't check WeightT_s, needed to remove duplicate edges
bool operator==(const NodeWeight &rhs) const
{
return v == rhs.v;
}
// doesn't check WeightT_s, needed to remove self edges
bool operator==(const NodeID_ &rhs) const
{
return v == rhs;
}
operator NodeID_()
{
return v;
}
};
template <typename NodeID_, typename WeightT_>
std::ostream &operator<<(std::ostream &os,
const NodeWeight<NodeID_, WeightT_> &nw)
{
os << nw.v << " " << nw.w;
return os;
}
template <typename NodeID_, typename WeightT_>
std::istream &operator>>(std::istream &is, NodeWeight<NodeID_, WeightT_> &nw)
{
is >> nw.v >> nw.w;
return is;
}
// Syntatic sugar for an edge
template <typename SrcT, typename DstT = SrcT>
struct EdgePair
{
SrcT u;
DstT v;
EdgePair() {}
EdgePair(SrcT u, DstT v) : u(u), v(v) {}
};
// SG = serialized graph, these types are for writing graph to file
typedef int32_t SGID;
typedef EdgePair<SGID> SGEdge;
typedef int64_t SGOffset;
template <class NodeID_, class DestID_ = NodeID_, bool MakeInverse = true>
class CSRGraph
{
// Used for *non-negative* offsets within a neighborhood
typedef std::make_unsigned<std::ptrdiff_t>::type OffsetT;
// Used to access neighbors of vertex, basically sugar for iterators
class Neighborhood
{
NodeID_ n_;
DestID_ **g_index_;
OffsetT start_offset_;
public:
Neighborhood(NodeID_ n, DestID_ **g_index, OffsetT start_offset) : n_(n), g_index_(g_index), start_offset_(0)
{
OffsetT max_offset = end() - begin();
start_offset_ = std::min(start_offset, max_offset);
}
typedef DestID_ *iterator;
iterator begin() { return g_index_[n_] + start_offset_; }
iterator end() { return g_index_[n_ + 1]; }
};
void ReleaseResources()
{
if (out_index_ != nullptr)
delete[] out_index_;
if (out_neighbors_ != nullptr)
delete[] out_neighbors_;
if (directed_)
{
if (in_index_ != nullptr)
delete[] in_index_;
if (in_neighbors_ != nullptr)
delete[] in_neighbors_;
}
}
public:
CSRGraph() : directed_(false), num_nodes_(-1), num_edges_(-1),
out_index_(nullptr), out_neighbors_(nullptr),
in_index_(nullptr), in_neighbors_(nullptr) {}
CSRGraph(int64_t num_nodes, DestID_ **index, DestID_ *neighs) : directed_(false), num_nodes_(num_nodes),
out_index_(index), out_neighbors_(neighs),
in_index_(index), in_neighbors_(neighs)
{
num_edges_ = (out_index_[num_nodes_] - out_index_[0]) / 2;
}
CSRGraph(int64_t num_nodes, DestID_ **out_index, DestID_ *out_neighs,
DestID_ **in_index, DestID_ *in_neighs) : directed_(true), num_nodes_(num_nodes),
out_index_(out_index), out_neighbors_(out_neighs),
in_index_(in_index), in_neighbors_(in_neighs)
{
num_edges_ = out_index_[num_nodes_] - out_index_[0];
}
CSRGraph(CSRGraph &&other) : directed_(other.directed_),
num_nodes_(other.num_nodes_), num_edges_(other.num_edges_),
out_index_(other.out_index_), out_neighbors_(other.out_neighbors_),
in_index_(other.in_index_), in_neighbors_(other.in_neighbors_)
{
other.num_edges_ = -1;
other.num_nodes_ = -1;
other.out_index_ = nullptr;
other.out_neighbors_ = nullptr;
other.in_index_ = nullptr;
other.in_neighbors_ = nullptr;
}
~CSRGraph()
{
ReleaseResources();
}
CSRGraph &operator=(CSRGraph &&other)
{
if (this != &other)
{
ReleaseResources();
directed_ = other.directed_;
num_edges_ = other.num_edges_;
num_nodes_ = other.num_nodes_;
out_index_ = other.out_index_;
out_neighbors_ = other.out_neighbors_;
in_index_ = other.in_index_;
in_neighbors_ = other.in_neighbors_;
other.num_edges_ = -1;
other.num_nodes_ = -1;
other.out_index_ = nullptr;
other.out_neighbors_ = nullptr;
other.in_index_ = nullptr;
other.in_neighbors_ = nullptr;
}
return *this;
}
bool directed() const
{
return directed_;
}
int64_t num_nodes() const
{
return num_nodes_;
}
int64_t num_edges() const
{
return num_edges_;
}
int64_t num_edges_directed() const
{
return directed_ ? num_edges_ : 2 * num_edges_;
}
int64_t out_degree(NodeID_ v) const
{
return out_index_[v + 1] - out_index_[v];
}
int64_t in_degree(NodeID_ v) const
{
static_assert(MakeInverse, "Graph inversion disabled but reading inverse");
return in_index_[v + 1] - in_index_[v];
}
Neighborhood out_neigh(NodeID_ n, OffsetT start_offset = 0) const
{
return Neighborhood(n, out_index_, start_offset);
}
Neighborhood in_neigh(NodeID_ n, OffsetT start_offset = 0) const
{
static_assert(MakeInverse, "Graph inversion disabled but reading inverse");
return Neighborhood(n, in_index_, start_offset);
}
void PrintStats() const
{
std::cout << "Graph has " << num_nodes_ << " nodes and "
<< num_edges_ << " ";
if (!directed_)
std::cout << "un";
std::cout << "directed edges for degree: ";
std::cout << num_edges_ / num_nodes_ << std::endl;
}
void PrintTopology() const
{
for (NodeID_ i = 0; i < num_nodes_; i++)
{
std::cout << i << ": ";
for (DestID_ j : out_neigh(i))
{
std::cout << j << " ";
}
std::cout << std::endl;
}
}
static DestID_ **GenIndex(const pvector<SGOffset> &offsets, DestID_ *neighs)
{
NodeID_ length = offsets.size();
DestID_ **index = new DestID_ *[length];
#pragma omp parallel for
for (NodeID_ n = 0; n < length; n++)
index[n] = neighs + offsets[n];
return index;
}
pvector<SGOffset> VertexOffsets(bool in_graph = false) const
{
pvector<SGOffset> offsets(num_nodes_ + 1);
for (NodeID_ n = 0; n < num_nodes_ + 1; n++)
if (in_graph)
offsets[n] = in_index_[n] - in_index_[0];
else
offsets[n] = out_index_[n] - out_index_[0];
return offsets;
}
Range<NodeID_> vertices() const
{
return Range<NodeID_>(num_nodes());
}
private:
bool directed_;
int64_t num_nodes_;
int64_t num_edges_;
DestID_ **out_index_;
DestID_ *out_neighbors_;
DestID_ **in_index_;
DestID_ *in_neighbors_;
};
#endif // GRAPH_H_
|
mandel_reduction.c
|
/*
** PROGRAM: Mandelbrot area (solution)
**
** PURPOSE: Program to compute the area of a Mandelbrot set.
** The correct answer should be around 1.510659.
**
** USAGE: Program runs without input ... just run the executable
**
** ADDITIONAL EXERCISES: Experiment with the schedule clause to fix
** the load imbalance. Experiment with atomic vs. critical vs.
** reduction for numoutside.
**
** HISTORY: Written: (Mark Bull, August 2011).
**
** Changed "complex" to "d_complex" to avoid collsion with
** math.h complex type. Fixed data environment errors
** (Tim Mattson, September 2011)
**
** Implememted a "reduction" version
** (Helen He, November 2020)
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
# define NPOINTS 1000
# define MXITR 1000
struct d_complex {
double r;
double i;
};
int testpoint(struct d_complex);
struct d_complex c;
int numoutside = 0;
int main ()
{
int i, j;
double area, error, eps = 1.0e-5;
// Loop over grid of points in the complex plane which contains the Mandelbrot set,
// testing each point to see whether it is inside or outside the set.
double initTime = omp_get_wtime();
#pragma omp parallel for private(c,j) firstprivate(eps) reduction(+:numoutside)
for (i = 0; i < NPOINTS; i++) {
for (j = 0; j < NPOINTS; j++) {
c.r = -2.0 + 2.5 * (double)(i)/(double)(NPOINTS) + eps;
c.i = 1.125 * (double)(j)/(double)(NPOINTS) + eps;
numoutside += testpoint(c);
}
}
// Calculate area of set and error estimate and output the results
area = 2.0 * 2.5 * 1.125 * (double)(NPOINTS * NPOINTS \
- numoutside)/(double)(NPOINTS * NPOINTS);
error = area / (double)NPOINTS;
double runtime = omp_get_wtime() - initTime;
printf("runtime = %lf seconds with %d threads\n",runtime, omp_get_num_threads());
printf("Area of Mandlebrot set = %12.8f +/- %12.8f\n",area,error);
printf("Correct answer should be around 1.510659\n");
}
int testpoint(struct d_complex c)
{
// Does the iteration z=z*z+c, until |z| > 2 when point is known to be outside set
// If loop count reaches MAXITER, point is considered to be inside the set
struct d_complex z;
int iter;
double temp;
int outside = 0;
z = c;
for (iter = 0; iter < MXITR; iter++) {
temp = (z.r * z.r) - (z.i * z.i) + c.r;
z.i = z.r * z.i * 2 + c.i;
z.r = temp;
if ((z.r * z.r + z.i * z.i) > 4.0) {
outside++;
break;
}
}
return outside;
}
|
convolution_3x3.h
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv3x3s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* kernel = _kernel;
const float* bias = _bias;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p + 1);
const float bias0 = bias ? bias[p] : 0.f;
const float bias1 = bias ? bias[p + 1] : 0.f;
out0.fill(bias0);
out1.fill(bias1);
const float* k0 = kernel + p * inch * 9;
const float* k1 = kernel + (p + 1) * inch * 9;
for (int q = 0; q < inch; q++)
{
float* outptr0 = out0;
float* outptr1 = out1;
float* outptr0n = outptr0 + outw;
float* outptr1n = outptr1 + outw;
const float* img0 = bottom_blob.channel(q);
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
#if __ARM_NEON
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k03 = vld1q_f32(k0 + 3);
float32x4_t _k06 = vld1q_f32(k0 + 6);
float32x4_t _k10 = vld1q_f32(k1);
float32x4_t _k13 = vld1q_f32(k1 + 3);
float32x4_t _k16 = vld1q_f32(k1 + 6);
#endif // __ARM_NEON
int i = 0;
for (; i + 1 < outh; i += 2)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v8.4s, v9.4s}, [%5] \n" // r0
"add %5, %5, #16 \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v14.4s, v15.4s}, [%8] \n" // r3
"add %8, %8, #16 \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v14.16b, v15.16b, #8 \n"
"0: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v6.4s}, [%1] \n" // _sum0
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v7.4s}, [%2] \n" // _sum1
"fmla v6.4s, v8.4s, %18.s[0] \n"
"fmla v7.4s, v8.4s, %21.s[0] \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v12.4s}, [%3] \n" // _sum0n
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v13.4s}, [%4] \n" // _sum1n
"fmla v12.4s, v14.4s, %20.s[0] \n"
"fmla v13.4s, v14.4s, %23.s[0] \n"
"ext v8.16b, v8.16b, v9.16b, #8 \n"
"ext v9.16b, v14.16b, v15.16b, #4 \n"
"fmla v6.4s, v10.4s, %18.s[1] \n"
"fmla v7.4s, v10.4s, %21.s[1] \n"
"fmla v12.4s, v11.4s, %20.s[2] \n"
"fmla v13.4s, v11.4s, %23.s[2] \n"
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v14.4s, v15.4s}, [%6] \n" // r1
"add %6, %6, #16 \n"
"fmla v6.4s, v8.4s, %18.s[2] \n"
"fmla v7.4s, v8.4s, %21.s[2] \n"
"fmla v12.4s, v9.4s, %20.s[1] \n"
"fmla v13.4s, v9.4s, %23.s[1] \n"
"ext v10.16b, v14.16b, v15.16b, #4 \n"
"fmla v6.4s, v14.4s, %19.s[0] \n"
"fmla v7.4s, v14.4s, %22.s[0] \n"
"fmla v12.4s, v14.4s, %18.s[0] \n"
"fmla v13.4s, v14.4s, %21.s[0] \n"
"ext v11.16b, v14.16b, v15.16b, #8 \n"
"fmla v6.4s, v10.4s, %19.s[1] \n"
"fmla v7.4s, v10.4s, %22.s[1] \n"
"fmla v12.4s, v10.4s, %18.s[1] \n"
"fmla v13.4s, v10.4s, %21.s[1] \n"
"prfm pldl1keep, [%7, #256] \n"
"ld1 {v8.4s, v9.4s}, [%7] \n" // r2
"add %7, %7, #16 \n"
"fmla v6.4s, v11.4s, %19.s[2] \n"
"fmla v7.4s, v11.4s, %22.s[2] \n"
"fmla v12.4s, v11.4s, %18.s[2] \n"
"fmla v13.4s, v11.4s, %21.s[2] \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"fmla v6.4s, v8.4s, %20.s[0] \n"
"fmla v7.4s, v8.4s, %23.s[0] \n"
"fmla v12.4s, v8.4s, %19.s[0] \n"
"fmla v13.4s, v8.4s, %22.s[0] \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"fmla v6.4s, v10.4s, %20.s[1] \n"
"fmla v7.4s, v10.4s, %23.s[1] \n"
"fmla v12.4s, v10.4s, %19.s[1] \n"
"fmla v13.4s, v10.4s, %22.s[1] \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v8.4s, v9.4s}, [%5] \n" // r0
"add %5, %5, #16 \n"
"fmla v6.4s, v11.4s, %20.s[2] \n"
"fmla v7.4s, v11.4s, %23.s[2] \n"
"fmla v12.4s, v11.4s, %19.s[2] \n"
"fmla v13.4s, v11.4s, %22.s[2] \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v14.4s, v15.4s}, [%8] \n" // r3
"add %8, %8, #16 \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"st1 {v6.4s}, [%1], #16 \n"
"st1 {v7.4s}, [%2], #16 \n"
"ext v11.16b, v14.16b, v15.16b, #8 \n"
"st1 {v12.4s}, [%3], #16 \n"
"st1 {v13.4s}, [%4], #16 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
"sub %5, %5, #16 \n"
"sub %8, %8, #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr0n), // %3
"=r"(outptr1n), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3) // %8
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr0n),
"4"(outptr1n),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3),
"w"(_k00), // %18
"w"(_k03), // %19
"w"(_k06), // %20
"w"(_k10), // %21
"w"(_k13), // %22
"w"(_k16) // %23
: "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
"pld [%5, #192] \n"
"vld1.f32 {d16-d18}, [%5 :64] \n" // r0
"add %5, #16 \n"
"pld [%8, #192] \n"
"vld1.f32 {d28-d30}, [%8] \n" // r3
"add %8, #16 \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q14, q15, #2 \n"
"0: \n"
"pld [%1, #128] \n"
"vld1.f32 {d12-d13}, [%1 :64] \n" // _sum0
"pld [%2, #128] \n"
"vld1.f32 {d14-d15}, [%2 :64] \n" // _sum1
"vmla.f32 q6, q8, %e18[0] \n"
"vmla.f32 q7, q8, %e21[0] \n"
"pld [%3, #128] \n"
"vld1.f32 {d24-d25}, [%3] \n" // _sum0n
"pld [%4, #128] \n"
"vld1.f32 {d26-d27}, [%4] \n" // _sum1n
"vmla.f32 q12, q14, %e20[0] \n"
"vmla.f32 q13, q14, %e23[0] \n"
"vext.32 q8, q8, q9, #2 \n"
"vext.32 q9, q14, q15, #1 \n"
"vmla.f32 q6, q10, %e18[1] \n"
"vmla.f32 q7, q10, %e21[1] \n"
"vmla.f32 q12, q11, %f20[0] \n"
"vmla.f32 q13, q11, %f23[0] \n"
"pld [%6, #192] \n"
"vld1.f32 {d28-d30}, [%6] \n" // r1
"add %6, #16 \n"
"vmla.f32 q6, q8, %f18[0] \n"
"vmla.f32 q7, q8, %f21[0] \n"
"vmla.f32 q12, q9, %e20[1] \n"
"vmla.f32 q13, q9, %e23[1] \n"
"vext.32 q10, q14, q15, #1 \n"
"vmla.f32 q6, q14, %e19[0] \n"
"vmla.f32 q7, q14, %e22[0] \n"
"vmla.f32 q12, q14, %e18[0] \n"
"vmla.f32 q13, q14, %e21[0] \n"
"vext.32 q11, q14, q15, #2 \n"
"vmla.f32 q6, q10, %e19[1] \n"
"vmla.f32 q7, q10, %e22[1] \n"
"vmla.f32 q12, q10, %e18[1] \n"
"vmla.f32 q13, q10, %e21[1] \n"
"pld [%7, #192] \n"
"vld1.f32 {d16-d18}, [%7 :64] \n" // r2
"add %7, #16 \n"
"vmla.f32 q6, q11, %f19[0] \n"
"vmla.f32 q7, q11, %f22[0] \n"
"vmla.f32 q12, q11, %f18[0] \n"
"vmla.f32 q13, q11, %f21[0] \n"
"vext.32 q10, q8, q9, #1 \n"
"vmla.f32 q6, q8, %e20[0] \n"
"vmla.f32 q7, q8, %e23[0] \n"
"vmla.f32 q12, q8, %e19[0] \n"
"vmla.f32 q13, q8, %e22[0] \n"
"vext.32 q11, q8, q9, #2 \n"
"vmla.f32 q6, q10, %e20[1] \n"
"vmla.f32 q7, q10, %e23[1] \n"
"vmla.f32 q12, q10, %e19[1] \n"
"vmla.f32 q13, q10, %e22[1] \n"
"pld [%5, #192] \n"
"vld1.f32 {d16-d18}, [%5 :64] \n" // r0
"add %5, #16 \n"
"vmla.f32 q6, q11, %f20[0] \n"
"vmla.f32 q7, q11, %f23[0] \n"
"vmla.f32 q12, q11, %f19[0] \n"
"vmla.f32 q13, q11, %f22[0] \n"
"pld [%8, #192] \n"
"vld1.f32 {d28-d30}, [%8] \n" // r3
"add %8, #16 \n"
"vext.32 q10, q8, q9, #1 \n"
"vst1.f32 {d12-d13}, [%1 : 64]!\n"
"vst1.f32 {d14-d15}, [%2 : 64]!\n"
"vext.32 q11, q14, q15, #2 \n"
"vst1.f32 {d24-d25}, [%3]! \n"
"vst1.f32 {d26-d27}, [%4]! \n"
"subs %0, #1 \n"
"bne 0b \n"
"sub %5, #16 \n"
"sub %8, #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr0n), // %3
"=r"(outptr1n), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3) // %8
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr0n),
"4"(outptr1n),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3),
"w"(_k00), // %18
"w"(_k03), // %19
"w"(_k06), // %20
"w"(_k10), // %21
"w"(_k13), // %22
"w"(_k16) // %23
: "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _sum0 = vmulq_f32(_r00, _k00);
float32x4_t _sum1 = vmulq_f32(_r00, _k10);
_sum0 = vmlaq_f32(_sum0, _r10, _k03);
_sum1 = vmlaq_f32(_sum1, _r10, _k13);
_sum0 = vmlaq_f32(_sum0, _r20, _k06);
_sum1 = vmlaq_f32(_sum1, _r20, _k16);
float32x4_t _sum0n = vmulq_f32(_r10, _k00);
float32x4_t _sum1n = vmulq_f32(_r10, _k10);
_sum0n = vmlaq_f32(_sum0n, _r20, _k03);
_sum1n = vmlaq_f32(_sum1n, _r20, _k13);
_sum0n = vmlaq_f32(_sum0n, _r30, _k06);
_sum1n = vmlaq_f32(_sum1n, _r30, _k16);
_sum0 = vsetq_lane_f32(*outptr0, _sum0, 3);
_sum1 = vsetq_lane_f32(*outptr1, _sum1, 3);
_sum0n = vsetq_lane_f32(*outptr0n, _sum0n, 3);
_sum1n = vsetq_lane_f32(*outptr1n, _sum1n, 3);
#if __aarch64__
*outptr0 = vaddvq_f32(_sum0);
*outptr1 = vaddvq_f32(_sum1);
*outptr0n = vaddvq_f32(_sum0n);
*outptr1n = vaddvq_f32(_sum1n);
#else
float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1));
float32x2_t _ss0n = vadd_f32(vget_low_f32(_sum0n), vget_high_f32(_sum0n));
float32x2_t _ss1n = vadd_f32(vget_low_f32(_sum1n), vget_high_f32(_sum1n));
float32x2_t _ss01 = vpadd_f32(_ss0, _ss1);
float32x2_t _ss01n = vpadd_f32(_ss0n, _ss1n);
*outptr0 = vget_lane_f32(_ss01, 0);
*outptr1 = vget_lane_f32(_ss01, 1);
*outptr0n = vget_lane_f32(_ss01n, 0);
*outptr1n = vget_lane_f32(_ss01n, 1);
#endif // __aarch64__
#else
float sum0 = 0.f;
float sum0n = 0.f;
float sum1 = 0.f;
float sum1n = 0.f;
sum0 += r0[0] * k0[0];
sum0 += r0[1] * k0[1];
sum0 += r0[2] * k0[2];
sum0 += r1[0] * k0[3];
sum0 += r1[1] * k0[4];
sum0 += r1[2] * k0[5];
sum0 += r2[0] * k0[6];
sum0 += r2[1] * k0[7];
sum0 += r2[2] * k0[8];
sum1 += r0[0] * k1[0];
sum1 += r0[1] * k1[1];
sum1 += r0[2] * k1[2];
sum1 += r1[0] * k1[3];
sum1 += r1[1] * k1[4];
sum1 += r1[2] * k1[5];
sum1 += r2[0] * k1[6];
sum1 += r2[1] * k1[7];
sum1 += r2[2] * k1[8];
sum0n += r1[0] * k0[0];
sum0n += r1[1] * k0[1];
sum0n += r1[2] * k0[2];
sum0n += r2[0] * k0[3];
sum0n += r2[1] * k0[4];
sum0n += r2[2] * k0[5];
sum0n += r3[0] * k0[6];
sum0n += r3[1] * k0[7];
sum0n += r3[2] * k0[8];
sum1n += r1[0] * k1[0];
sum1n += r1[1] * k1[1];
sum1n += r1[2] * k1[2];
sum1n += r2[0] * k1[3];
sum1n += r2[1] * k1[4];
sum1n += r2[2] * k1[5];
sum1n += r3[0] * k1[6];
sum1n += r3[1] * k1[7];
sum1n += r3[2] * k1[8];
*outptr0 += sum0;
*outptr1 += sum1;
*outptr0n += sum0n;
*outptr1n += sum1n;
#endif // __ARM_NEON
r0++;
r1++;
r2++;
r3++;
outptr0++;
outptr1++;
outptr0n++;
outptr1n++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr1 += outw;
outptr0n += outw;
outptr1n += outw;
}
for (; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v8.4s, v9.4s}, [%3] \n" // r0
"add %3, %3, #16 \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v6.4s}, [%1] \n" // _sum0
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v7.4s}, [%2] \n" // _sum1
"fmul v14.4s, v8.4s, %12.s[0] \n"
"fmul v15.4s, v8.4s, %15.s[0] \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"fmla v6.4s, v10.4s, %12.s[1] \n"
"fmla v7.4s, v10.4s, %15.s[1] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v8.4s, v9.4s}, [%4] \n" // r1
"add %4, %4, #16 \n"
"fmla v14.4s, v11.4s, %12.s[2] \n"
"fmla v15.4s, v11.4s, %15.s[2] \n"
"fmla v6.4s, v8.4s, %13.s[0] \n"
"fmla v7.4s, v8.4s, %16.s[0] \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"fmla v14.4s, v10.4s, %13.s[1] \n"
"fmla v15.4s, v10.4s, %16.s[1] \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v8.4s, v9.4s}, [%5] \n" // r2
"add %5, %5, #16 \n"
"fmla v6.4s, v11.4s, %13.s[2] \n"
"fmla v7.4s, v11.4s, %16.s[2] \n"
"fmla v14.4s, v8.4s, %14.s[0] \n"
"fmla v15.4s, v8.4s, %17.s[0] \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"fmla v6.4s, v10.4s, %14.s[1] \n"
"fmla v7.4s, v10.4s, %17.s[1] \n"
"fmla v14.4s, v11.4s, %14.s[2] \n"
"fmla v15.4s, v11.4s, %17.s[2] \n"
"fadd v6.4s, v6.4s, v14.4s \n"
"fadd v7.4s, v7.4s, v15.4s \n"
"st1 {v6.4s}, [%1], #16 \n"
"st1 {v7.4s}, [%2], #16 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00), // %12
"w"(_k03), // %13
"w"(_k06), // %14
"w"(_k10), // %15
"w"(_k13), // %16
"w"(_k16) // %17
: "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%3, #192] \n"
"vld1.f32 {d16-d18}, [%3] \n" // r0
"add %3, #16 \n"
"pld [%1, #128] \n"
"vld1.f32 {d12-d13}, [%1] \n" // _sum0
"pld [%2, #128] \n"
"vld1.f32 {d14-d15}, [%2] \n" // _sum1
"vmul.f32 q14, q8, %e12[0] \n"
"vmul.f32 q15, q8, %e15[0] \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vmla.f32 q6, q10, %e12[1] \n"
"vmla.f32 q7, q10, %e15[1] \n"
"pld [%4, #192] \n"
"vld1.f32 {d16-d18}, [%4] \n" // r1
"add %4, #16 \n"
"vmla.f32 q14, q11, %f12[0] \n"
"vmla.f32 q15, q11, %f15[0] \n"
"vmla.f32 q6, q8, %e13[0] \n"
"vmla.f32 q7, q8, %e16[0] \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vmla.f32 q14, q10, %e13[1] \n"
"vmla.f32 q15, q10, %e16[1] \n"
"pld [%5, #192] \n"
"vld1.f32 {d16-d18}, [%5] \n" // r2
"add %5, #16 \n"
"vmla.f32 q6, q11, %f13[0] \n"
"vmla.f32 q7, q11, %f16[0] \n"
"vmla.f32 q14, q8, %e14[0] \n"
"vmla.f32 q15, q8, %e17[0] \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vmla.f32 q6, q10, %e14[1] \n"
"vmla.f32 q7, q10, %e17[1] \n"
"vmla.f32 q14, q11, %f14[0] \n"
"vmla.f32 q15, q11, %f17[0] \n"
"vadd.f32 q6, q6, q14 \n"
"vadd.f32 q7, q7, q15 \n"
"vst1.f32 {d12-d13}, [%1]! \n"
"vst1.f32 {d14-d15}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00), // %12
"w"(_k03), // %13
"w"(_k06), // %14
"w"(_k10), // %15
"w"(_k13), // %16
"w"(_k16) // %17
: "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _sum0 = vmulq_f32(_r00, _k00);
float32x4_t _sum1 = vmulq_f32(_r00, _k10);
_sum0 = vmlaq_f32(_sum0, _r10, _k03);
_sum1 = vmlaq_f32(_sum1, _r10, _k13);
_sum0 = vmlaq_f32(_sum0, _r20, _k06);
_sum1 = vmlaq_f32(_sum1, _r20, _k16);
_sum0 = vsetq_lane_f32(*outptr0, _sum0, 3);
_sum1 = vsetq_lane_f32(*outptr1, _sum1, 3);
#if __aarch64__
*outptr0 = vaddvq_f32(_sum0);
*outptr1 = vaddvq_f32(_sum1);
#else
float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1));
float32x2_t _ss01 = vpadd_f32(_ss0, _ss1);
*outptr0 = vget_lane_f32(_ss01, 0);
*outptr1 = vget_lane_f32(_ss01, 1);
#endif // __aarch64__
#else
float sum0 = 0.f;
float sum1 = 0.f;
sum0 += r0[0] * k0[0];
sum0 += r0[1] * k0[1];
sum0 += r0[2] * k0[2];
sum0 += r1[0] * k0[3];
sum0 += r1[1] * k0[4];
sum0 += r1[2] * k0[5];
sum0 += r2[0] * k0[6];
sum0 += r2[1] * k0[7];
sum0 += r2[2] * k0[8];
sum1 += r0[0] * k1[0];
sum1 += r0[1] * k1[1];
sum1 += r0[2] * k1[2];
sum1 += r1[0] * k1[3];
sum1 += r1[1] * k1[4];
sum1 += r1[2] * k1[5];
sum1 += r2[0] * k1[6];
sum1 += r2[1] * k1[7];
sum1 += r2[2] * k1[8];
*outptr0 += sum0;
*outptr1 += sum1;
#endif // __ARM_NEON
r0++;
r1++;
r2++;
outptr0++;
outptr1++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
k0 += 9;
k1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
Mat out = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
out.fill(bias0);
const float* kernel0 = kernel + p * inch * 9;
for (int q = 0; q < inch; q++)
{
float* outptr = out;
float* outptr2 = outptr + outw;
const float* img0 = bottom_blob.channel(q);
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
#if __ARM_NEON
float32x4_t _k0123 = vld1q_f32(kernel0);
float32x4_t _k3456 = vld1q_f32(kernel0 + 3);
float32x4_t _k6789 = vld1q_f32(kernel0 + 6);
#else
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
#endif // __ARM_NEON
int i = 0;
for (; i + 1 < outh; i += 2)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v9.4s, v10.4s}, [%3] \n" // r0
"add %3, %3, #16 \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n"
"0: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v7.4s}, [%1] \n" // _sum
"fmla v7.4s, v9.4s, %14.s[0] \n"
"fmul v6.4s, v11.4s, %14.s[1] \n"
"fmul v13.4s, v12.4s, %14.s[2] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v9.4s, v10.4s}, [%4] \n" // r1
"add %4, %4, #16 \n"
"fmla v7.4s, v9.4s, %15.s[0] \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n"
"fmla v6.4s, v11.4s, %15.s[1] \n"
"fmla v13.4s, v12.4s, %15.s[2] \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v8.4s}, [%2] \n" // _sum2
"fmla v8.4s, v9.4s, %14.s[0] \n"
"fmul v14.4s, v11.4s, %14.s[1] \n"
"fmul v15.4s, v12.4s, %14.s[2] \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v9.4s, v10.4s}, [%5] \n" // r2
"add %5, %5, #16 \n"
"fmla v7.4s, v9.4s, %16.s[0] \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n"
"fmla v6.4s, v11.4s, %16.s[1] \n"
"fmla v13.4s, v12.4s, %16.s[2] \n"
"fmla v8.4s, v9.4s, %15.s[0] \n"
"fmla v14.4s, v11.4s, %15.s[1] \n"
"fmla v15.4s, v12.4s, %15.s[2] \n"
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v9.4s, v10.4s}, [%6] \n" // r3
"add %6, %6, #16 \n"
"fmla v8.4s, v9.4s, %16.s[0] \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n"
"fmla v14.4s, v11.4s, %16.s[1] \n"
"fmla v15.4s, v12.4s, %16.s[2] \n"
"fadd v7.4s, v7.4s, v6.4s \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v9.4s, v10.4s}, [%3] \n" // r0
"fadd v8.4s, v8.4s, v14.4s \n"
"fadd v7.4s, v7.4s, v13.4s \n"
"fadd v8.4s, v8.4s, v15.4s \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n"
"add %3, %3, #16 \n"
"st1 {v7.4s}, [%1], #16 \n"
"st1 {v8.4s}, [%2], #16 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
"sub %3, %3, #16 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(outptr2), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr),
"2"(outptr2),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3),
"w"(_k0123), // %14
"w"(_k3456), // %15
"w"(_k6789) // %16
: "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
"pld [%3, #192] \n"
"vld1.f32 {d18-d20}, [%3 :64] \n" // r0
"add %3, #16 \n"
"vext.32 q11, q9, q10, #1 \n"
"vext.32 q12, q9, q10, #2 \n"
"0: \n"
"pld [%1, #128] \n"
"vld1.f32 {d14-d15}, [%1 :64] \n" // _sum
"vmla.f32 q7, q9, %e14[0] \n"
"vmul.f32 q6, q11, %e14[1] \n"
"vmul.f32 q13, q12, %f14[0] \n"
"pld [%4, #192] \n"
"vld1.f32 {d18-d20}, [%4] \n" // r1
"add %4, #16 \n"
"vmla.f32 q7, q9, %e15[0] \n"
"vext.32 q11, q9, q10, #1 \n"
"vext.32 q12, q9, q10, #2 \n"
"vmla.f32 q6, q11, %e15[1] \n"
"vmla.f32 q13, q12, %f15[0] \n"
"pld [%2, #128] \n"
"vld1.f32 {d16-d17}, [%2] \n" // _sum2
"vmla.f32 q8, q9, %e14[0] \n"
"vmul.f32 q14, q11, %e14[1] \n"
"vmul.f32 q15, q12, %f14[0] \n"
"pld [%5, #192] \n"
"vld1.f32 {d18-d20}, [%5 :64] \n" // r2
"add %5, #16 \n"
"vmla.f32 q7, q9, %e16[0] \n"
"vext.32 q11, q9, q10, #1 \n"
"vext.32 q12, q9, q10, #2 \n"
"vmla.f32 q6, q11, %e16[1] \n"
"vmla.f32 q13, q12, %f16[0] \n"
"vmla.f32 q8, q9, %e15[0] \n"
"vmla.f32 q14, q11, %e15[1] \n"
"vmla.f32 q15, q12, %f15[0] \n"
"pld [%6, #192] \n"
"vld1.f32 {d18-d20}, [%6] \n" // r3
"add %6, #16 \n"
"vmla.f32 q8, q9, %e16[0] \n"
"vext.32 q11, q9, q10, #1 \n"
"vext.32 q12, q9, q10, #2 \n"
"vmla.f32 q14, q11, %e16[1] \n"
"vmla.f32 q15, q12, %f16[0] \n"
"vadd.f32 q7, q7, q6 \n"
"pld [%3, #192] \n"
"vld1.f32 {d18-d20}, [%3 :64] \n" // r0
"vadd.f32 q8, q8, q14 \n"
"vadd.f32 q7, q7, q13 \n"
"vadd.f32 q8, q8, q15 \n"
"vext.32 q11, q9, q10, #1 \n"
"vext.32 q12, q9, q10, #2 \n"
"add %3, #16 \n"
"vst1.f32 {d14-d15}, [%1]! \n"
"vst1.f32 {d16-d17}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
"sub %3, #16 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(outptr2), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr),
"2"(outptr2),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3),
"w"(_k0123), // %14
"w"(_k3456), // %15
"w"(_k6789) // %16
: "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _sum = vmulq_f32(_r00, _k0123);
_sum = vmlaq_f32(_sum, _r10, _k3456);
_sum = vmlaq_f32(_sum, _r20, _k6789);
float32x4_t _sum2 = vmulq_f32(_r10, _k0123);
_sum2 = vmlaq_f32(_sum2, _r20, _k3456);
_sum2 = vmlaq_f32(_sum2, _r30, _k6789);
_sum = vsetq_lane_f32(*outptr, _sum, 3);
_sum2 = vsetq_lane_f32(*outptr2, _sum2, 3);
#if __aarch64__
*outptr = vaddvq_f32(_sum);
*outptr2 = vaddvq_f32(_sum2);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum));
float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2));
float32x2_t _sss2 = vpadd_f32(_ss, _ss2);
*outptr = vget_lane_f32(_sss2, 0);
*outptr2 = vget_lane_f32(_sss2, 1);
#endif // __aarch64__
#else
float sum = 0;
float sum2 = 0;
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];
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;
#endif
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++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v8.4s, v9.4s}, [%2] \n" // r0
"add %2, %2, #16 \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"0: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v7.4s}, [%1] \n" // _sum
"fmla v7.4s, v8.4s, %10.s[0] \n"
"fmul v13.4s, v10.4s, %10.s[1] \n"
"fmul v14.4s, v11.4s, %10.s[2] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v8.4s, v9.4s}, [%3] \n" // r1
"add %3, %3, #16 \n"
"fmla v7.4s, v8.4s, %11.s[0] \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"fmla v13.4s, v10.4s, %11.s[1] \n"
"fmla v14.4s, v11.4s, %11.s[2] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v8.4s, v9.4s}, [%4] \n" // r2
"add %4, %4, #16 \n"
"fmla v7.4s, v8.4s, %12.s[0] \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"fmla v13.4s, v10.4s, %12.s[1] \n"
"fmla v14.4s, v11.4s, %12.s[2] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v8.4s, v9.4s}, [%2] \n" // r0
"add %2, %2, #16 \n"
"fadd v7.4s, v7.4s, v13.4s \n"
"fadd v7.4s, v7.4s, v14.4s \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n"
"ext v11.16b, v8.16b, v9.16b, #8 \n"
"st1 {v7.4s}, [%1], #16 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
"sub %2, %2, #16 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k0123), // %10
"w"(_k3456), // %11
"w"(_k6789) // %12
: "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
"pld [%2, #192] \n"
"vld1.f32 {d16-d18}, [%2] \n" // r0
"add %2, #16 \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"0: \n"
"pld [%1, #128] \n"
"vld1.f32 {d14-d15}, [%1] \n" // _sum
"vmla.f32 q7, q8, %e10[0] \n"
"vmul.f32 q13, q10, %e10[1] \n"
"vmul.f32 q14, q11, %f10[0] \n"
"pld [%3, #192] \n"
"vld1.f32 {d16-d18}, [%3] \n" // r1
"add %3, #16 \n"
"vmla.f32 q7, q8, %e11[0] \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vmla.f32 q13, q10, %e11[1] \n"
"vmla.f32 q14, q11, %f11[0] \n"
"pld [%4, #192] \n"
"vld1.f32 {d16-d18}, [%4] \n" // r2
"add %4, #16 \n"
"vmla.f32 q7, q8, %e12[0] \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vmla.f32 q13, q10, %e12[1] \n"
"vmla.f32 q14, q11, %f12[0] \n"
"pld [%2, #192] \n"
"vld1.f32 {d16-d18}, [%2] \n" // r0
"add %2, #16 \n"
"vadd.f32 q7, q7, q13 \n"
"vadd.f32 q7, q7, q14 \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vst1.f32 {d14-d15}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
"sub %2, #16 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k0123), // %10
"w"(_k3456), // %11
"w"(_k6789) // %12
: "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _sum = vmulq_f32(_r00, _k0123);
_sum = vmlaq_f32(_sum, _r10, _k3456);
_sum = vmlaq_f32(_sum, _r20, _k6789);
_sum = vsetq_lane_f32(*outptr, _sum, 3);
#if __aarch64__
*outptr = vaddvq_f32(_sum);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum));
_ss = vpadd_f32(_ss, _ss);
*outptr = vget_lane_f32(_ss, 0);
#endif // __aarch64__
#else
float sum = 0;
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;
#endif
r0++;
r1++;
r2++;
outptr++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
}
}
}
static void conv3x3s1_winograd64_transform_kernel_neon(const Mat& kernel, Mat& kernel_tm, int inch, int outch)
{
kernel_tm.create(8 * 8, inch, outch);
const float ktm[8][3] = {
{1.0f, 0.0f, 0.0f},
{-2.0f / 9, -2.0f / 9, -2.0f / 9},
{-2.0f / 9, 2.0f / 9, -2.0f / 9},
{1.0f / 90, 1.0f / 45, 2.0f / 45},
{1.0f / 90, -1.0f / 45, 2.0f / 45},
{1.0f / 45, 1.0f / 90, 1.0f / 180},
{1.0f / 45, -1.0f / 90, 1.0f / 180},
{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 = (const float*)kernel + p * inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel, transposed
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[8][3];
for (int i = 0; i < 8; 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];
}
// v
for (int j = 0; j < 8; j++)
{
float* tmpp = &tmp[j][0];
for (int i = 0; i < 8; i++)
{
kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// optimized layout for winograd4
// interleave weights
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
Mat kernel_tm2(8 * 8 * inch * 4, 1, nn_outch + (outch % 4 + 3) / 4);
#pragma omp parallel for
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 4;
float* ktm2 = kernel_tm2.channel(pp);
const Mat kernel0_tm = kernel_tm.channel(p);
const Mat kernel1_tm = kernel_tm.channel(p + 1);
const Mat kernel2_tm = kernel_tm.channel(p + 2);
const Mat kernel3_tm = kernel_tm.channel(p + 3);
int q = 0;
#if __ARM_NEON && __aarch64__
for (; q + 3 < inch; q += 4)
{
const float* k00 = kernel0_tm.row(q);
const float* k01 = kernel0_tm.row(q + 1);
const float* k02 = kernel0_tm.row(q + 2);
const float* k03 = kernel0_tm.row(q + 3);
const float* k10 = kernel1_tm.row(q);
const float* k11 = kernel1_tm.row(q + 1);
const float* k12 = kernel1_tm.row(q + 2);
const float* k13 = kernel1_tm.row(q + 3);
const float* k20 = kernel2_tm.row(q);
const float* k21 = kernel2_tm.row(q + 1);
const float* k22 = kernel2_tm.row(q + 2);
const float* k23 = kernel2_tm.row(q + 3);
const float* k30 = kernel3_tm.row(q);
const float* k31 = kernel3_tm.row(q + 1);
const float* k32 = kernel3_tm.row(q + 2);
const float* k33 = kernel3_tm.row(q + 3);
for (int r = 0; r < 16; r++)
{
// split into two asm blocks for gcc reject over 30 oprands :(
asm volatile(
"ld1 {v0.4s}, [%1], #16 \n"
"ld1 {v1.4s}, [%2], #16 \n"
"ld1 {v2.4s}, [%3], #16 \n"
"ld1 {v3.4s}, [%4], #16 \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"ld1 {v0.4s}, [%5], #16 \n"
"ld1 {v1.4s}, [%6], #16 \n"
"ld1 {v2.4s}, [%7], #16 \n"
"ld1 {v3.4s}, [%8], #16 \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
: "=r"(ktm2), // %0
"=r"(k00), // %1
"=r"(k01), // %2
"=r"(k02), // %3
"=r"(k03), // %4
"=r"(k10), // %5
"=r"(k11), // %6
"=r"(k12), // %7
"=r"(k13) // %8
: "0"(ktm2),
"1"(k00),
"2"(k01),
"3"(k02),
"4"(k03),
"5"(k10),
"6"(k11),
"7"(k12),
"8"(k13)
: "cc", "memory", "v0", "v1", "v2", "v3");
asm volatile(
"ld1 {v0.4s}, [%1], #16 \n"
"ld1 {v1.4s}, [%2], #16 \n"
"ld1 {v2.4s}, [%3], #16 \n"
"ld1 {v3.4s}, [%4], #16 \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"ld1 {v0.4s}, [%5], #16 \n"
"ld1 {v1.4s}, [%6], #16 \n"
"ld1 {v2.4s}, [%7], #16 \n"
"ld1 {v3.4s}, [%8], #16 \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
: "=r"(ktm2), // %0
"=r"(k20), // %1
"=r"(k21), // %2
"=r"(k22), // %3
"=r"(k23), // %4
"=r"(k30), // %5
"=r"(k31), // %6
"=r"(k32), // %7
"=r"(k33) // %8
: "0"(ktm2),
"1"(k20),
"2"(k21),
"3"(k22),
"4"(k23),
"5"(k30),
"6"(k31),
"7"(k32),
"8"(k33)
: "cc", "memory", "v0", "v1", "v2", "v3");
}
}
#endif // __ARM_NEON && __aarch64__
for (; q + 1 < inch; q += 2)
{
const float* k00 = kernel0_tm.row(q);
const float* k01 = kernel0_tm.row(q + 1);
const float* k10 = kernel1_tm.row(q);
const float* k11 = kernel1_tm.row(q + 1);
const float* k20 = kernel2_tm.row(q);
const float* k21 = kernel2_tm.row(q + 1);
const float* k30 = kernel3_tm.row(q);
const float* k31 = kernel3_tm.row(q + 1);
for (int r = 0; r < 16; r++)
{
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%1], #16 \n"
"ld1 {v1.4s}, [%2], #16 \n"
"st1 {v0.4s, v1.4s}, [%0], #32 \n"
"ld1 {v0.4s}, [%3], #16 \n"
"ld1 {v1.4s}, [%4], #16 \n"
"st1 {v0.4s, v1.4s}, [%0], #32 \n"
"ld1 {v0.4s}, [%5], #16 \n"
"ld1 {v1.4s}, [%6], #16 \n"
"st1 {v0.4s, v1.4s}, [%0], #32 \n"
"ld1 {v0.4s}, [%7], #16 \n"
"ld1 {v1.4s}, [%8], #16 \n"
"st1 {v0.4s, v1.4s}, [%0], #32 \n"
: "=r"(ktm2), // %0
"=r"(k00), // %1
"=r"(k01), // %2
"=r"(k10), // %3
"=r"(k11), // %4
"=r"(k20), // %5
"=r"(k21), // %6
"=r"(k30), // %7
"=r"(k31) // %8
: "0"(ktm2),
"1"(k00),
"2"(k01),
"3"(k10),
"4"(k11),
"5"(k20),
"6"(k21),
"7"(k30),
"8"(k31)
: "cc", "memory", "v0", "v1");
#else
asm volatile(
"vld1.f32 {d0-d1}, [%1 :128]! \n"
"vld1.f32 {d2-d3}, [%2 :128]! \n"
"vst1.f32 {d0-d3}, [%0 :128]! \n"
"vld1.f32 {d0-d1}, [%3 :128]! \n"
"vld1.f32 {d2-d3}, [%4 :128]! \n"
"vst1.f32 {d0-d3}, [%0 :128]! \n"
"vld1.f32 {d0-d1}, [%5 :128]! \n"
"vld1.f32 {d2-d3}, [%6 :128]! \n"
"vst1.f32 {d0-d3}, [%0 :128]! \n"
"vld1.f32 {d0-d1}, [%7 :128]! \n"
"vld1.f32 {d2-d3}, [%8 :128]! \n"
"vst1.f32 {d0-d3}, [%0 :128]! \n"
: "=r"(ktm2), // %0
"=r"(k00), // %1
"=r"(k01), // %2
"=r"(k10), // %3
"=r"(k11), // %4
"=r"(k20), // %5
"=r"(k21), // %6
"=r"(k30), // %7
"=r"(k31) // %8
: "0"(ktm2),
"1"(k00),
"2"(k01),
"3"(k10),
"4"(k11),
"5"(k20),
"6"(k21),
"7"(k30),
"8"(k31)
: "cc", "memory", "q0", "q1");
#endif // __aarch64__
#else
for (int m = 0; m < 4; m++)
{
ktm2[0 + m] = k00[m];
ktm2[4 + m] = k01[m];
ktm2[8 + m] = k10[m];
ktm2[12 + m] = k11[m];
ktm2[16 + m] = k20[m];
ktm2[20 + m] = k21[m];
ktm2[24 + m] = k30[m];
ktm2[28 + m] = k31[m];
}
k00 += 4;
k01 += 4;
k10 += 4;
k11 += 4;
k20 += 4;
k21 += 4;
k30 += 4;
k31 += 4;
ktm2 += 32;
#endif // __ARM_NEON
}
}
for (; q < inch; q++)
{
const float* k00 = kernel0_tm.row(q);
const float* k10 = kernel1_tm.row(q);
const float* k20 = kernel2_tm.row(q);
const float* k30 = kernel3_tm.row(q);
for (int r = 0; r < 16; r++)
{
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%1], #16 \n"
"ld1 {v1.4s}, [%2], #16 \n"
"st1 {v0.4s, v1.4s}, [%0], #32 \n"
"ld1 {v0.4s}, [%3], #16 \n"
"ld1 {v1.4s}, [%4], #16 \n"
"st1 {v0.4s, v1.4s}, [%0], #32 \n"
: "=r"(ktm2), // %0
"=r"(k00), // %1
"=r"(k10), // %2
"=r"(k20), // %3
"=r"(k30) // %4
: "0"(ktm2),
"1"(k00),
"2"(k10),
"3"(k20),
"4"(k30)
: "cc", "memory", "v0", "v1");
#else
asm volatile(
"vld1.f32 {d0-d1}, [%1 :128]! \n"
"vld1.f32 {d2-d3}, [%2 :128]! \n"
"vst1.f32 {d0-d3}, [%0 :128]! \n"
"vld1.f32 {d0-d1}, [%3 :128]! \n"
"vld1.f32 {d2-d3}, [%4 :128]! \n"
"vst1.f32 {d0-d3}, [%0 :128]! \n"
: "=r"(ktm2), // %0
"=r"(k00), // %1
"=r"(k10), // %2
"=r"(k20), // %3
"=r"(k30) // %4
: "0"(ktm2),
"1"(k00),
"2"(k10),
"3"(k20),
"4"(k30)
: "cc", "memory", "q0", "q1");
#endif // __aarch64__
#else
for (int m = 0; m < 4; m++)
{
ktm2[0 + m] = k00[m];
ktm2[4 + m] = k10[m];
ktm2[8 + m] = k20[m];
ktm2[12 + m] = k30[m];
}
k00 += 4;
k10 += 4;
k20 += 4;
k30 += 4;
ktm2 += 16;
#endif // __ARM_NEON
}
}
}
#pragma omp parallel for
for (int p = remain_outch_start; p < outch; p++)
{
float* ktm2 = (float*)kernel_tm2.channel(nn_outch) + 8 * 8 * inch * (p - remain_outch_start);
const Mat kernel0_tm = kernel_tm.channel(p);
int q = 0;
for (; q < inch; q++)
{
const float* k00 = kernel0_tm.row(q);
for (int r = 0; r < 16; r++)
{
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%1], #16 \n"
"st1 {v0.4s}, [%0], #16 \n"
: "=r"(ktm2), // %0
"=r"(k00) // %1
: "0"(ktm2),
"1"(k00)
: "cc", "memory", "v0");
#else
asm volatile(
"vld1.f32 {d0-d1}, [%1 :128]! \n"
"vst1.f32 {d0-d1}, [%0 :128]! \n"
: "=r"(ktm2), // %0
"=r"(k00) // %1
: "0"(ktm2),
"1"(k00)
: "cc", "memory", "q0");
#endif // __aarch64__
#else
for (int m = 0; m < 4; m++)
{
ktm2[m] = k00[m];
}
k00 += 4;
ktm2 += 4;
#endif // __ARM_NEON
}
}
}
kernel_tm = kernel_tm2;
}
static void conv3x3s1_winograd64_transform_kernel_neon5(const Mat& kernel, Mat& kernel_tm, int inch, int outch)
{
kernel_tm.create(8 * 8, inch, outch);
const float ktm[8][3] = {
{1.0f, 0.0f, 0.0f},
{-2.0f / 9, -2.0f / 9, -2.0f / 9},
{-2.0f / 9, 2.0f / 9, -2.0f / 9},
{1.0f / 90, 1.0f / 45, 2.0f / 45},
{1.0f / 90, -1.0f / 45, 2.0f / 45},
{1.0f / 45, 1.0f / 90, 1.0f / 180},
{1.0f / 45, -1.0f / 90, 1.0f / 180},
{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 = (const float*)kernel + p * inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel, transposed
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[8][3];
for (int i = 0; i < 8; 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];
}
// v
for (int j = 0; j < 8; j++)
{
float* tmpp = &tmp[j][0];
for (int i = 0; i < 8; i++)
{
kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// optimized layout for winograd5
// interleave weights
// Mat kernel_tm2(8*8, inch, outch);
// Mat kernel_tm2(inch, 64, outch);
#if __ARM_NEON && __aarch64__
Mat kernel_tm2(8 * 4 * (inch / 4) + 8 * (inch % 4), 64, outch / 8 + (outch % 8) / 4 + outch % 4);
#else
Mat kernel_tm2(4 * 4 * (inch / 4) + 4 * (inch % 4), 64, outch / 4 + outch % 4);
#endif
int p = 0;
#if __aarch64__
for (; p + 7 < outch; p += 8)
{
const Mat kernel0_tm = kernel_tm.channel(p);
const Mat kernel1_tm = kernel_tm.channel(p + 1);
const Mat kernel2_tm = kernel_tm.channel(p + 2);
const Mat kernel3_tm = kernel_tm.channel(p + 3);
const Mat kernel4_tm = kernel_tm.channel(p + 4);
const Mat kernel5_tm = kernel_tm.channel(p + 5);
const Mat kernel6_tm = kernel_tm.channel(p + 6);
const Mat kernel7_tm = kernel_tm.channel(p + 7);
Mat ktm2 = kernel_tm2.channel(p / 8);
for (int r = 0; r < 64; r++)
{
float* ktm2p = ktm2.row(r);
for (int q = 0; q < inch; q++)
{
const float* ktm0_0 = kernel0_tm.row(q);
const float* ktm1_0 = kernel1_tm.row(q);
const float* ktm2_0 = kernel2_tm.row(q);
const float* ktm3_0 = kernel3_tm.row(q);
const float* ktm4_0 = kernel4_tm.row(q);
const float* ktm5_0 = kernel5_tm.row(q);
const float* ktm6_0 = kernel6_tm.row(q);
const float* ktm7_0 = kernel7_tm.row(q);
ktm2p[0] = ktm0_0[r];
ktm2p[1] = ktm1_0[r];
ktm2p[2] = ktm2_0[r];
ktm2p[3] = ktm3_0[r];
ktm2p[4] = ktm4_0[r];
ktm2p[5] = ktm5_0[r];
ktm2p[6] = ktm6_0[r];
ktm2p[7] = ktm7_0[r];
ktm2p += 8;
}
}
}
#endif // __aarch64__
for (; p + 3 < outch; p += 4)
{
const Mat kernel0_tm = kernel_tm.channel(p);
const Mat kernel1_tm = kernel_tm.channel(p + 1);
const Mat kernel2_tm = kernel_tm.channel(p + 2);
const Mat kernel3_tm = kernel_tm.channel(p + 3);
#if __ARM_NEON && __aarch64__
Mat ktm2 = kernel_tm2.channel(p / 8 + (p % 8) / 4);
#else
Mat ktm2 = kernel_tm2.channel(p / 4);
#endif
for (int r = 0; r < 64; r++)
{
float* ktm2p = ktm2.row(r);
for (int q = 0; q < inch; q++)
{
const float* ktm0_0 = kernel0_tm.row(q);
const float* ktm1_0 = kernel1_tm.row(q);
const float* ktm2_0 = kernel2_tm.row(q);
const float* ktm3_0 = kernel3_tm.row(q);
ktm2p[0] = ktm0_0[r];
ktm2p[1] = ktm1_0[r];
ktm2p[2] = ktm2_0[r];
ktm2p[3] = ktm3_0[r];
ktm2p += 4;
}
}
}
for (; p < outch; p++)
{
const Mat kernel0_tm = kernel_tm.channel(p);
#if __ARM_NEON && __aarch64__
Mat ktm2 = kernel_tm2.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
Mat ktm2 = kernel_tm2.channel(p / 4 + p % 4);
#endif
for (int r = 0; r < 64; r++)
{
float* ktm2p = ktm2.row(r);
for (int q = 0; q < inch; q++)
{
const float* ktm0_0 = kernel0_tm.row(q);
ktm2p[0] = ktm0_0[r];
ktm2p += 1;
}
}
}
kernel_tm = kernel_tm2;
}
static void conv3x3s1_winograd64_neon4(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 6n+2
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 5) / 6 * 6;
outh = (outh + 5) / 6 * 6;
w = outw + 2;
h = outh + 2;
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b);
const float* bias = _bias;
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
bottom_blob_tm.create(4, 16 * w_tm / 8 * h_tm / 8, inch, 4u, opt.workspace_allocator);
const int tiles = w_tm / 8 * h_tm / 8;
// const float itm[8][8] = {
// {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f},
//
// {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f},
// {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f},
//
// {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f},
// {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f},
//
// {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f},
// {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f},
//
// {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f}
// };
// 0 = r00 - r06 + (r04 - r02) * 5.25
// 7 = r07 - r01 + (r03 - r05) * 5.25
// 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05)
// 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05)
// 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// reuse r04 * 1.25
// reuse r03 * 2.5
// 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5)
// 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5)
#if __ARM_NEON
const float coeff[8] = {
0.25f, 0.5f, -1.25f, 2.f,
-2.5f, 4.f, 4.25f, 5.25f
};
float32x4_t _coeff0 = vld1q_f32(coeff);
float32x4_t _coeff1 = vld1q_f32(coeff + 4);
#endif // __ARM_NEON
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < inch; q++)
{
const Mat img0 = bottom_blob_bordered.channel(q);
Mat img0_tm = bottom_blob_tm.channel(q);
float tmp[8][8];
// tile
for (int i = 0; i < h_tm / 8; i++)
{
for (int j = 0; j < w_tm / 8; j++)
{
#if __ARM_NEON
const float* r0 = img0.row(i * 6) + j * 6;
const float* r1 = r0 + w;
const float* r2 = r0 + w * 2;
const float* r3 = r0 + w * 3;
// the assembly block for armv7 input transform requires 13 general registers
// old gcc may fail to allocate register on debug build without -fomit-frame-pointer
// so, fallback to intrinsic version for armv7 debug build --- nihui
#if __aarch64__ || !defined(NDEBUG)
for (int m = 0; m + 3 < 8; m += 4)
{
float32x4_t _r0_0123 = vld1q_f32(r0);
float32x4_t _r0_4567 = vld1q_f32(r0 + 4);
float32x4_t _r1_0123 = vld1q_f32(r1);
float32x4_t _r1_4567 = vld1q_f32(r1 + 4);
float32x4_t _r2_0123 = vld1q_f32(r2);
float32x4_t _r2_4567 = vld1q_f32(r2 + 4);
float32x4_t _r3_0123 = vld1q_f32(r3);
float32x4_t _r3_4567 = vld1q_f32(r3 + 4);
float32x4x2_t _r01_00221133 = vtrnq_f32(_r0_0123, _r1_0123);
float32x4x2_t _r01_44665577 = vtrnq_f32(_r0_4567, _r1_4567);
float32x4x2_t _r23_00221133 = vtrnq_f32(_r2_0123, _r3_0123);
float32x4x2_t _r23_44665577 = vtrnq_f32(_r2_4567, _r3_4567);
// no vswp intrinsic :(
float32x4_t _r_00 = vcombine_f32(vget_low_f32(_r01_00221133.val[0]), vget_low_f32(_r23_00221133.val[0]));
float32x4_t _r_11 = vcombine_f32(vget_low_f32(_r01_00221133.val[1]), vget_low_f32(_r23_00221133.val[1]));
float32x4_t _r_22 = vcombine_f32(vget_high_f32(_r01_00221133.val[0]), vget_high_f32(_r23_00221133.val[0]));
float32x4_t _r_33 = vcombine_f32(vget_high_f32(_r01_00221133.val[1]), vget_high_f32(_r23_00221133.val[1]));
float32x4_t _r_44 = vcombine_f32(vget_low_f32(_r01_44665577.val[0]), vget_low_f32(_r23_44665577.val[0]));
float32x4_t _r_55 = vcombine_f32(vget_low_f32(_r01_44665577.val[1]), vget_low_f32(_r23_44665577.val[1]));
float32x4_t _r_66 = vcombine_f32(vget_high_f32(_r01_44665577.val[0]), vget_high_f32(_r23_44665577.val[0]));
float32x4_t _r_77 = vcombine_f32(vget_high_f32(_r01_44665577.val[1]), vget_high_f32(_r23_44665577.val[1]));
float32x4_t _r_0_m_6 = vsubq_f32(_r_00, _r_66);
float32x4_t _r_7_m_1 = vsubq_f32(_r_77, _r_11);
float32x4_t _r_4_m_2 = vsubq_f32(_r_44, _r_22);
float32x4_t _r_3_m_5 = vsubq_f32(_r_33, _r_55);
float32x4_t _tmp0 = vmlaq_lane_f32(_r_0_m_6, _r_4_m_2, vget_high_f32(_coeff1), 1);
float32x4_t _tmp7 = vmlaq_lane_f32(_r_7_m_1, _r_3_m_5, vget_high_f32(_coeff1), 1);
vst1q_f32(&tmp[0][m], _tmp0);
vst1q_f32(&tmp[7][m], _tmp7);
float32x4_t _r_2_a_6 = vaddq_f32(_r_22, _r_66);
float32x4_t _r_1_a_5 = vaddq_f32(_r_11, _r_55);
float32x4_t _tmp12a = vmlsq_lane_f32(_r_2_a_6, _r_44, vget_high_f32(_coeff1), 0);
float32x4_t _tmp12b = vmlsq_lane_f32(_r_1_a_5, _r_33, vget_high_f32(_coeff1), 0);
float32x4_t _tmp1 = vaddq_f32(_tmp12a, _tmp12b);
float32x4_t _tmp2 = vsubq_f32(_tmp12a, _tmp12b);
vst1q_f32(&tmp[1][m], _tmp1);
vst1q_f32(&tmp[2][m], _tmp2);
float32x4_t _r_4_x_c = vmulq_lane_f32(_r_44, vget_high_f32(_coeff0), 0);
float32x4_t _r_3_x_c = vmulq_lane_f32(_r_33, vget_low_f32(_coeff1), 0);
float32x4_t _tmp34a = vaddq_f32(_r_66, _r_4_x_c);
_tmp34a = vmlaq_lane_f32(_tmp34a, _r_22, vget_low_f32(_coeff0), 0);
float32x4_t _tmp34b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_low_f32(_coeff0), 1);
_tmp34b = vmlaq_lane_f32(_tmp34b, _r_55, vget_high_f32(_coeff0), 1);
float32x4_t _tmp3 = vaddq_f32(_tmp34a, _tmp34b);
float32x4_t _tmp4 = vsubq_f32(_tmp34a, _tmp34b);
vst1q_f32(&tmp[3][m], _tmp3);
vst1q_f32(&tmp[4][m], _tmp4);
// reuse r04 * 1.25
// reuse r03 * 2.5
float32x4_t _r_2_a_4c = vaddq_f32(_r_22, _r_4_x_c);
float32x4_t _tmp56a = vmlaq_lane_f32(_r_66, _r_2_a_4c, vget_low_f32(_coeff1), 1);
float32x4_t _tmp56b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_high_f32(_coeff0), 1);
_tmp56b = vmlaq_lane_f32(_tmp56b, _r_55, vget_low_f32(_coeff0), 1);
float32x4_t _tmp5 = vaddq_f32(_tmp56a, _tmp56b);
float32x4_t _tmp6 = vsubq_f32(_tmp56a, _tmp56b);
vst1q_f32(&tmp[5][m], _tmp5);
vst1q_f32(&tmp[6][m], _tmp6);
r0 += w * 4;
r1 += w * 4;
r2 += w * 4;
r3 += w * 4;
}
const float* t0 = tmp[0];
const float* t1 = tmp[1];
const float* t2 = tmp[2];
const float* t3 = tmp[3];
float* r0_tm0_0 = img0_tm.row(i * w_tm / 8 + j);
float* r0_tm0_4 = img0_tm.row(i * w_tm / 8 + j + tiles);
float* r0_tm1_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 2);
float* r0_tm1_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 3);
float* r0_tm2_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 4);
float* r0_tm2_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 5);
float* r0_tm3_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 6);
float* r0_tm3_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 7);
for (int m = 0; m + 3 < 8; m += 4)
{
float32x4_t _t0_0123 = vld1q_f32(t0);
float32x4_t _t0_4567 = vld1q_f32(t0 + 4);
float32x4_t _t1_0123 = vld1q_f32(t1);
float32x4_t _t1_4567 = vld1q_f32(t1 + 4);
float32x4_t _t2_0123 = vld1q_f32(t2);
float32x4_t _t2_4567 = vld1q_f32(t2 + 4);
float32x4_t _t3_0123 = vld1q_f32(t3);
float32x4_t _t3_4567 = vld1q_f32(t3 + 4);
float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123);
float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567);
float32x4x2_t _t23_00221133 = vtrnq_f32(_t2_0123, _t3_0123);
float32x4x2_t _t23_44665577 = vtrnq_f32(_t2_4567, _t3_4567);
// no vswp intrinsic :(
float32x4_t _t_00 = vcombine_f32(vget_low_f32(_t01_00221133.val[0]), vget_low_f32(_t23_00221133.val[0]));
float32x4_t _t_11 = vcombine_f32(vget_low_f32(_t01_00221133.val[1]), vget_low_f32(_t23_00221133.val[1]));
float32x4_t _t_22 = vcombine_f32(vget_high_f32(_t01_00221133.val[0]), vget_high_f32(_t23_00221133.val[0]));
float32x4_t _t_33 = vcombine_f32(vget_high_f32(_t01_00221133.val[1]), vget_high_f32(_t23_00221133.val[1]));
float32x4_t _t_44 = vcombine_f32(vget_low_f32(_t01_44665577.val[0]), vget_low_f32(_t23_44665577.val[0]));
float32x4_t _t_55 = vcombine_f32(vget_low_f32(_t01_44665577.val[1]), vget_low_f32(_t23_44665577.val[1]));
float32x4_t _t_66 = vcombine_f32(vget_high_f32(_t01_44665577.val[0]), vget_high_f32(_t23_44665577.val[0]));
float32x4_t _t_77 = vcombine_f32(vget_high_f32(_t01_44665577.val[1]), vget_high_f32(_t23_44665577.val[1]));
float32x4_t _t_0_m_6 = vsubq_f32(_t_00, _t_66);
float32x4_t _t_7_m_1 = vsubq_f32(_t_77, _t_11);
float32x4_t _t_4_m_2 = vsubq_f32(_t_44, _t_22);
float32x4_t _t_3_m_5 = vsubq_f32(_t_33, _t_55);
float32x4_t _r0_tm_0_0 = vmlaq_lane_f32(_t_0_m_6, _t_4_m_2, vget_high_f32(_coeff1), 1);
float32x4_t _r0_tm_4_3 = vmlaq_lane_f32(_t_7_m_1, _t_3_m_5, vget_high_f32(_coeff1), 1);
r0_tm0_0[0] = vgetq_lane_f32(_r0_tm_0_0, 0);
r0_tm1_0[0] = vgetq_lane_f32(_r0_tm_0_0, 1);
r0_tm2_0[0] = vgetq_lane_f32(_r0_tm_0_0, 2);
r0_tm3_0[0] = vgetq_lane_f32(_r0_tm_0_0, 3);
r0_tm0_4[3] = vgetq_lane_f32(_r0_tm_4_3, 0);
r0_tm1_4[3] = vgetq_lane_f32(_r0_tm_4_3, 1);
r0_tm2_4[3] = vgetq_lane_f32(_r0_tm_4_3, 2);
r0_tm3_4[3] = vgetq_lane_f32(_r0_tm_4_3, 3);
float32x4_t _t_2_m_6 = vaddq_f32(_t_22, _t_66);
float32x4_t _t_1_m_5 = vaddq_f32(_t_11, _t_55);
float32x4_t _tmp12a = vmlsq_lane_f32(_t_2_m_6, _t_44, vget_high_f32(_coeff1), 0);
float32x4_t _tmp12b = vmlsq_lane_f32(_t_1_m_5, _t_33, vget_high_f32(_coeff1), 0);
float32x4_t _r0_tm_0_1 = vaddq_f32(_tmp12a, _tmp12b);
float32x4_t _r0_tm_0_2 = vsubq_f32(_tmp12a, _tmp12b);
r0_tm0_0[1] = vgetq_lane_f32(_r0_tm_0_1, 0);
r0_tm1_0[1] = vgetq_lane_f32(_r0_tm_0_1, 1);
r0_tm2_0[1] = vgetq_lane_f32(_r0_tm_0_1, 2);
r0_tm3_0[1] = vgetq_lane_f32(_r0_tm_0_1, 3);
r0_tm0_0[2] = vgetq_lane_f32(_r0_tm_0_2, 0);
r0_tm1_0[2] = vgetq_lane_f32(_r0_tm_0_2, 1);
r0_tm2_0[2] = vgetq_lane_f32(_r0_tm_0_2, 2);
r0_tm3_0[2] = vgetq_lane_f32(_r0_tm_0_2, 3);
float32x4_t _t_4_x_c = vmulq_lane_f32(_t_44, vget_high_f32(_coeff0), 0);
float32x4_t _t_3_x_c = vmulq_lane_f32(_t_33, vget_low_f32(_coeff1), 0);
float32x4_t _tmp34a = vaddq_f32(_t_66, _t_4_x_c);
_tmp34a = vmlaq_lane_f32(_tmp34a, _t_22, vget_low_f32(_coeff0), 0);
float32x4_t _tmp34b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_low_f32(_coeff0), 1);
_tmp34b = vmlaq_lane_f32(_tmp34b, _t_55, vget_high_f32(_coeff0), 1);
float32x4_t _r0_tm_0_3 = vaddq_f32(_tmp34a, _tmp34b);
float32x4_t _r0_tm_4_0 = vsubq_f32(_tmp34a, _tmp34b);
r0_tm0_0[3] = vgetq_lane_f32(_r0_tm_0_3, 0);
r0_tm1_0[3] = vgetq_lane_f32(_r0_tm_0_3, 1);
r0_tm2_0[3] = vgetq_lane_f32(_r0_tm_0_3, 2);
r0_tm3_0[3] = vgetq_lane_f32(_r0_tm_0_3, 3);
r0_tm0_4[0] = vgetq_lane_f32(_r0_tm_4_0, 0);
r0_tm1_4[0] = vgetq_lane_f32(_r0_tm_4_0, 1);
r0_tm2_4[0] = vgetq_lane_f32(_r0_tm_4_0, 2);
r0_tm3_4[0] = vgetq_lane_f32(_r0_tm_4_0, 3);
float32x4_t _t_2_a_4c = vaddq_f32(_t_22, _t_4_x_c);
float32x4_t _tmp56a = vmlaq_lane_f32(_t_66, _t_2_a_4c, vget_low_f32(_coeff1), 1);
float32x4_t _tmp56b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_high_f32(_coeff0), 1);
_tmp56b = vmlaq_lane_f32(_tmp56b, _t_55, vget_low_f32(_coeff0), 1);
float32x4_t _r0_tm_4_1 = vaddq_f32(_tmp56a, _tmp56b);
float32x4_t _r0_tm_4_2 = vsubq_f32(_tmp56a, _tmp56b);
r0_tm0_4[1] = vgetq_lane_f32(_r0_tm_4_1, 0);
r0_tm1_4[1] = vgetq_lane_f32(_r0_tm_4_1, 1);
r0_tm2_4[1] = vgetq_lane_f32(_r0_tm_4_1, 2);
r0_tm3_4[1] = vgetq_lane_f32(_r0_tm_4_1, 3);
r0_tm0_4[2] = vgetq_lane_f32(_r0_tm_4_2, 0);
r0_tm1_4[2] = vgetq_lane_f32(_r0_tm_4_2, 1);
r0_tm2_4[2] = vgetq_lane_f32(_r0_tm_4_2, 2);
r0_tm3_4[2] = vgetq_lane_f32(_r0_tm_4_2, 3);
t0 += 8 * 4;
t1 += 8 * 4;
t2 += 8 * 4;
t3 += 8 * 4;
r0_tm0_0 += img0_tm.w * tiles * 2 * 4;
r0_tm0_4 += img0_tm.w * tiles * 2 * 4;
r0_tm1_0 += img0_tm.w * tiles * 2 * 4;
r0_tm1_4 += img0_tm.w * tiles * 2 * 4;
r0_tm2_0 += img0_tm.w * tiles * 2 * 4;
r0_tm2_4 += img0_tm.w * tiles * 2 * 4;
r0_tm3_0 += img0_tm.w * tiles * 2 * 4;
r0_tm3_4 += img0_tm.w * tiles * 2 * 4;
}
#else // __aarch64__
float* t0 = tmp[0];
float* t1 = tmp[1];
float* t2 = tmp[2];
float* t3 = tmp[3];
float* t4 = tmp[4];
float* t5 = tmp[5];
float* t6 = tmp[6];
float* t7 = tmp[7];
int stepw = w * 4 * 4;
asm volatile(
// loop0
"vld1.f32 {d16-d19}, [%8], %26 \n"
"vld1.f32 {d20-d23}, [%9], %26 \n"
"vld1.f32 {d24-d27}, [%10], %26 \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11], %26 \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4-d5}, [%0]! \n" // tmp[0][m]
"vmov q3, q7 \n" // use q7
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16-d17}, [%1]! \n" // tmp[1][m]
"vmla.f32 q4, q6, %e25[1] \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18-d19}, [%2]! \n" // tmp[2][m]
"vadd.f32 q8, q2, q3 \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vadd.f32 q2, q4, q5 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d16-d17}, [%3]! \n" // tmp[3][m]
"vst1.f32 {d18-d19}, [%4]! \n" // tmp[4][m]
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d4-d5}, [%5]! \n" // tmp[5][m]
"vst1.f32 {d6-d7}, [%6]! \n" // tmp[6][m]
"vst1.f32 {d12-d13}, [%7]! \n" // tmp[7][m]
// loop1
"vld1.f32 {d16-d19}, [%8] \n"
"vld1.f32 {d20-d23}, [%9] \n"
"vld1.f32 {d24-d27}, [%10] \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11] \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4-d5}, [%0]! \n" // tmp[0][m]
"vmov q3, q7 \n" // use q7
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16-d17}, [%1]! \n" // tmp[1][m]
"vmla.f32 q4, q6, %e25[1] \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18-d19}, [%2]! \n" // tmp[2][m]
"vadd.f32 q8, q2, q3 \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vadd.f32 q2, q4, q5 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d16-d17}, [%3]! \n" // tmp[3][m]
"vst1.f32 {d18-d19}, [%4]! \n" // tmp[4][m]
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d4-d5}, [%5]! \n" // tmp[5][m]
"vst1.f32 {d6-d7}, [%6]! \n" // tmp[6][m]
"vst1.f32 {d12-d13}, [%7]! \n" // tmp[7][m]
: "=r"(t0), // %0
"=r"(t1), // %1
"=r"(t2), // %2
"=r"(t3), // %3
"=r"(t4), // %4
"=r"(t5), // %5
"=r"(t6), // %6
"=r"(t7), // %7
"=r"(r0), // %8
"=r"(r1), // %9
"=r"(r2), // %10
"=r"(r3) // %11
: "0"(t0),
"1"(t1),
"2"(t2),
"3"(t3),
"4"(t4),
"5"(t5),
"6"(t6),
"7"(t7),
"8"(r0),
"9"(r1),
"10"(r2),
"11"(r3),
"w"(_coeff0), // %24
"w"(_coeff1), // %25
"r"(stepw) // %26
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
t0 = tmp[0];
t1 = tmp[1];
t2 = tmp[2];
t3 = tmp[3];
float* r0_tm0_0 = img0_tm.row(i * w_tm / 8 + j);
float* r0_tm0_4 = img0_tm.row(i * w_tm / 8 + j + tiles);
float* r0_tm1_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 2);
float* r0_tm1_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 3);
float* r0_tm2_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 4);
float* r0_tm2_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 5);
float* r0_tm3_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 6);
float* r0_tm3_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 7);
int step = img0_tm.w * tiles * 2 * 4 * 4;
asm volatile(
// loop0
"vld1.f32 {d16-d19}, [%8] \n"
"add %8, %8, #128 \n"
"vld1.f32 {d20-d23}, [%9] \n"
"add %9, %9, #128 \n"
"vld1.f32 {d24-d27}, [%10] \n"
"add %10, %10, #128 \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11] \n"
"add %11, %11, #128 \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4[0]}, [%0]! \n"
"vst1.f32 {d4[1]}, [%2]! \n"
"vmov q3, q7 \n" // use q7
"vst1.f32 {d5[0]}, [%4]! \n"
"vst1.f32 {d5[1]}, [%6]! \n"
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16[0]}, [%0]! \n"
"vst1.f32 {d16[1]}, [%2]! \n"
"vmla.f32 q4, q6, %e25[1] \n"
"vst1.f32 {d17[0]}, [%4]! \n"
"vst1.f32 {d17[1]}, [%6]! \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18[0]}, [%0]! \n"
"vst1.f32 {d18[1]}, [%2]! \n"
"vadd.f32 q8, q2, q3 \n"
"vst1.f32 {d19[0]}, [%4]! \n"
"vst1.f32 {d19[1]}, [%6]! \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vadd.f32 q2, q4, q5 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d16[0]}, [%0], %26 \n"
"vst1.f32 {d16[1]}, [%2], %26 \n"
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d17[0]}, [%4], %26 \n"
"vst1.f32 {d17[1]}, [%6], %26 \n"
"vtrn.32 q9, q2 \n"
"vtrn.32 q3, q6 \n"
"sub %0, %0, #12 \n"
"sub %2, %2, #12 \n"
"sub %4, %4, #12 \n"
"sub %6, %6, #12 \n"
"vswp d19, d6 \n"
"vswp d5, d12 \n"
"vst1.f32 {d18-d19}, [%1], %26 \n"
"vst1.f32 {d4-d5}, [%3], %26 \n"
"vst1.f32 {d6-d7}, [%5], %26 \n"
"vst1.f32 {d12-d13}, [%7], %26 \n"
// loop1
"vld1.f32 {d16-d19}, [%8] \n"
"vld1.f32 {d20-d23}, [%9] \n"
"vld1.f32 {d24-d27}, [%10] \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11] \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4[0]}, [%0]! \n"
"vst1.f32 {d4[1]}, [%2]! \n"
"vmov q3, q7 \n" // use q7
"vst1.f32 {d5[0]}, [%4]! \n"
"vst1.f32 {d5[1]}, [%6]! \n"
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16[0]}, [%0]! \n"
"vst1.f32 {d16[1]}, [%2]! \n"
"vmla.f32 q4, q6, %e25[1] \n"
"vst1.f32 {d17[0]}, [%4]! \n"
"vst1.f32 {d17[1]}, [%6]! \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18[0]}, [%0]! \n"
"vst1.f32 {d18[1]}, [%2]! \n"
"vadd.f32 q8, q2, q3 \n"
"vst1.f32 {d19[0]}, [%4]! \n"
"vst1.f32 {d19[1]}, [%6]! \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vadd.f32 q2, q4, q5 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d16[0]}, [%0] \n"
"vst1.f32 {d16[1]}, [%2] \n"
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d17[0]}, [%4] \n"
"vst1.f32 {d17[1]}, [%6] \n"
"vtrn.32 q9, q2 \n"
"vtrn.32 q3, q6 \n"
"vswp d19, d6 \n"
"vswp d5, d12 \n"
"vst1.f32 {d18-d19}, [%1] \n"
"vst1.f32 {d4-d5}, [%3] \n"
"vst1.f32 {d6-d7}, [%5] \n"
"vst1.f32 {d12-d13}, [%7] \n"
: "=r"(r0_tm0_0), // %0
"=r"(r0_tm0_4), // %1
"=r"(r0_tm1_0), // %2
"=r"(r0_tm1_4), // %3
"=r"(r0_tm2_0), // %4
"=r"(r0_tm2_4), // %5
"=r"(r0_tm3_0), // %6
"=r"(r0_tm3_4), // %7
"=r"(t0), // %8
"=r"(t1), // %9
"=r"(t2), // %10
"=r"(t3) // %11
: "0"(r0_tm0_0),
"1"(r0_tm0_4),
"2"(r0_tm1_0),
"3"(r0_tm1_4),
"4"(r0_tm2_0),
"5"(r0_tm2_4),
"6"(r0_tm3_0),
"7"(r0_tm3_4),
"8"(t0),
"9"(t1),
"10"(t2),
"11"(t3),
"w"(_coeff0), // %24
"w"(_coeff1), // %25
"r"(step) // %26
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
const float* r0 = img0.row(i * 6) + j * 6;
for (int m = 0; m < 8; m++)
{
tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25f;
tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25f;
float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25f);
float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25f);
tmp[1][m] = tmp12a + tmp12b;
tmp[2][m] = tmp12a - tmp12b;
float tmp34a = (r0[6] + r0[2] * 0.25f - r0[4] * 1.25f);
float tmp34b = (r0[1] * 0.5f - r0[3] * 2.5f + r0[5] * 2.f);
tmp[3][m] = tmp34a + tmp34b;
tmp[4][m] = tmp34a - tmp34b;
float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25f) * 4.f);
float tmp56b = (r0[1] * 2.f - r0[3] * 2.5f + r0[5] * 0.5f);
tmp[5][m] = tmp56a + tmp56b;
tmp[6][m] = tmp56a - tmp56b;
r0 += w;
}
float* r0_tm_0 = img0_tm.row(i * w_tm / 8 + j);
float* r0_tm_4 = img0_tm.row(i * w_tm / 8 + j + tiles);
for (int m = 0; m < 8; m++)
{
const float* tmp0 = tmp[m];
r0_tm_0[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25f;
r0_tm_4[3] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25f;
float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25f);
float tmp12b = (tmp0[1] - tmp0[3] * 4.25f + tmp0[5]);
r0_tm_0[1] = tmp12a + tmp12b;
r0_tm_0[2] = tmp12a - tmp12b;
float tmp34a = (tmp0[6] + tmp0[2] * 0.25f - tmp0[4] * 1.25f);
float tmp34b = (tmp0[1] * 0.5f - tmp0[3] * 2.5f + tmp0[5] * 2.f);
r0_tm_0[3] = tmp34a + tmp34b;
r0_tm_4[0] = tmp34a - tmp34b;
float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25f) * 4.f);
float tmp56b = (tmp0[1] * 2.f - tmp0[3] * 2.5f + tmp0[5] * 0.5f);
r0_tm_4[1] = tmp56a + tmp56b;
r0_tm_4[2] = tmp56a - tmp56b;
r0_tm_0 += img0_tm.w * tiles * 2;
r0_tm_4 += img0_tm.w * tiles * 2;
}
#endif // __ARM_NEON
}
}
}
}
bottom_blob_bordered = Mat();
// END transform input
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
top_blob_tm.create(4, 16 * w_tm / 8 * h_tm / 8, outch, 4u, opt.workspace_allocator);
const int tiles = h_tm / 8 * w_tm / 8;
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 4;
Mat out0_tm = top_blob_tm.channel(p);
Mat out1_tm = top_blob_tm.channel(p + 1);
Mat out2_tm = top_blob_tm.channel(p + 2);
Mat out3_tm = top_blob_tm.channel(p + 3);
const float* ktm = kernel_tm.channel(pp);
out0_tm.fill(0.f);
out1_tm.fill(0.f);
out2_tm.fill(0.f);
out3_tm.fill(0.f);
int q = 0;
#if __ARM_NEON && __aarch64__
for (; q + 3 < inch; q += 4)
{
const float* r0 = bottom_blob_tm.channel(q);
const float* r1 = bottom_blob_tm.channel(q + 1);
const float* r2 = bottom_blob_tm.channel(q + 2);
const float* r3 = bottom_blob_tm.channel(q + 3);
float* output0_tm = out0_tm;
float* output1_tm = out1_tm;
float* output2_tm = out2_tm;
float* output3_tm = out3_tm;
asm volatile(
"mov w0, #16 \n" // w0 = r = 16
"0: \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%8], #64 \n" // v0 v1 v2 v3 = _k00 _k01 _k02 _k03
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%8], #64 \n" // v4 v5 v6 v7 = _k10 _k11 _k12 _k13
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n" // v8 v9 v10 v11 = _k20 _k21 _k22 _k23
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%8], #64 \n" // v12 v13 v14 v15 = _k30 _k31 _k32 _k33
// tile loop
"lsr w1, %w18, #2 \n" // w1 = nn = tiles >> 2
"cmp w1, #0 \n"
"beq 2f \n"
//BEGIN tile loop
"prfm pldl1keep, [%4, #128] \n" //
"ld1 {v16.4s}, [%4], #16 \n"
"1: \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v20.4s}, [%0] \n"
"add x4, %0, #16 \n" // x4 = %0 next
"fmla v20.4s, v16.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v21.4s}, [%1] \n"
"add x5, %1, #16 \n" // x5 = %1 next
"fmla v21.4s, v16.4s, v4.4s \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v22.4s}, [%2] \n"
"add x6, %2, #16 \n" // x6 = %2 next
"fmla v22.4s, v16.4s, v8.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v23.4s}, [%3] \n"
"add x7, %3, #16 \n" // x7 = %3 next
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v17.4s}, [%5], #16 \n"
"fmla v23.4s, v16.4s, v12.4s \n"
"prfm pldl1keep, [x4, #128] \n"
"ld1 {v24.4s}, [x4] \n"
"fmla v20.4s, v17.4s, v1.4s \n"
"fmla v21.4s, v17.4s, v5.4s \n"
"prfm pldl1keep, [%6, #128] \n"
"ld1 {v18.4s}, [%6], #16 \n"
"fmla v22.4s, v17.4s, v9.4s \n"
"fmla v23.4s, v17.4s, v13.4s \n"
"prfm pldl1keep, [x5, #128] \n"
"ld1 {v25.4s}, [x5] \n"
"fmla v20.4s, v18.4s, v2.4s \n"
"fmla v21.4s, v18.4s, v6.4s \n"
"prfm pldl1keep, [%7, #128] \n"
"ld1 {v19.4s}, [%7], #16 \n"
"fmla v22.4s, v18.4s, v10.4s \n"
"fmla v23.4s, v18.4s, v14.4s \n"
"prfm pldl1keep, [x6, #128] \n"
"ld1 {v26.4s}, [x6] \n"
"fmla v20.4s, v19.4s, v3.4s \n"
"fmla v21.4s, v19.4s, v7.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v16.4s}, [%4], #16 \n"
"fmla v22.4s, v19.4s, v11.4s \n"
"fmla v23.4s, v19.4s, v15.4s \n"
///////
"prfm pldl1keep, [x7, #128] \n"
"ld1 {v27.4s}, [x7] \n"
"st1 {v20.4s}, [%0] \n"
"add %0, %0, #32 \n"
"fmla v24.4s, v16.4s, v0.4s \n"
"fmla v25.4s, v16.4s, v4.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v17.4s}, [%5], #16 \n"
"fmla v26.4s, v16.4s, v8.4s \n"
"fmla v27.4s, v16.4s, v12.4s \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v20.4s}, [%0] \n"
"st1 {v21.4s}, [%1] \n"
"add %1, %1, #32 \n"
"fmla v24.4s, v17.4s, v1.4s \n"
"fmla v25.4s, v17.4s, v5.4s \n"
"prfm pldl1keep, [%6, #128] \n"
"ld1 {v18.4s}, [%6], #16 \n"
"fmla v26.4s, v17.4s, v9.4s \n"
"fmla v27.4s, v17.4s, v13.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v21.4s}, [%1] \n"
"st1 {v22.4s}, [%2] \n"
"add %2, %2, #32 \n"
"fmla v24.4s, v18.4s, v2.4s \n"
"fmla v25.4s, v18.4s, v6.4s \n"
"prfm pldl1keep, [%7, #128] \n"
"ld1 {v19.4s}, [%7], #16 \n"
"fmla v26.4s, v18.4s, v10.4s \n"
"fmla v27.4s, v18.4s, v14.4s \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v22.4s}, [%2] \n"
"st1 {v23.4s}, [%3] \n"
"add %3, %3, #32 \n"
"fmla v24.4s, v19.4s, v3.4s \n"
"fmla v25.4s, v19.4s, v7.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v16.4s}, [%4], #16 \n"
"fmla v26.4s, v19.4s, v11.4s \n"
"fmla v27.4s, v19.4s, v15.4s \n"
///////
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v23.4s}, [%3] \n"
"st1 {v24.4s}, [x4] \n"
"add x4, x4, #32 \n"
"fmla v20.4s, v16.4s, v0.4s \n"
"fmla v21.4s, v16.4s, v4.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v17.4s}, [%5], #16 \n"
"fmla v22.4s, v16.4s, v8.4s \n"
"fmla v23.4s, v16.4s, v12.4s \n"
"prfm pldl1keep, [x4, #128] \n"
"ld1 {v24.4s}, [x4] \n"
"st1 {v25.4s}, [x5] \n"
"add x5, x5, #32 \n"
"fmla v20.4s, v17.4s, v1.4s \n"
"fmla v21.4s, v17.4s, v5.4s \n"
"prfm pldl1keep, [%6, #128] \n"
"ld1 {v18.4s}, [%6], #16 \n"
"fmla v22.4s, v17.4s, v9.4s \n"
"fmla v23.4s, v17.4s, v13.4s \n"
"prfm pldl1keep, [x5, #128] \n"
"ld1 {v25.4s}, [x5] \n"
"st1 {v26.4s}, [x6] \n"
"add x6, x6, #32 \n"
"fmla v20.4s, v18.4s, v2.4s \n"
"fmla v21.4s, v18.4s, v6.4s \n"
"prfm pldl1keep, [%7, #128] \n"
"ld1 {v19.4s}, [%7], #16 \n"
"fmla v22.4s, v18.4s, v10.4s \n"
"fmla v23.4s, v18.4s, v14.4s \n"
"prfm pldl1keep, [x6, #128] \n"
"ld1 {v26.4s}, [x6] \n"
"st1 {v27.4s}, [x7] \n"
"add x7, x7, #32 \n"
"fmla v20.4s, v19.4s, v3.4s \n"
"fmla v21.4s, v19.4s, v7.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v16.4s}, [%4], #16 \n"
"fmla v22.4s, v19.4s, v11.4s \n"
"fmla v23.4s, v19.4s, v15.4s \n"
///////
"prfm pldl1keep, [x7, #128] \n"
"ld1 {v27.4s}, [x7] \n"
"st1 {v20.4s}, [%0] \n"
"fmla v24.4s, v16.4s, v0.4s \n"
"fmla v25.4s, v16.4s, v4.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v17.4s}, [%5], #16 \n"
"fmla v26.4s, v16.4s, v8.4s \n"
"fmla v27.4s, v16.4s, v12.4s \n"
"st1 {v21.4s}, [%1] \n"
"fmla v24.4s, v17.4s, v1.4s \n"
"fmla v25.4s, v17.4s, v5.4s \n"
"prfm pldl1keep, [%6, #128] \n"
"ld1 {v18.4s}, [%6], #16 \n"
"fmla v26.4s, v17.4s, v9.4s \n"
"fmla v27.4s, v17.4s, v13.4s \n"
"st1 {v22.4s}, [%2] \n"
"fmla v24.4s, v18.4s, v2.4s \n"
"fmla v25.4s, v18.4s, v6.4s \n"
"prfm pldl1keep, [%7, #128] \n"
"ld1 {v19.4s}, [%7], #16 \n"
"fmla v26.4s, v18.4s, v10.4s \n"
"fmla v27.4s, v18.4s, v14.4s \n"
"st1 {v23.4s}, [%3] \n"
"fmla v24.4s, v19.4s, v3.4s \n"
"fmla v25.4s, v19.4s, v7.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v16.4s}, [%4], #16 \n"
"fmla v26.4s, v19.4s, v11.4s \n"
"fmla v27.4s, v19.4s, v15.4s \n"
"st1 {v24.4s}, [x4], #16 \n"
"mov %0, x4 \n"
"st1 {v25.4s}, [x5], #16 \n"
"mov %1, x5 \n"
"subs w1, w1, #1 \n"
"st1 {v26.4s}, [x6], #16 \n"
"mov %2, x6 \n"
"st1 {v27.4s}, [x7], #16 \n"
"mov %3, x7 \n"
"bne 1b \n"
"sub %4, %4, #16 \n"
//END tile loop
"2: \n"
// remain loop
"and w1, %w18, #3 \n" // w1 = remain = tiles & 3;
"cmp w1, #0 \n"
"beq 4f \n"
//BEGIN remain loop
"3: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v16.4s}, [%4], #16 \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v20.4s}, [%0] \n"
"fmla v20.4s, v16.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v21.4s}, [%1] \n"
"fmla v21.4s, v16.4s, v4.4s \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v22.4s}, [%2] \n"
"fmla v22.4s, v16.4s, v8.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v23.4s}, [%3] \n"
"fmla v23.4s, v16.4s, v12.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v17.4s}, [%5], #16 \n"
"fmla v20.4s, v17.4s, v1.4s \n"
"fmla v21.4s, v17.4s, v5.4s \n"
"fmla v22.4s, v17.4s, v9.4s \n"
"fmla v23.4s, v17.4s, v13.4s \n"
"prfm pldl1keep, [%6, #128] \n"
"ld1 {v18.4s}, [%6], #16 \n"
"fmla v20.4s, v18.4s, v2.4s \n"
"fmla v21.4s, v18.4s, v6.4s \n"
"fmla v22.4s, v18.4s, v10.4s \n"
"fmla v23.4s, v18.4s, v14.4s \n"
"prfm pldl1keep, [%7, #128] \n"
"ld1 {v19.4s}, [%7], #16 \n"
"fmla v20.4s, v19.4s, v3.4s \n"
"fmla v21.4s, v19.4s, v7.4s \n"
"fmla v22.4s, v19.4s, v11.4s \n"
"fmla v23.4s, v19.4s, v15.4s \n"
"st1 {v20.4s}, [%0], #16 \n"
"st1 {v21.4s}, [%1], #16 \n"
"subs w1, w1, #1 \n"
"st1 {v22.4s}, [%2], #16 \n"
"st1 {v23.4s}, [%3], #16 \n"
"bne 3b \n"
//END remain loop
"4: \n"
"subs w0, w0, #1 \n"
"bne 0b \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(r1), // %5
"=r"(r2), // %6
"=r"(r3), // %7
"=r"(ktm) // %8
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(r1),
"6"(r2),
"7"(r3),
"8"(ktm),
"r"(tiles) // %18
: "cc", "memory", "x0", "x1", "x4", "x5", "x6", "x7", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27");
}
#endif // __ARM_NEON && __aarch64__
for (; q + 1 < inch; q += 2)
{
const float* r0 = bottom_blob_tm.channel(q);
const float* r1 = bottom_blob_tm.channel(q + 1);
float* output0_tm = out0_tm;
float* output1_tm = out1_tm;
float* output2_tm = out2_tm;
float* output3_tm = out3_tm;
#if __ARM_NEON
#if __aarch64__
asm volatile(
"mov w0, #16 \n" // w0 = r = 16
"0: \n"
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v0.4s, v1.4s}, [%6], #32 \n" // v0 v1 = _k00 _k01
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v2.4s, v3.4s}, [%6], #32 \n" // v2 v3 = _k10 _k11
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v4.4s, v5.4s}, [%6], #32 \n" // v4 v5 = _k20 _k21
"prfm pldl1keep, [%6, #256] \n"
"ld1 {v6.4s, v7.4s}, [%6], #32 \n" // v6 v7 = _k30 _k31
// tile loop
"lsr w1, %w14, #2 \n" // w1 = nn = tiles >> 2
"cmp w1, #0 \n"
"beq 2f \n"
//BEGIN tile loop
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v20.4s}, [%4], #16 \n"
"1: \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v16.4s}, [%0] \n"
"fmla v16.4s, v20.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v17.4s}, [%1] \n"
"fmla v17.4s, v20.4s, v2.4s \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v18.4s}, [%2] \n"
"fmla v18.4s, v20.4s, v4.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v19.4s}, [%3] \n"
"fmla v19.4s, v20.4s, v6.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v21.4s}, [%5], #16 \n"
"fmla v16.4s, v21.4s, v1.4s \n"
"fmla v17.4s, v21.4s, v3.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v20.4s}, [%4], #16 \n"
"fmla v18.4s, v21.4s, v5.4s \n"
"fmla v19.4s, v21.4s, v7.4s \n"
"st1 {v16.4s}, [%0], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
////
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v16.4s}, [%0] \n"
"fmla v16.4s, v20.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v17.4s}, [%1] \n"
"fmla v17.4s, v20.4s, v2.4s \n"
"st1 {v18.4s}, [%2], #16 \n"
"st1 {v19.4s}, [%3], #16 \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v18.4s}, [%2] \n"
"fmla v18.4s, v20.4s, v4.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v19.4s}, [%3] \n"
"fmla v19.4s, v20.4s, v6.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v21.4s}, [%5], #16 \n"
"fmla v16.4s, v21.4s, v1.4s \n"
"fmla v17.4s, v21.4s, v3.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v20.4s}, [%4], #16 \n"
"fmla v18.4s, v21.4s, v5.4s \n"
"fmla v19.4s, v21.4s, v7.4s \n"
"st1 {v16.4s}, [%0], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
////
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v16.4s}, [%0] \n"
"fmla v16.4s, v20.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v17.4s}, [%1] \n"
"fmla v17.4s, v20.4s, v2.4s \n"
"st1 {v18.4s}, [%2], #16 \n"
"st1 {v19.4s}, [%3], #16 \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v18.4s}, [%2] \n"
"fmla v18.4s, v20.4s, v4.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v19.4s}, [%3] \n"
"fmla v19.4s, v20.4s, v6.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v21.4s}, [%5], #16 \n"
"fmla v16.4s, v21.4s, v1.4s \n"
"fmla v17.4s, v21.4s, v3.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v20.4s}, [%4], #16 \n"
"fmla v18.4s, v21.4s, v5.4s \n"
"fmla v19.4s, v21.4s, v7.4s \n"
"st1 {v16.4s}, [%0], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
////
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v16.4s}, [%0] \n"
"fmla v16.4s, v20.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v17.4s}, [%1] \n"
"fmla v17.4s, v20.4s, v2.4s \n"
"st1 {v18.4s}, [%2], #16 \n"
"st1 {v19.4s}, [%3], #16 \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v18.4s}, [%2] \n"
"fmla v18.4s, v20.4s, v4.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v19.4s}, [%3] \n"
"fmla v19.4s, v20.4s, v6.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v21.4s}, [%5], #16 \n"
"fmla v16.4s, v21.4s, v1.4s \n"
"fmla v17.4s, v21.4s, v3.4s \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v20.4s}, [%4], #16 \n"
"fmla v18.4s, v21.4s, v5.4s \n"
"fmla v19.4s, v21.4s, v7.4s \n"
"st1 {v16.4s}, [%0], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
"subs w1, w1, #1 \n"
"st1 {v18.4s}, [%2], #16 \n"
"st1 {v19.4s}, [%3], #16 \n"
"bne 1b \n"
"sub %4, %4, #16 \n"
//END tile loop
"2: \n"
// remain loop
"and w1, %w14, #3 \n" // w1 = remain = tiles & 3;
"cmp w1, #0 \n"
"beq 4f \n"
//BEGIN remain loop
"3: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v20.4s}, [%4], #16 \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v16.4s}, [%0] \n"
"fmla v16.4s, v20.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v17.4s}, [%1] \n"
"fmla v17.4s, v20.4s, v2.4s \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v18.4s}, [%2] \n"
"fmla v18.4s, v20.4s, v4.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v19.4s}, [%3] \n"
"fmla v19.4s, v20.4s, v6.4s \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v21.4s}, [%5], #16 \n"
"fmla v16.4s, v21.4s, v1.4s \n"
"fmla v17.4s, v21.4s, v3.4s \n"
"fmla v18.4s, v21.4s, v5.4s \n"
"fmla v19.4s, v21.4s, v7.4s \n"
"st1 {v16.4s}, [%0], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
"subs w1, w1, #1 \n"
"st1 {v18.4s}, [%2], #16 \n"
"st1 {v19.4s}, [%3], #16 \n"
"bne 3b \n"
//END remain loop
"4: \n"
"subs w0, w0, #1 \n"
"bne 0b \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(r1), // %5
"=r"(ktm) // %6
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(r1),
"6"(ktm),
"r"(tiles) // %14
: "cc", "memory", "x0", "x1", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21");
#else
asm volatile(
"mov r0, #16 \n" // r0 = r = 16
"0: \n"
"pld [%6, #256] \n"
"vld1.f32 {d0-d3}, [%6 :128]! \n" // q0 q1 = _k00 _k01
"pld [%6, #256] \n"
"vld1.f32 {d4-d7}, [%6 :128]! \n" // q2 q3 = _k10 _k11
"pld [%6, #256] \n"
"vld1.f32 {d8-d11}, [%6 :128]! \n" // q4 q5 = _k20 _k21
"pld [%6, #256] \n"
"vld1.f32 {d12-d15}, [%6 :128]! \n" // q6 q7 = _k30 _k31
// tile loop
"lsr r1, %14, #2 \n" // r1 = nn = tiles >> 2
"cmp r1, #0 \n"
"beq 2f \n"
//BEGIN tile loop
"pld [%4, #128] \n"
"vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0
"1: \n"
"pld [%0, #128] \n"
"vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm
"vmla.f32 q8, q12, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm
"vmla.f32 q9, q12, q2 \n"
"pld [%2, #128] \n"
"vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm
"vmla.f32 q10, q12, q4 \n"
"pld [%3, #128] \n"
"vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm
"vmla.f32 q11, q12, q6 \n"
"pld [%5, #128] \n"
"vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1
"vmla.f32 q8, q13, q1 \n"
"vmla.f32 q9, q13, q3 \n"
"pld [%4, #128] \n"
"vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0
"vmla.f32 q10, q13, q5 \n"
"vmla.f32 q11, q13, q7 \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
////
"pld [%0, #128] \n"
"vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm
"vmla.f32 q8, q12, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm
"vmla.f32 q9, q12, q2 \n"
"vst1.f32 {d20-d21}, [%2 :128]! \n"
"vst1.f32 {d22-d23}, [%3 :128]! \n"
"pld [%2, #128] \n"
"vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm
"vmla.f32 q10, q12, q4 \n"
"pld [%3, #128] \n"
"vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm
"vmla.f32 q11, q12, q6 \n"
"pld [%5, #128] \n"
"vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1
"vmla.f32 q8, q13, q1 \n"
"vmla.f32 q9, q13, q3 \n"
"pld [%4, #128] \n"
"vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0
"vmla.f32 q10, q13, q5 \n"
"vmla.f32 q11, q13, q7 \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
////
"pld [%0, #128] \n"
"vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm
"vmla.f32 q8, q12, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm
"vmla.f32 q9, q12, q2 \n"
"vst1.f32 {d20-d21}, [%2 :128]! \n"
"vst1.f32 {d22-d23}, [%3 :128]! \n"
"pld [%2, #128] \n"
"vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm
"vmla.f32 q10, q12, q4 \n"
"pld [%3, #128] \n"
"vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm
"vmla.f32 q11, q12, q6 \n"
"pld [%5, #128] \n"
"vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1
"vmla.f32 q8, q13, q1 \n"
"vmla.f32 q9, q13, q3 \n"
"pld [%4, #128] \n"
"vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0
"vmla.f32 q10, q13, q5 \n"
"vmla.f32 q11, q13, q7 \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
////
"pld [%0, #128] \n"
"vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm
"vmla.f32 q8, q12, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm
"vmla.f32 q9, q12, q2 \n"
"vst1.f32 {d20-d21}, [%2 :128]! \n"
"vst1.f32 {d22-d23}, [%3 :128]! \n"
"pld [%2, #128] \n"
"vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm
"vmla.f32 q10, q12, q4 \n"
"pld [%3, #128] \n"
"vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm
"vmla.f32 q11, q12, q6 \n"
"pld [%5, #128] \n"
"vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1
"vmla.f32 q8, q13, q1 \n"
"vmla.f32 q9, q13, q3 \n"
"pld [%4, #128] \n"
"vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0
"vmla.f32 q10, q13, q5 \n"
"vmla.f32 q11, q13, q7 \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
"subs r1, #1 \n"
"vst1.f32 {d20-d21}, [%2 :128]! \n"
"vst1.f32 {d22-d23}, [%3 :128]! \n"
"bne 1b \n"
"sub %4, %4, #16 \n"
//END tile loop
"2: \n"
// remain loop
"and r1, %14, #3 \n" // r1 = remain = tiles & 3;
"cmp r1, #0 \n"
"beq 4f \n"
//BEGIN remain loop
"3: \n"
"pld [%4, #128] \n"
"vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0
"pld [%0, #128] \n"
"vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm
"vmla.f32 q8, q12, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm
"vmla.f32 q9, q12, q2 \n"
"pld [%2, #128] \n"
"vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm
"vmla.f32 q10, q12, q4 \n"
"pld [%3, #128] \n"
"vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm
"vmla.f32 q11, q12, q6 \n"
"pld [%5, #128] \n"
"vld1.f32 {d26-d27}, [%5 :128]! \n" // q13 = _r1
"vmla.f32 q8, q13, q1 \n"
"vmla.f32 q9, q13, q3 \n"
"vmla.f32 q10, q13, q5 \n"
"vmla.f32 q11, q13, q7 \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
"subs r1, #1 \n"
"vst1.f32 {d20-d21}, [%2 :128]! \n"
"vst1.f32 {d22-d23}, [%3 :128]! \n"
"bne 3b \n"
//END remain loop
"4: \n"
"subs r0, #1 \n"
"bne 0b \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(r1), // %5
"=r"(ktm) // %6
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(r1),
"6"(ktm),
"r"(tiles) // %14
: "cc", "memory", "r0", "r1", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13");
#endif // __aarch64__
#else
for (int r = 0; r < 16; r++)
{
for (int t = 0; t < tiles; t++)
{
for (int m = 0; m < 4; m++)
{
output0_tm[m] += r0[m] * ktm[0 + m];
output0_tm[m] += r1[m] * ktm[4 + m];
output1_tm[m] += r0[m] * ktm[8 + m];
output1_tm[m] += r1[m] * ktm[12 + m];
output2_tm[m] += r0[m] * ktm[16 + m];
output2_tm[m] += r1[m] * ktm[20 + m];
output3_tm[m] += r0[m] * ktm[24 + m];
output3_tm[m] += r1[m] * ktm[28 + m];
}
r0 += 4;
r1 += 4;
output0_tm += 4;
output1_tm += 4;
output2_tm += 4;
output3_tm += 4;
}
ktm += 32;
}
#endif // __ARM_NEON
}
for (; q < inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q);
float* output0_tm = out0_tm;
float* output1_tm = out1_tm;
float* output2_tm = out2_tm;
float* output3_tm = out3_tm;
#if __ARM_NEON
#if __aarch64__
asm volatile(
"mov w0, #16 \n" // w0 = r = 16
"0: \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4s, v1.4s}, [%5], #32 \n" // v0 v1 = _k00 _k10
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v2.4s, v3.4s}, [%5], #32 \n" // v2 v3 = _k20 _k30
// tile loop
"mov w1, %w12 \n" // w1 = tiles
"cmp w1, #0 \n"
"beq 2f \n"
//BEGIN tile loop
"1: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v16.4s}, [%4], #16 \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v17.4s}, [%0] \n"
"fmla v17.4s, v16.4s, v0.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v18.4s}, [%1] \n"
"fmla v18.4s, v16.4s, v1.4s \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v19.4s}, [%2] \n"
"fmla v19.4s, v16.4s, v2.4s \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v20.4s}, [%3] \n"
"fmla v20.4s, v16.4s, v3.4s \n"
"st1 {v17.4s}, [%0], #16 \n"
"st1 {v18.4s}, [%1], #16 \n"
"subs w1, w1, #1 \n"
"st1 {v19.4s}, [%2], #16 \n"
"st1 {v20.4s}, [%3], #16 \n"
"bne 1b \n"
//END tile loop
"2: \n"
"subs w0, w0, #1 \n"
"bne 0b \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(ktm) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(ktm),
"r"(tiles) // %12
: "cc", "memory", "x0", "x1", "v0", "v1", "v2", "v3", "v16", "v17", "v18", "v19", "v20");
#else
asm volatile(
"mov r0, #16 \n" // r0 = r = 16
"0: \n"
"pld [%5, #256] \n"
"vld1.f32 {d0-d3}, [%5 :128]! \n" // q0 q1 = _k00 _k10
"pld [%5, #256] \n"
"vld1.f32 {d4-d7}, [%5 :128]! \n" // q2 q3 = _k20 _k30
// tile loop
"mov r1, %12 \n" // r1 = tiles
"cmp r1, #0 \n"
"beq 2f \n"
//BEGIN tile loop
"1: \n"
"pld [%4, #128] \n"
"vld1.f32 {d24-d25}, [%4 :128]! \n" // q12 = _r0
"pld [%0, #128] \n"
"vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm
"vmla.f32 q8, q12, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d18-d19}, [%1 :128] \n" // q9 = _output1_tm
"vmla.f32 q9, q12, q1 \n"
"pld [%2, #128] \n"
"vld1.f32 {d20-d21}, [%2 :128] \n" // q10 = _output2_tm
"vmla.f32 q10, q12, q2 \n"
"pld [%3, #128] \n"
"vld1.f32 {d22-d23}, [%3 :128] \n" // q11 = _output3_tm
"vmla.f32 q11, q12, q3 \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
"subs r1, #1 \n"
"vst1.f32 {d20-d21}, [%2 :128]! \n"
"vst1.f32 {d22-d23}, [%3 :128]! \n"
"bne 1b \n"
//END tile loop
"2: \n"
"subs r0, #1 \n"
"bne 0b \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(ktm) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(ktm),
"r"(tiles) // %12
: "cc", "memory", "r0", "r1", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13");
#endif // __aarch64__
#else
for (int r = 0; r < 16; r++)
{
for (int t = 0; t < tiles; t++)
{
for (int m = 0; m < 4; m++)
{
output0_tm[m] += r0[m] * ktm[0 + m];
output1_tm[m] += r0[m] * ktm[4 + m];
output2_tm[m] += r0[m] * ktm[8 + m];
output3_tm[m] += r0[m] * ktm[12 + m];
}
r0 += 4;
output0_tm += 4;
output1_tm += 4;
output2_tm += 4;
output3_tm += 4;
}
ktm += 16;
}
#endif // __ARM_NEON
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
Mat out0_tm = top_blob_tm.channel(p);
const float* ktm = (const float*)kernel_tm.channel(nn_outch) + 8 * 8 * inch * (p - remain_outch_start);
out0_tm.fill(0.f);
int q = 0;
for (; q < inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q);
float* output0_tm = out0_tm;
for (int r = 0; r < 16; r++)
{
#if __ARM_NEON
float32x4_t _k00 = vld1q_f32(ktm);
ktm += 4;
#endif // __ARM_NEON
// tile
for (int i = 0; i < tiles; i++)
{
#if __ARM_NEON
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v17.4s}, [%1], #16 \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v16.4s}, [%0] \n"
"fmla v16.4s, v17.4s, %4.4s \n"
"st1 {v16.4s}, [%0], #16 \n"
: "=r"(output0_tm), // %0
"=r"(r0) // %1
: "0"(output0_tm),
"1"(r0),
"w"(_k00) // %4
: "cc", "memory", "v16", "v17");
#else
asm volatile(
"pld [%1, #128] \n"
"vld1.f32 {d18-d19}, [%1 :128]! \n" // q9 = _r0
"pld [%0, #128] \n"
"vld1.f32 {d16-d17}, [%0 :128] \n" // q8 = _output0_tm
"vmla.f32 q8, q9, %q4 \n"
"vst1.f32 {d16-d17}, [%0 :128]! \n"
: "=r"(output0_tm), // %0
"=r"(r0) // %1
: "0"(output0_tm),
"1"(r0),
"w"(_k00) // %4
: "cc", "memory", "q8", "q9");
#endif // __aarch64__
#else
for (int m = 0; m < 4; m++)
{
output0_tm[m] += r0[m] * ktm[m];
}
r0 += 4;
output0_tm += 4;
#endif // __ARM_NEON
}
#if !__ARM_NEON
ktm += 4;
#endif // __ARM_NEON
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator);
{
// const float otm[6][8] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f}
// };
// 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32
// 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16
// 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8
// 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4
// 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2
// 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6)
#if __ARM_NEON
const float coeff[4] = {4.f, 8.f, 16.f, 32.f};
float32x4_t _coeff = vld1q_f32(coeff);
#endif // __ARM_NEON
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
const Mat out0_tm = top_blob_tm.channel(p);
Mat out0 = top_blob_bordered.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
#if __ARM_NEON
float32x2_t _bias0 = vdup_n_f32(bias0);
#endif // __ARM_NEON
float tmp[6][8];
// tile
for (int i = 0; i < outh / 6; i++)
{
for (int j = 0; j < outw / 6; j++)
{
#if __ARM_NEON
const float* output0_tm0_0 = out0_tm.row(i * w_tm / 8 + j);
const float* output0_tm0_4 = out0_tm.row(i * w_tm / 8 + j + tiles);
const float* output0_tm1_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 2);
const float* output0_tm1_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 3);
const float* output0_tm2_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 4);
const float* output0_tm2_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 5);
const float* output0_tm3_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 6);
const float* output0_tm3_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 7);
#if __aarch64__
for (int m = 0; m + 3 < 8; m += 4)
{
float32x4_t _output0_tm0_0123 = vld1q_f32(output0_tm0_0);
float32x4_t _output0_tm0_4567 = vld1q_f32(output0_tm0_4);
float32x4_t _output0_tm1_0123 = vld1q_f32(output0_tm1_0);
float32x4_t _output0_tm1_4567 = vld1q_f32(output0_tm1_4);
float32x4_t _output0_tm2_0123 = vld1q_f32(output0_tm2_0);
float32x4_t _output0_tm2_4567 = vld1q_f32(output0_tm2_4);
float32x4_t _output0_tm3_0123 = vld1q_f32(output0_tm3_0);
float32x4_t _output0_tm3_4567 = vld1q_f32(output0_tm3_4);
float32x4x2_t _output0_tm01_00221133 = vtrnq_f32(_output0_tm0_0123, _output0_tm1_0123);
float32x4x2_t _output0_tm01_44665577 = vtrnq_f32(_output0_tm0_4567, _output0_tm1_4567);
float32x4x2_t _output0_tm23_00221133 = vtrnq_f32(_output0_tm2_0123, _output0_tm3_0123);
float32x4x2_t _output0_tm23_44665577 = vtrnq_f32(_output0_tm2_4567, _output0_tm3_4567);
// no vswp intrinsic :(
float32x4_t _output0_tm_00 = vcombine_f32(vget_low_f32(_output0_tm01_00221133.val[0]), vget_low_f32(_output0_tm23_00221133.val[0]));
float32x4_t _output0_tm_11 = vcombine_f32(vget_low_f32(_output0_tm01_00221133.val[1]), vget_low_f32(_output0_tm23_00221133.val[1]));
float32x4_t _output0_tm_22 = vcombine_f32(vget_high_f32(_output0_tm01_00221133.val[0]), vget_high_f32(_output0_tm23_00221133.val[0]));
float32x4_t _output0_tm_33 = vcombine_f32(vget_high_f32(_output0_tm01_00221133.val[1]), vget_high_f32(_output0_tm23_00221133.val[1]));
float32x4_t _output0_tm_44 = vcombine_f32(vget_low_f32(_output0_tm01_44665577.val[0]), vget_low_f32(_output0_tm23_44665577.val[0]));
float32x4_t _output0_tm_55 = vcombine_f32(vget_low_f32(_output0_tm01_44665577.val[1]), vget_low_f32(_output0_tm23_44665577.val[1]));
float32x4_t _output0_tm_66 = vcombine_f32(vget_high_f32(_output0_tm01_44665577.val[0]), vget_high_f32(_output0_tm23_44665577.val[0]));
float32x4_t _output0_tm_77 = vcombine_f32(vget_high_f32(_output0_tm01_44665577.val[1]), vget_high_f32(_output0_tm23_44665577.val[1]));
float32x4_t _tmp024a = vaddq_f32(_output0_tm_11, _output0_tm_22);
float32x4_t _tmp135a = vsubq_f32(_output0_tm_11, _output0_tm_22);
float32x4_t _tmp024b = vaddq_f32(_output0_tm_33, _output0_tm_44);
float32x4_t _tmp135b = vsubq_f32(_output0_tm_33, _output0_tm_44);
float32x4_t _tmp024c = vaddq_f32(_output0_tm_55, _output0_tm_66);
float32x4_t _tmp135c = vsubq_f32(_output0_tm_55, _output0_tm_66);
float32x4_t _tmp0 = vaddq_f32(_output0_tm_00, _tmp024a);
_tmp0 = vmlaq_lane_f32(_tmp0, _tmp024c, vget_high_f32(_coeff), 1);
_tmp0 = vaddq_f32(_tmp0, _tmp024b);
float32x4_t _tmp2 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0);
_tmp2 = vmlaq_lane_f32(_tmp2, _tmp024c, vget_low_f32(_coeff), 1);
float32x4_t _tmp4 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0);
_tmp4 = vaddq_f32(_tmp4, _tmp024c);
_tmp4 = vaddq_f32(_tmp4, _tmp024c);
vst1q_f32(&tmp[0][m], _tmp0);
vst1q_f32(&tmp[2][m], _tmp2);
vst1q_f32(&tmp[4][m], _tmp4);
float32x4_t _tmp1 = vmlaq_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0);
_tmp1 = vaddq_f32(_tmp1, _tmp135b);
_tmp1 = vaddq_f32(_tmp1, _tmp135b);
float32x4_t _tmp3 = vmlaq_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1);
_tmp3 = vmlaq_lane_f32(_tmp3, _tmp135c, vget_low_f32(_coeff), 0);
float32x4_t _tmp5 = vaddq_f32(_output0_tm_77, _tmp135a);
_tmp5 = vmlaq_lane_f32(_tmp5, _tmp135b, vget_high_f32(_coeff), 1);
_tmp5 = vaddq_f32(_tmp5, _tmp135c);
vst1q_f32(&tmp[1][m], _tmp1);
vst1q_f32(&tmp[3][m], _tmp3);
vst1q_f32(&tmp[5][m], _tmp5);
output0_tm0_0 += out0_tm.w * tiles * 2 * 4;
output0_tm0_4 += out0_tm.w * tiles * 2 * 4;
output0_tm1_0 += out0_tm.w * tiles * 2 * 4;
output0_tm1_4 += out0_tm.w * tiles * 2 * 4;
output0_tm2_0 += out0_tm.w * tiles * 2 * 4;
output0_tm2_4 += out0_tm.w * tiles * 2 * 4;
output0_tm3_0 += out0_tm.w * tiles * 2 * 4;
output0_tm3_4 += out0_tm.w * tiles * 2 * 4;
}
const float* t0 = tmp[0];
const float* t1 = tmp[1];
float* output0 = out0.row(i * 6) + j * 6;
float* output1 = output0 + outw;
for (int m = 0; m + 1 < 6; m += 2)
{
float32x4_t _t0_0123 = vld1q_f32(t0);
float32x4_t _t0_4567 = vld1q_f32(t0 + 4);
float32x4_t _t1_0123 = vld1q_f32(t1);
float32x4_t _t1_4567 = vld1q_f32(t1 + 4);
float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123);
float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567);
float32x2_t _t_00 = vget_low_f32(_t01_00221133.val[0]);
float32x2_t _t_11 = vget_low_f32(_t01_00221133.val[1]);
float32x2_t _t_22 = vget_high_f32(_t01_00221133.val[0]);
float32x2_t _t_33 = vget_high_f32(_t01_00221133.val[1]);
float32x2_t _t_44 = vget_low_f32(_t01_44665577.val[0]);
float32x2_t _t_55 = vget_low_f32(_t01_44665577.val[1]);
float32x2_t _t_66 = vget_high_f32(_t01_44665577.val[0]);
float32x2_t _t_77 = vget_high_f32(_t01_44665577.val[1]);
float32x2_t _tmp024a = vadd_f32(_t_11, _t_22);
float32x2_t _tmp135a = vsub_f32(_t_11, _t_22);
float32x2_t _tmp024b = vadd_f32(_t_33, _t_44);
float32x2_t _tmp135b = vsub_f32(_t_33, _t_44);
float32x2_t _tmp024c = vadd_f32(_t_55, _t_66);
float32x2_t _tmp135c = vsub_f32(_t_55, _t_66);
float32x2_t _output_0 = vadd_f32(_t_00, _tmp024a);
_output_0 = vmla_lane_f32(_output_0, _tmp024c, vget_high_f32(_coeff), 1);
_output_0 = vadd_f32(_output_0, _tmp024b);
_output_0 = vadd_f32(_output_0, _bias0);
float32x2_t _output_2 = vmla_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0);
_output_2 = vmla_lane_f32(_output_2, _tmp024c, vget_low_f32(_coeff), 1);
_output_2 = vadd_f32(_output_2, _bias0);
float32x2_t _output_4 = vmla_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0);
_output_4 = vadd_f32(_output_4, _tmp024c);
_output_4 = vadd_f32(_output_4, _tmp024c);
_output_4 = vadd_f32(_output_4, _bias0);
output0[0] = vget_lane_f32(_output_0, 0);
output1[0] = vget_lane_f32(_output_0, 1);
output0[2] = vget_lane_f32(_output_2, 0);
output1[2] = vget_lane_f32(_output_2, 1);
output0[4] = vget_lane_f32(_output_4, 0);
output1[4] = vget_lane_f32(_output_4, 1);
float32x2_t _output_1 = vmla_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0);
_output_1 = vadd_f32(_output_1, _tmp135b);
_output_1 = vadd_f32(_output_1, _tmp135b);
_output_1 = vadd_f32(_output_1, _bias0);
float32x2_t _output_3 = vmla_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1);
_output_3 = vmla_lane_f32(_output_3, _tmp135c, vget_low_f32(_coeff), 0);
_output_3 = vadd_f32(_output_3, _bias0);
float32x2_t _output_5 = vadd_f32(_t_77, _tmp135a);
_output_5 = vmla_lane_f32(_output_5, _tmp135b, vget_high_f32(_coeff), 1);
_output_5 = vadd_f32(_output_5, _tmp135c);
_output_5 = vadd_f32(_output_5, _bias0);
output0[1] = vget_lane_f32(_output_1, 0);
output1[1] = vget_lane_f32(_output_1, 1);
output0[3] = vget_lane_f32(_output_3, 0);
output1[3] = vget_lane_f32(_output_3, 1);
output0[5] = vget_lane_f32(_output_5, 0);
output1[5] = vget_lane_f32(_output_5, 1);
t0 += 8 * 2;
t1 += 8 * 2;
output0 += outw * 2;
output1 += outw * 2;
}
#else // __aarch64__
float* t0 = tmp[0];
float* t1 = tmp[1];
int step = out0_tm.w * tiles * 2 * 4 * 4;
asm volatile(
// loop0
"vld1.f32 {d16-d17}, [%2], %21 \n"
"vld1.f32 {d18-d19}, [%3], %21 \n"
"vld1.f32 {d20-d21}, [%4], %21 \n"
"vld1.f32 {d22-d23}, [%5], %21 \n"
"vld1.f32 {d24-d25}, [%6], %21 \n"
"vld1.f32 {d26-d27}, [%7], %21 \n"
"vld1.f32 {d28-d29}, [%8], %21 \n"
"vld1.f32 {d30-d31}, [%9], %21 \n"
"vtrn.32 q8, q10 \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vadd.f32 q2, q10, q12 \n"
"vsub.f32 q3, q10, q12 \n"
"vadd.f32 q4, q14, q9 \n"
"vsub.f32 q5, q14, q9 \n"
"vadd.f32 q6, q11, q13 \n"
"vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14
"vmov q9, q3 \n"
"vadd.f32 q8, q8, q2 \n"
"vmla.f32 q9, q7, %f20[0] \n"
"vmov q12, q2 \n"
"vmov q10, q2 \n"
"vmov q11, q3 \n"
"vmla.f32 q12, q4, %f20[0] \n"
"vadd.f32 q15, q15, q3 \n"
"vmla.f32 q8, q6, %f20[1] \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q4, %e20[0] \n"
"vmla.f32 q11, q5, %e20[1] \n"
"vadd.f32 q12, q12, q6 \n"
"vmla.f32 q15, q5, %f20[1] \n"
"vadd.f32 q8, q8, q4 \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q6, %e20[1] \n"
"vmla.f32 q11, q7, %e20[0] \n"
"vadd.f32 q12, q12, q6 \n"
"vadd.f32 q15, q15, q7 \n"
"vst1.f32 {d16-d17}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d18-d19}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d20-d21}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d22-d23}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d24-d25}, [%0] \n"
"sub %0, %0, #112 \n"
"vst1.f32 {d30-d31}, [%1] \n"
"sub %1, %1, #112 \n"
// loop1
"vld1.f32 {d16-d17}, [%2] \n"
"vld1.f32 {d18-d19}, [%3] \n"
"vld1.f32 {d20-d21}, [%4] \n"
"vld1.f32 {d22-d23}, [%5] \n"
"vld1.f32 {d24-d25}, [%6] \n"
"vld1.f32 {d26-d27}, [%7] \n"
"vld1.f32 {d28-d29}, [%8] \n"
"vld1.f32 {d30-d31}, [%9] \n"
"vtrn.32 q8, q10 \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vadd.f32 q2, q10, q12 \n"
"vsub.f32 q3, q10, q12 \n"
"vadd.f32 q4, q14, q9 \n"
"vsub.f32 q5, q14, q9 \n"
"vadd.f32 q6, q11, q13 \n"
"vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14
"vmov q9, q3 \n"
"vadd.f32 q8, q8, q2 \n"
"vmla.f32 q9, q7, %f20[0] \n"
"vmov q12, q2 \n"
"vmov q10, q2 \n"
"vmov q11, q3 \n"
"vmla.f32 q12, q4, %f20[0] \n"
"vadd.f32 q15, q15, q3 \n"
"vmla.f32 q8, q6, %f20[1] \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q4, %e20[0] \n"
"vmla.f32 q11, q5, %e20[1] \n"
"vadd.f32 q12, q12, q6 \n"
"vmla.f32 q15, q5, %f20[1] \n"
"vadd.f32 q8, q8, q4 \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q6, %e20[1] \n"
"vmla.f32 q11, q7, %e20[0] \n"
"vadd.f32 q12, q12, q6 \n"
"vadd.f32 q15, q15, q7 \n"
"vst1.f32 {d16-d17}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d18-d19}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d20-d21}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d22-d23}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d24-d25}, [%0] \n"
"vst1.f32 {d30-d31}, [%1] \n"
: "=r"(t0), // %0
"=r"(t1), // %1
"=r"(output0_tm0_0), // %2
"=r"(output0_tm0_4), // %3
"=r"(output0_tm1_0), // %4
"=r"(output0_tm1_4), // %5
"=r"(output0_tm2_0), // %6
"=r"(output0_tm2_4), // %7
"=r"(output0_tm3_0), // %8
"=r"(output0_tm3_4) // %9
: "0"(t0),
"1"(t1),
"2"(output0_tm0_0),
"3"(output0_tm0_4),
"4"(output0_tm1_0),
"5"(output0_tm1_4),
"6"(output0_tm2_0),
"7"(output0_tm2_4),
"8"(output0_tm3_0),
"9"(output0_tm3_4),
"w"(_coeff), // %20
"r"(step) // %21
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
t0 = tmp[0];
t1 = tmp[1];
float* output0 = out0.row(i * 6) + j * 6;
float* output1 = output0 + outw;
int stepw = outw * 2 * 4;
asm volatile(
// loop0
"vld1.f32 {d16-d19}, [%2] \n"
"vld1.f32 {d20-d23}, [%3] \n"
"add %2, %2, #64 \n"
"add %3, %3, #64 \n"
"vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3
"vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7
"vadd.f32 d4, d20, d17 \n"
"vsub.f32 d5, d20, d17 \n"
"vadd.f32 d6, d21, d18 \n"
"vsub.f32 d7, d21, d18 \n"
"vadd.f32 d8, d22, d19 \n"
"vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22
"vmov d20, d5 \n"
"vmov d18, d4 \n"
"vadd.f32 d16, d16, d4 \n"
"vmla.f32 d20, d9, %f8[0] \n"
"vmov d17, d4 \n"
"vmov d21, d5 \n"
"vmla.f32 d18, d6, %f8[0] \n"
"vadd.f32 d22, d23, d5 \n"
"vmla.f32 d16, d8, %f8[1] \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d6, %e8[0] \n"
"vmla.f32 d21, d7, %e8[1] \n"
"vadd.f32 d18, d18, d8 \n"
"vmla.f32 d22, d7, %f8[1] \n"
"vadd.f32 d16, d16, d6 \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d8, %e8[1] \n"
"vmla.f32 d21, d9, %e8[0] \n"
"vadd.f32 d18, d18, d8 \n"
"vadd.f32 d22, d22, d9 \n"
"vadd.f32 d16, d16, %P9 \n" // _bias0
"vadd.f32 d20, d20, %P9 \n" // _bias0
"vadd.f32 d17, d17, %P9 \n" // _bias0
"vadd.f32 d21, d21, %P9 \n" // _bias0
"vadd.f32 d18, d18, %P9 \n" // _bias0
"vadd.f32 d22, d22, %P9 \n" // _bias0
"vtrn.f32 q8, q10 \n"
"vtrn.f32 d18, d22 \n"
"vst1.f32 {d16-d18}, [%0], %10 \n"
"vst1.f32 {d20-d22}, [%1], %10 \n"
// loop1
"vld1.f32 {d16-d19}, [%2] \n"
"vld1.f32 {d20-d23}, [%3] \n"
"add %2, %2, #64 \n"
"add %3, %3, #64 \n"
"vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3
"vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7
"vadd.f32 d4, d20, d17 \n"
"vsub.f32 d5, d20, d17 \n"
"vadd.f32 d6, d21, d18 \n"
"vsub.f32 d7, d21, d18 \n"
"vadd.f32 d8, d22, d19 \n"
"vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22
"vmov d20, d5 \n"
"vmov d18, d4 \n"
"vadd.f32 d16, d16, d4 \n"
"vmla.f32 d20, d9, %f8[0] \n"
"vmov d17, d4 \n"
"vmov d21, d5 \n"
"vmla.f32 d18, d6, %f8[0] \n"
"vadd.f32 d22, d23, d5 \n"
"vmla.f32 d16, d8, %f8[1] \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d6, %e8[0] \n"
"vmla.f32 d21, d7, %e8[1] \n"
"vadd.f32 d18, d18, d8 \n"
"vmla.f32 d22, d7, %f8[1] \n"
"vadd.f32 d16, d16, d6 \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d8, %e8[1] \n"
"vmla.f32 d21, d9, %e8[0] \n"
"vadd.f32 d18, d18, d8 \n"
"vadd.f32 d22, d22, d9 \n"
"vadd.f32 d16, d16, %P9 \n" // _bias0
"vadd.f32 d20, d20, %P9 \n" // _bias0
"vadd.f32 d17, d17, %P9 \n" // _bias0
"vadd.f32 d21, d21, %P9 \n" // _bias0
"vadd.f32 d18, d18, %P9 \n" // _bias0
"vadd.f32 d22, d22, %P9 \n" // _bias0
"vtrn.f32 q8, q10 \n"
"vtrn.f32 d18, d22 \n"
"vst1.f32 {d16-d18}, [%0], %10 \n"
"vst1.f32 {d20-d22}, [%1], %10 \n"
// loop2
"vld1.f32 {d16-d19}, [%2] \n"
"vld1.f32 {d20-d23}, [%3] \n"
"add %2, %2, #64 \n"
"add %3, %3, #64 \n"
"vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3
"vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7
"vadd.f32 d4, d20, d17 \n"
"vsub.f32 d5, d20, d17 \n"
"vadd.f32 d6, d21, d18 \n"
"vsub.f32 d7, d21, d18 \n"
"vadd.f32 d8, d22, d19 \n"
"vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22
"vmov d20, d5 \n"
"vmov d18, d4 \n"
"vadd.f32 d16, d16, d4 \n"
"vmla.f32 d20, d9, %f8[0] \n"
"vmov d17, d4 \n"
"vmov d21, d5 \n"
"vmla.f32 d18, d6, %f8[0] \n"
"vadd.f32 d22, d23, d5 \n"
"vmla.f32 d16, d8, %f8[1] \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d6, %e8[0] \n"
"vmla.f32 d21, d7, %e8[1] \n"
"vadd.f32 d18, d18, d8 \n"
"vmla.f32 d22, d7, %f8[1] \n"
"vadd.f32 d16, d16, d6 \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d8, %e8[1] \n"
"vmla.f32 d21, d9, %e8[0] \n"
"vadd.f32 d18, d18, d8 \n"
"vadd.f32 d22, d22, d9 \n"
"vadd.f32 d16, d16, %P9 \n" // _bias0
"vadd.f32 d20, d20, %P9 \n" // _bias0
"vadd.f32 d17, d17, %P9 \n" // _bias0
"vadd.f32 d21, d21, %P9 \n" // _bias0
"vadd.f32 d18, d18, %P9 \n" // _bias0
"vadd.f32 d22, d22, %P9 \n" // _bias0
"vtrn.f32 q8, q10 \n"
"vtrn.f32 d18, d22 \n"
"vst1.f32 {d16-d18}, [%0], %10 \n"
"vst1.f32 {d20-d22}, [%1], %10 \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(t0), // %2
"=r"(t1) // %3
: "0"(output0),
"1"(output1),
"2"(t0),
"3"(t1),
"w"(_coeff), // %8
"w"(_bias0), // %9
"r"(stepw) // %10
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
const float* output0_tm_0 = out0_tm.row(i * w_tm / 8 + j);
const float* output0_tm_4 = out0_tm.row(i * w_tm / 8 + j + tiles);
for (int m = 0; m < 8; m++)
{
float tmp024a = output0_tm_0[1] + output0_tm_0[2];
float tmp135a = output0_tm_0[1] - output0_tm_0[2];
float tmp024b = output0_tm_0[3] + output0_tm_4[0];
float tmp135b = output0_tm_0[3] - output0_tm_4[0];
float tmp024c = output0_tm_4[1] + output0_tm_4[2];
float tmp135c = output0_tm_4[1] - output0_tm_4[2];
tmp[0][m] = output0_tm_0[0] + tmp024a + tmp024b + tmp024c * 32;
tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8;
tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c;
tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16;
tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4;
tmp[5][m] = output0_tm_4[3] + tmp135a + tmp135b * 32 + tmp135c;
output0_tm_0 += out0_tm.w * tiles * 2;
output0_tm_4 += out0_tm.w * tiles * 2;
}
float* output0 = out0.row(i * 6) + j * 6;
for (int m = 0; m < 6; m++)
{
const float* tmp0 = tmp[m];
float tmp024a = tmp0[1] + tmp0[2];
float tmp135a = tmp0[1] - tmp0[2];
float tmp024b = tmp0[3] + tmp0[4];
float tmp135b = tmp0[3] - tmp0[4];
float tmp024c = tmp0[5] + tmp0[6];
float tmp135c = tmp0[5] - tmp0[6];
output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32;
output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8;
output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c;
output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16;
output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4;
output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c;
output0 += outw;
}
#endif // __ARM_NEON
}
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
static void conv3x3s1_winograd64_neon5(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 6n+2
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 5) / 6 * 6;
outh = (outh + 5) / 6 * 6;
w = outw + 2;
h = outh + 2;
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b);
const float* bias = _bias;
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
bottom_blob_tm.create(1, 64 * tiles, inch, 4u, opt.workspace_allocator);
// bottom_blob_tm.create(inch, tiles, 64);
// const float itm[8][8] = {
// {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f},
//
// {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f},
// {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f},
//
// {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f},
// {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f},
//
// {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f},
// {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f},
//
// {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f}
// };
// 0 = r00 - r06 + (r04 - r02) * 5.25
// 7 = r07 - r01 + (r03 - r05) * 5.25
// 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05)
// 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05)
// 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// reuse r04 * 1.25
// reuse r03 * 2.5
// 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5)
// 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5)
#if __ARM_NEON
const float coeff[8] = {
0.25f, 0.5f, -1.25f, 2.f,
-2.5f, 4.f, 4.25f, 5.25f
};
float32x4_t _coeff0 = vld1q_f32(coeff);
float32x4_t _coeff1 = vld1q_f32(coeff + 4);
#endif // __ARM_NEON
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < inch; q++)
{
const Mat img0 = bottom_blob_bordered.channel(q);
Mat img0_tm = bottom_blob_tm.channel(q);
float tmp[8][8];
// tile
for (int i = 0; i < h_tm / 8; i++)
{
for (int j = 0; j < w_tm / 8; j++)
{
#if __ARM_NEON
const float* r0 = img0.row(i * 6) + j * 6;
const float* r1 = r0 + w;
const float* r2 = r0 + w * 2;
const float* r3 = r0 + w * 3;
// the assembly block for armv7 input transform requires 13 general registers
// old gcc may fail to allocate register on debug build without -fomit-frame-pointer
// so, fallback to intrinsic version for armv7 debug build --- nihui
#if __aarch64__ || !defined(NDEBUG)
for (int m = 0; m + 3 < 8; m += 4)
{
float32x4_t _r0_0123 = vld1q_f32(r0);
float32x4_t _r0_4567 = vld1q_f32(r0 + 4);
float32x4_t _r1_0123 = vld1q_f32(r1);
float32x4_t _r1_4567 = vld1q_f32(r1 + 4);
float32x4_t _r2_0123 = vld1q_f32(r2);
float32x4_t _r2_4567 = vld1q_f32(r2 + 4);
float32x4_t _r3_0123 = vld1q_f32(r3);
float32x4_t _r3_4567 = vld1q_f32(r3 + 4);
float32x4x2_t _r01_00221133 = vtrnq_f32(_r0_0123, _r1_0123);
float32x4x2_t _r01_44665577 = vtrnq_f32(_r0_4567, _r1_4567);
float32x4x2_t _r23_00221133 = vtrnq_f32(_r2_0123, _r3_0123);
float32x4x2_t _r23_44665577 = vtrnq_f32(_r2_4567, _r3_4567);
// no vswp intrinsic :(
float32x4_t _r_00 = vcombine_f32(vget_low_f32(_r01_00221133.val[0]), vget_low_f32(_r23_00221133.val[0]));
float32x4_t _r_11 = vcombine_f32(vget_low_f32(_r01_00221133.val[1]), vget_low_f32(_r23_00221133.val[1]));
float32x4_t _r_22 = vcombine_f32(vget_high_f32(_r01_00221133.val[0]), vget_high_f32(_r23_00221133.val[0]));
float32x4_t _r_33 = vcombine_f32(vget_high_f32(_r01_00221133.val[1]), vget_high_f32(_r23_00221133.val[1]));
float32x4_t _r_44 = vcombine_f32(vget_low_f32(_r01_44665577.val[0]), vget_low_f32(_r23_44665577.val[0]));
float32x4_t _r_55 = vcombine_f32(vget_low_f32(_r01_44665577.val[1]), vget_low_f32(_r23_44665577.val[1]));
float32x4_t _r_66 = vcombine_f32(vget_high_f32(_r01_44665577.val[0]), vget_high_f32(_r23_44665577.val[0]));
float32x4_t _r_77 = vcombine_f32(vget_high_f32(_r01_44665577.val[1]), vget_high_f32(_r23_44665577.val[1]));
float32x4_t _r_0_m_6 = vsubq_f32(_r_00, _r_66);
float32x4_t _r_7_m_1 = vsubq_f32(_r_77, _r_11);
float32x4_t _r_4_m_2 = vsubq_f32(_r_44, _r_22);
float32x4_t _r_3_m_5 = vsubq_f32(_r_33, _r_55);
float32x4_t _tmp0 = vmlaq_lane_f32(_r_0_m_6, _r_4_m_2, vget_high_f32(_coeff1), 1);
float32x4_t _tmp7 = vmlaq_lane_f32(_r_7_m_1, _r_3_m_5, vget_high_f32(_coeff1), 1);
vst1q_f32(&tmp[0][m], _tmp0);
vst1q_f32(&tmp[7][m], _tmp7);
float32x4_t _r_2_a_6 = vaddq_f32(_r_22, _r_66);
float32x4_t _r_1_a_5 = vaddq_f32(_r_11, _r_55);
float32x4_t _tmp12a = vmlsq_lane_f32(_r_2_a_6, _r_44, vget_high_f32(_coeff1), 0);
float32x4_t _tmp12b = vmlsq_lane_f32(_r_1_a_5, _r_33, vget_high_f32(_coeff1), 0);
float32x4_t _tmp1 = vaddq_f32(_tmp12a, _tmp12b);
float32x4_t _tmp2 = vsubq_f32(_tmp12a, _tmp12b);
vst1q_f32(&tmp[1][m], _tmp1);
vst1q_f32(&tmp[2][m], _tmp2);
float32x4_t _r_4_x_c = vmulq_lane_f32(_r_44, vget_high_f32(_coeff0), 0);
float32x4_t _r_3_x_c = vmulq_lane_f32(_r_33, vget_low_f32(_coeff1), 0);
float32x4_t _tmp34a = vaddq_f32(_r_66, _r_4_x_c);
_tmp34a = vmlaq_lane_f32(_tmp34a, _r_22, vget_low_f32(_coeff0), 0);
float32x4_t _tmp34b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_low_f32(_coeff0), 1);
_tmp34b = vmlaq_lane_f32(_tmp34b, _r_55, vget_high_f32(_coeff0), 1);
float32x4_t _tmp3 = vaddq_f32(_tmp34a, _tmp34b);
float32x4_t _tmp4 = vsubq_f32(_tmp34a, _tmp34b);
vst1q_f32(&tmp[3][m], _tmp3);
vst1q_f32(&tmp[4][m], _tmp4);
// reuse r04 * 1.25
// reuse r03 * 2.5
float32x4_t _r_2_a_4c = vaddq_f32(_r_22, _r_4_x_c);
float32x4_t _tmp56a = vmlaq_lane_f32(_r_66, _r_2_a_4c, vget_low_f32(_coeff1), 1);
float32x4_t _tmp56b = vmlaq_lane_f32(_r_3_x_c, _r_11, vget_high_f32(_coeff0), 1);
_tmp56b = vmlaq_lane_f32(_tmp56b, _r_55, vget_low_f32(_coeff0), 1);
float32x4_t _tmp5 = vaddq_f32(_tmp56a, _tmp56b);
float32x4_t _tmp6 = vsubq_f32(_tmp56a, _tmp56b);
vst1q_f32(&tmp[5][m], _tmp5);
vst1q_f32(&tmp[6][m], _tmp6);
r0 += w * 4;
r1 += w * 4;
r2 += w * 4;
r3 += w * 4;
}
const float* t0 = tmp[0];
const float* t1 = tmp[1];
const float* t2 = tmp[2];
const float* t3 = tmp[3];
float* r0_tm0 = img0_tm.row(i * w_tm / 8 + j);
float* r0_tm1 = img0_tm.row(i * w_tm / 8 + j + tiles * 8);
float* r0_tm2 = img0_tm.row(i * w_tm / 8 + j + tiles * 16);
float* r0_tm3 = img0_tm.row(i * w_tm / 8 + j + tiles * 24);
for (int m = 0; m + 3 < 8; m += 4)
{
float32x4_t _t0_0123 = vld1q_f32(t0);
float32x4_t _t0_4567 = vld1q_f32(t0 + 4);
float32x4_t _t1_0123 = vld1q_f32(t1);
float32x4_t _t1_4567 = vld1q_f32(t1 + 4);
float32x4_t _t2_0123 = vld1q_f32(t2);
float32x4_t _t2_4567 = vld1q_f32(t2 + 4);
float32x4_t _t3_0123 = vld1q_f32(t3);
float32x4_t _t3_4567 = vld1q_f32(t3 + 4);
float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123);
float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567);
float32x4x2_t _t23_00221133 = vtrnq_f32(_t2_0123, _t3_0123);
float32x4x2_t _t23_44665577 = vtrnq_f32(_t2_4567, _t3_4567);
// no vswp intrinsic :(
float32x4_t _t_00 = vcombine_f32(vget_low_f32(_t01_00221133.val[0]), vget_low_f32(_t23_00221133.val[0]));
float32x4_t _t_11 = vcombine_f32(vget_low_f32(_t01_00221133.val[1]), vget_low_f32(_t23_00221133.val[1]));
float32x4_t _t_22 = vcombine_f32(vget_high_f32(_t01_00221133.val[0]), vget_high_f32(_t23_00221133.val[0]));
float32x4_t _t_33 = vcombine_f32(vget_high_f32(_t01_00221133.val[1]), vget_high_f32(_t23_00221133.val[1]));
float32x4_t _t_44 = vcombine_f32(vget_low_f32(_t01_44665577.val[0]), vget_low_f32(_t23_44665577.val[0]));
float32x4_t _t_55 = vcombine_f32(vget_low_f32(_t01_44665577.val[1]), vget_low_f32(_t23_44665577.val[1]));
float32x4_t _t_66 = vcombine_f32(vget_high_f32(_t01_44665577.val[0]), vget_high_f32(_t23_44665577.val[0]));
float32x4_t _t_77 = vcombine_f32(vget_high_f32(_t01_44665577.val[1]), vget_high_f32(_t23_44665577.val[1]));
float32x4_t _t_0_m_6 = vsubq_f32(_t_00, _t_66);
float32x4_t _t_7_m_1 = vsubq_f32(_t_77, _t_11);
float32x4_t _t_4_m_2 = vsubq_f32(_t_44, _t_22);
float32x4_t _t_3_m_5 = vsubq_f32(_t_33, _t_55);
float32x4_t _r0_tm_0_0 = vmlaq_lane_f32(_t_0_m_6, _t_4_m_2, vget_high_f32(_coeff1), 1);
float32x4_t _r0_tm_4_3 = vmlaq_lane_f32(_t_7_m_1, _t_3_m_5, vget_high_f32(_coeff1), 1);
r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_0, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_0, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_0, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_0, 3);
r0_tm0 += img0_tm.w * tiles;
r0_tm1 += img0_tm.w * tiles;
r0_tm2 += img0_tm.w * tiles;
r0_tm3 += img0_tm.w * tiles;
float32x4_t _t_2_m_6 = vaddq_f32(_t_22, _t_66);
float32x4_t _t_1_m_5 = vaddq_f32(_t_11, _t_55);
float32x4_t _tmp12a = vmlsq_lane_f32(_t_2_m_6, _t_44, vget_high_f32(_coeff1), 0);
float32x4_t _tmp12b = vmlsq_lane_f32(_t_1_m_5, _t_33, vget_high_f32(_coeff1), 0);
float32x4_t _r0_tm_0_1 = vaddq_f32(_tmp12a, _tmp12b);
float32x4_t _r0_tm_0_2 = vsubq_f32(_tmp12a, _tmp12b);
r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_1, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_1, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_1, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_1, 3);
r0_tm0 += img0_tm.w * tiles;
r0_tm1 += img0_tm.w * tiles;
r0_tm2 += img0_tm.w * tiles;
r0_tm3 += img0_tm.w * tiles;
r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_2, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_2, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_2, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_2, 3);
r0_tm0 += img0_tm.w * tiles;
r0_tm1 += img0_tm.w * tiles;
r0_tm2 += img0_tm.w * tiles;
r0_tm3 += img0_tm.w * tiles;
float32x4_t _t_4_x_c = vmulq_lane_f32(_t_44, vget_high_f32(_coeff0), 0);
float32x4_t _t_3_x_c = vmulq_lane_f32(_t_33, vget_low_f32(_coeff1), 0);
float32x4_t _tmp34a = vaddq_f32(_t_66, _t_4_x_c);
_tmp34a = vmlaq_lane_f32(_tmp34a, _t_22, vget_low_f32(_coeff0), 0);
float32x4_t _tmp34b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_low_f32(_coeff0), 1);
_tmp34b = vmlaq_lane_f32(_tmp34b, _t_55, vget_high_f32(_coeff0), 1);
float32x4_t _r0_tm_0_3 = vaddq_f32(_tmp34a, _tmp34b);
float32x4_t _r0_tm_4_0 = vsubq_f32(_tmp34a, _tmp34b);
r0_tm0[0] = vgetq_lane_f32(_r0_tm_0_3, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_0_3, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_0_3, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_0_3, 3);
r0_tm0 += img0_tm.w * tiles;
r0_tm1 += img0_tm.w * tiles;
r0_tm2 += img0_tm.w * tiles;
r0_tm3 += img0_tm.w * tiles;
r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_0, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_0, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_0, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_0, 3);
r0_tm0 += img0_tm.w * tiles;
r0_tm1 += img0_tm.w * tiles;
r0_tm2 += img0_tm.w * tiles;
r0_tm3 += img0_tm.w * tiles;
float32x4_t _t_2_a_4c = vaddq_f32(_t_22, _t_4_x_c);
float32x4_t _tmp56a = vmlaq_lane_f32(_t_66, _t_2_a_4c, vget_low_f32(_coeff1), 1);
float32x4_t _tmp56b = vmlaq_lane_f32(_t_3_x_c, _t_11, vget_high_f32(_coeff0), 1);
_tmp56b = vmlaq_lane_f32(_tmp56b, _t_55, vget_low_f32(_coeff0), 1);
float32x4_t _r0_tm_4_1 = vaddq_f32(_tmp56a, _tmp56b);
float32x4_t _r0_tm_4_2 = vsubq_f32(_tmp56a, _tmp56b);
r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_1, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_1, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_1, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_1, 3);
r0_tm0 += img0_tm.w * tiles;
r0_tm1 += img0_tm.w * tiles;
r0_tm2 += img0_tm.w * tiles;
r0_tm3 += img0_tm.w * tiles;
r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_2, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_2, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_2, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_2, 3);
r0_tm0 += img0_tm.w * tiles;
r0_tm1 += img0_tm.w * tiles;
r0_tm2 += img0_tm.w * tiles;
r0_tm3 += img0_tm.w * tiles;
r0_tm0[0] = vgetq_lane_f32(_r0_tm_4_3, 0);
r0_tm1[0] = vgetq_lane_f32(_r0_tm_4_3, 1);
r0_tm2[0] = vgetq_lane_f32(_r0_tm_4_3, 2);
r0_tm3[0] = vgetq_lane_f32(_r0_tm_4_3, 3);
t0 += 8 * 4;
t1 += 8 * 4;
t2 += 8 * 4;
t3 += 8 * 4;
r0_tm0 += img0_tm.w * tiles * 25;
r0_tm1 += img0_tm.w * tiles * 25;
r0_tm2 += img0_tm.w * tiles * 25;
r0_tm3 += img0_tm.w * tiles * 25;
}
#else // __aarch64__
float* t0 = tmp[0];
float* t1 = tmp[1];
float* t2 = tmp[2];
float* t3 = tmp[3];
float* t4 = tmp[4];
float* t5 = tmp[5];
float* t6 = tmp[6];
float* t7 = tmp[7];
int stepw = w * 4 * 4;
asm volatile(
// loop0
"vld1.f32 {d16-d19}, [%8], %26 \n"
"vld1.f32 {d20-d23}, [%9], %26 \n"
"vld1.f32 {d24-d27}, [%10], %26 \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11], %26 \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4-d5}, [%0]! \n" // tmp[0][m]
"vmov q3, q7 \n" // use q7
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16-d17}, [%1]! \n" // tmp[1][m]
"vmla.f32 q4, q6, %e25[1] \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18-d19}, [%2]! \n" // tmp[2][m]
"vadd.f32 q8, q2, q3 \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vadd.f32 q2, q4, q5 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d16-d17}, [%3]! \n" // tmp[3][m]
"vst1.f32 {d18-d19}, [%4]! \n" // tmp[4][m]
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d4-d5}, [%5]! \n" // tmp[5][m]
"vst1.f32 {d6-d7}, [%6]! \n" // tmp[6][m]
"vst1.f32 {d12-d13}, [%7]! \n" // tmp[7][m]
// loop1
"vld1.f32 {d16-d19}, [%8] \n"
"vld1.f32 {d20-d23}, [%9] \n"
"vld1.f32 {d24-d27}, [%10] \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11] \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4-d5}, [%0]! \n" // tmp[0][m]
"vmov q3, q7 \n" // use q7
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16-d17}, [%1]! \n" // tmp[1][m]
"vmla.f32 q4, q6, %e25[1] \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18-d19}, [%2]! \n" // tmp[2][m]
"vadd.f32 q8, q2, q3 \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vadd.f32 q2, q4, q5 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d16-d17}, [%3]! \n" // tmp[3][m]
"vst1.f32 {d18-d19}, [%4]! \n" // tmp[4][m]
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d4-d5}, [%5]! \n" // tmp[5][m]
"vst1.f32 {d6-d7}, [%6]! \n" // tmp[6][m]
"vst1.f32 {d12-d13}, [%7]! \n" // tmp[7][m]
: "=r"(t0), // %0
"=r"(t1), // %1
"=r"(t2), // %2
"=r"(t3), // %3
"=r"(t4), // %4
"=r"(t5), // %5
"=r"(t6), // %6
"=r"(t7), // %7
"=r"(r0), // %8
"=r"(r1), // %9
"=r"(r2), // %10
"=r"(r3) // %11
: "0"(t0),
"1"(t1),
"2"(t2),
"3"(t3),
"4"(t4),
"5"(t5),
"6"(t6),
"7"(t7),
"8"(r0),
"9"(r1),
"10"(r2),
"11"(r3),
"w"(_coeff0), // %24
"w"(_coeff1), // %25
"r"(stepw) // %26
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
t0 = tmp[0];
t1 = tmp[1];
t2 = tmp[2];
t3 = tmp[3];
float* r0_tm0_0 = img0_tm.row(i * w_tm / 8 + j);
float* r0_tm1_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 8);
float* r0_tm2_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 16);
float* r0_tm3_0 = img0_tm.row(i * w_tm / 8 + j + tiles * 24);
float* r0_tm0_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 32);
float* r0_tm1_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 40);
float* r0_tm2_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 48);
float* r0_tm3_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 56);
int step = img0_tm.w * tiles * 4;
asm volatile(
// loop0
"vld1.f32 {d16-d19}, [%8] \n"
"add %8, %8, #128 \n"
"vld1.f32 {d20-d23}, [%9] \n"
"add %9, %9, #128 \n"
"vld1.f32 {d24-d27}, [%10] \n"
"add %10, %10, #128 \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11] \n"
"add %11, %11, #128 \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4[0]}, [%0], %26 \n"
"vst1.f32 {d4[1]}, [%1], %26 \n"
"vmov q3, q7 \n" // use q7
"vst1.f32 {d5[0]}, [%2], %26 \n"
"vst1.f32 {d5[1]}, [%3], %26 \n"
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16[0]}, [%0], %26 \n"
"vst1.f32 {d16[1]}, [%1], %26 \n"
"vmla.f32 q4, q6, %e25[1] \n"
"vst1.f32 {d17[0]}, [%2], %26 \n"
"vst1.f32 {d17[1]}, [%3], %26 \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18[0]}, [%0], %26 \n"
"vst1.f32 {d18[1]}, [%1], %26 \n"
"vadd.f32 q8, q2, q3 \n"
"vst1.f32 {d19[0]}, [%2], %26 \n"
"vst1.f32 {d19[1]}, [%3], %26 \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vst1.f32 {d16[0]}, [%0], %26 \n"
"vst1.f32 {d16[1]}, [%1], %26 \n"
"vst1.f32 {d17[0]}, [%2], %26 \n"
"vst1.f32 {d17[1]}, [%3], %26 \n"
"vadd.f32 q2, q4, q5 \n"
"vst1.f32 {d18[0]}, [%0], %26 \n"
"vst1.f32 {d18[1]}, [%1], %26 \n"
"vst1.f32 {d19[0]}, [%2], %26 \n"
"vst1.f32 {d19[1]}, [%3], %26 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d4[0]}, [%0], %26 \n"
"vst1.f32 {d4[1]}, [%1], %26 \n"
"vst1.f32 {d5[0]}, [%2], %26 \n"
"vst1.f32 {d5[1]}, [%3], %26 \n"
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d6[0]}, [%0], %26 \n"
"vst1.f32 {d6[1]}, [%1], %26 \n"
"vst1.f32 {d7[0]}, [%2], %26 \n"
"vst1.f32 {d7[1]}, [%3], %26 \n"
"vst1.f32 {d12[0]}, [%0] \n"
"vst1.f32 {d12[1]}, [%1] \n"
"vst1.f32 {d13[0]}, [%2] \n"
"vst1.f32 {d13[1]}, [%3] \n"
// loop1
"vld1.f32 {d16-d19}, [%8] \n"
"vld1.f32 {d20-d23}, [%9] \n"
"vld1.f32 {d24-d27}, [%10] \n"
"vtrn.32 q8, q10 \n"
"vld1.f32 {d28-d31}, [%11] \n"
"vtrn.32 q9, q11 \n"
"vtrn.32 q12, q14 \n"
"vtrn.32 q13, q15 \n"
"vswp d17, d24 \n"
"vswp d19, d26 \n"
"vswp d21, d28 \n" // q8 = 00 q9 = 44 q10 = 11 q11 = 55
"vswp d23, d30 \n" // q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vsub.f32 q2, q8, q13 \n"
"vsub.f32 q3, q9, q12 \n"
"vadd.f32 q4, q12, q13 \n"
"vadd.f32 q5, q10, q11 \n"
"vmla.f32 q2, q3, %f25[1] \n"
"vmul.f32 q7, q14, %e25[0] \n" // q7 = _r_3_x_c
"vmul.f32 q6, q9, %f24[0] \n" // q6 = _r_4_x_c
"vmls.f32 q4, q9, %f25[0] \n"
"vmls.f32 q5, q14, %f25[0] \n"
"vst1.f32 {d4[0]}, [%4], %26 \n"
"vst1.f32 {d4[1]}, [%5], %26 \n"
"vmov q3, q7 \n" // use q7
"vst1.f32 {d5[0]}, [%6], %26 \n"
"vst1.f32 {d5[1]}, [%7], %26 \n"
"vadd.f32 q2, q13, q6 \n" // use q6
"vmla.f32 q3, q10, %e24[1] \n"
"vadd.f32 q8, q4, q5 \n"
"vsub.f32 q9, q4, q5 \n"
"vmov q5, q7 \n" // use q7
"vadd.f32 q6, q12, q6 \n" // use q6
"vmla.f32 q5, q10, %f24[1] \n"
"vmov q4, q13 \n"
"vmla.f32 q2, q12, %e24[0] \n"
"vmla.f32 q3, q11, %f24[1] \n"
"vst1.f32 {d16[0]}, [%4], %26 \n"
"vst1.f32 {d16[1]}, [%5], %26 \n"
"vmla.f32 q4, q6, %e25[1] \n"
"vst1.f32 {d17[0]}, [%6], %26 \n"
"vst1.f32 {d17[1]}, [%7], %26 \n"
"vmla.f32 q5, q11, %e24[1] \n"
"vst1.f32 {d18[0]}, [%4], %26 \n"
"vst1.f32 {d18[1]}, [%5], %26 \n"
"vadd.f32 q8, q2, q3 \n"
"vst1.f32 {d19[0]}, [%6], %26 \n"
"vst1.f32 {d19[1]}, [%7], %26 \n"
"vsub.f32 q9, q2, q3 \n"
"vsub.f32 q6, q15, q10 \n"
"vsub.f32 q7, q14, q11 \n"
"vst1.f32 {d16[0]}, [%4], %26 \n"
"vst1.f32 {d16[1]}, [%5], %26 \n"
"vst1.f32 {d17[0]}, [%6], %26 \n"
"vst1.f32 {d17[1]}, [%7], %26 \n"
"vadd.f32 q2, q4, q5 \n"
"vst1.f32 {d18[0]}, [%4], %26 \n"
"vst1.f32 {d18[1]}, [%5], %26 \n"
"vst1.f32 {d19[0]}, [%6], %26 \n"
"vst1.f32 {d19[1]}, [%7], %26 \n"
"vsub.f32 q3, q4, q5 \n"
"vst1.f32 {d4[0]}, [%4], %26 \n"
"vst1.f32 {d4[1]}, [%5], %26 \n"
"vst1.f32 {d5[0]}, [%6], %26 \n"
"vst1.f32 {d5[1]}, [%7], %26 \n"
"vmla.f32 q6, q7, %f25[1] \n"
"vst1.f32 {d6[0]}, [%4], %26 \n"
"vst1.f32 {d6[1]}, [%5], %26 \n"
"vst1.f32 {d7[0]}, [%6], %26 \n"
"vst1.f32 {d7[1]}, [%7], %26 \n"
"vst1.f32 {d12[0]}, [%4] \n"
"vst1.f32 {d12[1]}, [%5] \n"
"vst1.f32 {d13[0]}, [%6] \n"
"vst1.f32 {d13[1]}, [%7] \n"
: "=r"(r0_tm0_0), // %0
"=r"(r0_tm1_0), // %1
"=r"(r0_tm2_0), // %2
"=r"(r0_tm3_0), // %3
"=r"(r0_tm0_4), // %4
"=r"(r0_tm1_4), // %5
"=r"(r0_tm2_4), // %6
"=r"(r0_tm3_4), // %7
"=r"(t0), // %8
"=r"(t1), // %9
"=r"(t2), // %10
"=r"(t3) // %11
: "0"(r0_tm0_0),
"1"(r0_tm1_0),
"2"(r0_tm2_0),
"3"(r0_tm3_0),
"4"(r0_tm0_4),
"5"(r0_tm1_4),
"6"(r0_tm2_4),
"7"(r0_tm3_4),
"8"(t0),
"9"(t1),
"10"(t2),
"11"(t3),
"w"(_coeff0), // %24
"w"(_coeff1), // %25
"r"(step) // %26
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
const float* r0 = img0.row(i * 6) + j * 6;
for (int m = 0; m < 8; m++)
{
tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25f;
tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25f;
float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25f);
float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25f);
tmp[1][m] = tmp12a + tmp12b;
tmp[2][m] = tmp12a - tmp12b;
float tmp34a = (r0[6] + r0[2] * 0.25f - r0[4] * 1.25f);
float tmp34b = (r0[1] * 0.5f - r0[3] * 2.5f + r0[5] * 2.f);
tmp[3][m] = tmp34a + tmp34b;
tmp[4][m] = tmp34a - tmp34b;
float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25f) * 4.f);
float tmp56b = (r0[1] * 2.f - r0[3] * 2.5f + r0[5] * 0.5f);
tmp[5][m] = tmp56a + tmp56b;
tmp[6][m] = tmp56a - tmp56b;
r0 += w;
}
float* r0_tm_0 = img0_tm.row(i * w_tm / 8 + j);
float* r0_tm_1 = img0_tm.row(i * w_tm / 8 + j + tiles);
float* r0_tm_2 = img0_tm.row(i * w_tm / 8 + j + tiles * 2);
float* r0_tm_3 = img0_tm.row(i * w_tm / 8 + j + tiles * 3);
float* r0_tm_4 = img0_tm.row(i * w_tm / 8 + j + tiles * 4);
float* r0_tm_5 = img0_tm.row(i * w_tm / 8 + j + tiles * 5);
float* r0_tm_6 = img0_tm.row(i * w_tm / 8 + j + tiles * 6);
float* r0_tm_7 = img0_tm.row(i * w_tm / 8 + j + tiles * 7);
for (int m = 0; m < 8; m++)
{
const float* tmp0 = tmp[m];
r0_tm_0[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25f;
r0_tm_7[0] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25f;
float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25f);
float tmp12b = (tmp0[1] - tmp0[3] * 4.25f + tmp0[5]);
r0_tm_1[0] = tmp12a + tmp12b;
r0_tm_2[0] = tmp12a - tmp12b;
float tmp34a = (tmp0[6] + tmp0[2] * 0.25f - tmp0[4] * 1.25f);
float tmp34b = (tmp0[1] * 0.5f - tmp0[3] * 2.5f + tmp0[5] * 2.f);
r0_tm_3[0] = tmp34a + tmp34b;
r0_tm_4[0] = tmp34a - tmp34b;
float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25f) * 4.f);
float tmp56b = (tmp0[1] * 2.f - tmp0[3] * 2.5f + tmp0[5] * 0.5f);
r0_tm_5[0] = tmp56a + tmp56b;
r0_tm_6[0] = tmp56a - tmp56b;
r0_tm_0 += img0_tm.w * tiles * 8;
r0_tm_1 += img0_tm.w * tiles * 8;
r0_tm_2 += img0_tm.w * tiles * 8;
r0_tm_3 += img0_tm.w * tiles * 8;
r0_tm_4 += img0_tm.w * tiles * 8;
r0_tm_5 += img0_tm.w * tiles * 8;
r0_tm_6 += img0_tm.w * tiles * 8;
r0_tm_7 += img0_tm.w * tiles * 8;
}
#endif // __ARM_NEON
}
}
}
}
bottom_blob_bordered = Mat();
// END transform input
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
// permute
// bottom_blob_tm.create(1, 64 * tiles, inch);
// Mat bottom_blob_tm2(inch, tiles, 64);
Mat bottom_blob_tm2(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 64, 4u, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r = 0; r < 64; r++)
{
Mat tm2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
for (; i + 7 < tiles; i += 8)
{
float* tm2p = tm2.row(i / 8);
const float* r0 = bottom_blob_tm;
r0 += r * tiles + i;
for (int q = 0; q < inch; q++)
{
#if __ARM_NEON
float32x4_t _r0 = vld1q_f32(r0);
float32x4_t _r0n = vld1q_f32(r0 + 4);
vst1q_f32(tm2p, _r0);
vst1q_f32(tm2p + 4, _r0n);
#else
tm2p[0] = r0[0];
tm2p[1] = r0[1];
tm2p[2] = r0[2];
tm2p[3] = r0[3];
tm2p[4] = r0[4];
tm2p[5] = r0[5];
tm2p[6] = r0[6];
tm2p[7] = r0[7];
#endif // __ARM_NEON
r0 += bottom_blob_tm.cstep;
tm2p += 8;
}
}
for (; i + 3 < tiles; i += 4)
{
float* tm2p = tm2.row(i / 8 + (i % 8) / 4);
const float* r0 = bottom_blob_tm;
r0 += r * tiles + i;
for (int q = 0; q < inch; q++)
{
#if __ARM_NEON
float32x4_t _r0 = vld1q_f32(r0);
vst1q_f32(tm2p, _r0);
#else
tm2p[0] = r0[0];
tm2p[1] = r0[1];
tm2p[2] = r0[2];
tm2p[3] = r0[3];
#endif // __ARM_NEON
r0 += bottom_blob_tm.cstep;
tm2p += 4;
}
}
for (; i < tiles; i++)
{
float* tm2p = tm2.row(i / 8 + (i % 8) / 4 + i % 4);
const float* r0 = bottom_blob_tm;
r0 += r * tiles + i;
for (int q = 0; q < inch; q++)
{
tm2p[0] = r0[0];
r0 += bottom_blob_tm.cstep;
tm2p += 1;
}
}
}
bottom_blob_tm = Mat();
// permute end
top_blob_tm.create(1, 64 * tiles, outch);
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 8;
const Mat kernel_tm0 = kernel_tm.channel(p / 8);
Mat out0_tm = top_blob_tm.channel(p);
Mat out1_tm = top_blob_tm.channel(p + 1);
Mat out2_tm = top_blob_tm.channel(p + 2);
Mat out3_tm = top_blob_tm.channel(p + 3);
Mat out4_tm = top_blob_tm.channel(p + 4);
Mat out5_tm = top_blob_tm.channel(p + 5);
Mat out6_tm = top_blob_tm.channel(p + 6);
Mat out7_tm = top_blob_tm.channel(p + 7);
float* output0_tm = out0_tm;
float* output1_tm = out1_tm;
float* output2_tm = out2_tm;
float* output3_tm = out3_tm;
float* output4_tm = out4_tm;
float* output5_tm = out5_tm;
float* output6_tm = out6_tm;
float* output7_tm = out7_tm;
for (int r = 0; r < 64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
for (; i + 7 < tiles; i += 8)
{
const float* bb2p0 = bb2.row(i / 8);
const float* ktm0 = kernel_tm0.row(r);
asm volatile(
"eor v16.16b, v16.16b, v16.16b \n"
"eor v17.16b, v17.16b, v17.16b \n"
"eor v18.16b, v18.16b, v18.16b \n"
"eor v19.16b, v19.16b, v19.16b \n"
"eor v20.16b, v20.16b, v20.16b \n"
"eor v21.16b, v21.16b, v21.16b \n"
"eor v22.16b, v22.16b, v22.16b \n"
"eor v23.16b, v23.16b, v23.16b \n"
"eor v24.16b, v24.16b, v24.16b \n"
"eor v25.16b, v25.16b, v25.16b \n"
"eor v26.16b, v26.16b, v26.16b \n"
"eor v27.16b, v27.16b, v27.16b \n"
"eor v28.16b, v28.16b, v28.16b \n"
"eor v29.16b, v29.16b, v29.16b \n"
"eor v30.16b, v30.16b, v30.16b \n"
"eor v31.16b, v31.16b, v31.16b \n"
// inch loop
"lsr w4, %w20, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"fmla v18.4s, v8.4s, v0.s[1] \n"
"fmla v19.4s, v9.4s, v0.s[1] \n"
"fmla v20.4s, v8.4s, v0.s[2] \n"
"fmla v21.4s, v9.4s, v0.s[2] \n"
"fmla v22.4s, v8.4s, v0.s[3] \n"
"fmla v23.4s, v9.4s, v0.s[3] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n"
"fmla v24.4s, v8.4s, v1.s[0] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v26.4s, v8.4s, v1.s[1] \n"
"fmla v27.4s, v9.4s, v1.s[1] \n"
"fmla v28.4s, v8.4s, v1.s[2] \n"
"fmla v29.4s, v9.4s, v1.s[2] \n"
"fmla v30.4s, v8.4s, v1.s[3] \n"
"fmla v31.4s, v9.4s, v1.s[3] \n"
"fmla v16.4s, v10.4s, v2.s[0] \n"
"fmla v17.4s, v11.4s, v2.s[0] \n"
"fmla v18.4s, v10.4s, v2.s[1] \n"
"fmla v19.4s, v11.4s, v2.s[1] \n"
"fmla v20.4s, v10.4s, v2.s[2] \n"
"fmla v21.4s, v11.4s, v2.s[2] \n"
"fmla v22.4s, v10.4s, v2.s[3] \n"
"fmla v23.4s, v11.4s, v2.s[3] \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%8], #64 \n"
"fmla v24.4s, v10.4s, v3.s[0] \n"
"fmla v25.4s, v11.4s, v3.s[0] \n"
"fmla v26.4s, v10.4s, v3.s[1] \n"
"fmla v27.4s, v11.4s, v3.s[1] \n"
"fmla v28.4s, v10.4s, v3.s[2] \n"
"fmla v29.4s, v11.4s, v3.s[2] \n"
"fmla v30.4s, v10.4s, v3.s[3] \n"
"fmla v31.4s, v11.4s, v3.s[3] \n"
"fmla v16.4s, v12.4s, v4.s[0] \n"
"fmla v17.4s, v13.4s, v4.s[0] \n"
"fmla v18.4s, v12.4s, v4.s[1] \n"
"fmla v19.4s, v13.4s, v4.s[1] \n"
"fmla v20.4s, v12.4s, v4.s[2] \n"
"fmla v21.4s, v13.4s, v4.s[2] \n"
"fmla v22.4s, v12.4s, v4.s[3] \n"
"fmla v23.4s, v13.4s, v4.s[3] \n"
"fmla v24.4s, v12.4s, v5.s[0] \n"
"fmla v25.4s, v13.4s, v5.s[0] \n"
"fmla v26.4s, v12.4s, v5.s[1] \n"
"fmla v27.4s, v13.4s, v5.s[1] \n"
"fmla v28.4s, v12.4s, v5.s[2] \n"
"fmla v29.4s, v13.4s, v5.s[2] \n"
"fmla v30.4s, v12.4s, v5.s[3] \n"
"fmla v31.4s, v13.4s, v5.s[3] \n"
"fmla v16.4s, v14.4s, v6.s[0] \n"
"fmla v17.4s, v15.4s, v6.s[0] \n"
"fmla v18.4s, v14.4s, v6.s[1] \n"
"fmla v19.4s, v15.4s, v6.s[1] \n"
"fmla v20.4s, v14.4s, v6.s[2] \n"
"fmla v21.4s, v15.4s, v6.s[2] \n"
"fmla v22.4s, v14.4s, v6.s[3] \n"
"fmla v23.4s, v15.4s, v6.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v24.4s, v14.4s, v7.s[0] \n"
"fmla v25.4s, v15.4s, v7.s[0] \n"
"fmla v26.4s, v14.4s, v7.s[1] \n"
"fmla v27.4s, v15.4s, v7.s[1] \n"
"fmla v28.4s, v14.4s, v7.s[2] \n"
"fmla v29.4s, v15.4s, v7.s[2] \n"
"fmla v30.4s, v14.4s, v7.s[3] \n"
"fmla v31.4s, v15.4s, v7.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w20, #3 \n" // w4 = remain = tiles & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v8.4s, v9.4s}, [%8], #32 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s}, [%9], #32 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"fmla v18.4s, v8.4s, v0.s[1] \n"
"fmla v19.4s, v9.4s, v0.s[1] \n"
"fmla v20.4s, v8.4s, v0.s[2] \n"
"fmla v21.4s, v9.4s, v0.s[2] \n"
"fmla v22.4s, v8.4s, v0.s[3] \n"
"fmla v23.4s, v9.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v24.4s, v8.4s, v1.s[0] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v26.4s, v8.4s, v1.s[1] \n"
"fmla v27.4s, v9.4s, v1.s[1] \n"
"fmla v28.4s, v8.4s, v1.s[2] \n"
"fmla v29.4s, v9.4s, v1.s[2] \n"
"fmla v30.4s, v8.4s, v1.s[3] \n"
"fmla v31.4s, v9.4s, v1.s[3] \n"
"bne 2b \n"
"3: \n"
"st1 {v16.4s, v17.4s}, [%0], #32 \n"
"st1 {v18.4s, v19.4s}, [%1], #32 \n"
"st1 {v20.4s, v21.4s}, [%2], #32 \n"
"st1 {v22.4s, v23.4s}, [%3], #32 \n"
"st1 {v24.4s, v25.4s}, [%4], #32 \n"
"st1 {v26.4s, v27.4s}, [%5], #32 \n"
"st1 {v28.4s, v29.4s}, [%6], #32 \n"
"st1 {v30.4s, v31.4s}, [%7], #32 \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(bb2p0), // %8
"=r"(ktm0) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(bb2p0),
"9"(ktm0),
"r"(inch) // %20
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 3 < tiles; i += 4)
{
const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4);
const float* ktm0 = kernel_tm0.row(r);
asm volatile(
"eor v16.16b, v16.16b, v16.16b \n"
"eor v17.16b, v17.16b, v17.16b \n"
"eor v18.16b, v18.16b, v18.16b \n"
"eor v19.16b, v19.16b, v19.16b \n"
"eor v20.16b, v20.16b, v20.16b \n"
"eor v21.16b, v21.16b, v21.16b \n"
"eor v22.16b, v22.16b, v22.16b \n"
"eor v23.16b, v23.16b, v23.16b \n"
// inch loop
"lsr w4, %w20, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v0.s[1] \n"
"fmla v18.4s, v8.4s, v0.s[2] \n"
"fmla v19.4s, v8.4s, v0.s[3] \n"
"fmla v20.4s, v8.4s, v1.s[0] \n"
"fmla v21.4s, v8.4s, v1.s[1] \n"
"fmla v22.4s, v8.4s, v1.s[2] \n"
"fmla v23.4s, v8.4s, v1.s[3] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n"
"fmla v16.4s, v9.4s, v2.s[0] \n"
"fmla v17.4s, v9.4s, v2.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[2] \n"
"fmla v19.4s, v9.4s, v2.s[3] \n"
"fmla v20.4s, v9.4s, v3.s[0] \n"
"fmla v21.4s, v9.4s, v3.s[1] \n"
"fmla v22.4s, v9.4s, v3.s[2] \n"
"fmla v23.4s, v9.4s, v3.s[3] \n"
"fmla v16.4s, v10.4s, v4.s[0] \n"
"fmla v17.4s, v10.4s, v4.s[1] \n"
"fmla v18.4s, v10.4s, v4.s[2] \n"
"fmla v19.4s, v10.4s, v4.s[3] \n"
"fmla v20.4s, v10.4s, v5.s[0] \n"
"fmla v21.4s, v10.4s, v5.s[1] \n"
"fmla v22.4s, v10.4s, v5.s[2] \n"
"fmla v23.4s, v10.4s, v5.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v16.4s, v11.4s, v6.s[0] \n"
"fmla v17.4s, v11.4s, v6.s[1] \n"
"fmla v18.4s, v11.4s, v6.s[2] \n"
"fmla v19.4s, v11.4s, v6.s[3] \n"
"fmla v20.4s, v11.4s, v7.s[0] \n"
"fmla v21.4s, v11.4s, v7.s[1] \n"
"fmla v22.4s, v11.4s, v7.s[2] \n"
"fmla v23.4s, v11.4s, v7.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w20, #3 \n" // w4 = remain = tiles & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #128] \n"
"ld1 {v8.4s}, [%8], #16 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s}, [%9], #32 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v0.s[1] \n"
"fmla v18.4s, v8.4s, v0.s[2] \n"
"fmla v19.4s, v8.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v20.4s, v8.4s, v1.s[0] \n"
"fmla v21.4s, v8.4s, v1.s[1] \n"
"fmla v22.4s, v8.4s, v1.s[2] \n"
"fmla v23.4s, v8.4s, v1.s[3] \n"
"bne 2b \n"
"3: \n"
"st1 {v16.4s}, [%0], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
"st1 {v18.4s}, [%2], #16 \n"
"st1 {v19.4s}, [%3], #16 \n"
"st1 {v20.4s}, [%4], #16 \n"
"st1 {v21.4s}, [%5], #16 \n"
"st1 {v22.4s}, [%6], #16 \n"
"st1 {v23.4s}, [%7], #16 \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(bb2p0), // %8
"=r"(ktm0) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(bb2p0),
"9"(ktm0),
"r"(inch) // %20
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
}
for (; i < tiles; i++)
{
const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4);
const float* ktm0 = kernel_tm0.row(r);
float32x4_t _sum0123 = vdupq_n_f32(0.f);
float32x4_t _sum4567 = vdupq_n_f32(0.f);
int q = 0;
for (; q + 3 < inch; q += 4)
{
// asm volatile("prfm pldl1keep, [%0, #128] \n" : :"r"(bb2p0) :);
float32x4_t _bb2p0 = vld1q_f32(bb2p0);
bb2p0 += 4;
// asm volatile("prfm pldl1keep, [%0, #512] \n" : :"r"(ktm0) :);
float32x4_t _ktm0 = vld1q_f32(ktm0 + 0);
float32x4_t _ktm1 = vld1q_f32(ktm0 + 4);
float32x4_t _ktm2 = vld1q_f32(ktm0 + 8);
float32x4_t _ktm3 = vld1q_f32(ktm0 + 12);
ktm0 += 16;
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm0, _bb2p0, 0);
_sum4567 = vmlaq_laneq_f32(_sum4567, _ktm1, _bb2p0, 0);
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm2, _bb2p0, 1);
_sum4567 = vmlaq_laneq_f32(_sum4567, _ktm3, _bb2p0, 1);
// asm volatile("prfm pldl1keep, [%0, #512] \n" : :"r"(ktm0) :);
float32x4_t _ktm4 = vld1q_f32(ktm0 + 0);
float32x4_t _ktm5 = vld1q_f32(ktm0 + 4);
float32x4_t _ktm6 = vld1q_f32(ktm0 + 8);
float32x4_t _ktm7 = vld1q_f32(ktm0 + 12);
ktm0 += 16;
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm4, _bb2p0, 2);
_sum4567 = vmlaq_laneq_f32(_sum4567, _ktm5, _bb2p0, 2);
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm6, _bb2p0, 3);
_sum4567 = vmlaq_laneq_f32(_sum4567, _ktm7, _bb2p0, 3);
}
for (; q < inch; q++)
{
float32x4_t _bb2p0 = vld1q_dup_f32(bb2p0);
float32x4_t _ktm0123 = vld1q_f32(ktm0 + 0);
float32x4_t _ktm4567 = vld1q_f32(ktm0 + 4);
_sum0123 = vmlaq_f32(_sum0123, _bb2p0, _ktm0123);
_sum4567 = vmlaq_f32(_sum4567, _bb2p0, _ktm4567);
bb2p0 += 1;
ktm0 += 8;
}
float sum0 = vgetq_lane_f32(_sum0123, 0);
float sum1 = vgetq_lane_f32(_sum0123, 1);
float sum2 = vgetq_lane_f32(_sum0123, 2);
float sum3 = vgetq_lane_f32(_sum0123, 3);
float sum4 = vgetq_lane_f32(_sum4567, 0);
float sum5 = vgetq_lane_f32(_sum4567, 1);
float sum6 = vgetq_lane_f32(_sum4567, 2);
float sum7 = vgetq_lane_f32(_sum4567, 3);
output0_tm[0] = sum0;
output1_tm[0] = sum1;
output2_tm[0] = sum2;
output3_tm[0] = sum3;
output4_tm[0] = sum4;
output5_tm[0] = sum5;
output6_tm[0] = sum6;
output7_tm[0] = sum7;
output0_tm += 1;
output1_tm += 1;
output2_tm += 1;
output3_tm += 1;
output4_tm += 1;
output5_tm += 1;
output6_tm += 1;
output7_tm += 1;
}
}
}
#endif // __aarch64__
nn_outch = (outch - remain_outch_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
#if __ARM_NEON && __aarch64__
const Mat kernel_tm0 = kernel_tm.channel(p / 8 + (p % 8) / 4);
#else
const Mat kernel_tm0 = kernel_tm.channel(p / 4);
#endif
Mat out0_tm = top_blob_tm.channel(p);
Mat out1_tm = top_blob_tm.channel(p + 1);
Mat out2_tm = top_blob_tm.channel(p + 2);
Mat out3_tm = top_blob_tm.channel(p + 3);
float* output0_tm = out0_tm;
float* output1_tm = out1_tm;
float* output2_tm = out2_tm;
float* output3_tm = out3_tm;
for (int r = 0; r < 64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
for (; i + 7 < tiles; i += 8)
{
const float* bb2p0 = bb2.row(i / 8);
const float* ktm0 = kernel_tm0.row(r);
#if __ARM_NEON
#if __aarch64__
asm volatile(
"eor v8.16b, v8.16b, v8.16b \n"
"eor v9.16b, v9.16b, v9.16b \n"
"eor v10.16b, v10.16b, v10.16b \n"
"eor v11.16b, v11.16b, v11.16b \n"
"eor v12.16b, v12.16b, v12.16b \n"
"eor v13.16b, v13.16b, v13.16b \n"
"eor v14.16b, v14.16b, v14.16b \n"
"eor v15.16b, v15.16b, v15.16b \n"
// inch loop
"lsr w4, %w12, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"fmla v10.4s, v4.4s, v0.s[1] \n"
"fmla v11.4s, v5.4s, v0.s[1] \n"
"fmla v12.4s, v4.4s, v0.s[2] \n"
"fmla v13.4s, v5.4s, v0.s[2] \n"
"fmla v14.4s, v4.4s, v0.s[3] \n"
"fmla v15.4s, v5.4s, v0.s[3] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n"
"fmla v8.4s, v6.4s, v1.s[0] \n"
"fmla v9.4s, v7.4s, v1.s[0] \n"
"fmla v10.4s, v6.4s, v1.s[1] \n"
"fmla v11.4s, v7.4s, v1.s[1] \n"
"fmla v12.4s, v6.4s, v1.s[2] \n"
"fmla v13.4s, v7.4s, v1.s[2] \n"
"fmla v14.4s, v6.4s, v1.s[3] \n"
"fmla v15.4s, v7.4s, v1.s[3] \n"
"fmla v8.4s, v16.4s, v2.s[0] \n"
"fmla v9.4s, v17.4s, v2.s[0] \n"
"fmla v10.4s, v16.4s, v2.s[1] \n"
"fmla v11.4s, v17.4s, v2.s[1] \n"
"fmla v12.4s, v16.4s, v2.s[2] \n"
"fmla v13.4s, v17.4s, v2.s[2] \n"
"fmla v14.4s, v16.4s, v2.s[3] \n"
"fmla v15.4s, v17.4s, v2.s[3] \n"
"fmla v8.4s, v18.4s, v3.s[0] \n"
"fmla v9.4s, v19.4s, v3.s[0] \n"
"fmla v10.4s, v18.4s, v3.s[1] \n"
"fmla v11.4s, v19.4s, v3.s[1] \n"
"fmla v12.4s, v18.4s, v3.s[2] \n"
"fmla v13.4s, v19.4s, v3.s[2] \n"
"fmla v14.4s, v18.4s, v3.s[3] \n"
"fmla v15.4s, v19.4s, v3.s[3] \n"
"subs w4, w4, #1 \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w12, #3 \n" // w4 = remain = tiles & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v4.4s, v5.4s}, [%4], #32 \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"fmla v10.4s, v4.4s, v0.s[1] \n"
"fmla v11.4s, v5.4s, v0.s[1] \n"
"fmla v12.4s, v4.4s, v0.s[2] \n"
"fmla v13.4s, v5.4s, v0.s[2] \n"
"fmla v14.4s, v4.4s, v0.s[3] \n"
"fmla v15.4s, v5.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s, v9.4s}, [%0], #32 \n"
"st1 {v10.4s, v11.4s}, [%1], #32 \n"
"st1 {v12.4s, v13.4s}, [%2], #32 \n"
"st1 {v14.4s, v15.4s}, [%3], #32 \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(bb2p0), // %4
"=r"(ktm0) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(bb2p0),
"5"(ktm0),
"r"(inch) // %12
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
#else // __aarch64__
asm volatile(
"veor q8, q8, q8 \n"
"veor q9, q9, q9 \n"
"veor q10, q10, q10 \n"
"veor q11, q11, q11 \n"
"veor q12, q12, q12 \n"
"veor q13, q13, q13 \n"
"veor q14, q14, q14 \n"
"veor q15, q15, q15 \n"
// inch loop
"lsr r4, %12, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%4 :128]! \n"
// "vld1.f32 {d12-d15}, [%4 :128]! \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
// "vld1.f32 {d0-d3}, [%5 :128]! \n"
// "vld1.f32 {d4-d7}, [%5 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n"
"vmla.f32 q11, q5, d0[1] \n"
"vmla.f32 q12, q4, d1[0] \n"
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n"
"vmla.f32 q15, q5, d1[1] \n"
"vmla.f32 q8, q6, d2[0] \n"
"vmla.f32 q9, q7, d2[0] \n"
"vmla.f32 q10, q6, d2[1] \n"
"vmla.f32 q11, q7, d2[1] \n"
"vmla.f32 q12, q6, d3[0] \n"
"vmla.f32 q13, q7, d3[0] \n"
"vmla.f32 q14, q6, d3[1] \n"
"vmla.f32 q15, q7, d3[1] \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%4 :128]! \n"
// "vld1.f32 {d12-d15}, [%4 :128]! \n"
"vmla.f32 q8, q4, d4[0] \n"
"vmla.f32 q9, q5, d4[0] \n"
"vmla.f32 q10, q4, d4[1] \n"
"vmla.f32 q11, q5, d4[1] \n"
"vmla.f32 q12, q4, d5[0] \n"
"vmla.f32 q13, q5, d5[0] \n"
"vmla.f32 q14, q4, d5[1] \n"
"vmla.f32 q15, q5, d5[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q6, d6[0] \n"
"vmla.f32 q9, q7, d6[0] \n"
"vmla.f32 q10, q6, d6[1] \n"
"vmla.f32 q11, q7, d6[1] \n"
"vmla.f32 q12, q6, d7[0] \n"
"vmla.f32 q13, q7, d7[0] \n"
"vmla.f32 q14, q6, d7[1] \n"
"vmla.f32 q15, q7, d7[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %12, #3 \n" // r4 = remain = tiles & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #256] \n"
"vld1.f32 {d8-d11}, [%4 :128]! \n"
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n"
"vmla.f32 q11, q5, d0[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q12, q4, d1[0] \n"
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n"
"vmla.f32 q15, q5, d1[1] \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d19}, [%0]! \n"
"vst1.f32 {d20-d23}, [%1]! \n"
"vst1.f32 {d24-d27}, [%2]! \n"
"vst1.f32 {d28-d31}, [%3]! \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(bb2p0), // %4
"=r"(ktm0) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(bb2p0),
"5"(ktm0),
"r"(inch) // %12
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
float sum0_0 = 0.f;
float sum0_1 = 0.f;
float sum0_2 = 0.f;
float sum0_3 = 0.f;
float sum0_4 = 0.f;
float sum0_5 = 0.f;
float sum0_6 = 0.f;
float sum0_7 = 0.f;
float sum1_0 = 0.f;
float sum1_1 = 0.f;
float sum1_2 = 0.f;
float sum1_3 = 0.f;
float sum1_4 = 0.f;
float sum1_5 = 0.f;
float sum1_6 = 0.f;
float sum1_7 = 0.f;
float sum2_0 = 0.f;
float sum2_1 = 0.f;
float sum2_2 = 0.f;
float sum2_3 = 0.f;
float sum2_4 = 0.f;
float sum2_5 = 0.f;
float sum2_6 = 0.f;
float sum2_7 = 0.f;
float sum3_0 = 0.f;
float sum3_1 = 0.f;
float sum3_2 = 0.f;
float sum3_3 = 0.f;
float sum3_4 = 0.f;
float sum3_5 = 0.f;
float sum3_6 = 0.f;
float sum3_7 = 0.f;
for (int q = 0; q < inch; q++)
{
sum0_0 += bb2p0[0] * ktm0[0];
sum0_1 += bb2p0[1] * ktm0[0];
sum0_2 += bb2p0[2] * ktm0[0];
sum0_3 += bb2p0[3] * ktm0[0];
sum0_4 += bb2p0[4] * ktm0[0];
sum0_5 += bb2p0[5] * ktm0[0];
sum0_6 += bb2p0[6] * ktm0[0];
sum0_7 += bb2p0[7] * ktm0[0];
sum1_0 += bb2p0[0] * ktm0[1];
sum1_1 += bb2p0[1] * ktm0[1];
sum1_2 += bb2p0[2] * ktm0[1];
sum1_3 += bb2p0[3] * ktm0[1];
sum1_4 += bb2p0[4] * ktm0[1];
sum1_5 += bb2p0[5] * ktm0[1];
sum1_6 += bb2p0[6] * ktm0[1];
sum1_7 += bb2p0[7] * ktm0[1];
sum2_0 += bb2p0[0] * ktm0[2];
sum2_1 += bb2p0[1] * ktm0[2];
sum2_2 += bb2p0[2] * ktm0[2];
sum2_3 += bb2p0[3] * ktm0[2];
sum2_4 += bb2p0[4] * ktm0[2];
sum2_5 += bb2p0[5] * ktm0[2];
sum2_6 += bb2p0[6] * ktm0[2];
sum2_7 += bb2p0[7] * ktm0[2];
sum3_0 += bb2p0[0] * ktm0[3];
sum3_1 += bb2p0[1] * ktm0[3];
sum3_2 += bb2p0[2] * ktm0[3];
sum3_3 += bb2p0[3] * ktm0[3];
sum3_4 += bb2p0[4] * ktm0[3];
sum3_5 += bb2p0[5] * ktm0[3];
sum3_6 += bb2p0[6] * ktm0[3];
sum3_7 += bb2p0[7] * ktm0[3];
bb2p0 += 8;
ktm0 += 4;
}
output0_tm[0] = sum0_0;
output0_tm[1] = sum0_1;
output0_tm[2] = sum0_2;
output0_tm[3] = sum0_3;
output0_tm[4] = sum0_4;
output0_tm[5] = sum0_5;
output0_tm[6] = sum0_6;
output0_tm[7] = sum0_7;
output1_tm[0] = sum1_0;
output1_tm[1] = sum1_1;
output1_tm[2] = sum1_2;
output1_tm[3] = sum1_3;
output1_tm[4] = sum1_4;
output1_tm[5] = sum1_5;
output1_tm[6] = sum1_6;
output1_tm[7] = sum1_7;
output2_tm[0] = sum2_0;
output2_tm[1] = sum2_1;
output2_tm[2] = sum2_2;
output2_tm[3] = sum2_3;
output2_tm[4] = sum2_4;
output2_tm[5] = sum2_5;
output2_tm[6] = sum2_6;
output2_tm[7] = sum2_7;
output3_tm[0] = sum3_0;
output3_tm[1] = sum3_1;
output3_tm[2] = sum3_2;
output3_tm[3] = sum3_3;
output3_tm[4] = sum3_4;
output3_tm[5] = sum3_5;
output3_tm[6] = sum3_6;
output3_tm[7] = sum3_7;
output0_tm += 8;
output1_tm += 8;
output2_tm += 8;
output3_tm += 8;
#endif // __ARM_NEON
}
for (; i + 3 < tiles; i += 4)
{
const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4);
const float* ktm0 = kernel_tm0.row(r);
#if __ARM_NEON
#if __aarch64__
asm volatile(
"eor v8.16b, v8.16b, v8.16b \n"
"eor v9.16b, v9.16b, v9.16b \n"
"eor v10.16b, v10.16b, v10.16b \n"
"eor v11.16b, v11.16b, v11.16b \n"
// inch loop
"lsr w4, %w12, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v8.4s, v5.4s, v1.s[0] \n"
"fmla v9.4s, v5.4s, v1.s[1] \n"
"fmla v10.4s, v5.4s, v1.s[2] \n"
"fmla v11.4s, v5.4s, v1.s[3] \n"
"fmla v8.4s, v6.4s, v2.s[0] \n"
"fmla v9.4s, v6.4s, v2.s[1] \n"
"fmla v10.4s, v6.4s, v2.s[2] \n"
"fmla v11.4s, v6.4s, v2.s[3] \n"
"fmla v8.4s, v7.4s, v3.s[0] \n"
"fmla v9.4s, v7.4s, v3.s[1] \n"
"fmla v10.4s, v7.4s, v3.s[2] \n"
"fmla v11.4s, v7.4s, v3.s[3] \n"
"subs w4, w4, #1 \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w12, #3 \n" // w4 = remain = tiles & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v4.4s}, [%4], #16 \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s}, [%0], #16 \n"
"st1 {v9.4s}, [%1], #16 \n"
"st1 {v10.4s}, [%2], #16 \n"
"st1 {v11.4s}, [%3], #16 \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(bb2p0), // %4
"=r"(ktm0) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(bb2p0),
"5"(ktm0),
"r"(inch) // %12
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else // __aarch64__
asm volatile(
"veor q8, q8, q8 \n"
"veor q9, q9, q9 \n"
"veor q10, q10, q10 \n"
"veor q11, q11, q11 \n"
// inch loop
"lsr r4, %12, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%4 :128]! \n"
// "vld1.f32 {d12-d15}, [%4 :128]! \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
// "vld1.f32 {d0-d3}, [%5 :128]! \n"
// "vld1.f32 {d4-d7}, [%5 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"vmla.f32 q8, q5, d2[0] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q10, q5, d3[0] \n"
"vmla.f32 q11, q5, d3[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q6, d4[0] \n"
"vmla.f32 q9, q6, d4[1] \n"
"vmla.f32 q10, q6, d5[0] \n"
"vmla.f32 q11, q6, d5[1] \n"
"vmla.f32 q8, q7, d6[0] \n"
"vmla.f32 q9, q7, d6[1] \n"
"vmla.f32 q10, q7, d7[0] \n"
"vmla.f32 q11, q7, d7[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %12, #3 \n" // r4 = remain = tiles & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #128] \n"
"vld1.f32 {d8-d9}, [%4 :128]! \n"
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5 :128]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d17}, [%0]! \n"
"vst1.f32 {d18-d19}, [%1]! \n"
"vst1.f32 {d20-d21}, [%2]! \n"
"vst1.f32 {d22-d23}, [%3]! \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(bb2p0), // %4
"=r"(ktm0) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(bb2p0),
"5"(ktm0),
"r"(inch) // %12
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif // __aarch64__
#else
float sum0_0 = 0.f;
float sum0_1 = 0.f;
float sum0_2 = 0.f;
float sum0_3 = 0.f;
float sum1_0 = 0.f;
float sum1_1 = 0.f;
float sum1_2 = 0.f;
float sum1_3 = 0.f;
float sum2_0 = 0.f;
float sum2_1 = 0.f;
float sum2_2 = 0.f;
float sum2_3 = 0.f;
float sum3_0 = 0.f;
float sum3_1 = 0.f;
float sum3_2 = 0.f;
float sum3_3 = 0.f;
for (int q = 0; q < inch; q++)
{
sum0_0 += bb2p0[0] * ktm0[0];
sum0_1 += bb2p0[1] * ktm0[0];
sum0_2 += bb2p0[2] * ktm0[0];
sum0_3 += bb2p0[3] * ktm0[0];
sum1_0 += bb2p0[0] * ktm0[1];
sum1_1 += bb2p0[1] * ktm0[1];
sum1_2 += bb2p0[2] * ktm0[1];
sum1_3 += bb2p0[3] * ktm0[1];
sum2_0 += bb2p0[0] * ktm0[2];
sum2_1 += bb2p0[1] * ktm0[2];
sum2_2 += bb2p0[2] * ktm0[2];
sum2_3 += bb2p0[3] * ktm0[2];
sum3_0 += bb2p0[0] * ktm0[3];
sum3_1 += bb2p0[1] * ktm0[3];
sum3_2 += bb2p0[2] * ktm0[3];
sum3_3 += bb2p0[3] * ktm0[3];
bb2p0 += 4;
ktm0 += 4;
}
output0_tm[0] = sum0_0;
output0_tm[1] = sum0_1;
output0_tm[2] = sum0_2;
output0_tm[3] = sum0_3;
output1_tm[0] = sum1_0;
output1_tm[1] = sum1_1;
output1_tm[2] = sum1_2;
output1_tm[3] = sum1_3;
output2_tm[0] = sum2_0;
output2_tm[1] = sum2_1;
output2_tm[2] = sum2_2;
output2_tm[3] = sum2_3;
output3_tm[0] = sum3_0;
output3_tm[1] = sum3_1;
output3_tm[2] = sum3_2;
output3_tm[3] = sum3_3;
output0_tm += 4;
output1_tm += 4;
output2_tm += 4;
output3_tm += 4;
#endif // __ARM_NEON
}
for (; i < tiles; i++)
{
const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4);
const float* ktm0 = kernel_tm0.row(r);
#if __ARM_NEON
float32x4_t _sum0123 = vdupq_n_f32(0.f);
int q = 0;
for (; q + 3 < inch; q += 4)
{
// asm volatile("prfm pldl1keep, [%0, #128] \n" : :"r"(bb2p0) :);
float32x4_t _bb2p0 = vld1q_f32(bb2p0);
bb2p0 += 4;
// asm volatile("prfm pldl1keep, [%0, #512] \n" : :"r"(ktm0) :);
float32x4_t _ktm0 = vld1q_f32(ktm0 + 0);
float32x4_t _ktm1 = vld1q_f32(ktm0 + 4);
float32x4_t _ktm2 = vld1q_f32(ktm0 + 8);
float32x4_t _ktm3 = vld1q_f32(ktm0 + 12);
ktm0 += 16;
#if __aarch64__
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm0, _bb2p0, 0);
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm1, _bb2p0, 1);
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm2, _bb2p0, 2);
_sum0123 = vmlaq_laneq_f32(_sum0123, _ktm3, _bb2p0, 3);
#else
_sum0123 = vmlaq_lane_f32(_sum0123, _ktm0, vget_low_f32(_bb2p0), 0);
_sum0123 = vmlaq_lane_f32(_sum0123, _ktm1, vget_low_f32(_bb2p0), 1);
_sum0123 = vmlaq_lane_f32(_sum0123, _ktm2, vget_high_f32(_bb2p0), 0);
_sum0123 = vmlaq_lane_f32(_sum0123, _ktm3, vget_high_f32(_bb2p0), 1);
#endif // __aarch64__
}
for (; q < inch; q++)
{
float32x4_t _bb2p0 = vld1q_dup_f32(bb2p0);
float32x4_t _ktm0 = vld1q_f32(ktm0);
_sum0123 = vmlaq_f32(_sum0123, _bb2p0, _ktm0);
bb2p0 += 1;
ktm0 += 4;
}
float sum0 = vgetq_lane_f32(_sum0123, 0);
float sum1 = vgetq_lane_f32(_sum0123, 1);
float sum2 = vgetq_lane_f32(_sum0123, 2);
float sum3 = vgetq_lane_f32(_sum0123, 3);
#else
float sum0 = 0.f;
float sum1 = 0.f;
float sum2 = 0.f;
float sum3 = 0.f;
for (int q = 0; q < inch; q++)
{
sum0 += bb2p0[0] * ktm0[0];
sum1 += bb2p0[0] * ktm0[1];
sum2 += bb2p0[0] * ktm0[2];
sum3 += bb2p0[0] * ktm0[3];
bb2p0 += 1;
ktm0 += 4;
}
#endif // __ARM_NEON
output0_tm[0] = sum0;
output1_tm[0] = sum1;
output2_tm[0] = sum2;
output3_tm[0] = sum3;
output0_tm += 1;
output1_tm += 1;
output2_tm += 1;
output3_tm += 1;
}
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
#if __ARM_NEON && __aarch64__
const Mat kernel_tm0 = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
const Mat kernel_tm0 = kernel_tm.channel(p / 4 + p % 4);
#endif
Mat out0_tm = top_blob_tm.channel(p);
float* output0_tm = out0_tm;
for (int r = 0; r < 64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
for (; i + 7 < tiles; i += 8)
{
const float* bb2p0 = bb2.row(i / 8);
const float* ktm0 = kernel_tm0.row(r);
#if __ARM_NEON
#if __aarch64__
asm volatile(
"eor v8.16b, v8.16b, v8.16b \n"
"eor v9.16b, v9.16b, v9.16b \n"
// inch loop
"lsr w4, %w6, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4s}, [%2], #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"fmla v8.4s, v6.4s, v0.s[1] \n"
"fmla v9.4s, v7.4s, v0.s[1] \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"fmla v8.4s, v12.4s, v0.s[2] \n"
"fmla v9.4s, v13.4s, v0.s[2] \n"
"fmla v8.4s, v14.4s, v0.s[3] \n"
"fmla v9.4s, v15.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w6, #3 \n" // w4 = remain = tiles & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v4.4s, v5.4s}, [%1], #32 \n"
"prfm pldl1keep, [%2, #32] \n"
"ld1r {v0.4s}, [%2], #4 \n"
"fmla v8.4s, v4.4s, v0.4s \n"
"fmla v9.4s, v5.4s, v0.4s \n"
"subs w4, w4, #1 \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s, v9.4s}, [%0], #32 \n"
: "=r"(output0_tm), // %0
"=r"(bb2p0), // %1
"=r"(ktm0) // %2
: "0"(output0_tm),
"1"(bb2p0),
"2"(ktm0),
"r"(inch) // %6
: "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v12", "v13", "v14", "v15");
#else // __aarch64__
asm volatile(
"veor q8, q8, q8 \n"
"veor q9, q9, q9 \n"
// inch loop
"lsr r4, %6, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%1, #512] \n"
"vldm %1!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%1 :128]! \n"
// "vld1.f32 {d12-d15}, [%1 :128]! \n"
"pld [%2, #128] \n"
"vld1.f32 {d0-d1}, [%2 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q8, q6, d0[1] \n"
"vmla.f32 q9, q7, d0[1] \n"
"pld [%1, #512] \n"
"vldm %1!, {d24-d31} \n"
// "vld1.f32 {d24-d27}, [%1 :128]! \n"
// "vld1.f32 {d28-d31}, [%1 :128]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q12, d1[0] \n"
"vmla.f32 q9, q13, d1[0] \n"
"vmla.f32 q8, q14, d1[1] \n"
"vmla.f32 q9, q15, d1[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %6, #3 \n" // r4 = remain = tiles & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%1, #256] \n"
"vld1.f32 {d8-d11}, [%1 :128]! \n"
"pld [%2, #32] \n"
"vld1.f32 {d0[],d1[]}, [%2]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, q0 \n"
"vmla.f32 q9, q5, q0 \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d19}, [%0]! \n"
: "=r"(output0_tm), // %0
"=r"(bb2p0), // %1
"=r"(ktm0) // %2
: "0"(output0_tm),
"1"(bb2p0),
"2"(ktm0),
"r"(inch) // %6
: "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
float sum0 = 0.f;
float sum1 = 0.f;
float sum2 = 0.f;
float sum3 = 0.f;
float sum4 = 0.f;
float sum5 = 0.f;
float sum6 = 0.f;
float sum7 = 0.f;
for (int q = 0; q < inch; q++)
{
sum0 += bb2p0[0] * ktm0[0];
sum1 += bb2p0[1] * ktm0[0];
sum2 += bb2p0[2] * ktm0[0];
sum3 += bb2p0[3] * ktm0[0];
sum4 += bb2p0[4] * ktm0[0];
sum5 += bb2p0[5] * ktm0[0];
sum6 += bb2p0[6] * ktm0[0];
sum7 += bb2p0[7] * ktm0[0];
bb2p0 += 8;
ktm0 += 1;
}
output0_tm[0] = sum0;
output0_tm[1] = sum1;
output0_tm[2] = sum2;
output0_tm[3] = sum3;
output0_tm[4] = sum4;
output0_tm[5] = sum5;
output0_tm[6] = sum6;
output0_tm[7] = sum7;
output0_tm += 8;
#endif // __ARM_NEON
}
for (; i + 3 < tiles; i += 4)
{
const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4);
const float* ktm0 = kernel_tm0.row(r);
#if __ARM_NEON
#if __aarch64__
asm volatile(
"eor v8.16b, v8.16b, v8.16b \n"
// inch loop
"lsr w4, %w6, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v8.4s, v5.4s, v0.s[1] \n"
"fmla v8.4s, v6.4s, v0.s[2] \n"
"fmla v8.4s, v7.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w6, #3 \n" // w4 = remain = tiles & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v4.4s}, [%4], #16 \n"
"prfm pldl1keep, [%5, #32] \n"
"ld1r {v0.4s}, [%5], #4 \n"
"fmla v8.4s, v4.4s, v0.4s \n"
"subs w4, w4, #1 \n"
"bne 2b \n"
"3: \n"
"st1 {v8.4s}, [%0], #16 \n"
: "=r"(output0_tm), // %0
"=r"(bb2p0), // %1
"=r"(ktm0) // %2
: "0"(output0_tm),
"1"(bb2p0),
"2"(ktm0),
"r"(inch) // %6
: "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8");
#else // __aarch64__
asm volatile(
"veor q8, q8, q8 \n"
// inch loop
"lsr r4, %6, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n"
// "vld1.f32 {d8-d11}, [%4 :128]! \n"
// "vld1.f32 {d12-d15}, [%4 :128]! \n"
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5 :128]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q8, q7, d1[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %6, #3 \n" // r4 = remain = tiles & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #128] \n"
"vld1.f32 {d8-d9}, [%4]! \n"
"pld [%5, #32] \n"
"vld1.f32 {d0[],d1[]}, [%5]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, q0 \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d17}, [%0]! \n"
: "=r"(output0_tm), // %0
"=r"(bb2p0), // %1
"=r"(ktm0) // %2
: "0"(output0_tm),
"1"(bb2p0),
"2"(ktm0),
"r"(inch) // %6
: "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8");
#endif // __aarch64__
#else
float sum0 = 0.f;
float sum1 = 0.f;
float sum2 = 0.f;
float sum3 = 0.f;
for (int q = 0; q < inch; q++)
{
sum0 += bb2p0[0] * ktm0[0];
sum1 += bb2p0[1] * ktm0[0];
sum2 += bb2p0[2] * ktm0[0];
sum3 += bb2p0[3] * ktm0[0];
bb2p0 += 4;
ktm0 += 1;
}
output0_tm[0] = sum0;
output0_tm[1] = sum1;
output0_tm[2] = sum2;
output0_tm[3] = sum3;
output0_tm += 4;
#endif // __ARM_NEON
}
for (; i < tiles; i++)
{
const float* bb2p0 = bb2.row(i / 8 + (i % 8) / 4 + i % 4);
const float* ktm0 = kernel_tm0.row(r);
int q = 0;
#if __ARM_NEON
float32x4_t _sum0 = vdupq_n_f32(0.f);
for (; q + 3 < inch; q += 4)
{
// asm volatile("prfm pldl1keep, [%0, #128] \n" : :"r"(bb2p0) :);
float32x4_t _bb2p0 = vld1q_f32(bb2p0);
bb2p0 += 4;
float32x4_t _ktm0 = vld1q_f32(ktm0);
ktm0 += 4;
_sum0 = vmlaq_f32(_sum0, _bb2p0, _ktm0);
}
#if __aarch64__
float sum0 = vaddvq_f32(_sum0);
#else
float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float sum0 = vget_lane_f32(vpadd_f32(_ss0, _ss0), 0);
#endif // __aarch64__
#else
float sum0 = 0.f;
#endif
for (; q < inch; q++)
{
sum0 += bb2p0[0] * ktm0[0];
bb2p0 += 1;
ktm0 += 1;
}
output0_tm[0] = sum0;
output0_tm += 1;
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
if (outw == top_blob.w && outh == top_blob.h)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator);
}
{
// const float otm[6][8] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f}
// };
// 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32
// 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16
// 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8
// 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4
// 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2
// 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6)
#if __ARM_NEON
const float coeff[4] = {4.f, 8.f, 16.f, 32.f};
float32x4_t _coeff = vld1q_f32(coeff);
#endif // __ARM_NEON
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
const Mat out0_tm = top_blob_tm.channel(p);
Mat out0 = top_blob_bordered.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
#if __ARM_NEON
float32x2_t _bias0 = vdup_n_f32(bias0);
#endif // __ARM_NEON
float tmp[6][8];
// tile
for (int i = 0; i < outh / 6; i++)
{
for (int j = 0; j < outw / 6; j++)
{
#if __ARM_NEON
#if __aarch64__
const float* output0_tm0 = out0_tm.row(i * w_tm / 8 + j);
const float* output0_tm1 = out0_tm.row(i * w_tm / 8 + j + tiles * 8);
const float* output0_tm2 = out0_tm.row(i * w_tm / 8 + j + tiles * 16);
const float* output0_tm3 = out0_tm.row(i * w_tm / 8 + j + tiles * 24);
for (int m = 0; m + 3 < 8; m += 4)
{
float32x4_t _output0_tm_00 = {};
float32x4_t _output0_tm_11 = {};
float32x4_t _output0_tm_22 = {};
float32x4_t _output0_tm_33 = {};
float32x4_t _output0_tm_44 = {};
float32x4_t _output0_tm_55 = {};
float32x4_t _output0_tm_66 = {};
float32x4_t _output0_tm_77 = {};
_output0_tm_00 = vsetq_lane_f32(output0_tm0[0], _output0_tm_00, 0);
output0_tm0 += out0_tm.w * tiles;
_output0_tm_00 = vsetq_lane_f32(output0_tm1[0], _output0_tm_00, 1);
output0_tm1 += out0_tm.w * tiles;
_output0_tm_00 = vsetq_lane_f32(output0_tm2[0], _output0_tm_00, 2);
output0_tm2 += out0_tm.w * tiles;
_output0_tm_00 = vsetq_lane_f32(output0_tm3[0], _output0_tm_00, 3);
output0_tm3 += out0_tm.w * tiles;
_output0_tm_11 = vsetq_lane_f32(output0_tm0[0], _output0_tm_11, 0);
output0_tm0 += out0_tm.w * tiles;
_output0_tm_11 = vsetq_lane_f32(output0_tm1[0], _output0_tm_11, 1);
output0_tm1 += out0_tm.w * tiles;
_output0_tm_11 = vsetq_lane_f32(output0_tm2[0], _output0_tm_11, 2);
output0_tm2 += out0_tm.w * tiles;
_output0_tm_11 = vsetq_lane_f32(output0_tm3[0], _output0_tm_11, 3);
output0_tm3 += out0_tm.w * tiles;
_output0_tm_22 = vsetq_lane_f32(output0_tm0[0], _output0_tm_22, 0);
output0_tm0 += out0_tm.w * tiles;
_output0_tm_22 = vsetq_lane_f32(output0_tm1[0], _output0_tm_22, 1);
output0_tm1 += out0_tm.w * tiles;
_output0_tm_22 = vsetq_lane_f32(output0_tm2[0], _output0_tm_22, 2);
output0_tm2 += out0_tm.w * tiles;
_output0_tm_22 = vsetq_lane_f32(output0_tm3[0], _output0_tm_22, 3);
output0_tm3 += out0_tm.w * tiles;
_output0_tm_33 = vsetq_lane_f32(output0_tm0[0], _output0_tm_33, 0);
output0_tm0 += out0_tm.w * tiles;
_output0_tm_33 = vsetq_lane_f32(output0_tm1[0], _output0_tm_33, 1);
output0_tm1 += out0_tm.w * tiles;
_output0_tm_33 = vsetq_lane_f32(output0_tm2[0], _output0_tm_33, 2);
output0_tm2 += out0_tm.w * tiles;
_output0_tm_33 = vsetq_lane_f32(output0_tm3[0], _output0_tm_33, 3);
output0_tm3 += out0_tm.w * tiles;
_output0_tm_44 = vsetq_lane_f32(output0_tm0[0], _output0_tm_44, 0);
output0_tm0 += out0_tm.w * tiles;
_output0_tm_44 = vsetq_lane_f32(output0_tm1[0], _output0_tm_44, 1);
output0_tm1 += out0_tm.w * tiles;
_output0_tm_44 = vsetq_lane_f32(output0_tm2[0], _output0_tm_44, 2);
output0_tm2 += out0_tm.w * tiles;
_output0_tm_44 = vsetq_lane_f32(output0_tm3[0], _output0_tm_44, 3);
output0_tm3 += out0_tm.w * tiles;
_output0_tm_55 = vsetq_lane_f32(output0_tm0[0], _output0_tm_55, 0);
output0_tm0 += out0_tm.w * tiles;
_output0_tm_55 = vsetq_lane_f32(output0_tm1[0], _output0_tm_55, 1);
output0_tm1 += out0_tm.w * tiles;
_output0_tm_55 = vsetq_lane_f32(output0_tm2[0], _output0_tm_55, 2);
output0_tm2 += out0_tm.w * tiles;
_output0_tm_55 = vsetq_lane_f32(output0_tm3[0], _output0_tm_55, 3);
output0_tm3 += out0_tm.w * tiles;
_output0_tm_66 = vsetq_lane_f32(output0_tm0[0], _output0_tm_66, 0);
output0_tm0 += out0_tm.w * tiles;
_output0_tm_66 = vsetq_lane_f32(output0_tm1[0], _output0_tm_66, 1);
output0_tm1 += out0_tm.w * tiles;
_output0_tm_66 = vsetq_lane_f32(output0_tm2[0], _output0_tm_66, 2);
output0_tm2 += out0_tm.w * tiles;
_output0_tm_66 = vsetq_lane_f32(output0_tm3[0], _output0_tm_66, 3);
output0_tm3 += out0_tm.w * tiles;
_output0_tm_77 = vsetq_lane_f32(output0_tm0[0], _output0_tm_77, 0);
_output0_tm_77 = vsetq_lane_f32(output0_tm1[0], _output0_tm_77, 1);
_output0_tm_77 = vsetq_lane_f32(output0_tm2[0], _output0_tm_77, 2);
_output0_tm_77 = vsetq_lane_f32(output0_tm3[0], _output0_tm_77, 3);
float32x4_t _tmp024a = vaddq_f32(_output0_tm_11, _output0_tm_22);
float32x4_t _tmp135a = vsubq_f32(_output0_tm_11, _output0_tm_22);
float32x4_t _tmp024b = vaddq_f32(_output0_tm_33, _output0_tm_44);
float32x4_t _tmp135b = vsubq_f32(_output0_tm_33, _output0_tm_44);
float32x4_t _tmp024c = vaddq_f32(_output0_tm_55, _output0_tm_66);
float32x4_t _tmp135c = vsubq_f32(_output0_tm_55, _output0_tm_66);
float32x4_t _tmp0 = vaddq_f32(_output0_tm_00, _tmp024a);
_tmp0 = vmlaq_lane_f32(_tmp0, _tmp024c, vget_high_f32(_coeff), 1);
_tmp0 = vaddq_f32(_tmp0, _tmp024b);
float32x4_t _tmp2 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0);
_tmp2 = vmlaq_lane_f32(_tmp2, _tmp024c, vget_low_f32(_coeff), 1);
float32x4_t _tmp4 = vmlaq_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0);
_tmp4 = vaddq_f32(_tmp4, _tmp024c);
_tmp4 = vaddq_f32(_tmp4, _tmp024c);
vst1q_f32(&tmp[0][m], _tmp0);
vst1q_f32(&tmp[2][m], _tmp2);
vst1q_f32(&tmp[4][m], _tmp4);
float32x4_t _tmp1 = vmlaq_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0);
_tmp1 = vaddq_f32(_tmp1, _tmp135b);
_tmp1 = vaddq_f32(_tmp1, _tmp135b);
float32x4_t _tmp3 = vmlaq_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1);
_tmp3 = vmlaq_lane_f32(_tmp3, _tmp135c, vget_low_f32(_coeff), 0);
float32x4_t _tmp5 = vaddq_f32(_output0_tm_77, _tmp135a);
_tmp5 = vmlaq_lane_f32(_tmp5, _tmp135b, vget_high_f32(_coeff), 1);
_tmp5 = vaddq_f32(_tmp5, _tmp135c);
vst1q_f32(&tmp[1][m], _tmp1);
vst1q_f32(&tmp[3][m], _tmp3);
vst1q_f32(&tmp[5][m], _tmp5);
output0_tm0 += out0_tm.w * tiles * 25;
output0_tm1 += out0_tm.w * tiles * 25;
output0_tm2 += out0_tm.w * tiles * 25;
output0_tm3 += out0_tm.w * tiles * 25;
}
const float* t0 = tmp[0];
const float* t1 = tmp[1];
float* output0 = out0.row(i * 6) + j * 6;
float* output1 = output0 + outw;
for (int m = 0; m + 1 < 6; m += 2)
{
float32x4_t _t0_0123 = vld1q_f32(t0);
float32x4_t _t0_4567 = vld1q_f32(t0 + 4);
float32x4_t _t1_0123 = vld1q_f32(t1);
float32x4_t _t1_4567 = vld1q_f32(t1 + 4);
float32x4x2_t _t01_00221133 = vtrnq_f32(_t0_0123, _t1_0123);
float32x4x2_t _t01_44665577 = vtrnq_f32(_t0_4567, _t1_4567);
float32x2_t _t_00 = vget_low_f32(_t01_00221133.val[0]);
float32x2_t _t_11 = vget_low_f32(_t01_00221133.val[1]);
float32x2_t _t_22 = vget_high_f32(_t01_00221133.val[0]);
float32x2_t _t_33 = vget_high_f32(_t01_00221133.val[1]);
float32x2_t _t_44 = vget_low_f32(_t01_44665577.val[0]);
float32x2_t _t_55 = vget_low_f32(_t01_44665577.val[1]);
float32x2_t _t_66 = vget_high_f32(_t01_44665577.val[0]);
float32x2_t _t_77 = vget_high_f32(_t01_44665577.val[1]);
float32x2_t _tmp024a = vadd_f32(_t_11, _t_22);
float32x2_t _tmp135a = vsub_f32(_t_11, _t_22);
float32x2_t _tmp024b = vadd_f32(_t_33, _t_44);
float32x2_t _tmp135b = vsub_f32(_t_33, _t_44);
float32x2_t _tmp024c = vadd_f32(_t_55, _t_66);
float32x2_t _tmp135c = vsub_f32(_t_55, _t_66);
float32x2_t _output_0 = vadd_f32(_t_00, _tmp024a);
_output_0 = vmla_lane_f32(_output_0, _tmp024c, vget_high_f32(_coeff), 1);
_output_0 = vadd_f32(_output_0, _tmp024b);
_output_0 = vadd_f32(_output_0, _bias0);
float32x2_t _output_2 = vmla_lane_f32(_tmp024a, _tmp024b, vget_low_f32(_coeff), 0);
_output_2 = vmla_lane_f32(_output_2, _tmp024c, vget_low_f32(_coeff), 1);
_output_2 = vadd_f32(_output_2, _bias0);
float32x2_t _output_4 = vmla_lane_f32(_tmp024a, _tmp024b, vget_high_f32(_coeff), 0);
_output_4 = vadd_f32(_output_4, _tmp024c);
_output_4 = vadd_f32(_output_4, _tmp024c);
_output_4 = vadd_f32(_output_4, _bias0);
output0[0] = vget_lane_f32(_output_0, 0);
output1[0] = vget_lane_f32(_output_0, 1);
output0[2] = vget_lane_f32(_output_2, 0);
output1[2] = vget_lane_f32(_output_2, 1);
output0[4] = vget_lane_f32(_output_4, 0);
output1[4] = vget_lane_f32(_output_4, 1);
float32x2_t _output_1 = vmla_lane_f32(_tmp135a, _tmp135c, vget_high_f32(_coeff), 0);
_output_1 = vadd_f32(_output_1, _tmp135b);
_output_1 = vadd_f32(_output_1, _tmp135b);
_output_1 = vadd_f32(_output_1, _bias0);
float32x2_t _output_3 = vmla_lane_f32(_tmp135a, _tmp135b, vget_low_f32(_coeff), 1);
_output_3 = vmla_lane_f32(_output_3, _tmp135c, vget_low_f32(_coeff), 0);
_output_3 = vadd_f32(_output_3, _bias0);
float32x2_t _output_5 = vadd_f32(_t_77, _tmp135a);
_output_5 = vmla_lane_f32(_output_5, _tmp135b, vget_high_f32(_coeff), 1);
_output_5 = vadd_f32(_output_5, _tmp135c);
_output_5 = vadd_f32(_output_5, _bias0);
output0[1] = vget_lane_f32(_output_1, 0);
output1[1] = vget_lane_f32(_output_1, 1);
output0[3] = vget_lane_f32(_output_3, 0);
output1[3] = vget_lane_f32(_output_3, 1);
output0[5] = vget_lane_f32(_output_5, 0);
output1[5] = vget_lane_f32(_output_5, 1);
t0 += 8 * 2;
t1 += 8 * 2;
output0 += outw * 2;
output1 += outw * 2;
}
#else // __aarch64__
const float* output0_tm0_0 = out0_tm.row(i * w_tm / 8 + j);
const float* output0_tm1_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 8);
const float* output0_tm2_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 16);
const float* output0_tm3_0 = out0_tm.row(i * w_tm / 8 + j + tiles * 24);
const float* output0_tm0_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 32);
const float* output0_tm1_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 40);
const float* output0_tm2_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 48);
const float* output0_tm3_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 56);
float* t0 = tmp[0];
float* t1 = tmp[1];
// int step = out0_tm.w * tiles * 2*4 *4;
int step = out0_tm.w * tiles * 4;
asm volatile(
// loop0
// "vld1.f32 {d16-d17}, [%2], %21 \n"
// "vld1.f32 {d18-d19}, [%3], %21 \n"
// "vld1.f32 {d20-d21}, [%4], %21 \n"
// "vld1.f32 {d22-d23}, [%5], %21 \n"
// "vld1.f32 {d24-d25}, [%6], %21 \n"
// "vld1.f32 {d26-d27}, [%7], %21 \n"
// "vld1.f32 {d28-d29}, [%8], %21 \n"
// "vld1.f32 {d30-d31}, [%9], %21 \n"
// "vtrn.32 q8, q10 \n"
// "vtrn.32 q9, q11 \n"
// "vtrn.32 q12, q14 \n"
// "vtrn.32 q13, q15 \n"
// "vswp d17, d24 \n"
// "vswp d19, d26 \n"
// "vswp d21, d28 \n"// q8 = 00 q9 = 44 q10 = 11 q11 = 55
// "vswp d23, d30 \n"// q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vld1.f32 {d16[0]}, [%2], %21 \n"
"vld1.f32 {d16[1]}, [%3], %21 \n"
"vld1.f32 {d17[0]}, [%4], %21 \n"
"vld1.f32 {d17[1]}, [%5], %21 \n"
"vld1.f32 {d20[0]}, [%2], %21 \n"
"vld1.f32 {d20[1]}, [%3], %21 \n"
"vld1.f32 {d21[0]}, [%4], %21 \n"
"vld1.f32 {d21[1]}, [%5], %21 \n"
"vld1.f32 {d24[0]}, [%2], %21 \n"
"vld1.f32 {d24[1]}, [%3], %21 \n"
"vld1.f32 {d25[0]}, [%4], %21 \n"
"vld1.f32 {d25[1]}, [%5], %21 \n"
"vadd.f32 q2, q10, q12 \n"
"vsub.f32 q3, q10, q12 \n"
"vld1.f32 {d28[0]}, [%2], %21 \n"
"vld1.f32 {d28[1]}, [%3], %21 \n"
"vld1.f32 {d29[0]}, [%4], %21 \n"
"vld1.f32 {d29[1]}, [%5], %21 \n"
"vld1.f32 {d18[0]}, [%2], %21 \n"
"vld1.f32 {d18[1]}, [%3], %21 \n"
"vld1.f32 {d19[0]}, [%4], %21 \n"
"vld1.f32 {d19[1]}, [%5], %21 \n"
"vadd.f32 q4, q14, q9 \n"
"vsub.f32 q5, q14, q9 \n"
"vld1.f32 {d22[0]}, [%2], %21 \n"
"vld1.f32 {d22[1]}, [%3], %21 \n"
"vld1.f32 {d23[0]}, [%4], %21 \n"
"vld1.f32 {d23[1]}, [%5], %21 \n"
"vld1.f32 {d26[0]}, [%2], %21 \n"
"vld1.f32 {d26[1]}, [%3], %21 \n"
"vld1.f32 {d27[0]}, [%4], %21 \n"
"vld1.f32 {d27[1]}, [%5], %21 \n"
"vadd.f32 q6, q11, q13 \n"
"vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14
"vld1.f32 {d30[0]}, [%2] \n"
"vld1.f32 {d30[1]}, [%3] \n"
"vld1.f32 {d31[0]}, [%4] \n"
"vld1.f32 {d31[1]}, [%5] \n"
"vmov q9, q3 \n"
"vadd.f32 q8, q8, q2 \n"
"vmla.f32 q9, q7, %f20[0] \n"
"vmov q12, q2 \n"
"vmov q10, q2 \n"
"vmov q11, q3 \n"
"vmla.f32 q12, q4, %f20[0] \n"
"vadd.f32 q15, q15, q3 \n"
"vmla.f32 q8, q6, %f20[1] \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q4, %e20[0] \n"
"vmla.f32 q11, q5, %e20[1] \n"
"vadd.f32 q12, q12, q6 \n"
"vmla.f32 q15, q5, %f20[1] \n"
"vadd.f32 q8, q8, q4 \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q6, %e20[1] \n"
"vmla.f32 q11, q7, %e20[0] \n"
"vadd.f32 q12, q12, q6 \n"
"vadd.f32 q15, q15, q7 \n"
"vst1.f32 {d16-d17}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d18-d19}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d20-d21}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d22-d23}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d24-d25}, [%0] \n"
"sub %0, %0, #112 \n"
"vst1.f32 {d30-d31}, [%1] \n"
"sub %1, %1, #112 \n"
// loop1
// "vld1.f32 {d16-d17}, [%2] \n"
// "vld1.f32 {d18-d19}, [%3] \n"
// "vld1.f32 {d20-d21}, [%4] \n"
// "vld1.f32 {d22-d23}, [%5] \n"
// "vld1.f32 {d24-d25}, [%6] \n"
// "vld1.f32 {d26-d27}, [%7] \n"
// "vld1.f32 {d28-d29}, [%8] \n"
// "vld1.f32 {d30-d31}, [%9] \n"
// "vtrn.32 q8, q10 \n"
// "vtrn.32 q9, q11 \n"
// "vtrn.32 q12, q14 \n"
// "vtrn.32 q13, q15 \n"
// "vswp d17, d24 \n"
// "vswp d19, d26 \n"
// "vswp d21, d28 \n"// q8 = 00 q9 = 44 q10 = 11 q11 = 55
// "vswp d23, d30 \n"// q12 = 22 q13 = 66 q14 = 33 q15 = 77
"vld1.f32 {d16[0]}, [%6], %21 \n"
"vld1.f32 {d16[1]}, [%7], %21 \n"
"vld1.f32 {d17[0]}, [%8], %21 \n"
"vld1.f32 {d17[1]}, [%9], %21 \n"
"vld1.f32 {d20[0]}, [%6], %21 \n"
"vld1.f32 {d20[1]}, [%7], %21 \n"
"vld1.f32 {d21[0]}, [%8], %21 \n"
"vld1.f32 {d21[1]}, [%9], %21 \n"
"vld1.f32 {d24[0]}, [%6], %21 \n"
"vld1.f32 {d24[1]}, [%7], %21 \n"
"vld1.f32 {d25[0]}, [%8], %21 \n"
"vld1.f32 {d25[1]}, [%9], %21 \n"
"vadd.f32 q2, q10, q12 \n"
"vsub.f32 q3, q10, q12 \n"
"vld1.f32 {d28[0]}, [%6], %21 \n"
"vld1.f32 {d28[1]}, [%7], %21 \n"
"vld1.f32 {d29[0]}, [%8], %21 \n"
"vld1.f32 {d29[1]}, [%9], %21 \n"
"vld1.f32 {d18[0]}, [%6], %21 \n"
"vld1.f32 {d18[1]}, [%7], %21 \n"
"vld1.f32 {d19[0]}, [%8], %21 \n"
"vld1.f32 {d19[1]}, [%9], %21 \n"
"vadd.f32 q4, q14, q9 \n"
"vsub.f32 q5, q14, q9 \n"
"vld1.f32 {d22[0]}, [%6], %21 \n"
"vld1.f32 {d22[1]}, [%7], %21 \n"
"vld1.f32 {d23[0]}, [%8], %21 \n"
"vld1.f32 {d23[1]}, [%9], %21 \n"
"vld1.f32 {d26[0]}, [%6], %21 \n"
"vld1.f32 {d26[1]}, [%7], %21 \n"
"vld1.f32 {d27[0]}, [%8], %21 \n"
"vld1.f32 {d27[1]}, [%9], %21 \n"
"vadd.f32 q6, q11, q13 \n"
"vsub.f32 q7, q11, q13 \n" // spare q9 q10 q11 q12 q13 q14
"vld1.f32 {d30[0]}, [%6] \n"
"vld1.f32 {d30[1]}, [%7] \n"
"vld1.f32 {d31[0]}, [%8] \n"
"vld1.f32 {d31[1]}, [%9] \n"
"vmov q9, q3 \n"
"vadd.f32 q8, q8, q2 \n"
"vmla.f32 q9, q7, %f20[0] \n"
"vmov q12, q2 \n"
"vmov q10, q2 \n"
"vmov q11, q3 \n"
"vmla.f32 q12, q4, %f20[0] \n"
"vadd.f32 q15, q15, q3 \n"
"vmla.f32 q8, q6, %f20[1] \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q4, %e20[0] \n"
"vmla.f32 q11, q5, %e20[1] \n"
"vadd.f32 q12, q12, q6 \n"
"vmla.f32 q15, q5, %f20[1] \n"
"vadd.f32 q8, q8, q4 \n"
"vadd.f32 q9, q9, q5 \n"
"vmla.f32 q10, q6, %e20[1] \n"
"vmla.f32 q11, q7, %e20[0] \n"
"vadd.f32 q12, q12, q6 \n"
"vadd.f32 q15, q15, q7 \n"
"vst1.f32 {d16-d17}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d18-d19}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d20-d21}, [%0] \n"
"add %0, %0, #64 \n"
"vst1.f32 {d22-d23}, [%1] \n"
"add %1, %1, #64 \n"
"vst1.f32 {d24-d25}, [%0] \n"
"vst1.f32 {d30-d31}, [%1] \n"
: "=r"(t0), // %0
"=r"(t1), // %1
"=r"(output0_tm0_0), // %2
"=r"(output0_tm1_0), // %3
"=r"(output0_tm2_0), // %4
"=r"(output0_tm3_0), // %5
"=r"(output0_tm0_4), // %6
"=r"(output0_tm1_4), // %7
"=r"(output0_tm2_4), // %8
"=r"(output0_tm3_4) // %9
: "0"(t0),
"1"(t1),
"2"(output0_tm0_0),
"3"(output0_tm1_0),
"4"(output0_tm2_0),
"5"(output0_tm3_0),
"6"(output0_tm0_4),
"7"(output0_tm1_4),
"8"(output0_tm2_4),
"9"(output0_tm3_4),
"w"(_coeff), // %20
"r"(step) // %21
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
t0 = tmp[0];
t1 = tmp[1];
float* output0 = out0.row(i * 6) + j * 6;
float* output1 = output0 + outw;
int stepw = outw * 2 * 4;
asm volatile(
// loop0
"vld1.f32 {d16-d19}, [%2] \n"
"vld1.f32 {d20-d23}, [%3] \n"
"add %2, %2, #64 \n"
"add %3, %3, #64 \n"
"vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3
"vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7
"vadd.f32 d4, d20, d17 \n"
"vsub.f32 d5, d20, d17 \n"
"vadd.f32 d6, d21, d18 \n"
"vsub.f32 d7, d21, d18 \n"
"vadd.f32 d8, d22, d19 \n"
"vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22
"vmov d20, d5 \n"
"vmov d18, d4 \n"
"vadd.f32 d16, d16, d4 \n"
"vmla.f32 d20, d9, %f8[0] \n"
"vmov d17, d4 \n"
"vmov d21, d5 \n"
"vmla.f32 d18, d6, %f8[0] \n"
"vadd.f32 d22, d23, d5 \n"
"vmla.f32 d16, d8, %f8[1] \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d6, %e8[0] \n"
"vmla.f32 d21, d7, %e8[1] \n"
"vadd.f32 d18, d18, d8 \n"
"vmla.f32 d22, d7, %f8[1] \n"
"vadd.f32 d16, d16, d6 \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d8, %e8[1] \n"
"vmla.f32 d21, d9, %e8[0] \n"
"vadd.f32 d18, d18, d8 \n"
"vadd.f32 d22, d22, d9 \n"
"vadd.f32 d16, d16, %P9 \n" // _bias0
"vadd.f32 d20, d20, %P9 \n" // _bias0
"vadd.f32 d17, d17, %P9 \n" // _bias0
"vadd.f32 d21, d21, %P9 \n" // _bias0
"vadd.f32 d18, d18, %P9 \n" // _bias0
"vadd.f32 d22, d22, %P9 \n" // _bias0
"vtrn.f32 q8, q10 \n"
"vtrn.f32 d18, d22 \n"
"vst1.f32 {d16-d18}, [%0], %10 \n"
"vst1.f32 {d20-d22}, [%1], %10 \n"
// loop1
"vld1.f32 {d16-d19}, [%2] \n"
"vld1.f32 {d20-d23}, [%3] \n"
"add %2, %2, #64 \n"
"add %3, %3, #64 \n"
"vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3
"vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7
"vadd.f32 d4, d20, d17 \n"
"vsub.f32 d5, d20, d17 \n"
"vadd.f32 d6, d21, d18 \n"
"vsub.f32 d7, d21, d18 \n"
"vadd.f32 d8, d22, d19 \n"
"vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22
"vmov d20, d5 \n"
"vmov d18, d4 \n"
"vadd.f32 d16, d16, d4 \n"
"vmla.f32 d20, d9, %f8[0] \n"
"vmov d17, d4 \n"
"vmov d21, d5 \n"
"vmla.f32 d18, d6, %f8[0] \n"
"vadd.f32 d22, d23, d5 \n"
"vmla.f32 d16, d8, %f8[1] \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d6, %e8[0] \n"
"vmla.f32 d21, d7, %e8[1] \n"
"vadd.f32 d18, d18, d8 \n"
"vmla.f32 d22, d7, %f8[1] \n"
"vadd.f32 d16, d16, d6 \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d8, %e8[1] \n"
"vmla.f32 d21, d9, %e8[0] \n"
"vadd.f32 d18, d18, d8 \n"
"vadd.f32 d22, d22, d9 \n"
"vadd.f32 d16, d16, %P9 \n" // _bias0
"vadd.f32 d20, d20, %P9 \n" // _bias0
"vadd.f32 d17, d17, %P9 \n" // _bias0
"vadd.f32 d21, d21, %P9 \n" // _bias0
"vadd.f32 d18, d18, %P9 \n" // _bias0
"vadd.f32 d22, d22, %P9 \n" // _bias0
"vtrn.f32 q8, q10 \n"
"vtrn.f32 d18, d22 \n"
"vst1.f32 {d16-d18}, [%0], %10 \n"
"vst1.f32 {d20-d22}, [%1], %10 \n"
// loop2
"vld1.f32 {d16-d19}, [%2] \n"
"vld1.f32 {d20-d23}, [%3] \n"
"add %2, %2, #64 \n"
"add %3, %3, #64 \n"
"vtrn.32 q8, q10 \n" // q8 = 0 2 q10 = 1 3
"vtrn.32 q9, q11 \n" // q9 = 4 6 q11 = 5 7
"vadd.f32 d4, d20, d17 \n"
"vsub.f32 d5, d20, d17 \n"
"vadd.f32 d6, d21, d18 \n"
"vsub.f32 d7, d21, d18 \n"
"vadd.f32 d8, d22, d19 \n"
"vsub.f32 d9, d22, d19 \n" // spare d17 ~ d22
"vmov d20, d5 \n"
"vmov d18, d4 \n"
"vadd.f32 d16, d16, d4 \n"
"vmla.f32 d20, d9, %f8[0] \n"
"vmov d17, d4 \n"
"vmov d21, d5 \n"
"vmla.f32 d18, d6, %f8[0] \n"
"vadd.f32 d22, d23, d5 \n"
"vmla.f32 d16, d8, %f8[1] \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d6, %e8[0] \n"
"vmla.f32 d21, d7, %e8[1] \n"
"vadd.f32 d18, d18, d8 \n"
"vmla.f32 d22, d7, %f8[1] \n"
"vadd.f32 d16, d16, d6 \n"
"vadd.f32 d20, d20, d7 \n"
"vmla.f32 d17, d8, %e8[1] \n"
"vmla.f32 d21, d9, %e8[0] \n"
"vadd.f32 d18, d18, d8 \n"
"vadd.f32 d22, d22, d9 \n"
"vadd.f32 d16, d16, %P9 \n" // _bias0
"vadd.f32 d20, d20, %P9 \n" // _bias0
"vadd.f32 d17, d17, %P9 \n" // _bias0
"vadd.f32 d21, d21, %P9 \n" // _bias0
"vadd.f32 d18, d18, %P9 \n" // _bias0
"vadd.f32 d22, d22, %P9 \n" // _bias0
"vtrn.f32 q8, q10 \n"
"vtrn.f32 d18, d22 \n"
"vst1.f32 {d16-d18}, [%0], %10 \n"
"vst1.f32 {d20-d22}, [%1], %10 \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(t0), // %2
"=r"(t1) // %3
: "0"(output0),
"1"(output1),
"2"(t0),
"3"(t1),
"w"(_coeff), // %8
"w"(_bias0), // %9
"r"(stepw) // %10
: "memory", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
const float* output0_tm_0 = out0_tm.row(i * w_tm / 8 + j);
const float* output0_tm_1 = out0_tm.row(i * w_tm / 8 + j + tiles);
const float* output0_tm_2 = out0_tm.row(i * w_tm / 8 + j + tiles * 2);
const float* output0_tm_3 = out0_tm.row(i * w_tm / 8 + j + tiles * 3);
const float* output0_tm_4 = out0_tm.row(i * w_tm / 8 + j + tiles * 4);
const float* output0_tm_5 = out0_tm.row(i * w_tm / 8 + j + tiles * 5);
const float* output0_tm_6 = out0_tm.row(i * w_tm / 8 + j + tiles * 6);
const float* output0_tm_7 = out0_tm.row(i * w_tm / 8 + j + tiles * 7);
for (int m = 0; m < 8; m++)
{
float tmp024a = output0_tm_1[0] + output0_tm_2[0];
float tmp135a = output0_tm_1[0] - output0_tm_2[0];
float tmp024b = output0_tm_3[0] + output0_tm_4[0];
float tmp135b = output0_tm_3[0] - output0_tm_4[0];
float tmp024c = output0_tm_5[0] + output0_tm_6[0];
float tmp135c = output0_tm_5[0] - output0_tm_6[0];
tmp[0][m] = output0_tm_0[0] + tmp024a + tmp024b + tmp024c * 32;
tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8;
tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c;
tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16;
tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4;
tmp[5][m] = output0_tm_7[0] + tmp135a + tmp135b * 32 + tmp135c;
output0_tm_0 += out0_tm.w * tiles * 8;
output0_tm_1 += out0_tm.w * tiles * 8;
output0_tm_2 += out0_tm.w * tiles * 8;
output0_tm_3 += out0_tm.w * tiles * 8;
output0_tm_4 += out0_tm.w * tiles * 8;
output0_tm_5 += out0_tm.w * tiles * 8;
output0_tm_6 += out0_tm.w * tiles * 8;
output0_tm_7 += out0_tm.w * tiles * 8;
}
float* output0 = out0.row(i * 6) + j * 6;
for (int m = 0; m < 6; m++)
{
const float* tmp0 = tmp[m];
float tmp024a = tmp0[1] + tmp0[2];
float tmp135a = tmp0[1] - tmp0[2];
float tmp024b = tmp0[3] + tmp0[4];
float tmp135b = tmp0[3] - tmp0[4];
float tmp024c = tmp0[5] + tmp0[6];
float tmp135c = tmp0[5] - tmp0[6];
output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32;
output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8;
output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c;
output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16;
output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4;
output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c;
output0 += outw;
}
#endif // __ARM_NEON
}
}
}
}
// END transform output
// cut result pad
if (top_blob_bordered.w != top_blob.w || top_blob_bordered.h != top_blob.h)
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
static void conv3x3s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
const float* kernel = _kernel;
const float* bias = _bias;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p + 1);
const float bias0 = bias ? bias[p] : 0.f;
const float bias1 = bias ? bias[p + 1] : 0.f;
out0.fill(bias0);
out1.fill(bias1);
const float* k0 = kernel + p * inch * 9;
const float* k1 = kernel + (p + 1) * inch * 9;
for (int q = 0; q < inch; q++)
{
float* outptr0 = out0;
float* outptr1 = out1;
const float* img0 = bottom_blob.channel(q);
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
#if __ARM_NEON
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k03 = vld1q_f32(k0 + 3);
float32x4_t _k06 = vld1q_f32(k0 + 6);
float32x4_t _k10 = vld1q_f32(k1);
float32x4_t _k13 = vld1q_f32(k1 + 3);
float32x4_t _k16 = vld1q_f32(k1 + 6);
#endif // __ARM_NEON
int i = 0;
for (; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%3, #256] \n"
"ld2 {v8.4s, v9.4s}, [%3], #32 \n" // v8 v9 = r0
"0: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v6.4s}, [%1] \n" // v6 = _sum0
"fmul v12.4s, v8.4s, %12.s[0] \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v7.4s}, [%2] \n" // v7 = _sum1
"fmul v13.4s, v8.4s, %15.s[0] \n"
"prfm pldl1keep, [%3, #128] \n"
"ld2 {v10.4s, v11.4s}, [%3] \n" // v10
"fmla v6.4s, v9.4s, %12.s[1] \n"
"ext v14.16b, v8.16b, v10.16b, #4\n"
"fmla v7.4s, v9.4s, %15.s[1] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld2 {v8.4s, v9.4s}, [%4], #32 \n" // r1
"fmla v12.4s, v14.4s, %12.s[2] \n"
"fmla v13.4s, v14.4s, %15.s[2] \n"
"prfm pldl1keep, [%4, #128] \n"
"ld2 {v10.4s, v11.4s}, [%4] \n"
"fmla v6.4s, v8.4s, %13.s[0] \n"
"fmla v7.4s, v8.4s, %16.s[0] \n"
"ext v14.16b, v8.16b, v10.16b, #4\n"
"fmla v12.4s, v9.4s, %13.s[1] \n"
"fmla v13.4s, v9.4s, %16.s[1] \n"
"prfm pldl1keep, [%5, #256] \n"
"ld2 {v8.4s, v9.4s}, [%5], #32 \n" // r2
"fmla v6.4s, v14.4s, %13.s[2] \n"
"fmla v7.4s, v14.4s, %16.s[2] \n"
"prfm pldl1keep, [%5, #128] \n"
"ld2 {v10.4s, v11.4s}, [%5] \n"
"fmla v12.4s, v8.4s, %14.s[0] \n"
"fmla v13.4s, v8.4s, %17.s[0] \n"
"ext v14.16b, v8.16b, v10.16b, #4\n"
"fmla v6.4s, v9.4s, %14.s[1] \n"
"fmla v7.4s, v9.4s, %17.s[1] \n"
"fmla v12.4s, v14.4s, %14.s[2] \n"
"fmla v13.4s, v14.4s, %17.s[2] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld2 {v8.4s, v9.4s}, [%3], #32 \n" // v8 v9 = r0
"fadd v6.4s, v6.4s, v12.4s \n"
"fadd v7.4s, v7.4s, v13.4s \n"
"subs %w0, %w0, #1 \n"
"st1 {v6.4s}, [%1], #16 \n"
"st1 {v7.4s}, [%2], #16 \n"
"bne 0b \n"
"sub %3, %3, #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00), // %12
"w"(_k03), // %13
"w"(_k06), // %14
"w"(_k10), // %15
"w"(_k13), // %16
"w"(_k16) // %17
: "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
"pld [%3, #256] \n"
"vld2.f32 {d16-d19}, [%3]! \n" // q8 q9 = r0
"0: \n"
"pld [%1, #128] \n"
"vld1.f32 {d12-d13}, [%1] \n" // q6 = _sum0
"vmul.f32 q12, q8, %e12[0] \n"
"pld [%2, #128] \n"
"vld1.f32 {d14-d15}, [%2] \n" // q7 = _sum1
"vmul.f32 q13, q8, %e15[0] \n"
"pld [%3, #128] \n"
"vld2.f32 {d20-d21}, [%3] \n" // q10
"vmla.f32 q6, q9, %e12[1] \n"
"vext.32 q11, q8, q10, #1 \n"
"vmla.f32 q7, q9, %e15[1] \n"
"pld [%4, #256] \n"
"vld2.f32 {d16-d19}, [%4]! \n" // r1
"vmla.f32 q12, q11, %f12[0] \n"
"vmla.f32 q13, q11, %f15[0] \n"
"pld [%4, #128] \n"
"vld2.f32 {d20-d21}, [%4] \n"
"vmla.f32 q6, q8, %e13[0] \n"
"vmla.f32 q7, q8, %e16[0] \n"
"vext.32 q11, q8, q10, #1 \n"
"vmla.f32 q12, q9, %e13[1] \n"
"vmla.f32 q13, q9, %e16[1] \n"
"pld [%5, #256] \n"
"vld2.f32 {d16-d19}, [%5]! \n" // r2
"vmla.f32 q6, q11, %f13[0] \n"
"vmla.f32 q7, q11, %f16[0] \n"
"pld [%5, #128] \n"
"vld2.f32 {d20-d21}, [%5] \n"
"vmla.f32 q12, q8, %e14[0] \n"
"vmla.f32 q13, q8, %e17[0] \n"
"vext.32 q11, q8, q10, #1 \n"
"vmla.f32 q6, q9, %e14[1] \n"
"vmla.f32 q7, q9, %e17[1] \n"
"vmla.f32 q12, q11, %f14[0] \n"
"vmla.f32 q13, q11, %f17[0] \n"
"pld [%3, #256] \n"
"vld2.f32 {d16-d19}, [%3]! \n" // q8 q9 = r0
"vadd.f32 q6, q6, q12 \n"
"vadd.f32 q7, q7, q13 \n"
"subs %0, #1 \n"
"vst1.f32 {d12-d13}, [%1]! \n"
"vst1.f32 {d14-d15}, [%2]! \n"
"bne 0b \n"
"sub %3, #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00), // %12
"w"(_k03), // %13
"w"(_k06), // %14
"w"(_k10), // %15
"w"(_k13), // %16
"w"(_k16) // %17
: "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _sum0 = vmulq_f32(_r00, _k00);
float32x4_t _sum1 = vmulq_f32(_r00, _k10);
_sum0 = vmlaq_f32(_sum0, _r10, _k03);
_sum1 = vmlaq_f32(_sum1, _r10, _k13);
_sum0 = vmlaq_f32(_sum0, _r20, _k06);
_sum1 = vmlaq_f32(_sum1, _r20, _k16);
_sum0 = vsetq_lane_f32(*outptr0, _sum0, 3);
_sum1 = vsetq_lane_f32(*outptr1, _sum1, 3);
#if __aarch64__
*outptr0 = vaddvq_f32(_sum0);
*outptr1 = vaddvq_f32(_sum1);
#else
float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1));
float32x2_t _ss01 = vpadd_f32(_ss0, _ss1);
*outptr0 = vget_lane_f32(_ss01, 0);
*outptr1 = vget_lane_f32(_ss01, 1);
#endif // __aarch64__
#else
float sum0 = 0.f;
float sum1 = 0.f;
sum0 += r0[0] * k0[0];
sum0 += r0[1] * k0[1];
sum0 += r0[2] * k0[2];
sum0 += r1[0] * k0[3];
sum0 += r1[1] * k0[4];
sum0 += r1[2] * k0[5];
sum0 += r2[0] * k0[6];
sum0 += r2[1] * k0[7];
sum0 += r2[2] * k0[8];
sum1 += r0[0] * k1[0];
sum1 += r0[1] * k1[1];
sum1 += r0[2] * k1[2];
sum1 += r1[0] * k1[3];
sum1 += r1[1] * k1[4];
sum1 += r1[2] * k1[5];
sum1 += r2[0] * k1[6];
sum1 += r2[1] * k1[7];
sum1 += r2[2] * k1[8];
*outptr0 += sum0;
*outptr1 += sum1;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
outptr0++;
outptr1++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
k0 += 9;
k1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
Mat out = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
out.fill(bias0);
const float* kernel0 = kernel + p * inch * 9;
for (int q = 0; q < inch; q++)
{
float* outptr = out;
const float* img0 = bottom_blob.channel(q);
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;
#if __ARM_NEON
float32x4_t _k0123 = vld1q_f32(k0);
float32x4_t _k3456 = vld1q_f32(k1);
float32x4_t _k6789 = vld1q_f32(k2);
#endif // __ARM_NEON
int i = 0;
for (; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v2.4s, v3.4s}, [%2], #32 \n"
"0: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v0.4s}, [%1] \n"
"fmla v0.4s, v2.4s, %10.s[0] \n"
"fmul v10.4s, v3.4s, %10.s[1] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v8.4s, v9.4s}, [%2] \n"
"ext v1.16b, v2.16b, v8.16b, #4 \n"
"fmul v11.4s, v1.4s, %10.s[2] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld2 {v2.4s, v3.4s}, [%3], #32 \n"
"fmla v0.4s, v2.4s, %11.s[0] \n"
"fmla v10.4s, v3.4s, %11.s[1] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld2 {v8.4s, v9.4s}, [%3] \n"
"ext v1.16b, v2.16b, v8.16b, #4 \n"
"fmla v11.4s, v1.4s, %11.s[2] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld2 {v2.4s, v3.4s}, [%4], #32 \n"
"fmla v0.4s, v2.4s, %12.s[0] \n"
"fmla v10.4s, v3.4s, %12.s[1] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld2 {v8.4s, v9.4s}, [%4] \n"
"ext v1.16b, v2.16b, v8.16b, #4 \n"
"fmla v11.4s, v1.4s, %12.s[2] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v2.4s, v3.4s}, [%2], #32 \n"
"fadd v0.4s, v0.4s, v10.4s \n"
"fadd v0.4s, v0.4s, v11.4s \n"
"subs %w0, %w0, #1 \n"
"st1 {v0.4s}, [%1], #16 \n"
"bne 0b \n"
"sub %2, %2, #32 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k0123), // %10
"w"(_k3456), // %11
"w"(_k6789) // %12
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
"pld [%2, #256] \n"
"vld2.f32 {d4-d7}, [%2]! \n"
"0: \n"
"pld [%1, #128] \n"
"vld1.f32 {d0-d1}, [%1] \n"
"vmla.f32 q0, q2, %e10[0] \n"
"vmul.f32 q10, q3, %e10[1] \n"
"pld [%2, #128] \n"
"vld2.f32 {d16-d17}, [%2] \n"
"vext.32 q1, q2, q8, #1 \n"
"vmul.f32 q11, q1, %f10[0] \n"
"pld [%3, #256] \n"
"vld2.f32 {d4-d7}, [%3]! \n"
"vmla.f32 q0, q2, %e11[0] \n"
"vmla.f32 q10, q3, %e11[1] \n"
"pld [%3, #128] \n"
"vld2.f32 {d16-d17}, [%3] \n"
"vext.32 q1, q2, q8, #1 \n"
"vmla.f32 q11, q1, %f11[0] \n"
"pld [%4, #256] \n"
"vld2.f32 {d4-d7}, [%4]! \n"
"vmla.f32 q0, q2, %e12[0] \n"
"vmla.f32 q10, q3, %e12[1] \n"
"pld [%4, #128] \n"
"vld2.f32 {d16-d17}, [%4] \n"
"vext.32 q1, q2, q8, #1 \n"
"vmla.f32 q11, q1, %f12[0] \n"
"pld [%2, #256] \n"
"vld2.f32 {d4-d7}, [%2]! \n"
"vadd.f32 q0, q0, q10 \n"
"vadd.f32 q0, q0, q11 \n"
"subs %0, #1 \n"
"vst1.f32 {d0-d1}, [%1]! \n"
"bne 0b \n"
"sub %2, #32 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k0123), // %10
"w"(_k3456), // %11
"w"(_k6789) // %12
: "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _sum = vmulq_f32(_r00, _k0123);
_sum = vmlaq_f32(_sum, _r10, _k3456);
_sum = vmlaq_f32(_sum, _r20, _k6789);
_sum = vsetq_lane_f32(*outptr, _sum, 3);
#if __aarch64__
*outptr = vaddvq_f32(_sum);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum));
_ss = vpadd_f32(_ss, _ss);
*outptr = vget_lane_f32(_ss, 0);
#endif // __aarch64__
#else
float sum = 0;
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;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
}
}
}
static void conv3x3s2_transform_kernel_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch)
{
kernel_tm.create(8 * 9, inch, outch / 8 + outch % 8);
const float* kernel = _kernel;
int p = 0;
for (; p + 7 < outch; p += 8)
{
const float* k0 = kernel + (p + 0) * inch * 9;
const float* k1 = kernel + (p + 1) * inch * 9;
const float* k2 = kernel + (p + 2) * inch * 9;
const float* k3 = kernel + (p + 3) * inch * 9;
const float* k4 = kernel + (p + 4) * inch * 9;
const float* k5 = kernel + (p + 5) * inch * 9;
const float* k6 = kernel + (p + 6) * inch * 9;
const float* k7 = kernel + (p + 7) * inch * 9;
float* ktmp = kernel_tm.channel(p / 8);
for (int q = 0; q < inch; q++)
{
for (int k = 0; k < 9; k++)
{
ktmp[0] = k0[k];
ktmp[1] = k1[k];
ktmp[2] = k2[k];
ktmp[3] = k3[k];
ktmp[4] = k4[k];
ktmp[5] = k5[k];
ktmp[6] = k6[k];
ktmp[7] = k7[k];
ktmp += 8;
}
k0 += 9;
k1 += 9;
k2 += 9;
k3 += 9;
k4 += 9;
k5 += 9;
k6 += 9;
k7 += 9;
}
}
for (; p < outch; p++)
{
const float* k0 = kernel + (p + 0) * inch * 9;
float* ktmp = kernel_tm.channel(p / 8 + p % 8);
for (int q = 0; q < inch; q++)
{
for (int k = 0; k < 9; k++)
{
ktmp[k] = k0[k];
}
ktmp += 9;
k0 += 9;
}
}
}
static void conv3x3s2_packed_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
// const float* kernel = _kernel;
const float* bias = _bias;
int nn_outch = outch >> 3;
int remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 8;
Mat out0 = top_blob.channel(p + 0);
Mat out1 = top_blob.channel(p + 1);
Mat out2 = top_blob.channel(p + 2);
Mat out3 = top_blob.channel(p + 3);
Mat out4 = top_blob.channel(p + 4);
Mat out5 = top_blob.channel(p + 5);
Mat out6 = top_blob.channel(p + 6);
Mat out7 = top_blob.channel(p + 7);
const float bias0 = bias ? bias[p + 0] : 0.f;
const float bias1 = bias ? bias[p + 1] : 0.f;
const float bias2 = bias ? bias[p + 2] : 0.f;
const float bias3 = bias ? bias[p + 3] : 0.f;
const float bias4 = bias ? bias[p + 4] : 0.f;
const float bias5 = bias ? bias[p + 5] : 0.f;
const float bias6 = bias ? bias[p + 6] : 0.f;
const float bias7 = bias ? bias[p + 7] : 0.f;
out0.fill(bias0);
out1.fill(bias1);
out2.fill(bias2);
out3.fill(bias3);
out4.fill(bias4);
out5.fill(bias5);
out6.fill(bias6);
out7.fill(bias7);
const float* ktmp = _kernel.channel(p / 8);
for (int q = 0; q < inch; q++)
{
float* outptr0 = out0;
float* outptr1 = out1;
float* outptr2 = out2;
float* outptr3 = out3;
float* outptr4 = out4;
float* outptr5 = out5;
float* outptr6 = out6;
float* outptr7 = out7;
const float* img0 = bottom_blob.channel(q);
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
int i = 0;
for (; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v8.4s}, [%1] \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v9.4s}, [%2] \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v10.4s}, [%3] \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v11.4s}, [%4] \n"
///
"prfm pldl1keep, [%9, #256] \n"
"ld2 {v4.4s, v5.4s}, [%9], #32 \n" // v4=00 v5=01
"ld1 {v0.4s, v1.4s}, [%12], #32 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v12.4s}, [%5] \n"
"prfm pldl1keep, [%6, #128] \n"
"ld1 {v13.4s}, [%6] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"prfm pldl1keep, [%7, #128] \n"
"ld1 {v14.4s}, [%7] \n"
"prfm pldl1keep, [%8, #128] \n"
"ld1 {v15.4s}, [%8] \n"
"ld1 {v2.4s, v3.4s}, [%12], #32 \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"prfm pldl1keep, [%9, #256] \n"
"ld2 {v6.4s, v7.4s}, [%9] \n" // v6
"fmla v8.4s, v5.4s, v2.s[0] \n"
"fmla v9.4s, v5.4s, v2.s[1] \n"
"fmla v10.4s, v5.4s, v2.s[2] \n"
"fmla v11.4s, v5.4s, v2.s[3] \n"
"ext v6.16b, v4.16b, v6.16b, #4 \n" // v6=02
"ld1 {v0.4s, v1.4s}, [%12], #32 \n"
"fmla v12.4s, v5.4s, v3.s[0] \n"
"fmla v13.4s, v5.4s, v3.s[1] \n"
"fmla v14.4s, v5.4s, v3.s[2] \n"
"fmla v15.4s, v5.4s, v3.s[3] \n"
///
"prfm pldl1keep, [%10, #256] \n"
"ld2 {v4.4s, v5.4s}, [%10], #32 \n" // v4=10 v5=11
"fmla v8.4s, v6.4s, v0.s[0] \n"
"fmla v9.4s, v6.4s, v0.s[1] \n"
"fmla v10.4s, v6.4s, v0.s[2] \n"
"fmla v11.4s, v6.4s, v0.s[3] \n"
"ld1 {v2.4s, v3.4s}, [%12], #32 \n"
"fmla v12.4s, v6.4s, v1.s[0] \n"
"fmla v13.4s, v6.4s, v1.s[1] \n"
"fmla v14.4s, v6.4s, v1.s[2] \n"
"fmla v15.4s, v6.4s, v1.s[3] \n"
"fmla v8.4s, v4.4s, v2.s[0] \n"
"fmla v9.4s, v4.4s, v2.s[1] \n"
"fmla v10.4s, v4.4s, v2.s[2] \n"
"fmla v11.4s, v4.4s, v2.s[3] \n"
"ld1 {v0.4s, v1.4s}, [%12], #32 \n"
"fmla v12.4s, v4.4s, v3.s[0] \n"
"fmla v13.4s, v4.4s, v3.s[1] \n"
"fmla v14.4s, v4.4s, v3.s[2] \n"
"fmla v15.4s, v4.4s, v3.s[3] \n"
"prfm pldl1keep, [%10, #256] \n"
"ld2 {v6.4s, v7.4s}, [%10] \n" // v6
"fmla v8.4s, v5.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[1] \n"
"fmla v10.4s, v5.4s, v0.s[2] \n"
"fmla v11.4s, v5.4s, v0.s[3] \n"
"ld1 {v2.4s, v3.4s}, [%12], #32 \n"
"ext v6.16b, v4.16b, v6.16b, #4 \n" // v6=12
"fmla v12.4s, v5.4s, v1.s[0] \n"
"fmla v13.4s, v5.4s, v1.s[1] \n"
"fmla v14.4s, v5.4s, v1.s[2] \n"
"fmla v15.4s, v5.4s, v1.s[3] \n"
///
"prfm pldl1keep, [%11, #256] \n"
"ld2 {v4.4s, v5.4s}, [%11], #32 \n" // v4=20 v5=21
"fmla v8.4s, v6.4s, v2.s[0] \n"
"fmla v9.4s, v6.4s, v2.s[1] \n"
"fmla v10.4s, v6.4s, v2.s[2] \n"
"fmla v11.4s, v6.4s, v2.s[3] \n"
"ld1 {v0.4s, v1.4s}, [%12], #32 \n"
"fmla v12.4s, v6.4s, v3.s[0] \n"
"fmla v13.4s, v6.4s, v3.s[1] \n"
"fmla v14.4s, v6.4s, v3.s[2] \n"
"fmla v15.4s, v6.4s, v3.s[3] \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"ld1 {v2.4s, v3.4s}, [%12], #32 \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"prfm pldl1keep, [%11, #256] \n"
"ld2 {v6.4s, v7.4s}, [%11] \n" // v6
"fmla v8.4s, v5.4s, v2.s[0] \n"
"fmla v9.4s, v5.4s, v2.s[1] \n"
"fmla v10.4s, v5.4s, v2.s[2] \n"
"fmla v11.4s, v5.4s, v2.s[3] \n"
"ext v6.16b, v4.16b, v6.16b, #4 \n" // v6=22
"ld1 {v0.4s, v1.4s}, [%12], #32 \n"
"fmla v12.4s, v5.4s, v3.s[0] \n"
"fmla v13.4s, v5.4s, v3.s[1] \n"
"fmla v14.4s, v5.4s, v3.s[2] \n"
"fmla v15.4s, v5.4s, v3.s[3] \n"
"fmla v8.4s, v6.4s, v0.s[0] \n"
"fmla v9.4s, v6.4s, v0.s[1] \n"
"fmla v10.4s, v6.4s, v0.s[2] \n"
"fmla v11.4s, v6.4s, v0.s[3] \n"
"fmla v12.4s, v6.4s, v1.s[0] \n"
"fmla v13.4s, v6.4s, v1.s[1] \n"
"st1 {v8.4s}, [%1], #16 \n"
"st1 {v9.4s}, [%2], #16 \n"
"fmla v14.4s, v6.4s, v1.s[2] \n"
"fmla v15.4s, v6.4s, v1.s[3] \n"
"st1 {v10.4s}, [%3], #16 \n"
"st1 {v11.4s}, [%4], #16 \n"
"sub %12, %12, #288 \n"
"st1 {v12.4s}, [%5], #16 \n"
"st1 {v13.4s}, [%6], #16 \n"
"subs %w0, %w0, #1 \n"
"st1 {v14.4s}, [%7], #16 \n"
"st1 {v15.4s}, [%8], #16 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(r0), // %9
"=r"(r1), // %10
"=r"(r2), // %11
"=r"(ktmp) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(r0),
"10"(r1),
"11"(r2),
"12"(ktmp)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else // __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%1, #128] \n"
"vld1.f32 {d16-d17}, [%1] \n"
"pld [%2, #128] \n"
"vld1.f32 {d18-d19}, [%2] \n"
"pld [%3, #128] \n"
"vld1.f32 {d20-d21}, [%3] \n"
"pld [%4, #128] \n"
"vld1.f32 {d22-d23}, [%4] \n"
///
"pld [%9, #256] \n"
"vld2.f32 {d8-d11}, [%9]! \n" // q4=00 q5=01
"vld1.f32 {d0-d3}, [%12 :128]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"pld [%5, #128] \n"
"vld1.f32 {d24-d25}, [%5] \n"
"pld [%6, #128] \n"
"vld1.f32 {d26-d27}, [%6] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"pld [%7, #128] \n"
"vld1.f32 {d28-d29}, [%7] \n"
"pld [%8, #128] \n"
"vld1.f32 {d30-d31}, [%8] \n"
"vld1.f32 {d4-d7}, [%12 :128]! \n"
"vmla.f32 q12, q4, d2[0] \n"
"vmla.f32 q13, q4, d2[1] \n"
"vmla.f32 q14, q4, d3[0] \n"
"vmla.f32 q15, q4, d3[1] \n"
"pld [%9, #128] \n"
"vld2.f32 {d12-d13}, [%9] \n" // q6
"vmla.f32 q8, q5, d4[0] \n"
"vmla.f32 q9, q5, d4[1] \n"
"vmla.f32 q10, q5, d5[0] \n"
"vmla.f32 q11, q5, d5[1] \n"
"vext.f32 q6, q4, q6, #1 \n" // q6=02
"vld1.f32 {d0-d3}, [%12 :128]! \n"
"vmla.f32 q12, q5, d6[0] \n"
"vmla.f32 q13, q5, d6[1] \n"
"vmla.f32 q14, q5, d7[0] \n"
"vmla.f32 q15, q5, d7[1] \n"
///
"pld [%10, #256] \n"
"vld2.f32 {d8-d11}, [%10]! \n" // q4=10 q5=11
"vmla.f32 q8, q6, d0[0] \n"
"vmla.f32 q9, q6, d0[1] \n"
"vmla.f32 q10, q6, d1[0] \n"
"vmla.f32 q11, q6, d1[1] \n"
"vld1.f32 {d4-d7}, [%12 :128]! \n"
"vmla.f32 q12, q6, d2[0] \n"
"vmla.f32 q13, q6, d2[1] \n"
"vmla.f32 q14, q6, d3[0] \n"
"vmla.f32 q15, q6, d3[1] \n"
"vmla.f32 q8, q4, d4[0] \n"
"vmla.f32 q9, q4, d4[1] \n"
"vmla.f32 q10, q4, d5[0] \n"
"vmla.f32 q11, q4, d5[1] \n"
"vld1.f32 {d0-d3}, [%12 :128]! \n"
"vmla.f32 q12, q4, d6[0] \n"
"vmla.f32 q13, q4, d6[1] \n"
"vmla.f32 q14, q4, d7[0] \n"
"vmla.f32 q15, q4, d7[1] \n"
"pld [%10, #128] \n"
"vld2.f32 {d12-d13}, [%10] \n" // q6
"vmla.f32 q8, q5, d0[0] \n"
"vmla.f32 q9, q5, d0[1] \n"
"vmla.f32 q10, q5, d1[0] \n"
"vmla.f32 q11, q5, d1[1] \n"
"vld1.f32 {d4-d7}, [%12 :128]! \n"
"vext.f32 q6, q4, q6, #1 \n" // q6=12
"vmla.f32 q12, q5, d2[0] \n"
"vmla.f32 q13, q5, d2[1] \n"
"vmla.f32 q14, q5, d3[0] \n"
"vmla.f32 q15, q5, d3[1] \n"
///
"pld [%11, #256] \n"
"vld2.f32 {d8-d11}, [%11]! \n" // q4=20 q5=21
"vmla.f32 q8, q6, d4[0] \n"
"vmla.f32 q9, q6, d4[1] \n"
"vmla.f32 q10, q6, d5[0] \n"
"vmla.f32 q11, q6, d5[1] \n"
"vld1.f32 {d0-d3}, [%12 :128]! \n"
"vmla.f32 q12, q6, d6[0] \n"
"vmla.f32 q13, q6, d6[1] \n"
"vmla.f32 q14, q6, d7[0] \n"
"vmla.f32 q15, q6, d7[1] \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"vld1.f32 {d4-d7}, [%12 :128]! \n"
"vmla.f32 q12, q4, d2[0] \n"
"vmla.f32 q13, q4, d2[1] \n"
"vmla.f32 q14, q4, d3[0] \n"
"vmla.f32 q15, q4, d3[1] \n"
"pld [%11, #128] \n"
"vld2.f32 {d12-d13}, [%11] \n" // q6
"vmla.f32 q8, q5, d4[0] \n"
"vmla.f32 q9, q5, d4[1] \n"
"vmla.f32 q10, q5, d5[0] \n"
"vmla.f32 q11, q5, d5[1] \n"
"vext.f32 q6, q4, q6, #1 \n" // q6=22
"vld1.f32 {d0-d3}, [%12 :128]! \n"
"vmla.f32 q12, q5, d6[0] \n"
"vmla.f32 q13, q5, d6[1] \n"
"vmla.f32 q14, q5, d7[0] \n"
"vmla.f32 q15, q5, d7[1] \n"
"vmla.f32 q8, q6, d0[0] \n"
"vmla.f32 q9, q6, d0[1] \n"
"vmla.f32 q10, q6, d1[0] \n"
"vmla.f32 q11, q6, d1[1] \n"
"vmla.f32 q12, q6, d2[0] \n"
"vmla.f32 q13, q6, d2[1] \n"
"vst1.f32 {d16-d17}, [%1]! \n"
"vst1.f32 {d18-d19}, [%2]! \n"
"vmla.f32 q14, q6, d3[0] \n"
"vmla.f32 q15, q6, d3[1] \n"
"vst1.f32 {d20-d21}, [%3]! \n"
"vst1.f32 {d22-d23}, [%4]! \n"
"sub %12, %12, #288 \n"
"vst1.f32 {d24-d25}, [%5]! \n"
"vst1.f32 {d26-d27}, [%6]! \n"
"subs %0, #1 \n"
"vst1.f32 {d28-d29}, [%7]! \n"
"vst1.f32 {d30-d31}, [%8]! \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(r0), // %9
"=r"(r1), // %10
"=r"(r2), // %11
"=r"(ktmp) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(r0),
"10"(r1),
"11"(r2),
"12"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v10.4s, v11.4s}, [%11], #32 \n"
"prfm pldl1keep, [%8, #128] \n"
"ld1 {v0.4s}, [%8] \n"
"ld1 {v12.4s, v13.4s}, [%11], #32 \n"
"ld1 {v8.s}[0], [%0] \n"
"ld1 {v8.s}[1], [%1] \n"
"ld1 {v8.s}[2], [%2] \n"
"ld1 {v8.s}[3], [%3] \n"
"fmul v14.4s, v10.4s, v0.s[0] \n"
"fmul v15.4s, v11.4s, v0.s[0] \n"
"ld1 {v9.s}[0], [%4] \n"
"ld1 {v9.s}[1], [%5] \n"
"ld1 {v9.s}[2], [%6] \n"
"ld1 {v9.s}[3], [%7] \n"
"ld1 {v10.4s, v11.4s}, [%11], #32 \n"
"fmla v8.4s, v12.4s, v0.s[1] \n"
"fmla v9.4s, v13.4s, v0.s[1] \n"
"ld1 {v12.4s, v13.4s}, [%11], #32 \n"
"fmla v14.4s, v10.4s, v0.s[2] \n"
"fmla v15.4s, v11.4s, v0.s[2] \n"
"prfm pldl1keep, [%9, #128] \n"
"ld1 {v1.4s}, [%9] \n"
"ld1 {v10.4s, v11.4s}, [%11], #32 \n"
"fmla v8.4s, v12.4s, v1.s[0] \n"
"fmla v9.4s, v13.4s, v1.s[0] \n"
"ld1 {v12.4s, v13.4s}, [%11], #32 \n"
"fmla v14.4s, v10.4s, v1.s[1] \n"
"fmla v15.4s, v11.4s, v1.s[1] \n"
"ld1 {v10.4s, v11.4s}, [%11], #32 \n"
"fmla v8.4s, v12.4s, v1.s[2] \n"
"fmla v9.4s, v13.4s, v1.s[2] \n"
"prfm pldl1keep, [%10, #128] \n"
"ld1 {v0.4s}, [%10] \n"
"ld1 {v12.4s, v13.4s}, [%11], #32 \n"
"fmla v14.4s, v10.4s, v0.s[0] \n"
"fmla v15.4s, v11.4s, v0.s[0] \n"
"ld1 {v10.4s, v11.4s}, [%11], #32 \n"
"fmla v8.4s, v12.4s, v0.s[1] \n"
"fmla v9.4s, v13.4s, v0.s[1] \n"
"fmla v14.4s, v10.4s, v0.s[2] \n"
"fmla v15.4s, v11.4s, v0.s[2] \n"
"fadd v8.4s, v8.4s, v14.4s \n"
"fadd v9.4s, v9.4s, v15.4s \n"
"sub %11, %11, #288 \n"
"st1 {v8.s}[0], [%0], #4 \n"
"st1 {v8.s}[1], [%1], #4 \n"
"st1 {v8.s}[2], [%2], #4 \n"
"st1 {v8.s}[3], [%3], #4 \n"
"st1 {v9.s}[0], [%4], #4 \n"
"st1 {v9.s}[1], [%5], #4 \n"
"st1 {v9.s}[2], [%6], #4 \n"
"st1 {v9.s}[3], [%7], #4 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(r0), // %8
"=r"(r1), // %9
"=r"(r2), // %10
"=r"(ktmp) // %11
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(r0),
"9"(r1),
"10"(r2),
"11"(ktmp)
: "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
#else // __aarch64__
asm volatile(
"vld1.f32 {d20-d23}, [%11 :128]! \n"
"pld [%8, #128] \n"
"vld1.f32 {d0-d1}, [%8] \n"
"vld1.f32 {d24-d27}, [%11 :128]! \n"
"vld1.f32 {d16[0]}, [%0] \n"
"vld1.f32 {d16[1]}, [%1] \n"
"vld1.f32 {d17[0]}, [%2] \n"
"vld1.f32 {d17[1]}, [%3] \n"
"vmul.f32 q14, q10, d0[0] \n"
"vmul.f32 q15, q11, d0[0] \n"
"vld1.f32 {d18[0]}, [%4] \n"
"vld1.f32 {d18[1]}, [%5] \n"
"vld1.f32 {d19[0]}, [%6] \n"
"vld1.f32 {d19[1]}, [%7] \n"
"vld1.f32 {d20-d23}, [%11 :128]! \n"
"vmla.f32 q8, q12, d0[1] \n"
"vmla.f32 q9, q13, d0[1] \n"
"vld1.f32 {d24-d27}, [%11 :128]! \n"
"vmla.f32 q14, q10, d1[0] \n"
"vmla.f32 q15, q11, d1[0] \n"
"pld [%9, #128] \n"
"vld1.f32 {d2-d3}, [%9] \n"
"vld1.f32 {d20-d23}, [%11 :128]! \n"
"vmla.f32 q8, q12, d2[0] \n"
"vmla.f32 q9, q13, d2[0] \n"
"vld1.f32 {d24-d27}, [%11 :128]! \n"
"vmla.f32 q14, q10, d2[1] \n"
"vmla.f32 q15, q11, d2[1] \n"
"vld1.f32 {d20-d23}, [%11 :128]! \n"
"vmla.f32 q8, q12, d3[0] \n"
"vmla.f32 q9, q13, d3[0] \n"
"pld [%10, #128] \n"
"vld1.f32 {d0-d1}, [%10] \n"
"vld1.f32 {d24-d27}, [%11 :128]! \n"
"vmla.f32 q14, q10, d0[0] \n"
"vmla.f32 q15, q11, d0[0] \n"
"vld1.f32 {d20-d23}, [%11 :128]! \n"
"vmla.f32 q8, q12, d0[1] \n"
"vmla.f32 q9, q13, d0[1] \n"
"vmla.f32 q14, q10, d1[0] \n"
"vmla.f32 q15, q11, d1[0] \n"
"vadd.f32 q8, q8, q14 \n"
"vadd.f32 q9, q9, q15 \n"
"sub %11, %11, #288 \n"
"vst1.f32 {d16[0]}, [%0]! \n"
"vst1.f32 {d16[1]}, [%1]! \n"
"vst1.f32 {d17[0]}, [%2]! \n"
"vst1.f32 {d17[1]}, [%3]! \n"
"vst1.f32 {d18[0]}, [%4]! \n"
"vst1.f32 {d18[1]}, [%5]! \n"
"vst1.f32 {d19[0]}, [%6]! \n"
"vst1.f32 {d19[1]}, [%7]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(r0), // %8
"=r"(r1), // %9
"=r"(r2), // %10
"=r"(ktmp) // %11
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(r0),
"9"(r1),
"10"(r2),
"11"(ktmp)
: "memory", "q0", "q1", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else // __ARM_NEON
float sum0 = 0.f;
float sum1 = 0.f;
float sum2 = 0.f;
float sum3 = 0.f;
float sum4 = 0.f;
float sum5 = 0.f;
float sum6 = 0.f;
float sum7 = 0.f;
sum0 += r0[0] * ktmp[0];
sum1 += r0[0] * ktmp[1];
sum2 += r0[0] * ktmp[2];
sum3 += r0[0] * ktmp[3];
sum4 += r0[0] * ktmp[4];
sum5 += r0[0] * ktmp[5];
sum6 += r0[0] * ktmp[6];
sum7 += r0[0] * ktmp[7];
ktmp += 8;
sum0 += r0[1] * ktmp[0];
sum1 += r0[1] * ktmp[1];
sum2 += r0[1] * ktmp[2];
sum3 += r0[1] * ktmp[3];
sum4 += r0[1] * ktmp[4];
sum5 += r0[1] * ktmp[5];
sum6 += r0[1] * ktmp[6];
sum7 += r0[1] * ktmp[7];
ktmp += 8;
sum0 += r0[2] * ktmp[0];
sum1 += r0[2] * ktmp[1];
sum2 += r0[2] * ktmp[2];
sum3 += r0[2] * ktmp[3];
sum4 += r0[2] * ktmp[4];
sum5 += r0[2] * ktmp[5];
sum6 += r0[2] * ktmp[6];
sum7 += r0[2] * ktmp[7];
ktmp += 8;
sum0 += r1[0] * ktmp[0];
sum1 += r1[0] * ktmp[1];
sum2 += r1[0] * ktmp[2];
sum3 += r1[0] * ktmp[3];
sum4 += r1[0] * ktmp[4];
sum5 += r1[0] * ktmp[5];
sum6 += r1[0] * ktmp[6];
sum7 += r1[0] * ktmp[7];
ktmp += 8;
sum0 += r1[1] * ktmp[0];
sum1 += r1[1] * ktmp[1];
sum2 += r1[1] * ktmp[2];
sum3 += r1[1] * ktmp[3];
sum4 += r1[1] * ktmp[4];
sum5 += r1[1] * ktmp[5];
sum6 += r1[1] * ktmp[6];
sum7 += r1[1] * ktmp[7];
ktmp += 8;
sum0 += r1[2] * ktmp[0];
sum1 += r1[2] * ktmp[1];
sum2 += r1[2] * ktmp[2];
sum3 += r1[2] * ktmp[3];
sum4 += r1[2] * ktmp[4];
sum5 += r1[2] * ktmp[5];
sum6 += r1[2] * ktmp[6];
sum7 += r1[2] * ktmp[7];
ktmp += 8;
sum0 += r2[0] * ktmp[0];
sum1 += r2[0] * ktmp[1];
sum2 += r2[0] * ktmp[2];
sum3 += r2[0] * ktmp[3];
sum4 += r2[0] * ktmp[4];
sum5 += r2[0] * ktmp[5];
sum6 += r2[0] * ktmp[6];
sum7 += r2[0] * ktmp[7];
ktmp += 8;
sum0 += r2[1] * ktmp[0];
sum1 += r2[1] * ktmp[1];
sum2 += r2[1] * ktmp[2];
sum3 += r2[1] * ktmp[3];
sum4 += r2[1] * ktmp[4];
sum5 += r2[1] * ktmp[5];
sum6 += r2[1] * ktmp[6];
sum7 += r2[1] * ktmp[7];
ktmp += 8;
sum0 += r2[2] * ktmp[0];
sum1 += r2[2] * ktmp[1];
sum2 += r2[2] * ktmp[2];
sum3 += r2[2] * ktmp[3];
sum4 += r2[2] * ktmp[4];
sum5 += r2[2] * ktmp[5];
sum6 += r2[2] * ktmp[6];
sum7 += r2[2] * ktmp[7];
ktmp += 8;
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
*outptr4 += sum4;
*outptr5 += sum5;
*outptr6 += sum6;
*outptr7 += sum7;
ktmp -= 8 * 9;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
outptr4++;
outptr5++;
outptr6++;
outptr7++;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
ktmp += 8 * 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
Mat out = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
out.fill(bias0);
const float* ktmp = _kernel.channel(p / 8 + p % 8);
for (int q = 0; q < inch; q++)
{
float* outptr = out;
const float* img0 = bottom_blob.channel(q);
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* k0 = ktmp;
const float* k1 = ktmp + 3;
const float* k2 = ktmp + 6;
#if __ARM_NEON
float32x4_t _k0123 = vld1q_f32(k0);
float32x4_t _k3456 = vld1q_f32(k1);
float32x4_t _k6789 = vld1q_f32(k2);
#endif // __ARM_NEON
int i = 0;
for (; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw & 3;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v2.4s, v3.4s}, [%2], #32 \n"
"0: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v0.4s}, [%1] \n"
"fmla v0.4s, v2.4s, %10.s[0] \n"
"fmul v10.4s, v3.4s, %10.s[1] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v8.4s, v9.4s}, [%2] \n"
"ext v1.16b, v2.16b, v8.16b, #4 \n"
"fmul v11.4s, v1.4s, %10.s[2] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld2 {v2.4s, v3.4s}, [%3], #32 \n"
"fmla v0.4s, v2.4s, %11.s[0] \n"
"fmla v10.4s, v3.4s, %11.s[1] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld2 {v8.4s, v9.4s}, [%3] \n"
"ext v1.16b, v2.16b, v8.16b, #4 \n"
"fmla v11.4s, v1.4s, %11.s[2] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld2 {v2.4s, v3.4s}, [%4], #32 \n"
"fmla v0.4s, v2.4s, %12.s[0] \n"
"fmla v10.4s, v3.4s, %12.s[1] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld2 {v8.4s, v9.4s}, [%4] \n"
"ext v1.16b, v2.16b, v8.16b, #4 \n"
"fmla v11.4s, v1.4s, %12.s[2] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v2.4s, v3.4s}, [%2], #32 \n"
"fadd v0.4s, v0.4s, v10.4s \n"
"fadd v0.4s, v0.4s, v11.4s \n"
"subs %w0, %w0, #1 \n"
"st1 {v0.4s}, [%1], #16 \n"
"bne 0b \n"
"sub %2, %2, #32 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k0123), // %10
"w"(_k3456), // %11
"w"(_k6789) // %12
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
"pld [%2, #256] \n"
"vld2.f32 {d4-d7}, [%2]! \n"
"0: \n"
"pld [%1, #128] \n"
"vld1.f32 {d0-d1}, [%1] \n"
"vmla.f32 q0, q2, %e10[0] \n"
"vmul.f32 q10, q3, %e10[1] \n"
"pld [%2, #128] \n"
"vld2.f32 {d16-d17}, [%2] \n"
"vext.32 q1, q2, q8, #1 \n"
"vmul.f32 q11, q1, %f10[0] \n"
"pld [%3, #256] \n"
"vld2.f32 {d4-d7}, [%3]! \n"
"vmla.f32 q0, q2, %e11[0] \n"
"vmla.f32 q10, q3, %e11[1] \n"
"pld [%3, #128] \n"
"vld2.f32 {d16-d17}, [%3] \n"
"vext.32 q1, q2, q8, #1 \n"
"vmla.f32 q11, q1, %f11[0] \n"
"pld [%4, #256] \n"
"vld2.f32 {d4-d7}, [%4]! \n"
"vmla.f32 q0, q2, %e12[0] \n"
"vmla.f32 q10, q3, %e12[1] \n"
"pld [%4, #128] \n"
"vld2.f32 {d16-d17}, [%4] \n"
"vext.32 q1, q2, q8, #1 \n"
"vmla.f32 q11, q1, %f12[0] \n"
"pld [%2, #256] \n"
"vld2.f32 {d4-d7}, [%2]! \n"
"vadd.f32 q0, q0, q10 \n"
"vadd.f32 q0, q0, q11 \n"
"subs %0, #1 \n"
"vst1.f32 {d0-d1}, [%1]! \n"
"bne 0b \n"
"sub %2, #32 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k0123), // %10
"w"(_k3456), // %11
"w"(_k6789) // %12
: "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
#if __ARM_NEON
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _sum = vmulq_f32(_r00, _k0123);
_sum = vmlaq_f32(_sum, _r10, _k3456);
_sum = vmlaq_f32(_sum, _r20, _k6789);
_sum = vsetq_lane_f32(*outptr, _sum, 3);
#if __aarch64__
*outptr = vaddvq_f32(_sum);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum));
_ss = vpadd_f32(_ss, _ss);
*outptr = vget_lane_f32(_ss, 0);
#endif // __aarch64__
#else
float sum = 0;
sum += r0[0] * ktmp[0];
sum += r0[1] * ktmp[1];
sum += r0[2] * ktmp[2];
sum += r1[0] * ktmp[3];
sum += r1[1] * ktmp[4];
sum += r1[2] * ktmp[5];
sum += r2[0] * ktmp[6];
sum += r2[1] * ktmp[7];
sum += r2[2] * ktmp[8];
*outptr += sum;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
ktmp += 9;
}
}
}
|
parallel.c
|
/* Copyright (C) 2005-2017 Free Software Foundation, Inc.
Contributed by Richard Henderson <[email protected]>.
This file is part of the GNU Offloading and Multi Processing Library
(libgomp).
Libgomp is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/* This file handles the (bare) PARALLEL construct. */
#include "libgomp.h"
#include <limits.h>
/* Determine the number of threads to be launched for a PARALLEL construct.
This algorithm is explicitly described in OpenMP 3.0 section 2.4.1.
SPECIFIED is a combination of the NUM_THREADS clause and the IF clause.
If the IF clause is false, SPECIFIED is forced to 1. When NUM_THREADS
is not present, SPECIFIED is 0. */
unsigned
gomp_resolve_num_threads (unsigned specified, unsigned count)
{
struct gomp_thread *thr = gomp_thread ();
struct gomp_task_icv *icv;
unsigned threads_requested, max_num_threads, num_threads;
unsigned long busy;
struct gomp_thread_pool *pool;
icv = gomp_icv (false);
if (specified == 1)
return 1;
else if (thr->ts.active_level >= 1 && !icv->nest_var)
return 1;
else if (thr->ts.active_level >= gomp_max_active_levels_var)
return 1;
/* If NUM_THREADS not specified, use nthreads_var. */
if (specified == 0)
threads_requested = icv->nthreads_var;
else
threads_requested = specified;
max_num_threads = threads_requested;
/* If dynamic threads are enabled, bound the number of threads
that we launch. */
if (icv->dyn_var)
{
unsigned dyn = gomp_dynamic_max_threads ();
if (dyn < max_num_threads)
max_num_threads = dyn;
/* Optimization for parallel sections. */
if (count && count < max_num_threads)
max_num_threads = count;
}
/* UINT_MAX stands for infinity. */
if (__builtin_expect (icv->thread_limit_var == UINT_MAX, 1)
|| max_num_threads == 1)
return max_num_threads;
/* The threads_busy counter lives in thread_pool, if there
isn't a thread_pool yet, there must be just one thread
in the contention group. If thr->team is NULL, this isn't
nested parallel, so there is just one thread in the
contention group as well, no need to handle it atomically. */
pool = thr->thread_pool;
if (thr->ts.team == NULL || pool == NULL)
{
num_threads = max_num_threads;
if (num_threads > icv->thread_limit_var)
num_threads = icv->thread_limit_var;
if (pool)
pool->threads_busy = num_threads;
return num_threads;
}
#ifdef HAVE_SYNC_BUILTINS
do
{
busy = pool->threads_busy;
num_threads = max_num_threads;
if (icv->thread_limit_var - busy + 1 < num_threads)
num_threads = icv->thread_limit_var - busy + 1;
}
while (__sync_val_compare_and_swap (&pool->threads_busy,
busy, busy + num_threads - 1)
!= busy);
#else
gomp_mutex_lock (&gomp_managed_threads_lock);
num_threads = max_num_threads;
busy = pool->threads_busy;
if (icv->thread_limit_var - busy + 1 < num_threads)
num_threads = icv->thread_limit_var - busy + 1;
pool->threads_busy += num_threads - 1;
gomp_mutex_unlock (&gomp_managed_threads_lock);
#endif
return num_threads;
}
void
GOMP_parallel_start (void (*fn) (void *), void *data, unsigned num_threads)
{
num_threads = gomp_resolve_num_threads (num_threads, 0);
gomp_team_start (fn, data, num_threads, 0, gomp_new_team (num_threads));
}
void
GOMP_parallel_end (void)
{
struct gomp_task_icv *icv = gomp_icv (false);
if (__builtin_expect (icv->thread_limit_var != UINT_MAX, 0))
{
struct gomp_thread *thr = gomp_thread ();
struct gomp_team *team = thr->ts.team;
unsigned int nthreads = team ? team->nthreads : 1;
gomp_team_end ();
if (nthreads > 1)
{
/* If not nested, there is just one thread in the
contention group left, no need for atomicity. */
if (thr->ts.team == NULL)
thr->thread_pool->threads_busy = 1;
else
{
#ifdef HAVE_SYNC_BUILTINS
__sync_fetch_and_add (&thr->thread_pool->threads_busy,
1UL - nthreads);
#else
gomp_mutex_lock (&gomp_managed_threads_lock);
thr->thread_pool->threads_busy -= nthreads - 1;
gomp_mutex_unlock (&gomp_managed_threads_lock);
#endif
}
}
}
else
gomp_team_end ();
}
ialias (GOMP_parallel_end)
void
GOMP_parallel (void (*fn) (void *), void *data, unsigned num_threads, unsigned int flags)
{
num_threads = gomp_resolve_num_threads (num_threads, 0);
gomp_team_start (fn, data, num_threads, flags, gomp_new_team (num_threads));
fn (data);
ialias_call (GOMP_parallel_end) ();
}
bool
GOMP_cancellation_point (int which)
{
if (!gomp_cancel_var)
return false;
struct gomp_thread *thr = gomp_thread ();
struct gomp_team *team = thr->ts.team;
if (which & (GOMP_CANCEL_LOOP | GOMP_CANCEL_SECTIONS))
{
if (team == NULL)
return false;
return team->work_share_cancelled != 0;
}
else if (which & GOMP_CANCEL_TASKGROUP)
{
if (thr->task->taskgroup && thr->task->taskgroup->cancelled)
return true;
/* FALLTHRU into the GOMP_CANCEL_PARALLEL case,
as #pragma omp cancel parallel also cancels all explicit
tasks. */
}
if (team)
return gomp_team_barrier_cancelled (&team->barrier);
return false;
}
ialias (GOMP_cancellation_point)
bool
GOMP_cancel (int which, bool do_cancel)
{
if (!gomp_cancel_var)
return false;
if (!do_cancel)
return ialias_call (GOMP_cancellation_point) (which);
struct gomp_thread *thr = gomp_thread ();
struct gomp_team *team = thr->ts.team;
if (which & (GOMP_CANCEL_LOOP | GOMP_CANCEL_SECTIONS))
{
/* In orphaned worksharing region, all we want to cancel
is current thread. */
if (team != NULL)
team->work_share_cancelled = 1;
return true;
}
else if (which & GOMP_CANCEL_TASKGROUP)
{
if (thr->task->taskgroup && !thr->task->taskgroup->cancelled)
{
gomp_mutex_lock (&team->task_lock);
thr->task->taskgroup->cancelled = true;
gomp_mutex_unlock (&team->task_lock);
}
return true;
}
team->team_cancelled = 1;
gomp_team_barrier_cancel (team);
return true;
}
/* The public OpenMP API for thread and team related inquiries. */
int
omp_get_num_threads (void)
{
struct gomp_team *team = gomp_thread ()->ts.team;
return team ? team->nthreads : 1;
}
int
omp_get_thread_num (void)
{
return gomp_thread ()->ts.team_id;
}
/* This wasn't right for OpenMP 2.5. Active region used to be non-zero
when the IF clause doesn't evaluate to false, starting with OpenMP 3.0
it is non-zero with more than one thread in the team. */
int
omp_in_parallel (void)
{
return gomp_thread ()->ts.active_level > 0;
}
int
omp_get_level (void)
{
return gomp_thread ()->ts.level;
}
int
omp_get_ancestor_thread_num (int level)
{
struct gomp_team_state *ts = &gomp_thread ()->ts;
if (level < 0 || level > ts->level)
return -1;
for (level = ts->level - level; level > 0; --level)
ts = &ts->team->prev_ts;
return ts->team_id;
}
int
omp_get_team_size (int level)
{
struct gomp_team_state *ts = &gomp_thread ()->ts;
if (level < 0 || level > ts->level)
return -1;
for (level = ts->level - level; level > 0; --level)
ts = &ts->team->prev_ts;
if (ts->team == NULL)
return 1;
else
return ts->team->nthreads;
}
int
omp_get_active_level (void)
{
return gomp_thread ()->ts.active_level;
}
ialias (omp_get_num_threads)
ialias (omp_get_thread_num)
ialias (omp_in_parallel)
ialias (omp_get_level)
ialias (omp_get_ancestor_thread_num)
ialias (omp_get_team_size)
ialias (omp_get_active_level)
|
fenceIssue.c
|
extern int omp_get_thread_num();
extern int printf(char *[], ...);
int main () {
int X = 0;
int Y = 0;
#pragma omp parallel num_threads(2)
{
if (omp_get_thread_num() == 0) {
X = 42;
#pragma omp atomic write
Y = 1;
} else {
int t1;
while (1) {
#pragma omp atomic read
t1 = Y;
if (t1) {
break;
}
}
int t2 = X;
printf("t2: %d\n", t2);
}
}
}
|
ClangASTHelper.h
|
//
// Copyright (c) 2012, University of Erlangen-Nuremberg
// Copyright (c) 2012, Siemens AG
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//===--- ClangASTHelper.h - Implements helper class for easy clang AST handling. -----===//
//
// This file implements a helper class which contains a few methods for easy clang AST handling.
//
//===---------------------------------------------------------------------------------===//
#ifndef _HIPACC_BACKEND_CLANG_AST_HELPER_H_
#define _HIPACC_BACKEND_CLANG_AST_HELPER_H_
#include "hipacc/AST/ASTNode.h"
#include <clang/AST/DeclCXX.h>
#include <clang/AST/StmtOpenMP.h>
#include <clang/AST/ExprCXX.h>
#include <limits>
#include <string>
namespace clang
{
namespace hipacc
{
namespace Backend
{
/** \brief Helper class which contains a few methods for easy clang AST handling. */
class ClangASTHelper final
{
public:
template <typename ElementType> using VectorType = ::llvm::SmallVector<ElementType, 16U>; //!< Type alias for LLVM SmallVector type
typedef VectorType<::clang::Expr*> ExpressionVectorType; //!< Type definition for a vector of expressions.
typedef VectorType<::clang::FunctionDecl*> FunctionDeclarationVectorType; //!< Type definition for a vector of function declarations.
typedef VectorType<::clang::QualType> QualTypeVectorType; //!< Type definition for a vector of qualified types.
typedef VectorType<::clang::Stmt*> StatementVectorType; //!< Type definition for a vector of statements.
typedef VectorType<std::string> StringVectorType; //!< Type definition for a vector of strings.
private:
::clang::ASTContext &_rCtx; //!< A reference to the current AST context.
ClangASTHelper(const ClangASTHelper &) = delete;
ClangASTHelper& operator=(const ClangASTHelper &) = delete;
public:
/** \brief Constructor.
* \param rAstContext A reference to the current AST context. */
ClangASTHelper(::clang::ASTContext &rAstContext) : _rCtx(rAstContext) {}
/** \brief Returns a reference to the current AST context. */
inline ::clang::ASTContext& GetASTContext() { return _rCtx; }
/** \brief Returns the corresponding array type for a qualified clang type.
* \param crElementType A reference to the qualified type whose array type shall be returned.
* \param cszDimension The dimension of the array. */
::clang::QualType GetConstantArrayType(const ::clang::QualType &crElementType, const size_t cszDimension);
/** \brief Returns the corresponding pointer type for a qualified clang type.
* \param crPointeeType A reference to the qualified type whose pointer type shall be returned. */
inline ::clang::QualType GetPointerType(const ::clang::QualType &crPointeeType) { return GetASTContext().getPointerType(crPointeeType); }
/** \name AST node creation methods */
//@{
/** \brief Creates an subscript expression.
* \param pArrayRef A pointer to the expression which represents the array.
* \param pIndexExpression A pointer to the expression object, which returns the index of the subscript.
* \param crReturnType The return type of the array subscript.
* \param bIsLValue Specifies, whether the array subscript expression is used as a L-value of another expression. */
::clang::ArraySubscriptExpr* CreateArraySubscriptExpression(::clang::Expr *pArrayRef, ::clang::Expr *pIndexExpression, const ::clang::QualType &crReturnType, bool bIsLValue = false);
/** \brief Creates a binary operator object of a specified type.
* \param pLhs A pointer to the expression object, which shall be on the left-hand-side.
* \param pRhs A pointer to the expression object, which shall be on the right-hand-side.
* \param eOperatorKind The type of the binary operator.
* \param crReturnType The return type of the operator expression. */
::clang::BinaryOperator* CreateBinaryOperator(::clang::Expr *pLhs, ::clang::Expr *pRhs, ::clang::BinaryOperatorKind eOperatorKind, const ::clang::QualType &crReturnType);
/** \brief Creates a binary operator object which represents the "comma" operator.
* \param pLhs A pointer to the expression object, which shall be on the left-hand-side.
* \param pRhs A pointer to the expression object, which shall be on the right-hand-side. */
::clang::BinaryOperator* CreateBinaryOperatorComma(::clang::Expr *pLhs, ::clang::Expr *pRhs);
/** \brief Creates a binary operator object which represents a "less than" comparison.
* \param pLhs A pointer to the expression object, which shall be on the left-hand-side.
* \param pRhs A pointer to the expression object, which shall be on the right-hand-side. */
::clang::BinaryOperator* CreateBinaryOperatorLessThan(::clang::Expr *pLhs, ::clang::Expr *pRhs);
/** \brief Creates a bool literal expression (i.e. a compile time constant).
* \param bValue The value of the bool literal. */
::clang::CXXBoolLiteralExpr* CreateBoolLiteral(bool bValue);
/** \brief Creates a <b>break</b> statement. */
::clang::BreakStmt* CreateBreakStatement();
/** \brief Wraps a statement object into a compound statement object.
* \param pStatement A pointer to the statement object, which shall be encapsulated into an compound statement. */
::clang::CompoundStmt* CreateCompoundStatement(::clang::Stmt *pStatement);
/** \brief Constructs a compound statement object around a vector of statement objects.
* \param crvecStatements A reference to the statement vector. */
::clang::CompoundStmt* CreateCompoundStatement(const StatementVectorType &crvecStatements);
/** \brief Constructs a conditional operator expression object (i.e. the "<cond> ? <expr_1> : <expr_2>" operator).
* \param pCondition A pointer to the expression object, which represents the condition.
* \param pThenExpr A pointer to the expression object, which will be returned when the condition is evaluated to <b>true</b>.
* \param pElseExpr A pointer to the expression object, which will be returned when the condition is evaluated to <b>false</b>.
* \param crReturnType The return type of the operator expression. */
::clang::ConditionalOperator* CreateConditionalOperator(::clang::Expr *pCondition, ::clang::Expr *pThenExpr, ::clang::Expr *pElseExpr, const ::clang::QualType &crReturnType);
/** \brief Creates a <b>continue</b> statement. */
::clang::ContinueStmt* CreateContinueStatement();
/** \brief Constructs a declaration reference expression which points to a specific declaration.
* \param pValueDecl A pointer to the value declaration object. */
::clang::DeclRefExpr* CreateDeclarationReferenceExpression(::clang::ValueDecl *pValueDecl);
/** \brief Constructs a declaration statement for a specific declaration.
* \param pDeclRef A pointer to a declaration reference expression object which points to the specific declaration. */
::clang::DeclStmt* CreateDeclarationStatement(::clang::DeclRefExpr *pDeclRef);
/** \brief Constructs a declaration statement for a specific declaration.
* \param pValueDecl A pointer to the value declaration object. */
::clang::DeclStmt* CreateDeclarationStatement(::clang::ValueDecl *pValueDecl);
/** \brief Creates a floating point literal expression (i.e. a compile time constant).
* \tparam ValueType The value type of the floating point literal (must be <b>float</b> or <b>double</b>).
* \param TValue The value of the floating point literal. */
template <typename ValueType>
::clang::FloatingLiteral* CreateFloatingLiteral(ValueType TValue)
{
static_assert( ! std::numeric_limits<ValueType>::is_integer, "The value type of a floating point literal cannot be of an integer type!" );
return ASTNode::createFloatingLiteral(GetASTContext(), TValue);
}
/** \brief Constructs a function call expression.
* \param pFunctionDecl A pointer to the function declaration which the constructed call shall point to.
* \param crvecArguments A vector containing the argument expressions for the function call. */
::clang::CallExpr* CreateFunctionCall(::clang::FunctionDecl *pFunctionDecl, const ExpressionVectorType &crvecArguments);
/** \brief Constructs a function declaration statement.
* \param strFunctionName The desired name of the newly declared function.
* \param crReturnType The qualified return type of the function.
* \param crvecArgumentNames A vector containing the names of the function arguments.
* \param crvecArgumentTypes A vector containing the qualified types of the function arguments. */
::clang::FunctionDecl* CreateFunctionDeclaration(std::string strFunctionName, const ::clang::QualType &crReturnType, const StringVectorType &crvecArgumentNames, const QualTypeVectorType &crvecArgumentTypes);
/** \brief Constructs an <b>"if-then-else"</b>-statement.
* \param pCondition A pointer to the condition expression of the <b>if</b>-branch.
* \param pThenBranch A pointer to the body statement of the <b>if</b>-branch.
* \param pElseBranch A pointer to the body statement of the <b>else</b>-branch. If set to <b>nullptr</b>, no <b>else</b>-branch will be created. */
::clang::IfStmt* CreateIfStatement(::clang::Expr *pCondition, ::clang::Stmt *pThenBranch, ::clang::Stmt *pElseBranch = nullptr);
/** \brief Constructs a multi-branch <b>if</b>-statement (i.e. a <b>"if-{else if}-else"</b>-statement).
* \param crvecConditions A vector containing the conditions of all <b>if / else if</b> branches.
* \param crvecBranchBodies A vector containing the body statements of all conditional branches.
* \param pDefaultBranch A pointer to the body statement of the final <b>else</b>-branch. If set to <b>nullptr</b>, no <b>else</b>-branch will be created.
* \remarks The number of conditions must be equal to the number of branch bodies. */
::clang::IfStmt* CreateIfStatement(const ExpressionVectorType &crvecConditions, const StatementVectorType &crvecBranchBodies, ::clang::Stmt *pDefaultBranch = nullptr);
/** \brief Creates an implicit cast expression object.
* \param pOperandExpression A pointer to the expression object whose return type shall be implicitly casted.
* \param crReturnType The qualified return type of the cast.
* \param eCastKind The internal kind of the cast.
* \param bIsLValue Specifies, whether the implicit cast expression is used as a L-value of another expression. */
::clang::ImplicitCastExpr* CreateImplicitCastExpression(::clang::Expr *pOperandExpression, const ::clang::QualType &crReturnType, ::clang::CastKind eCastKind, bool bIsLValue = false);
/** \brief Constructs an init list expression object around a vector of expressions.
* \param crvecExpressions A reference to the expression vector. */
::clang::InitListExpr* CreateInitListExpression(const ExpressionVectorType &crvecExpressions);
/** \brief Creates an integer literal expression (i.e. a compile time constant).
* \tparam ValueType The value type of the integer literal (must be integral).
* \param TValue The value of the integer literal. */
template <typename ValueType>
::clang::IntegerLiteral* CreateIntegerLiteral(ValueType TValue)
{
static_assert( std::numeric_limits<ValueType>::is_integer, "The value type of an integer literal must be of an integer type!" );
return ASTNode::createIntegerLiteral(GetASTContext(), TValue);
}
/** \brief Creates a literal expression (i.e. a compile time constant).
* \tparam ValueType The value type of the literal.
* \param TValue The value of the literal.
* \remarks Depending on the value type, this function construct a bool, integer or floating point literal. */
template <typename ValueType>
::clang::Expr* CreateLiteral(ValueType TValue);
/** \brief Creates a <b>do-while</b>-loop statement.
* \param pCondition The condition expression of the loop.
* \param pBody The statement which represents the loop body. */
::clang::DoStmt* CreateLoopDoWhile(::clang::Expr *pCondition, ::clang::Stmt *pBody);
/** \brief Creates a <b>for</b>-loop statement.
* \param pCondition The condition expression of the loop.
* \param pBody The statement which represents the loop body.
* \param pInitializer The initializer statement of the for-loop (can be <b>NULL</b>).
* \param pIncrement The increment expression of the for-loop, i.e. the expression which will be evaluated after each iteration (can be <b>NULL</b>). */
::clang::ForStmt* CreateLoopFor(::clang::Expr *pCondition, ::clang::Stmt *pBody, ::clang::Stmt *pInitializer = nullptr, ::clang::Expr *pIncrement = nullptr);
/** \brief Creates a <b>while</b>-loop statement.
* \param pCondition The condition expression of the loop.
* \param pBody The statement which represents the loop body. */
::clang::WhileStmt* CreateLoopWhile(::clang::Expr *pCondition, ::clang::Stmt *pBody);
/** \brief Creates a <b>#pragma omp parallel for</b> directive.
* \param pLoop The for-loop statement associated to this directive.
* \param nChunkSize The chunk size of the optional schedule clause. */
::clang::Stmt* CreateOpenMPDirectiveParallelFor(::clang::ForStmt* pLoop, int nChunkSize=1);
/** \brief Creates a parenthesis expression around another expression.
* \param pSubExpression A pointer to the expression object which shall be encapsulated into a parenthesis expression. */
::clang::ParenExpr* CreateParenthesisExpression(::clang::Expr *pSubExpression);
/** \brief Constructs a post increment statement for a declaration reference expression object.
* \param pDeclRef A pointer to the declaration reference expression, which shall be used in the post increment operator. */
::clang::UnaryOperator* CreatePostIncrementOperator(::clang::DeclRefExpr *pDeclRef);
/** \brief Creates a reinterpret cast expression object.
* \param pOperandExpression A pointer to the expression object whose return type shall be implicitly casted.
* \param crReturnType The qualified return type of the cast.
* \param eCastKind The internal kind of the cast.
* \param bIsLValue Specifies, whether the reinterpret cast expression is used as a L-value of another expression. */
::clang::CXXReinterpretCastExpr* CreateReinterpretCast(::clang::Expr *pOperandExpression, const ::clang::QualType &crReturnType, ::clang::CastKind eCastKind, bool bIsLValue = false);
/** \brief Creates a <b>return</b> statement.
* \param pReturnValue A pointer to an expression object whose result shall be returned by the <b>return</b> statement (if set to <b>nullptr</b>, nothing will be returned). */
::clang::ReturnStmt* CreateReturnStatement(::clang::Expr *pReturnValue = nullptr);
/** \brief Creates a static cast expression object.
* \param pOperandExpression A pointer to the expression object whose return type shall be implicitly casted.
* \param crReturnType The qualified return type of the cast.
* \param eCastKind The internal kind of the cast.
* \param bIsLValue Specifies, whether the static cast expression is used as a L-value of another expression. */
::clang::CXXStaticCastExpr* CreateStaticCast(::clang::Expr *pOperandExpression, const ::clang::QualType &crReturnType, ::clang::CastKind eCastKind, bool bIsLValue = false);
/** \brief Creates a string literal expression (i.e. a constant C-string).
* \param strValue The value of the string literal. */
::clang::StringLiteral* CreateStringLiteral(std::string strValue);
/** \brief Creates an unary operator object of a specified type.
* \param pSubExpression A pointer to the expression object, which shall be the sub-expression of the operator.
* \param eOperatorKind The type of the unary operator.
* \param crResultType The return type of the operator expression. */
::clang::UnaryOperator* CreateUnaryOperator(::clang::Expr *pSubExpression, ::clang::UnaryOperatorKind eOperatorKind, const ::clang::QualType &crResultType);
/** \brief Creates a new variable declaration object.
* \param pDeclContext A pointer to the declaration context which the new variable shall be declared in.
* \param crstrVariableName The name of the newly declared variable.
* \param crVariableType The qualified type of newly declared variable.
* \param pInitExpression A pointer to the initialization expression object for the variable declaration (i.e. the R-value of the assignment).
* \remarks The created variable declaration is automatically added to the declaration context of the specified function declaration. */
::clang::VarDecl* CreateVariableDeclaration(::clang::DeclContext *pDeclContext, const std::string &crstrVariableName, const ::clang::QualType &crVariableType, ::clang::Expr *pInitExpression);
/** \brief Creates a new variable declaration object.
* \param pParentFunction A pointer to the function declaration object in whose context the new variable shall be declared.
* \param crstrVariableName The name of the newly declared variable.
* \param crVariableType The qualified type of newly declared variable.
* \param pInitExpression A pointer to the initialization expression object for the variable declaration (i.e. the R-value of the assignment).
* \remarks The created variable declaration is automatically added to the declaration context of the specified function declaration. */
::clang::VarDecl* CreateVariableDeclaration(::clang::FunctionDecl *pParentFunction, const std::string &crstrVariableName, const ::clang::QualType &crVariableType, ::clang::Expr *pInitExpression);
//@}
public:
/** \brief Checks, whether all function declaration objects in a function declaration vector have the same signature.
* \param crvecFunctionDecls A vector containing all function declaration objects whose signature shall be compared. */
static bool AreSignaturesEqual(const FunctionDeclarationVectorType &crvecFunctionDecls);
/** \brief Counts the number of declaration references to a specific declaration inside a statement tree.
* \param pStatement A pointer to the root of the statement tree which shall be parsed for the specified declaration references.
* \param crstrReferenceName The name of the declaration reference whose appearances shall be counted. */
static unsigned int CountNumberOfReferences(::clang::Stmt *pStatement, const std::string &crstrReferenceName);
/** \brief Looks up a specific declaration.
* \param pFunction A pointer to the function declaration object whose declaration context will be searched for the specified declaration.
* \param crstrDeclName The name of the declaration which shall be searched for.
* \return If successful, a pointer to a newly created declaration reference expression for the found declaration, and zero otherwise. */
::clang::DeclRefExpr* FindDeclaration(::clang::FunctionDecl *pFunction, const std::string &crstrDeclName);
/** \brief Returns the fully qualified name of a function declaration, i.e. the function name with all preceding namespace names.
* \param pFunctionDecl A pointer to the function declaration object, whose fully qualified name shall be retrieved. */
static std::string GetFullyQualifiedFunctionName(::clang::FunctionDecl *pFunctionDecl);
/** \brief Returns a vector of all known function declarations in the encapsulated AST context.
* \remarks This method parses all namespaces, beginning with the global namespace. */
FunctionDeclarationVectorType GetKnownFunctionDeclarations();
/** \brief Returns a vector of all known function declarations inside of a declaration context.
* \param pDeclContextRoot A pointer to the declaration context object which shall be parsed for function declarations.
* \remarks This method also parses all child declaration contexts of the specified root declaration context. */
FunctionDeclarationVectorType GetFunctionDeclarationsFromContext(::clang::DeclContext *pDeclContextRoot);
/** \brief Checks whether a statement tree has only one branch (i.e. none of its nodes has more than one child).
* \param pStatement A pointer to the root of the statement tree. */
static bool IsSingleBranchStatement(::clang::Stmt *pStatement);
/** \brief Replaces <b>all</b> instances of a declaration reference in a statement tree by a new value declaration.
* \param pStatement A pointer to the root of the statement tree which shall be parsed for the specified declaration references.
* \param crstrDeclRefName The name of the declaration reference which shall be replaced.
* \param pNewDecl A pointer to the value declaration to which all reference will be updated. */
static void ReplaceDeclarationReferences(::clang::Stmt* pStatement, const std::string &crstrDeclRefName, ::clang::ValueDecl *pNewDecl);
/** \brief Determines whether a pointer is referencing to a type marked by the const qualifier.
* \param crPointer The qualified type of the pointer. */
bool IsPointerToConstType(const QualType& crPointer);
};
// Template function specializations
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(bool TValue) { return CreateBoolLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(int8_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(uint8_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(int16_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(uint16_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(int32_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(uint32_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(int64_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(uint64_t TValue) { return CreateIntegerLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(float TValue) { return CreateFloatingLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(double TValue) { return CreateFloatingLiteral(TValue); }
template<> inline ::clang::Expr* ClangASTHelper::CreateLiteral(std::string TValue) { return CreateStringLiteral(TValue); }
} // end namespace Backend
} // end namespace hipacc
} // end namespace clang
#endif // _HIPACC_BACKEND_CLANG_AST_HELPER_H_
// vim: set ts=2 sw=2 sts=2 et ai:
|
GB_binop__bshift_int32.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bshift_int32)
// A.*B function (eWiseMult): GB (_AemultB_08__bshift_int32)
// A.*B function (eWiseMult): GB (_AemultB_02__bshift_int32)
// A.*B function (eWiseMult): GB (_AemultB_04__bshift_int32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_int32)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bshift_int32)
// C+=b function (dense accum): GB (_Cdense_accumb__bshift_int32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_int32)
// C=scalar+B GB (_bind1st__bshift_int32)
// C=scalar+B' GB (_bind1st_tran__bshift_int32)
// C=A+scalar GB (_bind2nd__bshift_int32)
// C=A'+scalar GB (_bind2nd_tran__bshift_int32)
// C type: int32_t
// A type: int32_t
// A pattern? 0
// B type: int8_t
// B pattern? 0
// BinaryOp: cij = GB_bitshift_int32 (aij, bij)
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int8_t
#define GB_CTYPE \
int32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
0
// 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 \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int32_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) \
int32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_bitshift_int32 (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BSHIFT || GxB_NO_INT32 || GxB_NO_BSHIFT_INT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__bshift_int32)
(
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__bshift_int32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bshift_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 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
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
int32_t *restrict Cx = (int32_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,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bshift_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 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) ;
int32_t alpha_scalar ;
int8_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int32_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__bshift_int32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bshift_int32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__bshift_int32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bshift_int32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bshift_int32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *Cx = (int32_t *) Cx_output ;
int32_t x = (*((int32_t *) x_input)) ;
int8_t *Bx = (int8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int8_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_bitshift_int32 (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bshift_int32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int32_t *Cx = (int32_t *) Cx_output ;
int32_t *Ax = (int32_t *) Ax_input ;
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 ;
int32_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_bitshift_int32 (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_bitshift_int32 (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__bshift_int32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_bitshift_int32 (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__bshift_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
trsm_c_sky_n_hi_col_conj.c
|
#include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include <memory.h>
#ifdef _OPENMP
#include <omp.h>
#endif
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, ALPHA_Number *y, const ALPHA_INT ldy)
{
ALPHA_INT m = A->rows;
ALPHA_Complex diag[m];
memset(diag, '\0', m * sizeof(ALPHA_Complex));
ALPHA_INT num_thread = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for (ALPHA_INT r = 1; r < A->rows + 1; r++)
{
const ALPHA_INT indx = A->pointers[r] - 1;
diag[r - 1].real = A->values[indx].real;
diag[r - 1].imag = -A->values[indx].imag;
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for(ALPHA_INT out_y_col = 0; out_y_col < columns; out_y_col++)
{
for (ALPHA_INT r = 0; r <A->rows; r++)
{
ALPHA_Complex temp = {.real = 0.f, .imag = 0.f};
ALPHA_INT start = A->pointers[r];
ALPHA_INT end = A->pointers[r + 1];
ALPHA_INT idx = 1;
ALPHA_INT eles_num = end - start;
for (ALPHA_INT ai = start; ai < end - 1; ++ai)
{
ALPHA_INT c = r - eles_num + idx;
ALPHA_Complex cv = A->values[ai];
alpha_conj(cv, cv);
alpha_madde(temp, cv, y[out_y_col * ldy + c]);
idx ++;
}
ALPHA_Complex t;
alpha_mul(t, alpha, x[out_y_col * ldx + r]);
alpha_sub(t, t, temp);
alpha_div(y[out_y_col * ldy + r], t, diag[r]);
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
residualbased_predictorcorrector_velocity_bossak_scheme.h
|
/*
==============================================================================
KratosStructuralApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).
Copyright 2007
Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel
[email protected]
[email protected]
[email protected]
[email protected]
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain
- Ruhr-University Bochum, Institute for Structural Mechanics, Germany
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following condition:
Distribution of this code for any commercial purpose is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================
*/
/* *********************************************************
*
* Last Modified by: $Author: Kazem $
* Date: $Date: 2008-07-25 14:48:17 $
* Revision: $Revision: 1.1 $
*
* ***********************************************************/
#if !defined(KRATOS_RESIDUALBASED_PREDICTOR_CORRECTOR_VELOCITY_BOSSAK_SCHEME )
#define KRATOS_RESIDUALBASED_PREDICTOR_CORRECTOR_VELOCITY_BOSSAK_SCHEME
/* System includes */
/* External includes */
#include "boost/smart_ptr.hpp"
/* Project includes */
#include "includes/define.h"
#include "includes/model_part.h"
#include "solving_strategies/schemes/scheme.h"
#include "includes/variables.h"
#include "containers/array_1d.h"
#include "utilities/openmp_utils.h"
#include "includes/cfd_variables.h"
namespace Kratos
{
/**@name Kratos Globals */
/*@{ */
/*@} */
/**@name Type Definitions */
/*@{ */
/*@} */
/**@name Enum's */
/*@{ */
/*@} */
/**@name Functions */
/*@{ */
/*@} */
/**@name Kratos Classes */
/*@{ */
/** Short class definition.
This class provides the implementation of the basic tasks that are needed by the solution strategy.
It is intended to be the place for tailoring the solution strategies to problem specific tasks.
Detail class definition.
\URL[Example of use html]{ extended_documentation/no_ex_of_use.html}
\URL[Example of use pdf]{ extended_documentation/no_ex_of_use.pdf}
\URL[Example of use doc]{ extended_documentation/no_ex_of_use.doc}
\URL[Example of use ps]{ extended_documentation/no_ex_of_use.ps}
\URL[Extended documentation html]{ extended_documentation/no_ext_doc.html}
\URL[Extended documentation pdf]{ extended_documentation/no_ext_doc.pdf}
\URL[Extended documentation doc]{ extended_documentation/no_ext_doc.doc}
\URL[Extended documentation ps]{ extended_documentation/no_ext_doc.ps}
*/
template<class TSparseSpace,
class TDenseSpace //= DenseSpace<double>
>
class ResidualBasedPredictorCorrectorVelocityBossakScheme : public Scheme<TSparseSpace, TDenseSpace>
{
public:
/**@name Type Definitions */
/*@{ */
KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedPredictorCorrectorVelocityBossakScheme);
typedef Scheme<TSparseSpace, TDenseSpace> BaseType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename Element::DofsVectorType DofsVectorType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
/*@} */
/**@name Life Cycle
*/
/*@{ */
/** Constructor.
*/
ResidualBasedPredictorCorrectorVelocityBossakScheme(double NewAlphaBossak, double MoveMeshStrategy)
: Scheme<TSparseSpace, TDenseSpace>()
{
//default values for the Newmark Scheme
mAlphaBossak = NewAlphaBossak;
mBetaNewmark = 0.25 * pow((1.00 - mAlphaBossak), 2);
mGammaNewmark = 0.5 - mAlphaBossak;
mMeshVelocity = MoveMeshStrategy;
//Allocate auxiliary memory
int NumThreads = OpenMPUtils::GetNumThreads();
mMass.resize(NumThreads);
mDamp.resize(NumThreads);
mvel.resize(NumThreads);
macc.resize(NumThreads);
maccold.resize(NumThreads);
// mAlphaBossak= 0.0;
// mGammaNewmark= 1.0;
//mGammaNewmark = 1.0;
//mBetaNewmark = 0.5;
//mAlphaBossak = 0.0;
//sizing work matrices
//mMass.resize(10,10);
//mDamp.resize(10,10);
//mvel.resize(10,false);
//macc.resize(10,false);
//maccold.resize(10,false);
std::cout << "using the velocity Bossak Time Integration Scheme" << std::endl;
}
/** Destructor.
*/
virtual ~ResidualBasedPredictorCorrectorVelocityBossakScheme()
{
}
/*@} */
/**@name Operators
*/
/*@{ */
/**
Performing the update of the solution.
*/
//***************************************************************************
void Update(
ModelPart& r_model_part,
DofsArrayType& rDofSet,
TSystemMatrixType& A,
TSystemVectorType& Dv,
TSystemVectorType& b
) override
{
KRATOS_TRY
BasicUpdateOperations(r_model_part, rDofSet, A, Dv, b);
AdditionalUpdateOperations(r_model_part, rDofSet, A, Dv, b);
KRATOS_CATCH("")
}
void BasicUpdateOperations(
ModelPart& r_model_part,
DofsArrayType& rDofSet,
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b)
{
mpDofUpdater->UpdateDofs(rDofSet,Dx);
}
void AdditionalUpdateOperations(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
TSystemMatrixType& A,
TSystemVectorType& Dv,
TSystemVectorType& b
)
{
KRATOS_TRY
int NumThreads = OpenMPUtils::GetNumThreads();
OpenMPUtils::PartitionVector NodePartition;
OpenMPUtils::DivideInPartitions(rModelPart.Nodes().size(),NumThreads,NodePartition);
//updating time derivatives (nodally for efficiency)
#pragma omp parallel
{
array_1d<double, 3 > DeltaVel;
int k = OpenMPUtils::ThisThread();
ModelPart::NodeIterator NodesBegin = rModelPart.NodesBegin() + NodePartition[k];
ModelPart::NodeIterator NodesEnd = rModelPart.NodesBegin() + NodePartition[k+1];
for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; itNode++)
{
noalias(DeltaVel) = (itNode)->FastGetSolutionStepValue(VELOCITY) - (itNode)->FastGetSolutionStepValue(VELOCITY, 1);
array_1d<double, 3 > & CurrentAcceleration = (itNode)->FastGetSolutionStepValue(ACCELERATION, 0);
array_1d<double, 3 > & OldAcceleration = (itNode)->FastGetSolutionStepValue(ACCELERATION, 1);
UpdateAcceleration(CurrentAcceleration, DeltaVel, OldAcceleration);
if (mMeshVelocity == 2)//Lagrangian
{
array_1d<double, 3 > & CurrentDisplacement = (itNode)->FastGetSolutionStepValue(DISPLACEMENT, 0);
array_1d<double, 3 > & OldDisplacement = (itNode)->FastGetSolutionStepValue(DISPLACEMENT, 1);
array_1d<double, 3 > & OldVelocity = (itNode)->FastGetSolutionStepValue(VELOCITY, 1);
noalias(itNode->FastGetSolutionStepValue(MESH_VELOCITY) ) = itNode->FastGetSolutionStepValue(VELOCITY);
UpdateDisplacement(CurrentDisplacement, OldDisplacement, OldVelocity, OldAcceleration, CurrentAcceleration);
}
}
}
KRATOS_CATCH("")
}
//***************************************************************************
//predicts the solution at the current step as
// v = vold
void Predict(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
TSystemMatrixType& A,
TSystemVectorType& Dv,
TSystemVectorType& b
) override
{
// std::cout << "prediction" << std::endl;
int NumThreads = OpenMPUtils::GetNumThreads();
OpenMPUtils::PartitionVector NodePartition;
OpenMPUtils::DivideInPartitions(rModelPart.Nodes().size(),NumThreads,NodePartition);
#pragma omp parallel
{
//array_1d<double, 3 > DeltaDisp;
int k = OpenMPUtils::ThisThread();
ModelPart::NodeIterator NodesBegin = rModelPart.NodesBegin() + NodePartition[k];
ModelPart::NodeIterator NodesEnd = rModelPart.NodesBegin() + NodePartition[k+1];
for (ModelPart::NodeIterator itNode = NodesBegin; itNode != NodesEnd; itNode++)
{
array_1d<double, 3 > & OldVelocity = (itNode)->FastGetSolutionStepValue(VELOCITY, 1);
double& OldPressure = (itNode)->FastGetSolutionStepValue(PRESSURE, 1);
double& OldAirPressure = (itNode)->FastGetSolutionStepValue(AIR_PRESSURE, 1);
//predicting velocity
//ATTENTION::: the prediction is performed only on free nodes
array_1d<double, 3 > & CurrentVelocity = (itNode)->FastGetSolutionStepValue(VELOCITY);
double& CurrentPressure = (itNode)->FastGetSolutionStepValue(PRESSURE);
double& CurrentAirPressure = (itNode)->FastGetSolutionStepValue(AIR_PRESSURE);
if ((itNode->pGetDof(VELOCITY_X))->IsFree())
(CurrentVelocity[0]) = OldVelocity[0];
if (itNode->pGetDof(VELOCITY_Y)->IsFree())
(CurrentVelocity[1]) = OldVelocity[1];
if (itNode->HasDofFor(VELOCITY_Z))
if (itNode->pGetDof(VELOCITY_Z)->IsFree())
(CurrentVelocity[2]) = OldVelocity[2];
if (itNode->pGetDof(PRESSURE)->IsFree())
CurrentPressure = OldPressure;
if (itNode->HasDofFor(AIR_PRESSURE))
if (itNode->pGetDof(AIR_PRESSURE)->IsFree())
CurrentAirPressure = OldAirPressure;
// updating time derivatives ::: please note that displacements and
// their time derivatives can not be consistently fixed separately
array_1d<double, 3 > DeltaVel;
noalias(DeltaVel) = CurrentVelocity - OldVelocity;
array_1d<double, 3 > & OldAcceleration = (itNode)->FastGetSolutionStepValue(ACCELERATION, 1);
array_1d<double, 3 > & CurrentAcceleration = (itNode)->FastGetSolutionStepValue(ACCELERATION);
UpdateAcceleration(CurrentAcceleration, DeltaVel, OldAcceleration);
if (mMeshVelocity == 2) //Lagrangian
{
array_1d<double, 3 > & OldDisplacement = (itNode)->FastGetSolutionStepValue(DISPLACEMENT, 1);
array_1d<double, 3 > & CurrentDisplacement = (itNode)->FastGetSolutionStepValue(DISPLACEMENT, 0);
noalias(itNode->FastGetSolutionStepValue(MESH_VELOCITY) ) = itNode->FastGetSolutionStepValue(VELOCITY);
UpdateDisplacement(CurrentDisplacement, OldDisplacement, OldVelocity, OldAcceleration, CurrentAcceleration);
}
}
}
// std::cout << "end of prediction" << std::endl;
}
//***************************************************************************
/** this function is designed to be called in the builder and solver
to introduce
the selected time integration scheme. It "asks" the matrix needed to
the element and
performs the operations needed to introduce the seected time
integration scheme.
this function calculates at the same time the contribution to the
LHS and to the RHS
of the system
*/
void CalculateSystemContributions(
Element::Pointer rCurrentElement,
LocalSystemMatrixType& LHS_Contribution,
LocalSystemVectorType& RHS_Contribution,
Element::EquationIdVectorType& EquationId,
ProcessInfo& CurrentProcessInfo
) override
{
KRATOS_TRY
int k = OpenMPUtils::ThisThread();
//Initializing the non linear iteration for the current element
(rCurrentElement) -> InitializeNonLinearIteration(CurrentProcessInfo);
//KRATOS_WATCH(LHS_Contribution);
//basic operations for the element considered
(rCurrentElement)->CalculateLocalSystem(LHS_Contribution, RHS_Contribution, CurrentProcessInfo);
//std::cout << rCurrentElement->Id() << " RHS = " << RHS_Contribution << std::endl;
(rCurrentElement)->CalculateMassMatrix(mMass[k], CurrentProcessInfo);
(rCurrentElement)->CalculateLocalVelocityContribution(mDamp[k], RHS_Contribution, CurrentProcessInfo);
(rCurrentElement)->EquationIdVector(EquationId, CurrentProcessInfo);
//adding the dynamic contributions (statics is already included)
AddDynamicsToLHS(LHS_Contribution, mDamp[k], mMass[k], CurrentProcessInfo);
AddDynamicsToRHS(rCurrentElement, RHS_Contribution, mDamp[k], mMass[k], CurrentProcessInfo);
KRATOS_CATCH("")
}
void Calculate_RHS_Contribution(
Element::Pointer rCurrentElement,
LocalSystemVectorType& RHS_Contribution,
Element::EquationIdVectorType& EquationId,
ProcessInfo& CurrentProcessInfo) override
{
int k = OpenMPUtils::ThisThread();
//Initializing the non linear iteration for the current element
(rCurrentElement) -> InitializeNonLinearIteration(CurrentProcessInfo);
//basic operations for the element considered
(rCurrentElement)->CalculateRightHandSide(RHS_Contribution, CurrentProcessInfo);
(rCurrentElement)->CalculateMassMatrix(mMass[k], CurrentProcessInfo);
(rCurrentElement)->CalculateLocalVelocityContribution(mDamp[k], RHS_Contribution, CurrentProcessInfo);
(rCurrentElement)->EquationIdVector(EquationId, CurrentProcessInfo);
//adding the dynamic contributions (static is already included)
AddDynamicsToRHS(rCurrentElement, RHS_Contribution, mDamp[k], mMass[k], CurrentProcessInfo);
}
/** functions totally analogous to the precedent but applied to
the "condition" objects
*/
virtual void Condition_CalculateSystemContributions(
Condition::Pointer rCurrentCondition,
LocalSystemMatrixType& LHS_Contribution,
LocalSystemVectorType& RHS_Contribution,
Element::EquationIdVectorType& EquationId,
ProcessInfo& CurrentProcessInfo) override
{
KRATOS_TRY
int k = OpenMPUtils::ThisThread();
//KRATOS_WATCH("CONDITION LOCALVELOCITYCONTRIBUTION IS NOT DEFINED");
(rCurrentCondition) -> InitializeNonLinearIteration(CurrentProcessInfo);
(rCurrentCondition)->CalculateLocalSystem(LHS_Contribution, RHS_Contribution, CurrentProcessInfo);
(rCurrentCondition)->CalculateMassMatrix(mMass[k], CurrentProcessInfo);
//(rCurrentCondition)->CalculateDampingMatrix(VelocityBossakAuxiliaries::mDamp,CurrentProcessInfo);
(rCurrentCondition)->CalculateLocalVelocityContribution(mDamp[k], RHS_Contribution, CurrentProcessInfo);
(rCurrentCondition)->EquationIdVector(EquationId, CurrentProcessInfo);
AddDynamicsToLHS(LHS_Contribution, mDamp[k], mMass[k], CurrentProcessInfo);
AddDynamicsToRHS(rCurrentCondition, RHS_Contribution, mDamp[k], mMass[k], CurrentProcessInfo);
KRATOS_CATCH("")
}
void Condition_Calculate_RHS_Contribution(
Condition::Pointer rCurrentCondition,
LocalSystemVectorType& RHS_Contribution,
Element::EquationIdVectorType& EquationId,
ProcessInfo& CurrentProcessInfo) override
{
KRATOS_TRY
int k = OpenMPUtils::ThisThread();
//KRATOS_WATCH("CONDITION LOCALVELOCITYCONTRIBUTION IS NOT DEFINED");
//Initializing the non linear iteration for the current condition
(rCurrentCondition) -> InitializeNonLinearIteration(CurrentProcessInfo);
//basic operations for the element considered
(rCurrentCondition)->CalculateRightHandSide(RHS_Contribution, CurrentProcessInfo);
(rCurrentCondition)->CalculateMassMatrix(mMass[k], CurrentProcessInfo);
//(rCurrentCondition)->CalculateDampingMatrix(VelocityBossakAuxiliaries::mDamp,CurrentProcessInfo);
(rCurrentCondition)->CalculateLocalVelocityContribution(mDamp[k], RHS_Contribution, CurrentProcessInfo);
(rCurrentCondition)->EquationIdVector(EquationId, CurrentProcessInfo);
//adding the dynamic contributions (static is already included)
AddDynamicsToRHS(rCurrentCondition, RHS_Contribution, mDamp[k], mMass[k], CurrentProcessInfo);
KRATOS_CATCH("")
}
//*************************************************************************************
//*************************************************************************************
void InitializeSolutionStep(
ModelPart& r_model_part,
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b
) override
{
ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo();
Scheme<TSparseSpace, TDenseSpace>::InitializeSolutionStep(r_model_part, A, Dx, b);
double DeltaTime = CurrentProcessInfo[DELTA_TIME];
if (DeltaTime == 0)
KRATOS_THROW_ERROR(std::logic_error, "detected delta_time = 0 in the Bossak Scheme ... check if the time step is created correctly for the current model part", "");
//initializing constants
ma0 = 1.0 / (mGammaNewmark * DeltaTime);
ma1 = DeltaTime * mBetaNewmark / mGammaNewmark;
ma2 = (-1 + mGammaNewmark) / mGammaNewmark;
ma3 = DeltaTime;
ma4 = pow(DeltaTime, 2)*(-2.0 * mBetaNewmark + 1.0) / 2.0;
ma5 = pow(DeltaTime, 2) * mBetaNewmark;
mam = (1.0 - mAlphaBossak) / (mGammaNewmark * DeltaTime);
}
//*************************************************************************************
//*************************************************************************************
void InitializeNonLinIteration(
ModelPart& r_model_part,
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b) override
{
KRATOS_TRY
ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo();
//if orthogonal subscales are computed
if (CurrentProcessInfo[OSS_SWITCH] == 1.0)
{
std::cout << ">>>>>>>>>>>>>>>Using OSS<<<<<<<<<<<<<<<<<<<" << std::endl;
for (typename ModelPart::NodesContainerType::iterator ind = r_model_part.NodesBegin(); ind != r_model_part.NodesEnd(); ind++)
{
noalias(ind->FastGetSolutionStepValue(ADVPROJ)) = ZeroVector(3);
ind->FastGetSolutionStepValue(DIVPROJ) = 0.0;
ind->FastGetSolutionStepValue(NODAL_AREA) = 0.0;
}//end of loop over nodes
//loop on nodes to compute ADVPROJ CONVPROJ NODALAREA
array_1d<double, 3 > output;
for (typename ModelPart::ElementsContainerType::iterator elem = r_model_part.ElementsBegin(); elem != r_model_part.ElementsEnd(); elem++)
{
elem->Calculate(ADVPROJ, output, CurrentProcessInfo);
}
r_model_part.GetCommunicator().AssembleCurrentData(NODAL_AREA);
r_model_part.GetCommunicator().AssembleCurrentData(DIVPROJ);
r_model_part.GetCommunicator().AssembleCurrentData(ADVPROJ);
for (typename ModelPart::NodesContainerType::iterator ind = r_model_part.NodesBegin(); ind != r_model_part.NodesEnd(); ind++)
{
if (ind->FastGetSolutionStepValue(NODAL_AREA) == 0.0)
{
ind->FastGetSolutionStepValue(NODAL_AREA) = 1.0;
//KRATOS_WATCH("*********ATTENTION: NODAL AREA IS ZERRROOOO************");
}
const double Area = ind->FastGetSolutionStepValue(NODAL_AREA);
ind->FastGetSolutionStepValue(ADVPROJ) /= Area;
ind->FastGetSolutionStepValue(DIVPROJ) /= Area;
}
}
KRATOS_CATCH("")
}
//************************************************************************************************
//************************************************************************************************
void Clear() override
{
this->mpDofUpdater->Clear();
}
/*@} */
/**@name Operations */
/*@{ */
/*@} */
/**@name Access */
/*@{ */
/*@} */
/**@name Inquiry */
/*@{ */
/*@} */
/**@name Friends */
/*@{ */
/*@} */
protected:
/**@name Protected static Member Variables */
/*@{ */
/*@} */
/**@name Protected member Variables */
/*@{ */
double mAlphaBossak;
double mBetaNewmark;
double mGammaNewmark;
double mMeshVelocity;
double ma0;
double ma1;
double ma2;
double ma3;
double ma4;
double ma5;
double mam;
std::vector< Matrix >mMass;
std::vector< Matrix >mDamp;
std::vector< Vector >mvel;
std::vector< Vector >macc;
std::vector< Vector >maccold;
/*@} */
/**@name Protected Operators*/
/*@{ */
//*********************************************************************************
//Updating first time Derivative
//*********************************************************************************
void UpdateDisplacement(array_1d<double, 3 > & CurrentDisplacement,
const array_1d<double, 3 > & OldDisplacement,
const array_1d<double, 3 > & OldVelocity,
const array_1d<double, 3 > & OldAcceleration,
const array_1d<double, 3 > & CurrentAcceleration)
{
noalias(CurrentDisplacement) = OldDisplacement + ma3 * OldVelocity + ma4 * OldAcceleration + ma5*CurrentAcceleration;
}
//**************************************************************************
void UpdateAcceleration(array_1d<double, 3 > & CurrentAcceleration,
const array_1d<double, 3 > & DeltaVel,
const array_1d<double, 3 > & OldAcceleration)
{
noalias(CurrentAcceleration) = ma0 * DeltaVel + ma2*OldAcceleration;
}
//****************************************************************************
/**
Kdyn = a0*M + D + a1*K
*/
void AddDynamicsToLHS(
LocalSystemMatrixType& LHS_Contribution,
LocalSystemMatrixType& D,
LocalSystemMatrixType& M,
ProcessInfo& CurrentProcessInfo)
{
//multipling time scheme factor
LHS_Contribution *= ma1;
// adding mass contribution to the dynamic stiffness
if (M.size1() != 0) // if M matrix declared
{
noalias(LHS_Contribution) += mam*M;
}
//adding damping contribution
if (D.size1() != 0) // if M matrix declared
{
noalias(LHS_Contribution) += D;
}
}
//****************************************************************************
/**
bdyn = b - M*acc - D*vel
*/
void AddDynamicsToRHS(
Element::Pointer rCurrentElement,
LocalSystemVectorType& RHS_Contribution,
LocalSystemMatrixType& D,
LocalSystemMatrixType& M,
ProcessInfo& CurrentProcessInfo)
{
//adding inertia contributionDISPLACEMENT
if (M.size1() != 0)
{
int k = OpenMPUtils::ThisThread();
rCurrentElement->GetSecondDerivativesVector(macc[k], 0);
(macc[k]) *= (1.00 - mAlphaBossak);
rCurrentElement->GetSecondDerivativesVector(maccold[k], 1);
noalias(macc[k]) += mAlphaBossak * maccold[k];
noalias(RHS_Contribution) -= prod(M, macc[k]);
}
//adding damping contribution
//damping contribution
// if (D.size1() != 0) {
// rCurrentElement->GetFirstDerivativesVector(VelocityBossakAuxiliaries::mvel, 0);
// noalias(RHS_Contribution) -= prod(D, VelocityBossakAuxiliaries::mvel);
// }
}
void AddDynamicsToRHS(
Condition::Pointer rCurrentElement,
LocalSystemVectorType& RHS_Contribution,
LocalSystemMatrixType& D,
LocalSystemMatrixType& M,
ProcessInfo& CurrentProcessInfo)
{
//adding inertia contributionDISPLACEMENT
if (M.size1() != 0)
{
int k = OpenMPUtils::ThisThread();
rCurrentElement->GetSecondDerivativesVector(macc[k], 0);
(macc[k]) *= (1.00 - mAlphaBossak);
rCurrentElement->GetSecondDerivativesVector(maccold[k], 1);
noalias(macc[k]) += mAlphaBossak * maccold[k];
noalias(RHS_Contribution) -= prod(M, macc[k]);
}
//adding damping contribution
//damping contribution
// if (D.size1() != 0) {
// rCurrentElement->GetFirstDerivativesVector(VelocityBossakAuxiliaries::mvel, 0);
// noalias(RHS_Contribution) -= prod(D, VelocityBossakAuxiliaries::mvel);
// }
}
/*@} */
/**@name Protected Operations*/
/*@{ */
/*@} */
/**@name Protected Access */
/*@{ */
/*@} */
/**@name Protected Inquiry */
/*@{ */
/*@} */
/**@name Protected LifeCycle */
/*@{ */
/*@} */
private:
/**@name Static Member Variables */
/*@{ */
/*@} */
/**@name Member Variables */
/*@{ */
typename TSparseSpace::DofUpdaterPointerType mpDofUpdater = TSparseSpace::CreateDofUpdater();
/* Matrix mMass;
Matrix mDamp;
Vector mvel;
Vector macc;
Vector maccold;
DofsVectorType mElementalDofList;
*/
/*@} */
/**@name Private Operators*/
/*@{ */
/*@} */
/**@name Private Operations*/
/*@{ */
/*@} */
/**@name Private Access */
/*@{ */
/*@} */
/**@name Private Inquiry */
/*@{ */
/*@} */
/**@name Un accessible methods */
/*@{ */
/*@} */
}; /* Class Scheme */
/*@} */
/**@name Type Definitions */
/*@{ */
/*@} */
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUALBASED_PREDICTOR_CORRECTOR_BOSSAK_SCHEME defined */
|
stat_ops_dm.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "stat_ops_dm.h"
#include "utility.h"
#include "constant.h"
// calculate norm
double dm_state_norm_squared(const CTYPE *state, ITYPE dim) {
ITYPE index;
double norm = 0;
#ifdef _OPENMP
#pragma omp parallel for reduction(+:norm)
#endif
for (index = 0; index < dim; ++index){
norm += creal(state[index*dim+index]);
}
return norm;
}
// calculate entropy of probability distribution of Z-basis measurements
double dm_measurement_distribution_entropy(const CTYPE *state, ITYPE dim){
ITYPE index;
double ent=0;
const double eps = 1e-15;
#ifdef _OPENMP
#pragma omp parallel for reduction(+:ent)
#endif
for(index = 0; index < dim; ++index){
double prob = creal(state[index*dim + index]);
if(prob > eps){
ent += -1.0*prob*log(prob);
}
}
return ent;
}
// calculate probability with which we obtain 0 at target qubit
double dm_M0_prob(UINT target_qubit_index, const CTYPE* state, ITYPE dim){
const ITYPE loop_dim = dim/2;
const ITYPE mask = 1ULL << target_qubit_index;
ITYPE state_index;
double sum =0.;
#ifdef _OPENMP
#pragma omp parallel for reduction(+:sum)
#endif
for(state_index=0;state_index<loop_dim;++state_index){
ITYPE basis_0 = insert_zero_to_basis_index(state_index,mask,target_qubit_index);
sum += creal(state[basis_0*dim+basis_0]);
}
return sum;
}
// calculate probability with which we obtain 1 at target qubit
double dm_M1_prob(UINT target_qubit_index, const CTYPE* state, ITYPE dim){
const ITYPE loop_dim = dim/2;
const ITYPE mask = 1ULL << target_qubit_index;
ITYPE state_index;
double sum =0.;
#ifdef _OPENMP
#pragma omp parallel for reduction(+:sum)
#endif
for(state_index=0;state_index<loop_dim;++state_index){
ITYPE basis_1 = insert_zero_to_basis_index(state_index,mask,target_qubit_index) ^ mask;
sum += creal(state[basis_1*dim + basis_1]);
}
return sum;
}
// calculate merginal probability with which we obtain the set of values measured_value_list at sorted_target_qubit_index_list
// warning: sorted_target_qubit_index_list must be sorted.
double dm_marginal_prob(const UINT* sorted_target_qubit_index_list, const UINT* measured_value_list, UINT target_qubit_index_count, const CTYPE* state, ITYPE dim){
ITYPE loop_dim = dim >> target_qubit_index_count;
ITYPE state_index;
double sum=0.;
#ifdef _OPENMP
#pragma omp parallel for reduction(+:sum)
#endif
for(state_index = 0;state_index < loop_dim; ++state_index){
ITYPE basis = state_index;
for(UINT cursor=0; cursor < target_qubit_index_count ; cursor++){
UINT insert_index = sorted_target_qubit_index_list[cursor];
ITYPE mask = 1ULL << insert_index;
basis = insert_zero_to_basis_index(basis, mask , insert_index );
basis ^= mask * measured_value_list[cursor];
}
sum += creal(state[basis*dim+basis]);
}
return sum;
}
void dm_state_add(const CTYPE *state_added, CTYPE *state, ITYPE dim) {
ITYPE index;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < dim*dim; ++index) {
state[index] += state_added[index];
}
}
void dm_state_multiply(CTYPE coef, CTYPE *state, ITYPE dim) {
ITYPE index;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < dim*dim; ++index) {
state[index] *= coef;
}
}
double dm_expectation_value_multi_qubit_Pauli_operator_partial_list(const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list, UINT target_qubit_index_count, const CTYPE* state, ITYPE dim) {
const ITYPE matrix_dim = 1ULL << target_qubit_index_count;
CTYPE* matrix = (CTYPE*)malloc(sizeof(CTYPE)*matrix_dim*matrix_dim);
for (ITYPE y = 0; y < matrix_dim; ++y) {
for (ITYPE x = 0; x < matrix_dim; ++x) {
CTYPE coef = 1.0;
for (UINT i = 0; i < target_qubit_index_count; ++i) {
ITYPE xi = (x >> i) % 2;
ITYPE yi = (y >> i) % 2;
coef *= PAULI_MATRIX[Pauli_operator_type_list[i]][yi * 2 + xi];
}
matrix[y*matrix_dim + x] = coef;
}
}
const ITYPE* matrix_mask_list = create_matrix_mask_list(target_qubit_index_list, target_qubit_index_count);
CTYPE sum = 0;
for (ITYPE state_index = 0; state_index< dim; ++state_index) {
ITYPE small_dim_index = 0;
ITYPE basis_0 = state_index;
for (UINT i = 0; i < target_qubit_index_count; ++i) {
UINT target_qubit_index = target_qubit_index_list[i];
if (state_index & (1ULL << target_qubit_index)) {
small_dim_index += (1ULL << i);
basis_0 ^= (1ULL << target_qubit_index);
}
}
for (ITYPE i = 0; i < matrix_dim; ++i) {
sum += matrix[small_dim_index*matrix_dim + i] * state[state_index*dim + (basis_0 ^ matrix_mask_list[i])];
}
}
free(matrix);
free((ITYPE*)matrix_mask_list);
return creal(sum);
}
|
beta_projectors_strain_deriv.h
|
#ifndef __BETA_PROJECTORS_STRAIN_DERIV_H__
#define __BETA_PROJECTORS_STRAIN_DERIV_H__
#include "beta_projectors_base.h"
namespace sirius {
class Beta_projectors_strain_deriv : public Beta_projectors_base<9>
{
private:
void generate_pw_coefs_t(std::vector<int> const& igk__)
{
PROFILE("sirius::Beta_projectors_strain_deriv::generate_pw_coefs_t");
if (!num_beta_t()) {
return;
}
auto& beta_ri0 = ctx_.beta_ri();
auto& beta_ri1 = ctx_.beta_ri_djl();
int lmax = ctx_.unit_cell().lmax();
int lmmax = Utils::lmmax(lmax);
mdarray<double, 2> rlm_g(lmmax, num_gkvec_loc());
mdarray<double, 3> rlm_dg(lmmax, 3, num_gkvec_loc());
/* array of real spherical harmonics and derivatives for each G-vector */
#pragma omp parallel for schedule(static)
for (int igkloc = 0; igkloc < num_gkvec_loc(); igkloc++) {
auto gvc = gkvec_.gkvec_cart(igk__[igkloc]);
auto rtp = SHT::spherical_coordinates(gvc);
double theta = rtp[1];
double phi = rtp[2];
SHT::spherical_harmonics(lmax, theta, phi, &rlm_g(0, igkloc));
mdarray<double, 2> rlm_dg_tmp(&rlm_dg(0, 0, igkloc), lmmax, 3);
SHT::dRlm_dr(lmax, gvc, rlm_dg_tmp);
}
/* compute d <G+k|beta> / d epsilon_{mu, nu} */
#pragma omp parallel for schedule(static)
for (int igkloc = 0; igkloc < num_gkvec_loc(); igkloc++) {
auto gvc = gkvec_.gkvec_cart(igk__[igkloc]);
/* vs = {r, theta, phi} */
auto gvs = SHT::spherical_coordinates(gvc);
/* |G+k|=0 case */
if (gvs[0] < 1e-10) {
for (int nu = 0; nu < 3; nu++) {
for (int mu = 0; mu < 3; mu++) {
double p = (mu == nu) ? 0.5 : 0;
for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) {
auto& atom_type = ctx_.unit_cell().atom_type(iat);
for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) {
int l = atom_type.indexb(xi).l;
int idxrf = atom_type.indexb(xi).idxrf;
if (l == 0) {
auto z = fourpi / std::sqrt(ctx_.unit_cell().omega());
auto d1 = beta_ri0.value<int, int>(idxrf, iat, gvs[0]) * (-p * y00);
pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) = z * d1;
} else {
pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) = 0;
}
}
}
}
}
continue;
}
for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) {
auto& atom_type = ctx_.unit_cell().atom_type(iat);
auto ri0 = beta_ri0.values(iat, gvs[0]);
auto ri1 = beta_ri1.values(iat, gvs[0]);
for (int nu = 0; nu < 3; nu++) {
for (int mu = 0; mu < 3; mu++) {
double p = (mu == nu) ? 0.5 : 0;
for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) {
int l = atom_type.indexb(xi).l;
int lm = atom_type.indexb(xi).lm;
int idxrf = atom_type.indexb(xi).idxrf;
auto z = std::pow(double_complex(0, -1), l) * fourpi / std::sqrt(ctx_.unit_cell().omega());
auto d1 = ri0(idxrf) * (-gvc[mu] * rlm_dg(lm, nu, igkloc) - p * rlm_g(lm, igkloc));
auto d2 = ri1(idxrf) * rlm_g(lm, igkloc) * (-gvc[mu] * gvc[nu] / gvs[0]);
pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) = z * (d1 + d2);
}
}
}
}
}
}
//void generate_pw_coefs_t_v2()
//{
// PROFILE("sirius::Beta_projectors_strain_deriv::generate_pw_coefs_t_v2");
// auto& bchunk = ctx_.beta_projector_chunks();
// if (!bchunk.num_beta_t()) {
// return;
// }
// Radial_integrals_beta<false> beta_ri0(ctx_.unit_cell(), ctx_.gk_cutoff(), ctx_.settings().nprii_beta_);
// Radial_integrals_beta_jl beta_ri1(ctx_.unit_cell(), ctx_.gk_cutoff(), ctx_.settings().nprii_beta_);
// vector3d<int> r_m({1, -1, 0});
// vector3d<double> r_f({-2 * std::sqrt(pi / 3), -2 * std::sqrt(pi / 3), 2 * std::sqrt(pi / 3)});
// auto& comm = gkvec_.comm();
// /* zero array */
// for (int i = 0; i < 9; i++) {
// pw_coeffs_t_[i].zero();
// }
// std::vector<double_complex> zil(lmax_beta_ + 2);
// for (int l = 0; l < lmax_beta_ + 2; l++) {
// zil[l] = std::pow(double_complex(0, -1), l);
// }
// Gaunt_coefficients<double> gc(1, lmax_beta_ + 2, lmax_beta_, SHT::gaunt_rlm);
// /* compute d <G+k|beta> / d epsilon_{mu, nu} */
// #pragma omp parallel for schedule(static)
// for (int igkloc = 0; igkloc < num_gkvec_loc(); igkloc++) {
// int igk = gkvec_.gvec_offset(comm.rank()) + igkloc;
// auto gvc = gkvec_.gkvec_cart(igk);
// /* vs = {r, theta, phi} */
// auto gvs = SHT::spherical_coordinates(gvc);
// /* compute real spherical harmonics for G+k vector */
// std::vector<double> gkvec_rlm(Utils::lmmax(lmax_beta_ + 2));
// SHT::spherical_harmonics(lmax_beta_ + 2, gvs[1], gvs[2], &gkvec_rlm[0]);
// mdarray<double, 3> tmp(ctx_.unit_cell().max_mt_radial_basis_size(), lmax_beta_ + 3, ctx_.unit_cell().num_atom_types());
// for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) {
// for (int l = 0; l <= lmax_beta_ + 2; l++) {
// for (int j = 0; j < ctx_.unit_cell().atom_type(iat).mt_radial_basis_size(); j++) {
// tmp(j, l, iat) = beta_ri1.value<int, int, int>(j, l, iat, gvs[0]);
// }
// }
// }
// for (int nu = 0; nu < 3; nu++) {
// for (int mu = 0; mu < 3; mu++) {
// double p = (mu == nu) ? 0.5 : 0;
// auto z1 = fourpi / std::sqrt(ctx_.unit_cell().omega());
// auto z2 = z1 * gvc[mu] * double_complex(0, 1) * r_f[nu];
// for (int iat = 0; iat < ctx_.unit_cell().num_atom_types(); iat++) {
// auto& atom_type = ctx_.unit_cell().atom_type(iat);
// for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) {
// int l = atom_type.indexb(xi).l;
// int lm = atom_type.indexb(xi).lm;
// int idxrf = atom_type.indexb(xi).idxrf;
//
// double_complex z3(0, 0);
// for (int k = 0; k < gc.num_gaunt(Utils::lm_by_l_m(1, r_m[nu]), lm); k++) {
// auto& c = gc.gaunt(Utils::lm_by_l_m(1, r_m[nu]), lm, k);
// int l3 = c.l3;
// z3 += zil[l3] * gkvec_rlm[c.lm3] * c.coef * tmp(idxrf, l3, iat);
// }
// //pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) +=
// // gvc[mu] * std::pow(double_complex(0, -1), l3) * z * double_complex(0, 1) *
// // gkvec_rlm[c.lm3] * c.coef * tmp(idxrf, l3, iat) * r_f[nu];
// pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) += z3 * z2;
// auto d2 = beta_ri0.value<int, int>(idxrf, iat, gvs[0]) * (-p * gkvec_rlm[lm]);
// pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi) += z1 * d2 * zil[l];
// }
// }
// } // mu
// //for (int mu = 0; mu <= nu; mu++) {
// // for (int xi = 0; xi < atom_type.mt_basis_size(); xi++) {
// // pw_coeffs_t_[nu + mu * 3](igkloc, atom_type.offset_lo() + xi) = pw_coeffs_t_[mu + nu * 3](igkloc, atom_type.offset_lo() + xi);
// // }
// //}
// } // nu
// }
//}
public:
Beta_projectors_strain_deriv(Simulation_context& ctx__,
Gvec const& gkvec__,
std::vector<int> const& igk__)
: Beta_projectors_base<9>(ctx__, gkvec__, igk__)
{
generate_pw_coefs_t(igk__);
//generate_pw_coefs_t_v2();
//if (ctx__.processing_unit() == GPU) {
// for (int j = 0; j < 9; j++) {
// pw_coeffs_t_[j].copy<memory_t::host, memory_t::device>();
// }
//}
}
};
}
#endif
|
GB_unaryop__abs_int64_int16.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_int64_int16
// op(A') function: GB_tran__abs_int64_int16
// C type: int64_t
// A type: int16_t
// cast: int64_t cij = (int64_t) aij
// unaryop: cij = GB_IABS (aij)
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IABS (x) ;
// casting
#define GB_CASTING(z, x) \
int64_t z = (int64_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_INT64 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_int64_int16
(
int64_t *restrict Cx,
const int16_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_int64_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__cos_fp32_fp32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__cos_fp32_fp32)
// op(A') function: GB (_unop_tran__cos_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = cosf (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = cosf (x) ;
// casting
#define GB_CAST(z, aij) \
float z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = aij ; \
Cx [pC] = cosf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_COS || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__cos_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = cosf (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = cosf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__cos_fp32_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
laplace2d.c
|
/*
* Copyright 2012 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include <string.h>
#include "timer.h"
#include <stdio.h>
#ifndef VERIFICATION
#define VERIFICATION 0
#endif
#ifndef NN
#define NN 4096
#endif
#ifndef NM
#define NM 4096
#endif
double A[NN][NM];
double Anew[NN][NM];
#if VERIFICATION == 1
double A_CPU[NN][NM];
double Anew_CPU[NN][NM];
#endif
int main(int argc, char** argv)
{
int n = NN;
int m = NM;
int iter_max = 1000;
double tol = 1.0e-6;
double error = 1.0;
int i, j;
int iter = 0;
double runtime;
memset(A, 0, n * m * sizeof(double));
memset(Anew, 0, n * m * sizeof(double));
#if VERIFICATION == 1
memset(A_CPU, 0, n * m * sizeof(double));
memset(Anew_CPU, 0, n * m * sizeof(double));
#endif
for (j = 0; j < n; j++)
{
A[j][0] = 1.0;
Anew[j][0] = 1.0;
#if VERIFICATION == 1
A_CPU[j][0] = 1.0;
Anew_CPU[j][0] = 1.0;
#endif
}
printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m);
StartTimer();
#pragma aspen enter modelregion
//aspen_param_whilecnt = 1000 for NN = NM = 4096
//aspen_param_whilecnt = 1000 for NN = NM = 8192
#pragma aspen declare param(aspen_param_whilecnt:1000)
#pragma aspen control loop(aspen_param_whilecnt)
#pragma acc data copy(A), create(Anew)
while ( error > tol && iter < iter_max )
{
error = 0.0;
//#pragma omp parallel for shared(m, n, Anew, A)
#pragma acc parallel num_gangs(16) num_workers(32) reduction(max:error) private(j)
{
double lerror = 0.0;
#pragma acc loop gang
for( j = 1; j < n-1; j++)
{
#pragma acc loop worker reduction(max:lerror)
for( i = 1; i < m-1; i++ )
{
Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1]
+ A[j-1][i] + A[j+1][i]);
lerror = fmax( lerror, fabs(Anew[j][i] - A[j][i]));
}
error = fmax(error, lerror);
}
}
//#pragma omp parallel for shared(m, n, Anew, A)
#pragma acc kernels loop gang(16) worker(16)
for( j = 1; j < n-1; j++)
{
#pragma acc loop gang(16) worker(16)
for( i = 1; i < m-1; i++ )
{
A[j][i] = Anew[j][i];
}
}
if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error);
iter++;
}
#pragma aspen exit modelregion
printf("iter: %d\n", iter);
runtime = GetTimer();
#if VERIFICATION == 1
{
error = 1.0;
iter = 0;
while ( error > tol && iter < iter_max )
{
error = 0.0;
{
for( j = 1; j < n-1; j++)
{
for( i = 1; i < m-1; i++ )
{
Anew_CPU[j][i] = 0.25 * ( A_CPU[j][i+1] + A_CPU[j][i-1]
+ A_CPU[j-1][i] + A_CPU[j+1][i]);
error = fmax( error, fabs(Anew_CPU[j][i] - A_CPU[j][i]));
}
}
}
for( j = 1; j < n-1; j++)
{
for( i = 1; i < m-1; i++ )
{
A_CPU[j][i] = Anew_CPU[j][i];
}
}
if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error);
iter++;
}
{
double cpu_sum = 0.0f;
double gpu_sum = 0.0f;
double rel_err = 0.0f;
for (i = 1; i < m-1; i++)
{
cpu_sum += A_CPU[i][i]*A_CPU[i][i];
gpu_sum += A[i][i]*A[i][i];
}
cpu_sum = sqrt(cpu_sum);
gpu_sum = sqrt(gpu_sum);
if( cpu_sum > gpu_sum ) {
rel_err = (cpu_sum-gpu_sum)/cpu_sum;
} else {
rel_err = (gpu_sum-cpu_sum)/cpu_sum;
}
if(rel_err < 1e-6)
{
printf("Verification Successful err = %e\n", rel_err);
}
else
{
printf("Verification Fail err = %e\n", rel_err);
}
}
}
#endif
printf("Accelerator Elapsed %f s\n", runtime / 1000);
}
|
GB_binop__minus_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 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__minus_int8
// A.*B function (eWiseMult): GB_AemultB__minus_int8
// A*D function (colscale): GB_AxD__minus_int8
// D*A function (rowscale): GB_DxB__minus_int8
// C+=B function (dense accum): GB_Cdense_accumB__minus_int8
// C+=b function (dense accum): GB_Cdense_accumb__minus_int8
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__minus_int8
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__minus_int8
// C=scalar+B GB_bind1st__minus_int8
// C=scalar+B' GB_bind1st_tran__minus_int8
// C=A+scalar GB_bind2nd__minus_int8
// C=A'+scalar GB_bind2nd_tran__minus_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, 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_MINUS || GxB_NO_INT8 || GxB_NO_MINUS_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__minus_int8
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__minus_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__minus_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__minus_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__minus_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__minus_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
//------------------------------------------------------------------------------
#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__minus_int8
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *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__minus_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 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__minus_int8
(
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
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++)
{
if (!GBB (Bb, p)) continue ;
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__minus_int8
(
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 ;
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 = 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) \
{ \
int8_t aij = Ax [pA] ; \
Cx [pC] = (x - aij) ; \
}
GrB_Info GB_bind1st_tran__minus_int8
(
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 \
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 = Ax [pA] ; \
Cx [pC] = (aij - y) ; \
}
GrB_Info GB_bind2nd_tran__minus_int8
(
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
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
data.h
|
/*!
* Copyright (c) 2015 by Contributors
* \file data.h
* \brief The input data structure of tsoobgx.
* \author Tianqi Chen
*/
#ifndef TSOOBGX_DATA_H_
#define TSOOBGX_DATA_H_
#include <dmlc/base.h>
#include <dmlc/data.h>
#include <rabit/rabit.h>
#include <cstring>
#include <memory>
#include <numeric>
#include <algorithm>
#include <string>
#include <vector>
#include "./base.h"
#include "../../src/common/span.h"
#include "../../src/common/group_data.h"
#include "../../src/common/host_device_vector.h"
namespace tsoobgx {
// forward declare learner.
class LearnerImpl;
/*! \brief data type accepted by tsoobgx interface */
enum DataType {
kFloat32 = 1,
kDouble = 2,
kUInt32 = 3,
kUInt64 = 4
};
/*!
* \brief Meta information about dataset, always sit in memory.
*/
class MetaInfo {
public:
/*! \brief number of rows in the data */
uint64_t num_row_{0};
/*! \brief number of columns in the data */
uint64_t num_col_{0};
/*! \brief number of nonzero entries in the data */
uint64_t num_nonzero_{0};
/*! \brief label of each instance */
HostDeviceVector<bst_float> labels_;
/*!
* \brief specified root index of each instance,
* can be used for multi task setting
*/
std::vector<bst_uint> root_index_;
/*!
* \brief the index of begin and end of a group
* needed when the learning task is ranking.
*/
std::vector<bst_uint> group_ptr_;
/*! \brief weights of each instance, optional */
HostDeviceVector<bst_float> weights_;
/*! \brief session-id of each instance, optional */
std::vector<uint64_t> qids_;
/*!
* \brief initialized margins,
* if specified, tsoobgx will start from this init margin
* can be used to specify initial prediction to boost from.
*/
HostDeviceVector<bst_float> base_margin_;
/*! \brief version flag, used to check version of this info */
static const int kVersion = 2;
/*! \brief version that introduced qid field */
static const int kVersionQidAdded = 2;
/*! \brief default constructor */
MetaInfo() = default;
/*!
* \brief Get weight of each instances.
* \param i Instance index.
* \return The weight.
*/
inline bst_float GetWeight(size_t i) const {
return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f;
}
/*!
* \brief Get the root index of i-th instance.
* \param i Instance index.
* \return The pre-defined root index of i-th instance.
*/
inline unsigned GetRoot(size_t i) const {
return root_index_.size() != 0 ? root_index_[i] : 0U;
}
/*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */
inline const std::vector<size_t>& LabelAbsSort() const {
if (label_order_cache_.size() == labels_.Size()) {
return label_order_cache_;
}
label_order_cache_.resize(labels_.Size());
std::iota(label_order_cache_.begin(), label_order_cache_.end(), 0);
const auto& l = labels_.HostVector();
TSOOBGX_PARALLEL_SORT(label_order_cache_.begin(), label_order_cache_.end(),
[&l](size_t i1, size_t i2) {return std::abs(l[i1]) < std::abs(l[i2]);});
return label_order_cache_;
}
/*! \brief clear all the information */
void Clear();
/*!
* \brief Load the Meta info from binary stream.
* \param fi The input stream
*/
void LoadBinary(dmlc::Stream* fi);
/*!
* \brief Save the Meta info to binary stream
* \param fo The output stream.
*/
void SaveBinary(dmlc::Stream* fo) const;
/*!
* \brief Set information in the meta info.
* \param key The key of the information.
* \param dptr The data pointer of the source array.
* \param dtype The type of the source data.
* \param num Number of elements in the source array.
*/
void SetInfo(const char* key, const void* dptr, DataType dtype, size_t num);
private:
/*! \brief argsort of labels */
mutable std::vector<size_t> label_order_cache_;
};
/*! \brief Element from a sparse vector */
struct Entry {
/*! \brief feature index */
bst_uint index;
/*! \brief feature value */
bst_float fvalue;
/*! \brief default constructor */
Entry() = default;
/*!
* \brief constructor with index and value
* \param index The feature or row index.
* \param fvalue The feature value.
*/
Entry(bst_uint index, bst_float fvalue) : index(index), fvalue(fvalue) {}
/*! \brief reversely compare feature values */
inline static bool CmpValue(const Entry& a, const Entry& b) {
return a.fvalue < b.fvalue;
}
inline bool operator==(const Entry& other) const {
return (this->index == other.index && this->fvalue == other.fvalue);
}
};
/*!
* \brief In-memory storage unit of sparse batch, stored in CSR format.
*/
class SparsePage {
public:
// Offset for each row.
HostDeviceVector<size_t> offset;
/*! \brief the data of the segments */
HostDeviceVector<Entry> data;
size_t base_rowid;
/*! \brief an instance of sparse vector in the batch */
using Inst = common::Span<Entry const>;
/*! \brief get i-th row from the batch */
inline Inst operator[](size_t i) const {
const auto& data_vec = data.HostVector();
const auto& offset_vec = offset.HostVector();
size_t size;
// in distributed mode, some partitions may not get any instance for a feature. Therefore
// we should set the size as zero
if (rabit::IsDistributed() && i + 1 >= offset_vec.size()) {
size = 0;
} else {
size = offset_vec[i + 1] - offset_vec[i];
}
return {data_vec.data() + offset_vec[i],
static_cast<Inst::index_type>(size)};
}
/*! \brief constructor */
SparsePage() {
this->Clear();
}
/*! \return number of instance in the page */
inline size_t Size() const {
return offset.Size() - 1;
}
/*! \return estimation of memory cost of this page */
inline size_t MemCostBytes() const {
return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry);
}
/*! \brief clear the page */
inline void Clear() {
base_rowid = 0;
auto& offset_vec = offset.HostVector();
offset_vec.clear();
offset_vec.push_back(0);
data.HostVector().clear();
}
SparsePage GetTranspose(int num_columns) const {
SparsePage transpose;
common::ParallelGroupBuilder<Entry> builder(&transpose.offset.HostVector(),
&transpose.data.HostVector());
const int nthread = omp_get_max_threads();
builder.InitBudget(num_columns, nthread);
long batch_size = static_cast<long>(this->Size()); // NOLINT(*)
#pragma omp parallel for schedule(static)
for (long i = 0; i < batch_size; ++i) { // NOLINT(*)
int tid = omp_get_thread_num();
auto inst = (*this)[i];
for (bst_uint j = 0; j < inst.size(); ++j) {
builder.AddBudget(inst[j].index, tid);
}
}
builder.InitStorage();
#pragma omp parallel for schedule(static)
for (long i = 0; i < batch_size; ++i) { // NOLINT(*)
int tid = omp_get_thread_num();
auto inst = (*this)[i];
for (bst_uint j = 0; j < inst.size(); ++j) {
builder.Push(
inst[j].index,
Entry(static_cast<bst_uint>(this->base_rowid + i), inst[j].fvalue),
tid);
}
}
return transpose;
}
void SortRows() {
auto ncol = static_cast<bst_omp_uint>(this->Size());
#pragma omp parallel for schedule(dynamic, 1)
for (bst_omp_uint i = 0; i < ncol; ++i) {
if (this->offset.HostVector()[i] < this->offset.HostVector()[i + 1]) {
std::sort(
this->data.HostVector().begin() + this->offset.HostVector()[i],
this->data.HostVector().begin() + this->offset.HostVector()[i + 1],
Entry::CmpValue);
}
}
}
/*!
* \brief Push row block into the page.
* \param batch the row batch.
*/
void Push(const dmlc::RowBlock<uint32_t>& batch);
/*!
* \brief Push a sparse page
* \param batch the row page
*/
void Push(const SparsePage &batch);
/*!
* \brief Push a SparsePage stored in CSC format
* \param batch The row batch to be pushed
*/
void PushCSC(const SparsePage& batch);
/*!
* \brief Push one instance into page
* \param inst an instance row
*/
inline void Push(const Inst &inst) {
auto& data_vec = data.HostVector();
auto& offset_vec = offset.HostVector();
offset_vec.push_back(offset_vec.back() + inst.size());
size_t begin = data_vec.size();
data_vec.resize(begin + inst.size());
if (inst.size() != 0) {
std::memcpy(dmlc::BeginPtr(data_vec) + begin, inst.data(),
sizeof(Entry) * inst.size());
}
}
size_t Size() { return offset.Size() - 1; }
};
class BatchIteratorImpl {
public:
virtual ~BatchIteratorImpl() {}
virtual BatchIteratorImpl* Clone() = 0;
virtual SparsePage& operator*() = 0;
virtual const SparsePage& operator*() const = 0;
virtual void operator++() = 0;
virtual bool AtEnd() const = 0;
};
class BatchIterator {
public:
using iterator_category = std::forward_iterator_tag;
explicit BatchIterator(BatchIteratorImpl* impl) { impl_.reset(impl); }
BatchIterator(const BatchIterator& other) {
if (other.impl_) {
impl_.reset(other.impl_->Clone());
} else {
impl_.reset();
}
}
void operator++() {
CHECK(impl_ != nullptr);
++(*impl_);
}
SparsePage& operator*() {
CHECK(impl_ != nullptr);
return *(*impl_);
}
const SparsePage& operator*() const {
CHECK(impl_ != nullptr);
return *(*impl_);
}
bool operator!=(const BatchIterator& rhs) const {
CHECK(impl_ != nullptr);
return !impl_->AtEnd();
}
bool AtEnd() const {
CHECK(impl_ != nullptr);
return impl_->AtEnd();
}
private:
std::unique_ptr<BatchIteratorImpl> impl_;
};
class BatchSet {
public:
explicit BatchSet(BatchIterator begin_iter) : begin_iter_(begin_iter) {}
BatchIterator begin() { return begin_iter_; }
BatchIterator end() { return BatchIterator(nullptr); }
private:
BatchIterator begin_iter_;
};
/*!
* \brief This is data structure that user can pass to DMatrix::Create
* to create a DMatrix for training, user can create this data structure
* for customized Data Loading on single machine.
*
* On distributed setting, usually an customized dmlc::Parser is needed instead.
*/
class DataSource : public dmlc::DataIter<SparsePage> {
public:
/*!
* \brief Meta information about the dataset
* The subclass need to be able to load this correctly from data.
*/
MetaInfo info;
};
/*!
* \brief A vector-like structure to represent set of rows.
* But saves the memory when all rows are in the set (common case in bgx)
*/
class RowSet {
public:
/*! \return i-th row index */
inline bst_uint operator[](size_t i) const;
/*! \return the size of the set. */
inline size_t Size() const;
/*! \brief push the index back to the set */
inline void PushBack(bst_uint i);
/*! \brief clear the set */
inline void Clear();
/*!
* \brief save rowset to file.
* \param fo The file to be saved.
*/
inline void Save(dmlc::Stream* fo) const;
/*!
* \brief Load rowset from file.
* \param fi The file to be loaded.
* \return if read is successful.
*/
inline bool Load(dmlc::Stream* fi);
/*! \brief constructor */
RowSet() = default;
private:
/*! \brief The internal data structure of size */
uint64_t size_{0};
/*! \brief The internal data structure of row set if not all*/
std::vector<bst_uint> rows_;
};
/*!
* \brief Internal data structured used by tsooBGX during training.
* There are two ways to create a customized DMatrix that reads in user defined-format.
*
* - Provide a dmlc::Parser and pass into the DMatrix::Create
* - Alternatively, if data can be represented by an URL, define a new dmlc::Parser and register by DMLC_REGISTER_DATA_PARSER;
* - This works best for user defined data input source, such as data-base, filesystem.
* - Provide a DataSource, that can be passed to DMatrix::Create
* This can be used to re-use inmemory data structure into DMatrix.
*/
class DMatrix {
public:
/*! \brief default constructor */
DMatrix() = default;
/*! \brief meta information of the dataset */
virtual MetaInfo& Info() = 0;
/*! \brief meta information of the dataset */
virtual const MetaInfo& Info() const = 0;
/**
* \brief Gets row batches. Use range based for loop over BatchSet to access individual batches.
*/
virtual BatchSet GetRowBatches() = 0;
virtual BatchSet GetSortedColumnBatches() = 0;
virtual BatchSet GetColumnBatches() = 0;
// the following are column meta data, should be able to answer them fast.
/*! \return Whether the data columns single column block. */
virtual bool SingleColBlock() const = 0;
/*! \brief get column density */
virtual float GetColDensity(size_t cidx) = 0;
/*! \brief virtual destructor */
virtual ~DMatrix() = default;
/*!
* \brief Save DMatrix to local file.
* The saved file only works for non-sharded dataset(single machine training).
* This API is deprecated and dis-encouraged to use.
* \param fname The file name to be saved.
* \return The created DMatrix.
*/
virtual void SaveToLocalFile(const std::string& fname);
/*!
* \brief Load DMatrix from URI.
* \param uri The URI of input.
* \param silent Whether print information during loading.
* \param load_row_split Flag to read in part of rows, divided among the workers in distributed mode.
* \param file_format The format type of the file, used for dmlc::Parser::Create.
* By default "auto" will be able to load in both local binary file.
* \param page_size Page size for external memory.
* \return The created DMatrix.
*/
static DMatrix* Load(const std::string& uri,
bool silent,
bool load_row_split,
const std::string& file_format = "auto",
const size_t page_size = kPageSize);
/*!
* \brief create a new DMatrix, by wrapping a row_iterator, and meta info.
* \param source The source iterator of the data, the create function takes ownership of the source.
* \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode.
* This can be nullptr for common cases, and in-memory mode will be used.
* \return a Created DMatrix.
*/
static DMatrix* Create(std::unique_ptr<DataSource>&& source,
const std::string& cache_prefix = "");
/*!
* \brief Create a DMatrix by loading data from parser.
* Parser can later be deleted after the DMatrix i created.
* \param parser The input data parser
* \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode.
* This can be nullptr for common cases, and in-memory mode will be used.
* \param page_size Page size for external memory.
* \sa dmlc::Parser
* \note dmlc-core provides efficient distributed data parser for libsvm format.
* User can create and register customized parser to load their own format using DMLC_REGISTER_DATA_PARSER.
* See "dmlc-core/include/dmlc/data.h" for detail.
* \return A created DMatrix.
*/
static DMatrix* Create(dmlc::Parser<uint32_t>* parser,
const std::string& cache_prefix = "",
const size_t page_size = kPageSize);
/*! \brief page size 32 MB */
static const size_t kPageSize = 32UL << 20UL;
};
// implementation of inline functions
inline bst_uint RowSet::operator[](size_t i) const {
return rows_.size() == 0 ? static_cast<bst_uint>(i) : rows_[i];
}
inline size_t RowSet::Size() const {
return size_;
}
inline void RowSet::Clear() {
rows_.clear(); size_ = 0;
}
inline void RowSet::PushBack(bst_uint i) {
if (rows_.size() == 0) {
if (i == size_) {
++size_; return;
} else {
rows_.resize(size_);
for (size_t i = 0; i < size_; ++i) {
rows_[i] = static_cast<bst_uint>(i);
}
}
}
rows_.push_back(i);
++size_;
}
inline void RowSet::Save(dmlc::Stream* fo) const {
fo->Write(rows_);
fo->Write(&size_, sizeof(size_));
}
inline bool RowSet::Load(dmlc::Stream* fi) {
if (!fi->Read(&rows_)) return false;
if (rows_.size() != 0) return true;
return fi->Read(&size_, sizeof(size_)) == sizeof(size_);
}
} // namespace tsoobgx
namespace dmlc {
DMLC_DECLARE_TRAITS(is_pod, tsoobgx::Entry, true);
DMLC_DECLARE_TRAITS(has_saveload, tsoobgx::RowSet, true);
}
#endif // TSOOBGX_DATA_H_
|
nlk_pv.c
|
/******************************************************************************
* NLK - Neural Language Kit
*
* Copyright (c) 2014 Luis Rei <[email protected]> http://luisrei.com @lmrei
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*****************************************************************************/
/** @file nlk_pv.c
* Paragraph Vector Inference functions
* @note: code relative to training a PV model is in nlk_w2v.c
*/
#include <errno.h>
#include <stdio.h>
#include <omp.h>
#include "nlk_err.h"
#include "nlk_array.h"
#include "nlk_tic.h"
#include "nlk_text.h"
#include "nlk_corpus.h"
#include "nlk_random.h"
#include "nlk_w2v.h"
#include "nlk_learn_rate.h"
#include "nlk_pv.h"
/**
* Display progress of paragraph vector generation
*
* @param generated number of PVs generated so far
* @param total total number of PVs to generate
*/
static void
nlk_pv_display(const size_t generated, const size_t total)
{
char display_str[64];
float progress = (generated / (float) total) * 100;
snprintf(display_str, 64,
"Progress: %.2f%% (%zu/%zu) Threads: %d\t",
progress, generated, total, omp_get_num_threads());
nlk_tic(display_str, false);
}
/**
* Sets Paragraph Vector Inference Mode (ie. PV generation)
* In this mode, gradients are only propagated into the Paragraphs Table and
* not into the Words Table or the second (HS/NEG) layers.
*
* @param nn the neural network structure
*/
void
nlk_pv_inference_mode(struct nlk_neuralnet_t *nn)
{
/* Prevent Layer Weights From Changing: Words & HS/Neg */
nn->words->update = false;
if(nn->train_opts.hs) {
nn->hs->update = false;
}
if(nn->train_opts.negative) {
nn->neg->update = false;
}
}
/**
* Disables Paragraph Vector Inference Mode (i.e. PV generation)
* In learn mode, gradients are backpropagate to all layers.
*
* @param nn the neural network structure
*/
void
nlk_pv_learn_mode(struct nlk_neuralnet_t *nn)
{
/* Allow Layer Weights to Change: Words & HS/Neg */
nn->words->update = true;
if(nn->train_opts.hs) {
nn->hs->update = true;
}
if(nn->train_opts.negative) {
nn->neg->update = true;
}
}
/**
* Infer Paragraph Vector for a line
* This is function is the function that does the inference part for
* nlk_pv_gen and nlk_pv_gen_string.
*
* @param nn the neural network structure
* @param line the line structure holding the input
* @param epochs the number of epochs or iterations to generate a PV
* @param paragraphs the paragraph table that will be updated (output)
* @param line_sample will hold sampled line for each epoch
* @param contexts will hold the contexts generated for each epoch
* @param grad_acc for accumulating grandients
* @param layer1_out for holding the output of the first layer
*/
inline static void
nlk_pv_gen_line(struct nlk_neuralnet_t *nn,
struct nlk_line_t *line,
const unsigned int epochs,
struct nlk_layer_lookup_t *paragraphs,
struct nlk_line_t *line_sample,
struct nlk_context_t **contexts, NLK_ARRAY *grad_acc,
NLK_ARRAY *layer1_out)
{
NLK_LM model_type = nn->train_opts.model_type;
nlk_real learn_rate = nn->train_opts.learn_rate;
const nlk_real learn_rate_start = nn->train_opts.learn_rate;
uint64_t train_words = nn->train_opts.word_count;
const float sample_rate = nn->train_opts.sample;
/* Generate PV for this line */
unsigned int n_examples;
unsigned int ex;
uint64_t line_words;
uint64_t word_count_actual = 0;
line_words = line->len;
/** @section Generate Contexts Update Vector Loop
*/
unsigned int local_epoch = 0;
for(local_epoch = 0; local_epoch < epochs; local_epoch++) {
word_count_actual += line_words;
/* subsample line */
nlk_vocab_line_subsample(line, train_words, sample_rate,
line_sample);
/* single word, nothing to do ... */
if(line_sample->len < 2) {
continue;
}
/* generate contexts */
n_examples = nlk_context_window(line_sample->varray,
line_sample->len,
line_sample->line_id,
&nn->context_opts,
contexts);
/** @subsection Update the Paragraph Vector with these contexts
*/
switch(model_type) {
case NLK_PVDBOW:
for(ex = 0; ex < n_examples; ex++) {
nlk_pvdbow(nn, paragraphs, learn_rate,
contexts[ex], grad_acc, layer1_out);
}
break;
case NLK_PVDM:
for(ex = 0; ex < n_examples; ex++) {
nlk_pvdm(nn, paragraphs, learn_rate, contexts[ex],
grad_acc, layer1_out);
}
break;
case NLK_PVDM_CONCAT:
for(ex = 0; ex < n_examples; ex++) {
nlk_pvdm_cc(nn, paragraphs, learn_rate, contexts[ex],
grad_acc, layer1_out);
}
break;
case NLK_MODEL_NULL:
case NLK_CBOW:
case NLK_CBOW_SUM:
case NLK_SKIPGRAM:
default:
NLK_ERROR_ABORT("invalid model type", NLK_EINVAL);
/* unreachable */
} /* end of model switch */
learn_rate = nlk_learn_rate_w2v(learn_rate, learn_rate_start,
epochs, word_count_actual,
line_words);
} /* end of contexts: pv has been generated */
}
/**
* Paragraph Vector Inference
* Creates a new Paragraph Table and uses the neural network and the corpus
* to generate a PV for each line in the corpus.
*
* @param nn the neural network structure
* @param corpus the input corpus
* @param epochs the number of epochs or iterations to generate a PV
* @param verbose siplay progress and print other stuff that is useful
*
* @return a paragraph table (lookup layer) with the PVs generated
*/
struct nlk_layer_lookup_t *
nlk_pv_gen(struct nlk_neuralnet_t *nn, const struct nlk_corpus_t *corpus,
const unsigned int epochs, const bool verbose)
{
if(verbose) {
nlk_tic("Generating paragraph vectors", false);
printf(" (%u iterations)\n", epochs);
}
/* create new paragraph table */
struct nlk_layer_lookup_t *paragraphs;
paragraphs = nlk_layer_lookup_create(corpus->len, nn->words->weights->cols);
nlk_layer_lookup_init(paragraphs);
/* unpack options */
unsigned int ctx_size = nn->context_opts.max_size;
unsigned int layer_size2 = 0;
if(nn->train_opts.hs) {
layer_size2 = nn->hs->weights->cols;
} else if(nn->train_opts.negative) {
layer_size2 = nn->neg->weights->cols;
}
/* lines shortcut */
struct nlk_line_t *lines = corpus->lines;
/* prevent weights from changing for words and hs/neg */
nlk_pv_inference_mode(nn);
/* progress */
size_t generated = 0;
const size_t total = corpus->len;
/** @section Parallel Generation of PVs
*/
#pragma omp parallel shared(generated)
{
struct nlk_line_t *line = NULL;
/* for converting a sentence to a series of training contexts */
struct nlk_context_t **contexts = NULL;
contexts = nlk_context_create_array(ctx_size);
/* for undersampling words in a line */
struct nlk_line_t *line_sample = nlk_line_create(NLK_MAX_LINE_SIZE);
/* output of the first layer */
NLK_ARRAY *layer1_out = nlk_array_create(layer_size2, 1);
/* for storing gradients */
NLK_ARRAY *grad_acc = nlk_array_create(1, layer_size2);
/* variables for handling splitting the corpus among threads */
int num_threads = omp_get_num_threads();
size_t line_cur;
size_t end_line;
#pragma omp for
for(int thread_id = 0; thread_id < num_threads; thread_id++) {
/* get the thread's part of the corpus */
line_cur = nlk_text_get_split_start_line(total, num_threads,
thread_id);
end_line = nlk_text_get_split_end_line(total, num_threads,
thread_id);
/* for each line, generate it's PV */
while(line_cur < end_line) {
/* get the next line */
line = &lines[line_cur];
/* generate the paragraph vector */
nlk_pv_gen_line(nn, line, epochs, paragraphs, line_sample,
contexts, grad_acc, layer1_out);
/* go to next line */
line_cur++;
generated++;
/* display progress */
if(verbose) {
nlk_pv_display(generated, total);
}
} /* end of PV */
} /* end of all PVs (thread loop) */
if(verbose) {
nlk_pv_display(generated, total);
}
/* free thread memory */
nlk_context_free_array(contexts);
nlk_line_free(line_sample);
nlk_array_free(layer1_out);
nlk_array_free(grad_acc);
} /* end of parallel section */
if(verbose) {
printf("\n");
}
nlk_pv_learn_mode(nn);
return paragraphs;
}
/**
* Infer Paragraph Vector for a string
*
* @param nn the neural netowrk
* @param str the string
* @param epochs epochs (iterations) to use in generating the PVs
*
* @return a paragraph table (lookup layer) with the PV generated (id = 0)
*
* @warning terribly inneficient function that allocates and frees all memory
* each time it is called.
*/
struct nlk_layer_lookup_t *
nlk_pv_gen_string(struct nlk_neuralnet_t *nn, char *str,
const unsigned int epochs)
{
/** @section Initialization
*/
struct nlk_layer_lookup_t *paragraphs = NULL;
paragraphs = nlk_layer_lookup_create(1, nn->words->weights->cols);
nlk_layer_lookup_init(paragraphs);
/* unpack options */
unsigned int ctx_size = nn->context_opts.max_size;
unsigned int layer_size2 = 0;
if(nn->train_opts.hs) {
layer_size2 = nn->hs->weights->cols;
} else if(nn->train_opts.negative) {
layer_size2 = nn->neg->weights->cols;
}
/* representation of the line as an array of pointer to strings */
char **tline = nlk_text_line_create();
struct nlk_line_t *line = nlk_line_create(NLK_MAX_LINE_SIZE);
line->line_id = 0;
/* for converting a sentence to a series of training contexts */
struct nlk_context_t **contexts = NULL;
contexts = nlk_context_create_array(ctx_size);
/* for undersampling words in a line */
struct nlk_line_t *line_sample = nlk_line_create(NLK_MAX_LINE_SIZE);
/* output of the first layer */
NLK_ARRAY *layer1_out = nlk_array_create(layer_size2, 1);
/* for storing gradients */
NLK_ARRAY *grad_acc = nlk_array_create(1, layer_size2);
/** @section Vocabularize & Generate Paragraph Vector
*/
const size_t len = strlen(str);
/* 1 - convert to **text_line */
nlk_text_line_read(str, len, tline);
/* 2 - vocabularity */
line->len = nlk_vocab_vocabularize(&nn->vocab, tline, NULL, line->varray);
/* 3 - generate the paragraph vector */
nlk_pv_gen_line(nn, line, epochs, paragraphs, line_sample,
contexts, grad_acc, layer1_out);
/**@section Free memory
*/
nlk_text_line_free(tline);
nlk_line_free(line);
nlk_context_free_array(contexts);
nlk_line_free(line_sample);
nlk_array_free(layer1_out);
nlk_array_free(grad_acc);
return paragraphs;
}
|
GB_unop__exp2_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__exp2_fc32_fc32)
// op(A') function: GB (_unop_tran__exp2_fc32_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = aij
// unaryop: cij = GB_cexp2f (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 = GB_cexp2f (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] = GB_cexp2f (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_EXP2 || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__exp2_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] = GB_cexp2f (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] = GB_cexp2f (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__exp2_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
|
saxpy.c
|
/**
* @file saxpy.c
*
* @mainpage saxpy
*
* @author Xin Wu (PC²)
* @date 05.04.2020
* @copyright CC BY-SA 2.0
*
* saxpy performs the \c saxpy operation on host as well as accelerator.
* The performance (in MB/s) for different implementations is also compared.
*
* The \c saxpy operation is defined as:
*
* y := a * x + y
*
* where:
*
* - a is a scalar.
* - x and y are single-precision vectors each with n elements.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <omp.h>
#include "hsaxpy.h"
#include "asaxpy.h"
#include "check1ns.h"
#include "wtcalc.h"
#define TWO26 (1 << 26)
#define NLUP (32)
/**
* @brief Main entry point for saxpy.
*/
int main(int argc, char *argv[])
{
int i, n,
iret,
ial;
size_t nbytes;
float a = 2.0f,
*x, *y,
*yhost,
*yaccl,
maxabserr;
struct timespec rt[2];
double wt; // walltime
/*
* We need 1 ns time resolution.
*/
check1ns();
printf("The system supports 1 ns time resolution\n");
/*
* check the number of accelerators
*/
if (0 == omp_get_num_devices()) {
printf("No accelerator found ... exit\n");
exit(EXIT_FAILURE);
}
/*
* preparation
*/
n = TWO26;
nbytes = sizeof(float) * n;
iret = 0;
if (NULL == (x = (float *) malloc(nbytes))) iret = -1;
if (NULL == (y = (float *) malloc(nbytes))) iret = -1;
if (NULL == (yhost = (float *) malloc(nbytes))) iret = -1;
if (NULL == (yaccl = (float *) malloc(nbytes))) iret = -1;
if (0 != iret) {
printf("error: memory allocation\n");
free(x); free(y);
free(yhost); free(yaccl);
exit(EXIT_FAILURE);
}
#pragma omp parallel for default(none) \
shared(a, x, y, yhost, yaccl, n) private(i)
for (i = 0; i < n; ++i) {
x[i] = rand() % 32 / 32.0f;
y[i] = rand() % 32 / 32.0f;
yhost[i] = a * x[i] + y[i]; // yhost will be used as reference value
yaccl[i] = 0.0f;
}
printf("total size of x and y is %9.1f MB\n", 2.0 * nbytes / (1 << 20));
printf("tests are averaged over %2d loops\n", NLUP);
/*
* saxpy on host
*/
/*
* See hsaxpy.c for details:
*/
memcpy(yaccl, y, nbytes);
wtcalc = -1.0;
// skip 1st run for timing
hsaxpy(n, a, x, yaccl);
// check yaccl
maxabserr = -1.0f;
for (i = 0; i < n; ++i) {
maxabserr = fabsf(yaccl[i] - yhost[i]) > maxabserr?
fabsf(yaccl[i] - yhost[i]) : maxabserr;
}
// skip 2nd run for timing
hsaxpy(n, a, x, yaccl);
// timing : start
wtcalc = 0.0;
clock_gettime(CLOCK_REALTIME, rt + 0);
for (int ilup = 0; ilup < 1; ++ilup) {
hsaxpy(n, a, x, yaccl);
}
clock_gettime(CLOCK_REALTIME, rt + 1);
wt=(rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec);
printf("saxpy on host: %9.1f MB/s %9.1f MB/s maxabserr = %9.1f\n",
3.0 * nbytes / ((1 << 20) * wt),
3.0 * nbytes / ((1 << 20) * wtcalc), maxabserr);
/*
* saxpy on accl
*/
for (ial = 0; ial < 6; ++ial) {
/*
* See asaxpy.c for details:
*
* ial:
*
* 0: <<<2^7 , 2^7 >>>, auto scheduling
* 1: <<<2^16, 2^10>>>, manual scheduling
* 2: <<<2^15, 2^7 >>>, manual scheduling, 16x loop unrolling (2^15*2^7*16==2^26)
* 3: <<<2^12, 2^7 >>>, auto scheduling, 16x loop unrolling
* 4: de-linearize the vector and then collapse the ji-loop.
* otherwise: hipblasSaxpy in HIPBLAS
*/
memcpy(yaccl, y, nbytes);
wtcalc = -1.0;
// skip 1st run for timing
asaxpy(n, a, x, yaccl, ial);
// check yaccl
maxabserr = -1.0f;
for (i = 0; i < n; ++i) {
maxabserr = fabsf(yaccl[i] - yhost[i]) > maxabserr?
fabsf(yaccl[i] - yhost[i]) : maxabserr;
}
// skip 2nd run for timing
asaxpy(n, a, x, yaccl, ial);
// timing : start
wtcalc = 0.0;
clock_gettime(CLOCK_REALTIME, rt + 0);
for (int ilup = 0; ilup < NLUP; ++ilup) {
asaxpy(n, a, x, yaccl, ial);
}
clock_gettime(CLOCK_REALTIME, rt + 1);
wt=(rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec);
printf("saxpy on accl (impl. %d)\ntotal: %9.1f MB/s kernel: %9.1f MB/s maxabserr = %9.1f\n\n",
ial, NLUP * 3.0 * nbytes / ((1 << 20) * wt),
NLUP * 3.0 * nbytes / ((1 << 20) * wtcalc), maxabserr);
}
/*
* release memory
*/
free(x); free(y);
free(yhost); free(yaccl);
return 0;
}
|
GB_unaryop__minv_int64_bool.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_int64_bool
// op(A') function: GB_tran__minv_int64_bool
// C type: int64_t
// A type: bool
// cast: int64_t cij = (int64_t) aij
// unaryop: cij = GB_IMINV_SIGNED (aij, 64)
#define GB_ATYPE \
bool
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_SIGNED (x, 64) ;
// casting
#define GB_CASTING(z, aij) \
int64_t z = (int64_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_INT64 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_int64_bool
(
int64_t *Cx, // Cx and Ax may be aliased
bool *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_int64_bool
(
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
|
GB_unaryop__identity_int64_uint64.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__identity_int64_uint64
// op(A') function: GB_tran__identity_int64_uint64
// C type: int64_t
// A type: uint64_t
// cast: int64_t cij = (int64_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
int64_t z = (int64_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT64 || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_int64_uint64
(
int64_t *restrict Cx,
const uint64_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__identity_int64_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_critical_section.c
|
//------------------------------------------------------------------------------
// Source/Template/GB_critical_section: execute code in a critical section
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// All access to the global matrix queue, via GB_queue_* operations, must
// be done through a critical section. No other part of SuiteSparse:GraphBLAS
// uses this critical section; it is only used for accessing the global matrix
// queue via GB_queue_*. All GB_queue_* operations use the GB_CRITICAL macro
// to check the result, and if the critical section fails (ok == false),
// they return GrB_PANIC.
// Critical sections for Windows threads and ANSI C11 threads are listed below
// as drafts, but these threading models are not yet supported.
{
//--------------------------------------------------------------------------
// POSIX pthreads
//--------------------------------------------------------------------------
#if defined (USER_POSIX_THREADS)
{
ok = (pthread_mutex_lock (&GB_sync) == 0) ;
GB_CRITICAL_SECTION ;
ok = ok && (pthread_mutex_unlock (&GB_sync) == 0) ;
}
//--------------------------------------------------------------------------
// Microsoft Windows
//--------------------------------------------------------------------------
#elif defined (USER_WINDOWS_THREADS)
{
// This should work, per the Windows spec, but is not yet supported.
EnterCriticalSection (&GB_sync) ;
GB_CRITICAL_SECTION ;
LeaveCriticalSection (&GB_sync) ;
}
//--------------------------------------------------------------------------
// ANSI C11 threads
//--------------------------------------------------------------------------
#elif defined (USER_ANSI_THREADS)
{
// This should work per the ANSI C11 Spec, but is not yet supported.
ok = (mtx_lock (&GB_sync) == thrd_success) ;
GB_CRITICAL_SECTION ;
ok = ok && (mtx_unlock (&GB_sync) == thrd_success) ;
}
//--------------------------------------------------------------------------
// OpenMP
//--------------------------------------------------------------------------
#else // USER_OPENMP_THREADS or USER_NO_THREADS
{
// default: use a named OpenMP critical section. If OpenMP is not
// available, then the #pragma is ignored and this becomes vanilla,
// single-threaded code.
#pragma omp critical(GB_critical_section)
GB_CRITICAL_SECTION ;
}
#endif
}
#undef GB_CRITICAL_SECTION
|
jacobi-ompacc.c
|
#include <stdio.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif
// Add timing support
#include <sys/time.h>
double time_stamp()
{
struct timeval t;
double time;
gettimeofday(&t, NULL);
time = t.tv_sec + 1.0e-6*t.tv_usec;
return time;
}
double time1, time2;
void driver(void);
void initialize(void);
void jacobi(void);
void error_check(void);
/************************************************************
* program to solve a finite difference
* discretization of Helmholtz equation :
* (d2/dx2)u + (d2/dy2)u - alpha u = f
* using Jacobi iterative method.
*
* Modified: Sanjiv Shah, Kuck and Associates, Inc. (KAI), 1998
* Author: Joseph Robicheaux, Kuck and Associates, Inc. (KAI), 1998
*
* This c version program is translated by
* Chunhua Liao, University of Houston, Jan, 2005
*
* Directives are used in this code to achieve parallelism.
* All do loops are parallelized with default 'static' scheduling.
*
* Input : n - grid dimension in x direction
* m - grid dimension in y direction
* alpha - Helmholtz constant (always greater than 0.0)
* tol - error tolerance for iterative solver
* relax - Successice over relaxation parameter
* mits - Maximum iterations for iterative solver
*
* On output
* : u(n,m) - Dependent variable (solutions)
* : f(n,m) - Right hand side function
*************************************************************/
#define MSIZE 512
int n,m,mits;
#define REAL float // flexible between float and double
REAL tol,relax=1.0,alpha=0.0543;
REAL u[MSIZE][MSIZE],f[MSIZE][MSIZE],uold[MSIZE][MSIZE];
REAL dx,dy;
int main (void)
{
// float toler;
/* printf("Input n,m (< %d) - grid dimension in x,y direction:\n",MSIZE);
scanf ("%d",&n);
scanf ("%d",&m);
printf("Input tol - error tolerance for iterative solver\n");
scanf("%f",&toler);
tol=(double)toler;
printf("Input mits - Maximum iterations for solver\n");
scanf("%d",&mits);
*/
n=MSIZE;
m=MSIZE;
tol=0.0000000001;
mits=5000;
#if 0 // Not yet support concurrent CPU and GPU threads
#ifdef _OPENMP
#pragma omp parallel
{
#pragma omp single
printf("Running using %d threads...\n",omp_get_num_threads());
}
#endif
#endif
driver ( ) ;
return 0;
}
/*************************************************************
* Subroutine driver ()
* This is where the arrays are allocated and initialzed.
*
* Working varaibles/arrays
* dx - grid spacing in x direction
* dy - grid spacing in y direction
*************************************************************/
void driver( )
{
initialize();
time1 = time_stamp();
/* Solve Helmholtz equation */
jacobi ();
time2 = time_stamp();
printf("------------------------\n");
printf("Execution time = %f\n",time2-time1);
/* error_check (n,m,alpha,dx,dy,u,f)*/
error_check ( );
}
/* subroutine initialize (n,m,alpha,dx,dy,u,f)
******************************************************
* Initializes data
* Assumes exact solution is u(x,y) = (1-x^2)*(1-y^2)
*
******************************************************/
void initialize( )
{
int i,j, xx,yy;
//double PI=3.1415926;
dx = 2.0 / (n-1);
dy = 2.0 / (m-1);
/* Initialize initial condition and RHS */
//#pragma omp parallel for private(xx,yy,j,i)
for (i=0;i<n;i++)
for (j=0;j<m;j++)
{
xx =(int)( -1.0 + dx * (i-1));
yy = (int)(-1.0 + dy * (j-1)) ;
u[i][j] = 0.0;
f[i][j] = -1.0*alpha *(1.0-xx*xx)*(1.0-yy*yy)\
- 2.0*(1.0-xx*xx)-2.0*(1.0-yy*yy);
}
}
/* subroutine jacobi (n,m,dx,dy,alpha,omega,u,f,tol,maxit)
******************************************************************
* Subroutine HelmholtzJ
* Solves poisson equation on rectangular grid assuming :
* (1) Uniform discretization in each direction, and
* (2) Dirichlect boundary conditions
*
* Jacobi method is used in this routine
*
* Input : n,m Number of grid points in the X/Y directions
* dx,dy Grid spacing in the X/Y directions
* alpha Helmholtz eqn. coefficient
* omega Relaxation factor
* f(n,m) Right hand side function
* u(n,m) Dependent variable/Solution
* tol Tolerance for iterative solver
* maxit Maximum number of iterations
*
* Output : u(n,m) - Solution
*****************************************************************/
void jacobi( )
{
REAL omega;
int i,j,k;
REAL error,resid,ax,ay,b;
// double error_local;
// float ta,tb,tc,td,te,ta1,ta2,tb1,tb2,tc1,tc2,td1,td2;
// float te1,te2;
// float second;
omega=relax;
/*
* Initialize coefficients */
ax = 1.0/(dx*dx); /* X-direction coef */
ay = 1.0/(dy*dy); /* Y-direction coef */
b = -2.0/(dx*dx)-2.0/(dy*dy) - alpha; /* Central coeff */
error = 10.0 * tol;
k = 1;
while ((k<=mits)&&(error>tol))
{
error = 0.0;
/* Copy new solution into old */
// Must split the omp for into two parallel for regions since the translation focuses on parallel to generate the outlined kernel
// We need two CUDA kernels for implementing global synchronization so we have to have two omp parallel directives!!
//#pragma omp target map(in:n, m, omega, ax, ay, u[0:n][0:m],f[0:n][0:m]) map(alloc:uold[0:n][0:m])
//#pragma omp parallel
// {
#pragma omp target map(in:n, m, u[0:n][0:m]) map(out:uold[0:n][0:m])
#pragma omp parallel for private(j,i)
for(i=0;i<n;i++)
for(j=0;j<m;j++)
uold[i][j] = u[i][j];
#pragma omp target map(in:n, m, omega, ax, ay, b, f[0:n][0:m], uold[0:n][0:m]) map(out:u[0:n][0:m])
#pragma omp parallel for private(resid,j,i) reduction(+:error) // nowait
for (i=1;i<(n-1);i++)
for (j=1;j<(m-1);j++)
{
resid = (ax*(uold[i-1][j] + uold[i+1][j])\
+ ay*(uold[i][j-1] + uold[i][j+1])+ b * uold[i][j] - f[i][j])/b;
u[i][j] = uold[i][j] - omega * resid;
error = error + resid*resid ;
}
// }
/* omp end parallel */
/* Error check */
if (k%500==0)
printf("Finished %d iteration with error =%f\n",k, error);
error = sqrt(error)/(n*m);
k = k + 1;
} /* End iteration loop */
printf("Total Number of Iterations:%d\n",k);
printf("Residual:%E\n", error);
}
/* subroutine error_check (n,m,alpha,dx,dy,u,f)
implicit none
************************************************************
* Checks error between numerical and exact solution
*
************************************************************/
void error_check ( )
{
int i,j;
REAL xx,yy,temp,error;
dx = 2.0 / (n-1);
dy = 2.0 / (m-1);
error = 0.0 ;
//#pragma omp parallel for private(xx,yy,temp,j,i) reduction(+:error)
for (i=0;i<n;i++)
for (j=0;j<m;j++)
{
xx = -1.0 + dx * (i-1);
yy = -1.0 + dy * (j-1);
temp = u[i][j] - (1.0-xx*xx)*(1.0-yy*yy);
error = error + temp*temp;
}
error = sqrt(error)/(n*m);
printf("Solution Error :%E \n",error);
}
|
GB_unop__identity_fp32_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 GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_fp32_uint8)
// op(A') function: GB (_unop_tran__identity_fp32_uint8)
// C type: float
// A type: uint8_t
// cast: float cij = (float) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
float
// 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) \
float z = (float) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint8_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = (float) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fp32_uint8)
(
float *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] ;
float z = (float) 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] ;
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_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
|
11_omp_mpi_simple.c
|
// clang-format off
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | %apply-typeart -typeart-alloca -call-filter -S 2>&1 | FileCheck %s
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | opt -O2 -S | %apply-typeart -typeart-alloca -call-filter -S 2>&1 | FileCheck %s
// REQUIRES: openmp
// XFAIL: *
// clang-format on
#include "omp.h"
void MPI_test(void*);
void foo(int* x) {
#pragma omp parallel // transformed to @__kmpc_fork_call
{ MPI_test(x); }
}
void bar() {
int x;
foo(&x);
}
// FIXME: the opt pass tracks 2 allocs in bar (alloca x and alloca x.addr (which is passed to the outlined region))
// CHECK: TypeArtPass [Heap & Stack]
// CHECK-NEXT: Malloc : 0
// CHECK-NEXT: Free : 0
// CHECK-NEXT: Alloca : 1
// CHECK-NEXT: Global : 0
|
GB_binop__times_int8.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__times_int8)
// A.*B function (eWiseMult): GB (_AemultB_08__times_int8)
// A.*B function (eWiseMult): GB (_AemultB_02__times_int8)
// A.*B function (eWiseMult): GB (_AemultB_04__times_int8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__times_int8)
// A*D function (colscale): GB (_AxD__times_int8)
// D*A function (rowscale): GB (_DxB__times_int8)
// C+=B function (dense accum): GB (_Cdense_accumB__times_int8)
// C+=b function (dense accum): GB (_Cdense_accumb__times_int8)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_int8)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_int8)
// C=scalar+B GB (_bind1st__times_int8)
// C=scalar+B' GB (_bind1st_tran__times_int8)
// C=A+scalar GB (_bind2nd__times_int8)
// C=A'+scalar GB (_bind2nd_tran__times_int8)
// C type: int8_t
// A type: int8_t
// A pattern? 0
// B type: int8_t
// B pattern? 0
// 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,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 = (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_TIMES || GxB_NO_INT8 || GxB_NO_TIMES_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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] = (x * bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__times_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] = (aij * y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x * aij) ; \
}
GrB_Info GB (_bind1st_tran__times_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] = (aij * y) ; \
}
GrB_Info GB (_bind2nd_tran__times_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
|
rt_dsymm.c
|
#include "runtime.h"
#ifdef PLASMA_WITH_SMP
#pragma omp target device (smp) copy_deps
#pragma omp task in([lda*m]A, [ldb*n]B) inout([ldc*n]C) label(ldsymm_smp)
void CORE_ldsymm_ompss(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
CORE_dsymm(PlasmaLeft, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc);
}
#pragma omp target device (smp) copy_deps
#pragma omp task in([lda*n]A, [ldb*n]B) inout([ldc*n]C) label(rdsymm_smp)
void CORE_rdsymm_ompss(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
CORE_dsymm(PlasmaRight, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc);
}
#endif
//CUDA support
#ifdef PLASMA_WITH_CUDA_HYBRID
#pragma omp target device (smp) copy_deps
#pragma omp task in([lda*m]A, [ldb*n]B) inout([ldc*n]C) label(ldsymm_hyb_smp)
void CORE_ldsymm_ompss(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
CORE_dsymm(PlasmaLeft, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc);
}
#pragma omp target device (smp) copy_deps
#pragma omp task in([lda*n]A, [ldb*n]B) inout([ldc*n]C) label(rdsymm_hyb_smp)
void CORE_rdsymm_ompss(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
CORE_dsymm(PlasmaRight, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc);
}
//Alternative implementations
#pragma omp target device (cuda) copy_deps implements(CORE_ldsymm_ompss)
#pragma omp task in([lda*m]A, [ldb*n]B) inout([ldc*n]C) label(ldsymm_hyb_cuda)
void CORE_ldsymm_cuda(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
cublasFillMode_t cuplo;
if ( uplo == PlasmaUpper )
cuplo = CUBLAS_FILL_MODE_UPPER;
else
cuplo = CUBLAS_FILL_MODE_LOWER;
cublasHandle_t handle = nanos_get_cublas_handle();
cudaStream_t stream = nanos_get_kernel_execution_stream();
cublasSetStream(handle, stream);
cublasDsymm(handle, CUBLAS_SIDE_LEFT, cuplo, m, n, &alpha, A, lda, B, ldb, &beta, C, ldc);
}
#pragma omp target device (cuda) copy_deps implements(CORE_rdsymm_ompss)
#pragma omp task in([lda*n]A, [ldb*n]B) inout([ldc*n]C) label(rdsymm_hyb_cuda)
void CORE_rdsymm_cuda(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
cublasFillMode_t cuplo;
if ( uplo == PlasmaUpper )
cuplo = CUBLAS_FILL_MODE_UPPER;
else
cuplo = CUBLAS_FILL_MODE_LOWER;
cublasHandle_t handle = nanos_get_cublas_handle();
cudaStream_t stream = nanos_get_kernel_execution_stream();
cublasSetStream(handle, stream);
cublasDsymm(handle, CUBLAS_SIDE_RIGHT, cuplo, m, n, &alpha, A, lda, B, ldb, &beta, C, ldc);
}
#endif
#ifdef PLASMA_WITH_CUDA_PURE
#pragma omp target device (cuda) copy_deps
#pragma omp task in([lda*m]A, [ldb*n]B) inout([ldc*n]C) label(ldsymm_cuda)
void CORE_ldsymm_ompss(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
cublasFillMode_t cuplo;
if ( uplo == PlasmaUpper )
cuplo = CUBLAS_FILL_MODE_UPPER;
else
cuplo = CUBLAS_FILL_MODE_LOWER;
cublasHandle_t handle = nanos_get_cublas_handle();
cudaStream_t stream = nanos_get_kernel_execution_stream();
cublasSetStream(handle, stream);
cublasDsymm(handle, CUBLAS_SIDE_LEFT, cuplo, m, n, &alpha, A, lda, B, ldb, &beta, C, ldc);
}
#pragma omp target device (cuda) copy_deps
#pragma omp task in([lda*n]A, [ldb*n]B) inout([ldc*n]C) label(rdsymm_cuda)
void CORE_rdsymm_ompss(PLASMA_enum uplo, int m , int n, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc, int nb)
{
cublasFillMode_t cuplo;
if ( uplo == PlasmaUpper )
cuplo = CUBLAS_FILL_MODE_UPPER;
else
cuplo = CUBLAS_FILL_MODE_LOWER;
cublasHandle_t handle = nanos_get_cublas_handle();
cudaStream_t stream = nanos_get_kernel_execution_stream();
cublasSetStream(handle, stream);
cublasDsymm(handle, CUBLAS_SIDE_RIGHT, cuplo, m, n, &alpha, A, lda, B, ldb, &beta, C, ldc);
}
#endif
void RT_CORE_dsymm(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum side, PLASMA_enum uplo,
int m, int n, int nb,
double alpha, double *A, int lda,
double *B, int ldb,
double beta, double *C, int ldc)
{
plasma_context_t *plasma;
plasma = plasma_context_self();
if (plasma->runtime == PLASMA_QUARK) {
QUARK_CORE_dsymm( quark, task_flags,
side, uplo, m, n, nb,
alpha, A, lda, B, ldb,
beta, C, ldc);
} else if (plasma->runtime == PLASMA_OMPSS) {
if (side == PlasmaLeft){
CORE_ldsymm_ompss(uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc, nb);
} else {
CORE_rdsymm_ompss(uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc, nb);
}
}
}
|
dynmat.c
|
/* Copyright (C) 2015 Atsushi Togo */
/* All rights reserved. */
/* This file is part of phonopy. */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions */
/* are met: */
/* * Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* * Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the */
/* distribution. */
/* * Neither the name of the phonopy project nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */
/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */
/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */
/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */
/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */
/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
#include <math.h>
#include <stdlib.h>
#include <dynmat.h>
#define PI 3.14159265358979323846
static void get_dynmat_ij(double *dynamical_matrix,
const int num_patom,
const int num_satom,
const double *fc,
const double *q,
const double *r,
const int *multi,
const double *mass,
const int *s2p_map,
const int *p2s_map,
const double *charge_sum,
const int i,
const int j);
static void get_dm(double dm_real[3][3],
double dm_imag[3][3],
const int num_patom,
const int num_satom,
const double *fc,
const double *q,
const double *r,
const int *multi,
const double mass_sqrt,
const int *p2s_map,
const double *charge_sum,
const int i,
const int j,
const int k);
static double get_dielectric_part(const double q[3],
const double *dielectric);
int get_dynamical_matrix_at_q(double *dynamical_matrix,
const int num_patom,
const int num_satom,
const double *fc,
const double *q,
const double *r,
const int *multi,
const double *mass,
const int *s2p_map,
const int *p2s_map,
const double *charge_sum,
const int with_openmp)
{
int i, j, ij, adrs, adrsT;
if (with_openmp) {
#pragma omp parallel for
for (ij = 0; ij < num_patom * num_patom ; ij++) {
get_dynmat_ij(dynamical_matrix,
num_patom,
num_satom,
fc,
q,
r,
multi,
mass,
s2p_map,
p2s_map,
charge_sum,
ij / num_patom, /* i */
ij % num_patom); /* j */
}
} else {
for (i = 0; i < num_patom; i++) {
for (j = 0; j < num_patom; j++) {
get_dynmat_ij(dynamical_matrix,
num_patom,
num_satom,
fc,
q,
r,
multi,
mass,
s2p_map,
p2s_map,
charge_sum,
i,
j);
}
}
}
/* Symmetrize to be a Hermitian matrix */
for (i = 0; i < num_patom * 3; i++) {
for (j = i; j < num_patom * 3; j++) {
adrs = i * num_patom * 6 + j * 2;
adrsT = j * num_patom * 6 + i * 2;
dynamical_matrix[adrs] += dynamical_matrix[adrsT];
dynamical_matrix[adrs] /= 2;
dynamical_matrix[adrs + 1] -= dynamical_matrix[adrsT+ 1];
dynamical_matrix[adrs + 1] /= 2;
dynamical_matrix[adrsT] = dynamical_matrix[adrs];
dynamical_matrix[adrsT + 1] = -dynamical_matrix[adrs + 1];
}
}
return 0;
}
void get_dipole_dipole(double *dd, /* [natom, 3, natom, 3, (real, imag)] */
const double *K_list, /* [num_kvec, 3] */
const int num_K,
const int num_patom,
const double *q_vector,
const double *q_direction,
const double *born,
const double *dielectric,
const double factor, /* 4pi/V*unit-conv */
const double *pos, /* [natom, 3] */
const double tolerance)
{
int i, j, k, l, g, adrs;
double q_K[3], q_G[3];
double norm, cos_phase, sin_phase, phase, z;
double *charge_sum;
charge_sum = NULL;
for (i = 0; i < num_patom * num_patom * 18; i++) {
dd[i] = 0;
}
charge_sum = (double*) malloc(sizeof(double) * num_patom * num_patom * 9);
for (g = 0; g < num_K; g++) {
norm = 0;
for (i = 0; i < 3; i++) {
norm += K_list[g * 3 + i] * K_list[g * 3 + i];
}
if (sqrt(norm) < tolerance) {
if (!q_direction) {
continue;
} else {
for (i = 0; i < 3; i++) {q_K[i] = q_direction[i];}
}
} else {
for (i = 0; i < 3; i++) {q_K[i] = K_list[g * 3 + i];}
}
get_charge_sum(charge_sum,
num_patom,
factor / get_dielectric_part(q_K, dielectric),
q_K,
born);
for (i = 0; i < num_patom; i++) {
for (j = 0; j < num_patom; j++) {
phase = 0;
for (k = 0; k < 3; k++) {
phase += (pos[i * 3 + k] - pos[j * 3 + k]) * K_list[g * 3 + k];
}
phase *= 2 * PI;
cos_phase = cos(phase);
sin_phase = sin(phase);
for (k = 0; k < 3; k++) {
for (l = 0; l < 3; l++) {
adrs = i * num_patom * 18 + k * num_patom * 6 + j * 6 + l * 2;
z = charge_sum[i * num_patom * 9 + j * 9 + k * 3 + l];
dd[adrs] += z * cos_phase;
dd[adrs + 1] += z * sin_phase;
}
}
}
}
}
for (g = 0; g < num_K; g++) {
norm = 0;
for (i = 0; i < 3; i++) {
q_G[i] = K_list[g * 3 + i] - q_vector[i];
norm += q_G[i] * q_G[i];
}
if (sqrt(norm) < tolerance) {
continue;
}
get_charge_sum(charge_sum,
num_patom,
factor / get_dielectric_part(q_G, dielectric),
q_G,
born);
for (i = 0; i < num_patom; i++) {
for (j = 0; j < num_patom; j++) {
phase = 0;
for (k = 0; k < 3; k++) {
phase += (pos[i * 3 + k] - pos[j * 3 + k]) * q_G[k];
}
phase *= 2 * PI;
cos_phase = cos(phase);
sin_phase = sin(phase);
for (k = 0; k < 3; k++) {
for (l = 0; l < 3; l++) {
/* i is correct about the third index, not j */
adrs = i * num_patom * 18 + k * num_patom * 6 + i * 6 + l * 2;
z = charge_sum[i * num_patom * 9 + j * 9 + k * 3 + l];
dd[adrs] -= z * cos_phase;
dd[adrs + 1] -= z * sin_phase;
}
}
}
}
}
free(charge_sum);
charge_sum = NULL;
}
void get_charge_sum(double *charge_sum,
const int num_patom,
const double factor, /* 4pi/V*unit-conv and denominator */
const double q_vector[3],
const double *born)
{
int i, j, k, a, b;
double (*q_born)[3];
q_born = (double (*)[3]) malloc(sizeof(double[3]) * num_patom);
for (i = 0; i < num_patom; i++) {
for (j = 0; j < 3; j++) {
q_born[i][j] = 0;
}
}
for (i = 0; i < num_patom; i++) {
for (j = 0; j < 3; j++) {
for (k = 0; k < 3; k++) {
q_born[i][j] += q_vector[k] * born[i * 9 + k * 3 + j];
}
}
}
for (i = 0; i < num_patom; i++) {
for (j = 0; j < num_patom; j++) {
for (a = 0; a < 3; a++) {
for (b = 0; b < 3; b++) {
charge_sum[i * 9 * num_patom + j * 9 + a * 3 + b] =
q_born[i][a] * q_born[j][b] * factor;
}
}
}
}
free(q_born);
q_born = NULL;
}
static void get_dynmat_ij(double *dynamical_matrix,
const int num_patom,
const int num_satom,
const double *fc,
const double *q,
const double *r,
const int *multi,
const double *mass,
const int *s2p_map,
const int *p2s_map,
const double *charge_sum,
const int i,
const int j)
{
int k, l, adrs;
double mass_sqrt;
double dm_real[3][3], dm_imag[3][3];
mass_sqrt = sqrt(mass[i] * mass[j]);
for (k = 0; k < 3; k++) {
for (l = 0; l < 3; l++) {
dm_real[k][l] = 0;
dm_imag[k][l] = 0;
}
}
for (k = 0; k < num_satom; k++) { /* Lattice points of right index of fc */
if (s2p_map[k] != p2s_map[j]) {
continue;
}
get_dm(dm_real,
dm_imag,
num_patom,
num_satom,
fc,
q,
r,
multi,
mass_sqrt,
p2s_map,
charge_sum,
i,
j,
k);
}
for (k = 0; k < 3; k++) {
for (l = 0; l < 3; l++) {
adrs = (i * 3 + k) * num_patom * 6 + j * 6 + l * 2;
dynamical_matrix[adrs] = dm_real[k][l];
dynamical_matrix[adrs + 1] = dm_imag[k][l];
}
}
}
static void get_dm(double dm_real[3][3],
double dm_imag[3][3],
const int num_patom,
const int num_satom,
const double *fc,
const double *q,
const double *r,
const int *multi,
const double mass_sqrt,
const int *p2s_map,
const double *charge_sum,
const int i,
const int j,
const int k)
{
int l, m;
double phase, cos_phase, sin_phase, fc_elem;
cos_phase = 0;
sin_phase = 0;
for (l = 0; l < multi[k * num_patom + i]; l++) {
phase = 0;
for (m = 0; m < 3; m++) {
phase += q[m] * r[k * num_patom * 81 + i * 81 + l * 3 + m];
}
cos_phase += cos(phase * 2 * PI) / multi[k * num_patom + i];
sin_phase += sin(phase * 2 * PI) / multi[k * num_patom + i];
}
for (l = 0; l < 3; l++) {
for (m = 0; m < 3; m++) {
if (charge_sum) {
fc_elem = (fc[p2s_map[i] * num_satom * 9 + k * 9 + l * 3 + m] +
charge_sum[i * num_patom * 9 +
j * 9 + l * 3 + m]) / mass_sqrt;
} else {
fc_elem = fc[p2s_map[i] * num_satom * 9 +
k * 9 + l * 3 + m] / mass_sqrt;
}
dm_real[l][m] += fc_elem * cos_phase;
dm_imag[l][m] += fc_elem * sin_phase;
}
}
}
static double get_dielectric_part(const double q[3],
const double *dielectric)
{
int i, j;
double x[3];
double sum;
for (i = 0; i < 3; i++) {
x[i] = 0;
for (j = 0; j < 3; j++) {
x[i] += dielectric[i * 3 + j] * q[j];
}
}
sum = 0;
for (i = 0; i < 3; i++) {
sum += q[i] * x[i];
}
return sum;
}
|
trsv_x_sky_n_hi.c
|
#include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include "alphasparse/opt.h"
#include <memory.h>
#ifdef _OPENMP
#include <omp.h>
#endif
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, ALPHA_Number *y)
{
ALPHA_Number diag[A->cols];
memset(diag, '\0', A->rows * sizeof(ALPHA_Number));
int num_thread = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for (ALPHA_INT r = 1; r < A->rows + 1; r++)
{
const ALPHA_INT indx = A->pointers[r] - 1;
diag[r - 1] = A->values[indx];
}
for (ALPHA_INT c = A->cols - 1; c >= 0; c--)
{
ALPHA_Number temp;
alpha_setzero(temp);
for (ALPHA_INT ic = A->cols - 1; ic > c; ic--)
{
ALPHA_INT start = A->pointers[ic];
ALPHA_INT end = A->pointers[ic + 1];
ALPHA_INT eles_num = ic - c;
if(end - eles_num - 1 >= start)
alpha_madde(temp, A->values[end - eles_num - 1], y[ic]);
}
ALPHA_Number t;
alpha_mul(t, alpha, x[c]);
alpha_sub(t, t, temp);
alpha_div(y[c], t, diag[c]);
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
GB_assign_zombie4.c
|
//------------------------------------------------------------------------------
// GB_assign_zombie4: delete entries in C(i,:) for C_replace_phase
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// For GrB_Row_assign or GrB_Col_assign, C(i,J)<M,repl>=..., if C_replace is
// true, and mask M is present, then any entry C(i,j) outside the list J must
// be deleted, if M(0,j)=0.
// GB_assign_zombie3 and GB_assign_zombie4 are transposes of each other.
// C must be sparse or hypersparse.
// M can have any sparsity structure: hypersparse, sparse, bitmap, or full
#include "GB_assign.h"
#include "GB_assign_zombie.h"
void GB_assign_zombie4
(
GrB_Matrix C, // the matrix C, or a copy
const GrB_Matrix M,
const bool Mask_comp,
const bool Mask_struct,
const int64_t i, // index of entries to delete
const GrB_Index *J,
const int64_t nJ,
const int Jkind,
const int64_t Jcolon [3],
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (!GB_IS_FULL (C)) ;
ASSERT (!GB_IS_BITMAP (C)) ;
ASSERT (GB_ZOMBIES_OK (C)) ;
ASSERT (!GB_JUMBLED (C)) ; // binary search on C
ASSERT (!GB_PENDING (C)) ;
ASSERT (!GB_ZOMBIES (M)) ;
ASSERT (!GB_JUMBLED (M)) ;
ASSERT (!GB_PENDING (M)) ;
ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M
//--------------------------------------------------------------------------
// get C
//--------------------------------------------------------------------------
const int64_t *GB_RESTRICT Ch = C->h ;
const int64_t *GB_RESTRICT Cp = C->p ;
const int64_t Cnvec = C->nvec ;
int64_t *GB_RESTRICT Ci = C->i ;
int64_t nzombies = C->nzombies ;
const int64_t zorig = nzombies ;
//--------------------------------------------------------------------------
// get M
//--------------------------------------------------------------------------
const int64_t *GB_RESTRICT Mp = M->p ;
const int64_t *GB_RESTRICT Mh = M->h ;
const int8_t *GB_RESTRICT Mb = M->b ;
const GB_void *GB_RESTRICT Mx = (GB_void *) (Mask_struct ? NULL : (M->x)) ;
const size_t msize = M->type->size ;
const int64_t Mnvec = M->nvec ;
const int64_t Mvlen = M->vlen ;
ASSERT (Mvlen == 1) ;
const bool M_is_hyper = GB_IS_HYPERSPARSE (M) ;
const bool M_is_bitmap = GB_IS_BITMAP (M) ;
const bool M_is_full = GB_IS_FULL (M) ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (Cnvec, chunk, nthreads_max) ;
int ntasks = (nthreads == 1) ? 1 : (64 * nthreads) ;
//--------------------------------------------------------------------------
// delete entries in C(i,:)
//--------------------------------------------------------------------------
// The entry C(i,j) is deleted if j is not in the J, and if M(0,j)=0 (if
// the mask is not complemented) or M(0,j)=1 (if the mask is complemented.
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
int64_t kfirst, klast ;
GB_PARTITION (kfirst, klast, Cnvec, taskid, ntasks) ;
for (int64_t k = kfirst ; k < klast ; k++)
{
//------------------------------------------------------------------
// get C(:,j) and determine if j is outside the list J
//------------------------------------------------------------------
int64_t j = GBH (Ch, k) ;
bool j_outside = !GB_ij_is_in_list (J, nJ, j, Jkind, Jcolon) ;
if (j_outside)
{
//--------------------------------------------------------------
// j is not in J; find C(i,j)
//--------------------------------------------------------------
int64_t pC = Cp [k] ;
int64_t pC_end = Cp [k+1] ;
int64_t pright = pC_end - 1 ;
bool found, is_zombie ;
GB_BINARY_SEARCH_ZOMBIE (i, Ci, pC, pright, found, zorig,
is_zombie) ;
//--------------------------------------------------------------
// delete C(i,j) if found, not a zombie, and M(0,j) allows it
//--------------------------------------------------------------
if (found && !is_zombie)
{
//----------------------------------------------------------
// C(i,j) is a live entry not in the C(I,J) submatrix
//----------------------------------------------------------
// Check the mask M to see if it should be deleted.
bool mij = false ;
if (M_is_bitmap || M_is_full)
{
// M is bitmap/full, no need for GB_lookup
int64_t pM = j ;
mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ;
}
else
{
// M is sparse or hypersparse
int64_t pM, pM_end ;
int64_t pleft = 0 ;
int64_t pright = Mnvec - 1 ;
GB_lookup (M_is_hyper, Mh, Mp, Mvlen, &pleft, pright,
j, &pM, &pM_end) ;
if (pM < pM_end)
{
// found it
mij = GB_mcast (Mx, pM, msize) ;
}
}
if (Mask_comp)
{
// negate the mask if Mask_comp is true
mij = !mij ;
}
if (!mij)
{
// delete C(i,j) by marking it as a zombie
nzombies++ ;
Ci [pC] = GB_FLIP (i) ;
}
}
}
}
}
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
C->nzombies = nzombies ;
}
|
HYPRE_IJMatrix.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)
******************************************************************************/
/******************************************************************************
*
* HYPRE_IJMatrix interface
*
*****************************************************************************/
#include "./_hypre_IJ_mv.h"
#include "../HYPRE.h"
/*--------------------------------------------------------------------------
* HYPRE_IJMatrixCreate
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixCreate( MPI_Comm comm,
HYPRE_BigInt ilower,
HYPRE_BigInt iupper,
HYPRE_BigInt jlower,
HYPRE_BigInt jupper,
HYPRE_IJMatrix *matrix )
{
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_BigInt *info;
HYPRE_Int num_procs;
HYPRE_Int myid;
hypre_IJMatrix *ijmatrix;
HYPRE_BigInt row0, col0, rowN, colN;
ijmatrix = hypre_CTAlloc(hypre_IJMatrix, 1, HYPRE_MEMORY_HOST);
hypre_IJMatrixComm(ijmatrix) = comm;
hypre_IJMatrixObject(ijmatrix) = NULL;
hypre_IJMatrixTranslator(ijmatrix) = NULL;
hypre_IJMatrixAssumedPart(ijmatrix) = NULL;
hypre_IJMatrixObjectType(ijmatrix) = HYPRE_UNITIALIZED;
hypre_IJMatrixAssembleFlag(ijmatrix) = 0;
hypre_IJMatrixPrintLevel(ijmatrix) = 0;
hypre_IJMatrixOMPFlag(ijmatrix) = 0;
hypre_MPI_Comm_size(comm,&num_procs);
hypre_MPI_Comm_rank(comm, &myid);
if (ilower > iupper+1 || ilower < 0)
{
hypre_error_in_arg(2);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (iupper < -1)
{
hypre_error_in_arg(3);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (jlower > jupper+1 || jlower < 0)
{
hypre_error_in_arg(4);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (jupper < -1)
{
hypre_error_in_arg(5);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
info = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
row_partitioning = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
col_partitioning = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
row_partitioning[0] = ilower;
row_partitioning[1] = iupper+1;
col_partitioning[0] = jlower;
col_partitioning[1] = jupper+1;
/* now we need the global number of rows and columns as well
as the global first row and column index */
/* proc 0 has the first row and col */
if (myid == 0)
{
info[0] = ilower;
info[1] = jlower;
}
hypre_MPI_Bcast(info, 2, HYPRE_MPI_BIG_INT, 0, comm);
row0 = info[0];
col0 = info[1];
/* proc (num_procs-1) has the last row and col */
if (myid == (num_procs-1))
{
info[0] = iupper;
info[1] = jupper;
}
hypre_MPI_Bcast(info, 2, HYPRE_MPI_BIG_INT, num_procs-1, comm);
rowN = info[0];
colN = info[1];
hypre_IJMatrixGlobalFirstRow(ijmatrix) = row0;
hypre_IJMatrixGlobalFirstCol(ijmatrix) = col0;
hypre_IJMatrixGlobalNumRows(ijmatrix) = rowN - row0 + 1;
hypre_IJMatrixGlobalNumCols(ijmatrix) = colN - col0 + 1;
hypre_TFree(info, HYPRE_MEMORY_HOST);
hypre_IJMatrixRowPartitioning(ijmatrix) = row_partitioning;
hypre_IJMatrixColPartitioning(ijmatrix) = col_partitioning;
*matrix = (HYPRE_IJMatrix) ijmatrix;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixDestroy( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (ijmatrix)
{
if (hypre_IJMatrixRowPartitioning(ijmatrix) ==
hypre_IJMatrixColPartitioning(ijmatrix))
{
hypre_TFree(hypre_IJMatrixRowPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
}
else
{
hypre_TFree(hypre_IJMatrixRowPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
hypre_TFree(hypre_IJMatrixColPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
}
if hypre_IJMatrixAssumedPart(ijmatrix)
{
hypre_AssumedPartitionDestroy((hypre_IJAssumedPart*)hypre_IJMatrixAssumedPart(ijmatrix));
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixDestroyParCSR( ijmatrix );
}
else if ( hypre_IJMatrixObjectType(ijmatrix) != -1 )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
}
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixInitialize( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixInitializeParCSR( ijmatrix ) ;
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
HYPRE_Int
HYPRE_IJMatrixInitialize_v2( HYPRE_IJMatrix matrix, HYPRE_MemoryLocation memory_location )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixInitializeParCSR_v2( ijmatrix, memory_location ) ;
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetPrintLevel( HYPRE_IJMatrix matrix,
HYPRE_Int print_level )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixPrintLevel(ijmatrix) = 1;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* This is a helper routine to compute a prefix sum of integer values.
*
* The current implementation is okay for modest numbers of threads.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_PrefixSumInt(HYPRE_Int nvals,
HYPRE_Int *vals,
HYPRE_Int *sums)
{
HYPRE_Int j, nthreads, bsize;
nthreads = hypre_NumThreads();
bsize = (nvals + nthreads - 1) / nthreads; /* This distributes the remainder */
if (nvals < nthreads || bsize == 1)
{
sums[0] = 0;
for (j=1; j < nvals; j++)
sums[j] += sums[j-1] + vals[j-1];
}
else
{
/* Compute preliminary partial sums (in parallel) within each interval */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < nvals; j += bsize)
{
HYPRE_Int i, n = hypre_min((j+bsize), nvals);
sums[0] = 0;
for (i = j+1; i < n; i++)
{
sums[i] = sums[i-1] + vals[i-1];
}
}
/* Compute final partial sums (in serial) for the first entry of every interval */
for (j = bsize; j < nvals; j += bsize)
{
sums[j] = sums[j-bsize] + sums[j-1] + vals[j-1];
}
/* Compute final partial sums (in parallel) for the remaining entries */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for (j = bsize; j < nvals; j += bsize)
{
HYPRE_Int i, n = hypre_min((j+bsize), nvals);
for (i = j+1; i < n; i++)
{
sums[i] += sums[j];
}
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
HYPRE_IJMatrixSetValues2(matrix, nrows, ncols, rows, NULL, cols, values);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetValues2( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_Int *row_indexes,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(7);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
#if defined(HYPRE_USING_CUDA)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
hypre_IJMatrixSetAddValuesParCSRDevice(ijmatrix, nrows, ncols, rows, row_indexes, cols, values, "set");
}
else
#endif
{
HYPRE_Int *row_indexes_tmp = (HYPRE_Int *) row_indexes;
HYPRE_Int *ncols_tmp = ncols;
if (!ncols_tmp)
{
HYPRE_Int i;
ncols_tmp = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
for (i = 0; i < nrows; i++)
{
ncols_tmp[i] = 1;
}
}
if (!row_indexes)
{
row_indexes_tmp = hypre_CTAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
hypre_PrefixSumInt(nrows, ncols_tmp, row_indexes_tmp);
}
if (hypre_IJMatrixOMPFlag(ijmatrix))
{
hypre_IJMatrixSetValuesOMPParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
else
{
hypre_IJMatrixSetValuesParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
if (!ncols)
{
hypre_TFree(ncols_tmp, HYPRE_MEMORY_HOST);
}
if (!row_indexes)
{
hypre_TFree(row_indexes_tmp, HYPRE_MEMORY_HOST);
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetConstantValues( HYPRE_IJMatrix matrix, HYPRE_Complex value)
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetConstantValuesParCSR( ijmatrix, value));
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAddToValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
HYPRE_IJMatrixAddToValues2(matrix, nrows, ncols, rows, NULL, cols, values);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAddToValues2( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_Int *row_indexes,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(7);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
#if defined(HYPRE_USING_CUDA)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
hypre_IJMatrixSetAddValuesParCSRDevice(ijmatrix, nrows, ncols, rows, row_indexes, cols, values, "add");
}
else
#endif
{
HYPRE_Int *row_indexes_tmp = (HYPRE_Int *) row_indexes;
HYPRE_Int *ncols_tmp = ncols;
if (!ncols_tmp)
{
HYPRE_Int i;
ncols_tmp = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
for (i = 0; i < nrows; i++)
{
ncols_tmp[i] = 1;
}
}
if (!row_indexes)
{
row_indexes_tmp = hypre_CTAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
hypre_PrefixSumInt(nrows, ncols_tmp, row_indexes_tmp);
}
if (hypre_IJMatrixOMPFlag(ijmatrix))
{
hypre_IJMatrixAddToValuesOMPParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
else
{
hypre_IJMatrixAddToValuesParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
if (!ncols)
{
hypre_TFree(ncols_tmp, HYPRE_MEMORY_HOST);
}
if (!row_indexes)
{
hypre_TFree(row_indexes_tmp, HYPRE_MEMORY_HOST);
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAssemble( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
#if defined(HYPRE_USING_CUDA)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
return( hypre_IJMatrixAssembleParCSRDevice( ijmatrix ) );
}
else
#endif
{
return( hypre_IJMatrixAssembleParCSR( ijmatrix ) );
}
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetRowCounts( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_BigInt *rows,
HYPRE_Int *ncols )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
if (!rows)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
if (!ncols)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixGetRowCountsParCSR( ijmatrix, nrows, rows, ncols );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
HYPRE_BigInt *rows,
HYPRE_BigInt *cols,
HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixGetValuesParCSR( ijmatrix, nrows, ncols,
rows, cols, values );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetObjectType( HYPRE_IJMatrix matrix,
HYPRE_Int type )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixObjectType(ijmatrix) = type;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetObjectType( HYPRE_IJMatrix matrix,
HYPRE_Int *type )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
*type = hypre_IJMatrixObjectType(ijmatrix);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetLocalRange( HYPRE_IJMatrix matrix,
HYPRE_BigInt *ilower,
HYPRE_BigInt *iupper,
HYPRE_BigInt *jlower,
HYPRE_BigInt *jupper )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
MPI_Comm comm;
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_Int my_id;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
comm = hypre_IJMatrixComm(ijmatrix);
row_partitioning = hypre_IJMatrixRowPartitioning(ijmatrix);
col_partitioning = hypre_IJMatrixColPartitioning(ijmatrix);
hypre_MPI_Comm_rank(comm, &my_id);
*ilower = row_partitioning[0];
*iupper = row_partitioning[1]-1;
*jlower = col_partitioning[0];
*jupper = col_partitioning[1]-1;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
/**
Returns a pointer to an underlying ijmatrix type used to implement IJMatrix.
Assumes that the implementation has an underlying matrix, so it would not
work with a direct implementation of IJMatrix.
@return integer error code
@param IJMatrix [IN]
The ijmatrix to be pointed to.
*/
HYPRE_Int
HYPRE_IJMatrixGetObject( HYPRE_IJMatrix matrix,
void **object )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
*object = hypre_IJMatrixObject( ijmatrix );
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetRowSizes( HYPRE_IJMatrix matrix,
const HYPRE_Int *sizes )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetRowSizesParCSR( ijmatrix , sizes ) );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetDiagOffdSizes( HYPRE_IJMatrix matrix,
const HYPRE_Int *diag_sizes,
const HYPRE_Int *offdiag_sizes )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixSetDiagOffdSizesParCSR( ijmatrix, diag_sizes, offdiag_sizes );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetMaxOffProcElmts( HYPRE_IJMatrix matrix,
HYPRE_Int max_off_proc_elmts)
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetMaxOffProcElmtsParCSR(ijmatrix,
max_off_proc_elmts) );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixRead( const char *filename,
MPI_Comm comm,
HYPRE_Int type,
HYPRE_IJMatrix *matrix_ptr )
{
HYPRE_IJMatrix matrix;
HYPRE_BigInt ilower, iupper, jlower, jupper;
HYPRE_BigInt I, J;
HYPRE_Int ncols;
HYPRE_Complex value;
HYPRE_Int myid, ret;
char new_filename[255];
FILE *file;
hypre_MPI_Comm_rank(comm, &myid);
hypre_sprintf(new_filename,"%s.%05d", filename, myid);
if ((file = fopen(new_filename, "r")) == NULL)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_fscanf(file, "%b %b %b %b", &ilower, &iupper, &jlower, &jupper);
HYPRE_IJMatrixCreate(comm, ilower, iupper, jlower, jupper, &matrix);
HYPRE_IJMatrixSetObjectType(matrix, type);
HYPRE_IJMatrixInitialize_v2(matrix, HYPRE_MEMORY_HOST);
/* It is important to ensure that whitespace follows the index value to help
* catch mistakes in the input file. See comments in IJVectorRead(). */
ncols = 1;
while ( (ret = hypre_fscanf(file, "%b %b%*[ \t]%le", &I, &J, &value)) != EOF )
{
if (ret != 3)
{
hypre_error_w_msg(HYPRE_ERROR_GENERIC, "Error in IJ matrix input file.");
return hypre_error_flag;
}
if (I < ilower || I > iupper)
{
HYPRE_IJMatrixAddToValues(matrix, 1, &ncols, &I, &J, &value);
}
else
{
HYPRE_IJMatrixSetValues(matrix, 1, &ncols, &I, &J, &value);
}
}
HYPRE_IJMatrixAssemble(matrix);
fclose(file);
*matrix_ptr = matrix;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixPrint( HYPRE_IJMatrix matrix,
const char *filename )
{
MPI_Comm comm;
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_BigInt ilower, iupper, jlower, jupper;
HYPRE_BigInt i, ii;
HYPRE_Int j;
HYPRE_Int ncols;
HYPRE_BigInt *cols;
HYPRE_Complex *values;
HYPRE_Int myid;
char new_filename[255];
FILE *file;
void *object;
if (!matrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( (hypre_IJMatrixObjectType(matrix) != HYPRE_PARCSR) )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
comm = hypre_IJMatrixComm(matrix);
hypre_MPI_Comm_rank(comm, &myid);
hypre_sprintf(new_filename,"%s.%05d", filename, myid);
if ((file = fopen(new_filename, "w")) == NULL)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
row_partitioning = hypre_IJMatrixRowPartitioning(matrix);
col_partitioning = hypre_IJMatrixColPartitioning(matrix);
ilower = row_partitioning[0];
iupper = row_partitioning[1] - 1;
jlower = col_partitioning[0];
jupper = col_partitioning[1] - 1;
hypre_fprintf(file, "%b %b %b %b\n", ilower, iupper, jlower, jupper);
HYPRE_IJMatrixGetObject(matrix, &object);
for (i = ilower; i <= iupper; i++)
{
if ( hypre_IJMatrixObjectType(matrix) == HYPRE_PARCSR )
{
ii = i - hypre_IJMatrixGlobalFirstRow(matrix);
HYPRE_ParCSRMatrixGetRow((HYPRE_ParCSRMatrix) object,
ii, &ncols, &cols, &values);
for (j = 0; j < ncols; j++)
{
cols[j] += hypre_IJMatrixGlobalFirstCol(matrix);
}
}
for (j = 0; j < ncols; j++)
{
hypre_fprintf(file, "%b %b %.14e\n", i, cols[j], values[j]);
}
if ( hypre_IJMatrixObjectType(matrix) == HYPRE_PARCSR )
{
for (j = 0; j < ncols; j++)
{
cols[j] -= hypre_IJMatrixGlobalFirstCol(matrix);
}
HYPRE_ParCSRMatrixRestoreRow((HYPRE_ParCSRMatrix) object,
ii, &ncols, &cols, &values);
}
}
fclose(file);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetOMPFlag( HYPRE_IJMatrix matrix,
HYPRE_Int omp_flag )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixOMPFlag(ijmatrix) = omp_flag;
return hypre_error_flag;
}
|
ex02.c
|
#include <stdio.h>
#include <omp.h>
static long num_steps = 1000000;
double step;
int main(int argv, char* argc)
{
int num_threads;
double pi, total_sum = 0.0;
step = 1.0 / (double) num_steps;
int num_procs = omp_get_num_procs();
// omp_set_num_threads(num_procs);
double* sum;
int steps_per_thread;
// int num_threads = omp_get_num_threads(); // Sequential section always returns 1 thread -> Move to parallel section
double startTime = omp_get_wtime();
#pragma omp parallel
{
#pragma omp single
{
num_threads = omp_get_num_threads();
steps_per_thread = num_steps / num_threads;
sum = (double*) malloc(sizeof(double) * num_threads);
printf ("Found %d CPUs. Using %d threads and computing %d steps per thread.\n", num_procs, num_threads, steps_per_thread);
// Implicit barrier at the end
}
int i, id = omp_get_thread_num();
printf("Executing thread %d out of %d\n", id, num_threads);
double x;
for (i = id * steps_per_thread; i < (id + 1) * steps_per_thread; i++)
{
x = (i + 0.5) * step;
sum[id] += 4.0 / (1.0 + x * x);
}
}
int i;
for (i = 0; i < num_procs; i++)
total_sum += sum[i];
pi = step * total_sum;
double endTime = omp_get_wtime();
printf ("Computed integral: %f\n", pi);
printf ("Time elapsed: %f secs\n", (endTime - startTime));
return 0;
}
int main_serial(int argv, char* argc)
{
int i;
double x, pi, sum = 0.0;
step = 1.0 / (double) num_steps;
for (i = 0; i < num_steps; i++)
{
x = (i + 0.5) * step;
sum = sum + 4.0 / (1.0 + x * x);
}
pi = step * sum;
printf ("Computed integral: %f\n", pi);
return 0;
}
|
pbkdf2_hmac_sha256_fmt_plug.c
|
/* This software is Copyright (c) 2012 Lukas Odzioba <[email protected]>
* 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.
*
* Based on hmac-sha512 by magnum
*
* Minor fixes, format unification and OMP support done by Dhiru Kholia
* <[email protected]>
*
* Fixed for supporting $ml$ "dave" format as well as GRUB native format by
* magnum 2013. Note: We support a binary size of >512 bits (64 bytes / 128
* chars of hex) but we currently do not calculate it even in cmp_exact(). The
* chance for a 512-bit hash collision should be pretty dang slim.
*
* the pbkdf2_sha256_hmac was so messed up, I simply copied sha512 over the top
* of it, replacing the code in totality. JimF.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_pbkdf2_hmac_sha256;
#elif FMT_REGISTERS_H
john_register_one(&fmt_pbkdf2_hmac_sha256);
#else
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include "misc.h"
#include "arch.h"
#include "common.h"
#include "formats.h"
#include "base64_convert.h"
#include "sha2.h"
#include "johnswap.h"
#include "stdint.h"
#include "pbkdf2_hmac_sha256.h"
#include "pbkdf2_hmac_common.h"
#define FORMAT_LABEL "PBKDF2-HMAC-SHA256"
#define FORMAT_NAME ""
#ifdef SIMD_COEF_32
#define ALGORITHM_NAME "PBKDF2-SHA256 " SHA256_ALGORITHM_NAME
#else
#if ARCH_BITS >= 64
#define ALGORITHM_NAME "PBKDF2-SHA256 64/" ARCH_BITS_STR " " SHA2_LIB
#else
#define ALGORITHM_NAME "PBKDF2-SHA256 32/" ARCH_BITS_STR " " SHA2_LIB
#endif
#endif
#define MAX_CIPHERTEXT_LENGTH 1024 /* Bump this and code will adopt */
#define SALT_SIZE sizeof(struct custom_salt)
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
#define BENCHMARK_LENGTH -1
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 4
#endif
#endif
#include "memdbg.h"
#define PAD_SIZE 128
#define PLAINTEXT_LENGTH 125
static struct custom_salt {
uint8_t length;
uint8_t salt[PBKDF2_32_MAX_SALT_SIZE + 3];
uint32_t rounds;
} *cur_salt;
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static ARCH_WORD_32 (*crypt_out)[PBKDF2_SHA256_BINARY_SIZE / sizeof(ARCH_WORD_32)];
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
}
static void done(void)
{
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
static void *get_salt(char *ciphertext)
{
static struct custom_salt salt;
char *p, *c = ciphertext;
uint32_t rounds;
memset(&salt, 0, sizeof(salt));
c += PBKDF2_SHA256_TAG_LEN;
rounds = strtol(c, NULL, 10);
c = strchr(c, '$') + 1;
p = strchr(c, '$');
if (p-c==14 && rounds==20000) {
// for now, assume this is a cisco8 hash
strnzcpy((char*)(salt.salt), c, 15);
salt.length = 14;
salt.rounds = rounds;
return (void*)&salt;
}
salt.length = base64_convert(c, e_b64_mime, p-c, salt.salt, e_b64_raw, sizeof(salt.salt), flg_Base64_MIME_PLUS_TO_DOT, 0);
salt.rounds = rounds;
return (void *)&salt;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
}
static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; }
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT)
{
#ifdef SSE_GROUP_SZ_SHA256
int lens[SSE_GROUP_SZ_SHA256], i;
unsigned char *pin[SSE_GROUP_SZ_SHA256];
union {
ARCH_WORD_32 *pout[SSE_GROUP_SZ_SHA256];
unsigned char *poutc;
} x;
for (i = 0; i < SSE_GROUP_SZ_SHA256; ++i) {
lens[i] = strlen(saved_key[index+i]);
pin[i] = (unsigned char*)saved_key[index+i];
x.pout[i] = crypt_out[index+i];
}
pbkdf2_sha256_sse((const unsigned char **)pin, lens, cur_salt->salt, cur_salt->length, cur_salt->rounds, &(x.poutc), PBKDF2_SHA256_BINARY_SIZE, 0);
#else
pbkdf2_sha256((const unsigned char*)(saved_key[index]), strlen(saved_key[index]),
cur_salt->salt, cur_salt->length,
cur_salt->rounds, (unsigned char*)crypt_out[index], PBKDF2_SHA256_BINARY_SIZE, 0);
#endif
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
for (; index < count; index++)
if (!memcmp(binary, crypt_out[index], ARCH_SIZE))
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], PBKDF2_SHA256_BINARY_SIZE);
}
/* Check the FULL binary, just for good measure. There is no chance we'll
have a false positive here but this function is not performance sensitive.
This function not done linke pbkdf2_hmac_sha512. Simply return 1.
*/
static int cmp_exact(char *source, int index)
{
return 1;
}
static void set_key(char *key, int index)
{
int saved_len = strlen(key);
if (saved_len > PLAINTEXT_LENGTH)
saved_len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_len);
saved_key[index][saved_len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
static unsigned int iteration_count(void *salt)
{
struct custom_salt *my_salt;
my_salt = salt;
return (unsigned int) my_salt->rounds;
}
struct fmt_main fmt_pbkdf2_hmac_sha256 = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
PBKDF2_SHA256_BINARY_SIZE,
PBKDF2_32_BINARY_ALIGN,
SALT_SIZE,
sizeof(ARCH_WORD),
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
{
"iteration count",
},
{ PBKDF2_SHA256_FORMAT_TAG, FORMAT_TAG_CISCO8 },
pbkdf2_hmac_sha256_common_tests
}, {
init,
done,
fmt_default_reset,
pbkdf2_hmac_sha256_prepare,
pbkdf2_hmac_sha256_valid,
fmt_default_split,
pbkdf2_hmac_sha256_binary,
get_salt,
{
iteration_count,
},
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
omp_multiplicacao.c
|
/******************************************************************************
* FILE: mm.c
* DESCRIPTION:
* Matrix Multiply - C Version
* Modified from Blaise Barney OpenMP code.
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <sys/time.h>
#define NRA 2048 /* number of rows in matrix A */
#define NCA 2048 /* number of columns in matrix A */
#define NCB 2048 /* number of columns in matrix B */
//gcc omp_multiplicacao.c -fopenmp -o ompmultiplicacao
//for i in `seq 1 10`; do ./ompmultiplicacao; done
double wtime()
{
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec + t.tv_usec / 1000000.0;
}
int main (int argc, char *argv[])
{
int i, j, k;
double start_time, end_time;
// double a[NRA][NCA], /* matrix A to be multiplied */
// b[NCA][NCB], /* matrix B to be multiplied */
// c[NRA][NCB]; /* result matrix C */
double **a, **b, **c;
a = malloc(NRA*sizeof(double*));
for(i=0;i<NRA;i++){
a[i] = malloc(NCA*sizeof(double));
}
b = malloc(NCA*sizeof(double*));
for(i=0;i<NCA;i++){
b[i] = malloc(NCB*sizeof(double));
}
c = malloc(NRA*sizeof(double*));
for(i=0;i<NRA;i++){
c[i] = malloc(NCB*sizeof(double));
}
#pragma omp parallel private(i, j, k) shared(a, b, c)
{
/*** Initialize matrices ***/
#pragma omp for schedule(dynamic) nowait
for (i=0; i<NRA; i++)
for (j=0; j<NCA; j++)
a[i][j]= i+j;
#pragma omp for schedule(dynamic) nowait
for (i=0; i<NCA; i++)
for (j=0; j<NCB; j++)
b[i][j]= i*j;
#pragma omp for schedule(dynamic) nowait
for (i=0; i<NRA; i++)
for (j=0; j<NCB; j++)
c[i][j]= 0;
}
start_time = wtime();
#pragma omp parallel private(i, j, k) shared(a, b, c)
{
/*** Do matrix multiply ***/
#pragma omp for schedule(dynamic) nowait
for (i=0; i<NRA; i++)
for(j=0; j<NCB; j++)
for (k=0; k<NCA; k++)
c[i][j] += a[i][k] * b[k][j];
}
end_time = wtime();
/*** Print results ***/
/*
printf("******************************************************\n");
printf("Result Matrix:\n");
for (i=0; i<NRA; i++)
{
for (j=0; j<NCB; j++)
printf("%6.2f ", c[i][j]);
printf("\n");
}
printf("******************************************************\n");
*/
printf ("%f\n", end_time - start_time);
}
|
GB_unop__frexpe_fp64_fp64.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__frexpe_fp64_fp64
// op(A') function: GB_unop_tran__frexpe_fp64_fp64
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = GB_frexpe (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_frexpe (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = GB_frexpe (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_FREXPE || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__frexpe_fp64_fp64
(
double *Cx, // Cx and Ax may be aliased
const 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++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = GB_frexpe (z) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__frexpe_fp64_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
profile.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR OOO FFFFF IIIII L EEEEE %
% P P R R O O F I L E %
% PPPP RRRR O O FFF I L EEE %
% P R R O O F I L E %
% P R R OOO F IIIII LLLLL EEEEE %
% %
% %
% MagickCore Image Profile Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/configure.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/linked-list.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/option-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/profile-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H)
#include <wchar.h>
#include <lcms/lcms2.h>
#else
#include <wchar.h>
#include "lcms2.h"
#endif
#endif
#if defined(MAGICKCORE_XML_DELEGATE)
# if defined(MAGICKCORE_WINDOWS_SUPPORT)
# if !defined(__MINGW32__)
# include <win32config.h>
# endif
# endif
# include <libxml/parser.h>
# include <libxml/tree.h>
#endif
/*
Forward declarations
*/
static MagickBooleanType
SetImageProfileInternal(Image *,const char *,const StringInfo *,
const MagickBooleanType,ExceptionInfo *);
static void
WriteTo8BimProfile(Image *,const char*,const StringInfo *);
/*
Typedef declarations
*/
struct _ProfileInfo
{
char
*name;
size_t
length;
unsigned char
*info;
size_t
signature;
};
typedef struct _CMSExceptionInfo
{
Image
*image;
ExceptionInfo
*exception;
} CMSExceptionInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageProfiles() clones one or more image profiles.
%
% The format of the CloneImageProfiles method is:
%
% MagickBooleanType CloneImageProfiles(Image *image,
% const Image *clone_image)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone_image: the clone image.
%
*/
MagickExport MagickBooleanType CloneImageProfiles(Image *image,
const Image *clone_image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clone_image != (const Image *) NULL);
assert(clone_image->signature == MagickCoreSignature);
if (clone_image->profiles != (void *) NULL)
{
if (image->profiles != (void *) NULL)
DestroyImageProfiles(image);
image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles,
(void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e l e t e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeleteImageProfile() deletes a profile from the image by its name.
%
% The format of the DeleteImageProfile method is:
%
% MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return(MagickFalse);
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageProfiles() releases memory associated with an image profile map.
%
% The format of the DestroyProfiles method is:
%
% void DestroyImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImageProfiles(Image *image)
{
if (image->profiles != (SplayTreeInfo *) NULL)
image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageProfile() gets a profile associated with an image by name.
%
% The format of the GetImageProfile method is:
%
% const StringInfo *GetImageProfile(const Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport const StringInfo *GetImageProfile(const Image *image,
const char *name)
{
const StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t N e x t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNextImageProfile() gets the next profile name for an image.
%
% The format of the GetNextImageProfile method is:
%
% char *GetNextImageProfile(const Image *image)
%
% A description of each parameter follows:
%
% o hash_info: the hash info.
%
*/
MagickExport char *GetNextImageProfile(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((char *) NULL);
return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P r o f i l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ProfileImage() associates, applies, or removes an ICM, IPTC, or generic
% profile with / to / from an image. If the profile is NULL, it is removed
% from the image otherwise added or applied. Use a name of '*' and a profile
% of NULL to remove all profiles from the image.
%
% ICC and ICM profiles are handled as follows: If the image does not have
% an associated color profile, the one you provide is associated with the
% image and the image pixels are not transformed. Otherwise, the colorspace
% transform defined by the existing and new profile are applied to the image
% pixels and the new profile is associated with the image.
%
% The format of the ProfileImage method is:
%
% MagickBooleanType ProfileImage(Image *image,const char *name,
% const void *datum,const size_t length,const MagickBooleanType clone)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: Name of profile to add or remove: ICC, IPTC, or generic profile.
%
% o datum: the profile data.
%
% o length: the length of the profile.
%
% o clone: should be MagickFalse.
%
*/
#if defined(MAGICKCORE_LCMS_DELEGATE)
typedef struct _LCMSInfo
{
ColorspaceType
colorspace;
cmsUInt32Number
type;
size_t
channels;
cmsHPROFILE
profile;
int
intent;
double
scale,
translate;
void
**magick_restrict pixels;
} LCMSInfo;
#if LCMS_VERSION < 2060
static void* cmsGetContextUserData(cmsContext ContextID)
{
return(ContextID);
}
static cmsContext cmsCreateContext(void *magick_unused(Plugin),void *UserData)
{
magick_unreferenced(Plugin);
return((cmsContext) UserData);
}
static void cmsSetLogErrorHandlerTHR(cmsContext magick_unused(ContextID),
cmsLogErrorHandlerFunction Fn)
{
magick_unreferenced(ContextID);
cmsSetLogErrorHandler(Fn);
}
static void cmsDeleteContext(cmsContext magick_unused(ContextID))
{
magick_unreferenced(ContextID);
}
#endif
static void **DestroyPixelThreadSet(void **pixels)
{
register ssize_t
i;
if (pixels == (void **) NULL)
return((void **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (void *) NULL)
pixels[i]=RelinquishMagickMemory(pixels[i]);
pixels=(void **) RelinquishMagickMemory(pixels);
return(pixels);
}
static void **AcquirePixelThreadSet(const size_t columns,
const size_t channels,MagickBooleanType highres)
{
register ssize_t
i;
size_t
number_threads;
size_t
size;
void
**pixels;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(void **) AcquireQuantumMemory(number_threads,sizeof(*pixels));
if (pixels == (void **) NULL)
return((void **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
size=sizeof(double);
if (highres == MagickFalse)
size=sizeof(Quantum);
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=AcquireQuantumMemory(columns,channels*size);
if (pixels[i] == (void *) NULL)
return(DestroyPixelThreadSet(pixels));
}
return(pixels);
}
static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform)
{
register ssize_t
i;
assert(transform != (cmsHTRANSFORM *) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (transform[i] != (cmsHTRANSFORM) NULL)
cmsDeleteTransform(transform[i]);
transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform);
return(transform);
}
static cmsHTRANSFORM *AcquireTransformThreadSet(const LCMSInfo *source_info,
const LCMSInfo *target_info,const cmsUInt32Number flags,
cmsContext cms_context)
{
cmsHTRANSFORM
*transform;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads,
sizeof(*transform));
if (transform == (cmsHTRANSFORM *) NULL)
return((cmsHTRANSFORM *) NULL);
(void) memset(transform,0,number_threads*sizeof(*transform));
for (i=0; i < (ssize_t) number_threads; i++)
{
transform[i]=cmsCreateTransformTHR(cms_context,source_info->profile,
source_info->type,target_info->profile,target_info->type,
target_info->intent,flags);
if (transform[i] == (cmsHTRANSFORM) NULL)
return(DestroyTransformThreadSet(transform));
}
return(transform);
}
static void CMSExceptionHandler(cmsContext context,cmsUInt32Number severity,
const char *message)
{
CMSExceptionInfo
*cms_exception;
ExceptionInfo
*exception;
Image
*image;
cms_exception=(CMSExceptionInfo *) cmsGetContextUserData(context);
if (cms_exception == (CMSExceptionInfo *) NULL)
return;
exception=cms_exception->exception;
if (exception == (ExceptionInfo *) NULL)
return;
image=cms_exception->image;
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageWarning,
"UnableToTransformColorspace","`%s'","unknown context");
return;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s",
severity,message != (char *) NULL ? message : "no message");
(void) ThrowMagickException(exception,GetMagickModule(),ImageWarning,
"UnableToTransformColorspace","`%s', %s (#%u)",image->filename,
message != (char *) NULL ? message : "no message",severity);
}
static void TransformDoublePixels(const int id,const Image* image,
const LCMSInfo *source_info,const LCMSInfo *target_info,
const cmsHTRANSFORM *transform,Quantum *q)
{
#define GetLCMSPixel(source_info,pixel) \
(source_info->scale*QuantumScale*(pixel)+source_info->translate)
#define SetLCMSPixel(target_info,pixel) \
ClampToQuantum(target_info->scale*QuantumRange*(pixel)+target_info->translate)
register double
*p;
register ssize_t
x;
p=(double *) source_info->pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
*p++=GetLCMSPixel(source_info,GetPixelRed(image,q));
if (source_info->channels > 1)
{
*p++=GetLCMSPixel(source_info,GetPixelGreen(image,q));
*p++=GetLCMSPixel(source_info,GetPixelBlue(image,q));
}
if (source_info->channels > 3)
*p++=GetLCMSPixel(source_info,GetPixelBlack(image,q));
q+=GetPixelChannels(image);
}
cmsDoTransform(transform[id],source_info->pixels[id],
target_info->pixels[id],(unsigned int) image->columns);
p=(double *) target_info->pixels[id];
q-=GetPixelChannels(image)*image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (target_info->channels == 1)
SetPixelGray(image,SetLCMSPixel(target_info,*p),q);
else
SetPixelRed(image,SetLCMSPixel(target_info,*p),q);
p++;
if (target_info->channels > 1)
{
SetPixelGreen(image,SetLCMSPixel(target_info,*p),q);
p++;
SetPixelBlue(image,SetLCMSPixel(target_info,*p),q);
p++;
}
if (target_info->channels > 3)
{
SetPixelBlack(image,SetLCMSPixel(target_info,*p),q);
p++;
}
q+=GetPixelChannels(image);
}
}
static void TransformQuantumPixels(const int id,const Image* image,
const LCMSInfo *source_info,const LCMSInfo *target_info,
const cmsHTRANSFORM *transform,Quantum *q)
{
register Quantum
*p;
register ssize_t
x;
p=(Quantum *) source_info->pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
*p++=GetPixelRed(image,q);
if (source_info->channels > 1)
{
*p++=GetPixelGreen(image,q);
*p++=GetPixelBlue(image,q);
}
if (source_info->channels > 3)
*p++=GetPixelBlack(image,q);
q+=GetPixelChannels(image);
}
cmsDoTransform(transform[id],source_info->pixels[id],
target_info->pixels[id],(unsigned int) image->columns);
p=(Quantum *) target_info->pixels[id];
q-=GetPixelChannels(image)*image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (target_info->channels == 1)
SetPixelGray(image,*p++,q);
else
SetPixelRed(image,*p++,q);
if (target_info->channels > 1)
{
SetPixelGreen(image,*p++,q);
SetPixelBlue(image,*p++,q);
}
if (target_info->channels > 3)
SetPixelBlack(image,*p++,q);
q+=GetPixelChannels(image);
}
}
#endif
static MagickBooleanType SetsRGBImageProfile(Image *image,
ExceptionInfo *exception)
{
static unsigned char
sRGBProfile[] =
{
0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00,
0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a,
0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99,
0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67,
0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70,
0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c,
0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24,
0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14,
0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24,
0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14,
0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14,
0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14,
0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14,
0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14,
0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f,
0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36,
0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76,
0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77,
0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39,
0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c,
0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31,
0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75,
0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77,
0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20,
0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66,
0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d,
0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f,
0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20,
0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57,
0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65,
0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e,
0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20,
0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e,
0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61,
0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43,
0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c,
0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2,
0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d,
0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0,
0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87,
0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4,
0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19,
0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54,
0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90,
0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb,
0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d,
0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59,
0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1,
0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14,
0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84,
0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00,
0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a,
0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20,
0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4,
0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77,
0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37,
0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07,
0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5,
0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2,
0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf,
0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc,
0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9,
0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26,
0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64,
0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3,
0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13,
0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84,
0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06,
0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b,
0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41,
0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa,
0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5,
0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3,
0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94,
0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98,
0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf,
0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda,
0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18,
0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b,
0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1,
0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c,
0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb,
0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f,
0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37,
0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05,
0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8,
0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0,
0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee,
0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12,
0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b,
0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a,
0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00,
0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c,
0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f,
0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8,
0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78,
0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f,
0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d,
0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43,
0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60,
0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95,
0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1,
0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46,
0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2,
0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57,
0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04,
0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca,
0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8,
0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f,
0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf,
0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8,
0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a,
0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75,
0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea,
0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79,
0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21,
0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3,
0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf,
0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5,
0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6,
0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1,
0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36,
0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96,
0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11,
0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7,
0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57,
0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
};
StringInfo
*profile;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (GetImageProfile(image,"icc") != (const StringInfo *) NULL)
return(MagickFalse);
profile=AcquireStringInfo(sizeof(sRGBProfile));
SetStringInfoDatum(profile,sRGBProfile);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
return(status);
}
MagickExport MagickBooleanType ProfileImage(Image *image,const char *name,
const void *datum,const size_t length,ExceptionInfo *exception)
{
#define ProfileImageTag "Profile/Image"
#ifndef TYPE_XYZ_8
#define TYPE_XYZ_8 (COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(1))
#endif
#define ThrowProfileException(severity,tag,context) \
{ \
if (profile != (StringInfo *) NULL) \
profile=DestroyStringInfo(profile); \
if (cms_context != (cmsContext) NULL) \
cmsDeleteContext(cms_context); \
if (source_info.profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(source_info.profile); \
if (target_info.profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(target_info.profile); \
ThrowBinaryException(severity,tag,context); \
}
MagickBooleanType
status;
StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(name != (const char *) NULL);
if ((datum == (const void *) NULL) || (length == 0))
{
char
*next;
/*
Delete image profile(s).
*/
ResetImageProfileIterator(image);
for (next=GetNextImageProfile(image); next != (const char *) NULL; )
{
if (IsOptionMember(next,name) != MagickFalse)
{
(void) DeleteImageProfile(image,next);
ResetImageProfileIterator(image);
}
next=GetNextImageProfile(image);
}
return(MagickTrue);
}
/*
Add a ICC, IPTC, or generic profile to the image.
*/
status=MagickTrue;
profile=AcquireStringInfo((size_t) length);
SetStringInfoDatum(profile,(unsigned char *) datum);
if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0))
status=SetImageProfile(image,name,profile,exception);
else
{
const StringInfo
*icc_profile;
icc_profile=GetImageProfile(image,"icc");
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
const char
*value;
value=GetImageProperty(image,"exif:ColorSpace",exception);
(void) value;
if (LocaleCompare(value,"1") != 0)
(void) SetsRGBImageProfile(image,exception);
value=GetImageProperty(image,"exif:InteroperabilityIndex",exception);
if (LocaleCompare(value,"R98.") != 0)
(void) SetsRGBImageProfile(image,exception);
icc_profile=GetImageProfile(image,"icc");
}
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
profile=DestroyStringInfo(profile);
return(MagickTrue);
}
#if !defined(MAGICKCORE_LCMS_DELEGATE)
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (LCMS)",image->filename);
#else
{
cmsContext
cms_context;
CMSExceptionInfo
cms_exception;
LCMSInfo
source_info,
target_info;
/*
Transform pixel colors as defined by the color profiles.
*/
cms_exception.image=image;
cms_exception.exception=exception;
cms_context=cmsCreateContext(NULL,&cms_exception);
if (cms_context == (cmsContext) NULL)
ThrowBinaryException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
cmsSetLogErrorHandlerTHR(cms_context,CMSExceptionHandler);
source_info.profile=cmsOpenProfileFromMemTHR(cms_context,
GetStringInfoDatum(profile),(cmsUInt32Number)
GetStringInfoLength(profile));
if (source_info.profile == (cmsHPROFILE) NULL)
{
cmsDeleteContext(cms_context);
ThrowBinaryException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
}
if ((cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass) &&
(icc_profile == (StringInfo *) NULL))
status=SetImageProfile(image,name,profile,exception);
else
{
CacheView
*image_view;
cmsColorSpaceSignature
signature;
cmsHTRANSFORM
*magick_restrict transform;
cmsUInt32Number
flags;
#if !defined(MAGICKCORE_HDRI_SUPPORT)
const char
*artifact;
#endif
MagickBooleanType
highres;
MagickOffsetType
progress;
ssize_t
y;
target_info.profile=(cmsHPROFILE) NULL;
if (icc_profile != (StringInfo *) NULL)
{
target_info.profile=source_info.profile;
source_info.profile=cmsOpenProfileFromMemTHR(cms_context,
GetStringInfoDatum(icc_profile),
(cmsUInt32Number) GetStringInfoLength(icc_profile));
if (source_info.profile == (cmsHPROFILE) NULL)
ThrowProfileException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
}
highres=MagickTrue;
#if !defined(MAGICKCORE_HDRI_SUPPORT)
artifact=GetImageArtifact(image,"profile:highres-transform");
if (IsStringFalse(artifact) != MagickFalse)
highres=MagickFalse;
#endif
source_info.scale=1.0;
source_info.translate=0.0;
source_info.colorspace=sRGBColorspace;
source_info.channels=3;
switch (cmsGetColorSpace(source_info.profile))
{
case cmsSigCmykData:
{
source_info.colorspace=CMYKColorspace;
source_info.channels=4;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_CMYK_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_CMYK_16;
else
#endif
{
source_info.type=(cmsUInt32Number) TYPE_CMYK_DBL;
source_info.scale=100.0;
}
break;
}
case cmsSigGrayData:
{
source_info.colorspace=GRAYColorspace;
source_info.channels=1;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_GRAY_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_GRAY_16;
else
#endif
source_info.type=(cmsUInt32Number) TYPE_GRAY_DBL;
break;
}
case cmsSigLabData:
{
source_info.colorspace=LabColorspace;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_Lab_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_Lab_16;
else
#endif
{
source_info.type=(cmsUInt32Number) TYPE_Lab_DBL;
source_info.scale=100.0;
source_info.translate=(-0.5);
}
break;
}
case cmsSigRgbData:
{
source_info.colorspace=sRGBColorspace;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_RGB_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_RGB_16;
else
#endif
source_info.type=(cmsUInt32Number) TYPE_RGB_DBL;
break;
}
case cmsSigXYZData:
{
source_info.colorspace=XYZColorspace;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_XYZ_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_XYZ_16;
else
#endif
source_info.type=(cmsUInt32Number) TYPE_XYZ_DBL;
break;
}
default:
ThrowProfileException(ImageError,
"ColorspaceColorProfileMismatch",name);
}
signature=cmsGetPCS(source_info.profile);
if (target_info.profile != (cmsHPROFILE) NULL)
signature=cmsGetColorSpace(target_info.profile);
target_info.scale=1.0;
target_info.translate=0.0;
target_info.channels=3;
switch (signature)
{
case cmsSigCmykData:
{
target_info.colorspace=CMYKColorspace;
target_info.channels=4;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_CMYK_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_CMYK_16;
else
#endif
{
target_info.type=(cmsUInt32Number) TYPE_CMYK_DBL;
target_info.scale=0.01;
}
break;
}
case cmsSigGrayData:
{
target_info.colorspace=GRAYColorspace;
target_info.channels=1;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_GRAY_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_GRAY_16;
else
#endif
target_info.type=(cmsUInt32Number) TYPE_GRAY_DBL;
break;
}
case cmsSigLabData:
{
target_info.colorspace=LabColorspace;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_Lab_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_Lab_16;
else
#endif
{
target_info.type=(cmsUInt32Number) TYPE_Lab_DBL;
target_info.scale=0.01;
target_info.translate=0.5;
}
break;
}
case cmsSigRgbData:
{
target_info.colorspace=sRGBColorspace;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_RGB_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_RGB_16;
else
#endif
target_info.type=(cmsUInt32Number) TYPE_RGB_DBL;
break;
}
case cmsSigXYZData:
{
target_info.colorspace=XYZColorspace;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (highres == MagickFalse)
target_info.type=(cmsUInt32Number) TYPE_XYZ_8;
else
#elif (MAGICKCORE_QUANTUM_DEPTH == 16)
if (highres == MagickFalse)
source_info.type=(cmsUInt32Number) TYPE_XYZ_16;
else
#endif
target_info.type=(cmsUInt32Number) TYPE_XYZ_DBL;
break;
}
default:
ThrowProfileException(ImageError,
"ColorspaceColorProfileMismatch",name);
}
switch (image->rendering_intent)
{
case AbsoluteIntent:
{
target_info.intent=INTENT_ABSOLUTE_COLORIMETRIC;
break;
}
case PerceptualIntent:
{
target_info.intent=INTENT_PERCEPTUAL;
break;
}
case RelativeIntent:
{
target_info.intent=INTENT_RELATIVE_COLORIMETRIC;
break;
}
case SaturationIntent:
{
target_info.intent=INTENT_SATURATION;
break;
}
default:
{
target_info.intent=INTENT_PERCEPTUAL;
break;
}
}
flags=cmsFLAGS_HIGHRESPRECALC;
#if defined(cmsFLAGS_BLACKPOINTCOMPENSATION)
if (image->black_point_compensation != MagickFalse)
flags|=cmsFLAGS_BLACKPOINTCOMPENSATION;
#endif
transform=AcquireTransformThreadSet(&source_info,&target_info,
flags,cms_context);
if (transform == (cmsHTRANSFORM *) NULL)
ThrowProfileException(ImageError,"UnableToCreateColorTransform",
name);
/*
Transform image as dictated by the source & target image profiles.
*/
source_info.pixels=AcquirePixelThreadSet(image->columns,
source_info.channels,highres);
target_info.pixels=AcquirePixelThreadSet(image->columns,
target_info.channels,highres);
if ((source_info.pixels == (void **) NULL) ||
(target_info.pixels == (void **) NULL))
{
target_info.pixels=DestroyPixelThreadSet(target_info.pixels);
source_info.pixels=DestroyPixelThreadSet(source_info.pixels);
transform=DestroyTransformThreadSet(transform);
ThrowProfileException(ResourceLimitError,
"MemoryAllocationFailed",image->filename);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
target_info.pixels=DestroyPixelThreadSet(target_info.pixels);
source_info.pixels=DestroyPixelThreadSet(source_info.pixels);
transform=DestroyTransformThreadSet(transform);
if (source_info.profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(source_info.profile);
if (target_info.profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_info.profile);
return(MagickFalse);
}
if (target_info.colorspace == CMYKColorspace)
(void) SetImageColorspace(image,target_info.colorspace,exception);
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
if (highres != MagickFalse)
TransformDoublePixels(id,image,&source_info,&target_info,transform,q);
else
TransformQuantumPixels(id,image,&source_info,&target_info,transform,q);
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ProfileImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) SetImageColorspace(image,target_info.colorspace,exception);
switch (signature)
{
case cmsSigRgbData:
{
image->type=image->alpha_trait == UndefinedPixelTrait ?
TrueColorType : TrueColorAlphaType;
break;
}
case cmsSigCmykData:
{
image->type=image->alpha_trait == UndefinedPixelTrait ?
ColorSeparationType : ColorSeparationAlphaType;
break;
}
case cmsSigGrayData:
{
image->type=image->alpha_trait == UndefinedPixelTrait ?
GrayscaleType : GrayscaleAlphaType;
break;
}
default:
break;
}
target_info.pixels=DestroyPixelThreadSet(target_info.pixels);
source_info.pixels=DestroyPixelThreadSet(source_info.pixels);
transform=DestroyTransformThreadSet(transform);
if ((status != MagickFalse) &&
(cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass))
status=SetImageProfile(image,name,profile,exception);
if (target_info.profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_info.profile);
}
(void) cmsCloseProfile(source_info.profile);
cmsDeleteContext(cms_context);
}
#endif
}
profile=DestroyStringInfo(profile);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m o v e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemoveImageProfile() removes a named profile from the image and returns its
% value.
%
% The format of the RemoveImageProfile method is:
%
% void *RemoveImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name)
{
StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t P r o f i l e I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImageProfileIterator() resets the image profile iterator. Use it in
% conjunction with GetNextImageProfile() to iterate over all the profiles
% associated with an image.
%
% The format of the ResetImageProfileIterator method is:
%
% ResetImageProfileIterator(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void ResetImageProfileIterator(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return;
ResetSplayTreeIterator((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageProfile() adds a named profile to the image. If a profile with the
% same name already exists, it is replaced. This method differs from the
% ProfileImage() method in that it does not apply CMS color profiles.
%
% The format of the SetImageProfile method is:
%
% MagickBooleanType SetImageProfile(Image *image,const char *name,
% const StringInfo *profile)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name, for example icc, exif, and 8bim (8bim is the
% Photoshop wrapper for iptc profiles).
%
% o profile: A StringInfo structure that contains the named profile.
%
*/
static void *DestroyProfile(void *profile)
{
return((void *) DestroyStringInfo((StringInfo *) profile));
}
static inline const unsigned char *ReadResourceByte(const unsigned char *p,
unsigned char *quantum)
{
*quantum=(*p++);
return(p);
}
static inline const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(unsigned int) (*p++) << 24;
*quantum|=(unsigned int) (*p++) << 16;
*quantum|=(unsigned int) (*p++) << 8;
*quantum|=(unsigned int) (*p++);
return(p);
}
static inline const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++) << 8;
*quantum|=(unsigned short) (*p++);
return(p);
}
static inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) (quantum >> 24);
buffer[1]=(unsigned char) (quantum >> 16);
buffer[2]=(unsigned char) (quantum >> 8);
buffer[3]=(unsigned char) quantum;
(void) memcpy(p,buffer,4);
}
static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) memcpy(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) memcpy(extract_profile->datum,datum,offset-4);
WriteResourceLong(extract_profile->datum+offset-4,(unsigned int)
profile->length);
(void) memcpy(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) memcpy(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
static void GetProfilesFromResourceBlock(Image *image,
const StringInfo *resource_block,ExceptionInfo *exception)
{
const unsigned char
*datum;
register const unsigned char
*p;
size_t
length;
ssize_t
count;
StringInfo
*profile;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id;
datum=GetStringInfoDatum(resource_block);
length=GetStringInfoLength(resource_block);
for (p=datum; p < (datum+length-16); )
{
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0))
break;
switch (id)
{
case 0x03ed:
{
unsigned int
resolution;
unsigned short
units;
/*
Resolution.
*/
if (count < 10)
break;
p=ReadResourceLong(p,&resolution);
image->resolution.x=((double) resolution)/65536.0;
p=ReadResourceShort(p,&units)+2;
p=ReadResourceLong(p,&resolution)+4;
image->resolution.y=((double) resolution)/65536.0;
/*
Values are always stored as pixels per inch.
*/
if ((ResolutionType) units != PixelsPerCentimeterResolution)
image->units=PixelsPerInchResolution;
else
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x/=2.54;
image->resolution.y/=2.54;
}
break;
}
case 0x0404:
{
/*
IPTC Profile
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"iptc",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x040c:
{
/*
Thumbnail.
*/
p+=count;
break;
}
case 0x040f:
{
/*
ICC Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"icc",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0422:
{
/*
EXIF Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"exif",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0424:
{
/*
XMP Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"xmp",profile,MagickTrue,
exception);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
}
static void PatchCorruptProfile(const char *name,StringInfo *profile)
{
register unsigned char
*p;
size_t
length;
/*
Detect corrupt profiles and if discovered, repair.
*/
if (LocaleCompare(name,"xmp") == 0)
{
/*
Remove garbage after xpacket end.
*/
p=GetStringInfoDatum(profile);
p=(unsigned char *) strstr((const char *) p,"<?xpacket end=\"w\"?>");
if (p != (unsigned char *) NULL)
{
p+=19;
length=p-GetStringInfoDatum(profile);
if (length != GetStringInfoLength(profile))
{
*p='\0';
SetStringInfoLength(profile,length);
}
}
return;
}
if (LocaleCompare(name,"exif") == 0)
{
/*
Check if profile starts with byte order marker instead of Exif.
*/
p=GetStringInfoDatum(profile);
if ((LocaleNCompare((const char *) p,"MM",2) == 0) ||
(LocaleNCompare((const char *) p,"II",2) == 0))
{
const unsigned char
profile_start[] = "Exif\0\0";
StringInfo
*exif_profile;
exif_profile=AcquireStringInfo(6);
if (exif_profile != (StringInfo *) NULL)
{
SetStringInfoDatum(exif_profile,profile_start);
ConcatenateStringInfo(exif_profile,profile);
SetStringInfoLength(profile,GetStringInfoLength(exif_profile));
SetStringInfo(profile,exif_profile);
exif_profile=DestroyStringInfo(exif_profile);
}
}
}
}
#if defined(MAGICKCORE_XML_DELEGATE)
static MagickBooleanType ValidateXMPProfile(Image *image,
const StringInfo *profile,ExceptionInfo *exception)
{
xmlDocPtr
document;
/*
Parse XML profile.
*/
document=xmlReadMemory((const char *) GetStringInfoDatum(profile),(int)
GetStringInfoLength(profile),"xmp.xml",NULL,XML_PARSE_NOERROR |
XML_PARSE_NOWARNING);
if (document == (xmlDocPtr) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageWarning,
"CorruptImageProfile","`%s' (XMP)",image->filename);
return(MagickFalse);
}
xmlFreeDoc(document);
return(MagickTrue);
}
#else
static MagickBooleanType ValidateXMPProfile(Image *image,
const StringInfo *profile,ExceptionInfo *exception)
{
(void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError,
"DelegateLibrarySupportNotBuiltIn","'%s' (XML)",image->filename);
return(MagickFalse);
}
#endif
static MagickBooleanType SetImageProfileInternal(Image *image,const char *name,
const StringInfo *profile,const MagickBooleanType recursive,
ExceptionInfo *exception)
{
char
key[MagickPathExtent];
MagickBooleanType
status;
StringInfo
*clone_profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
clone_profile=CloneStringInfo(profile);
PatchCorruptProfile(name,clone_profile);
if ((LocaleCompare(name,"xmp") == 0) &&
(ValidateXMPProfile(image,clone_profile,exception) == MagickFalse))
{
clone_profile=DestroyStringInfo(clone_profile);
return(MagickTrue);
}
if (image->profiles == (SplayTreeInfo *) NULL)
image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
DestroyProfile);
(void) CopyMagickString(key,name,MagickPathExtent);
LocaleLower(key);
status=AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString(key),clone_profile);
if (status != MagickFalse)
{
if (LocaleCompare(name,"8bim") == 0)
GetProfilesFromResourceBlock(image,clone_profile,exception);
else
if (recursive == MagickFalse)
WriteTo8BimProfile(image,name,clone_profile);
}
return(status);
}
MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name,
const StringInfo *profile,ExceptionInfo *exception)
{
return(SetImageProfileInternal(image,name,profile,MagickFalse,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageProfiles() synchronizes image properties with the image profiles.
% Currently we only support updating the EXIF resolution and orientation.
%
% The format of the SyncImageProfiles method is:
%
% MagickBooleanType SyncImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static inline int ReadProfileByte(unsigned char **p,size_t *length)
{
int
c;
if (*length < 1)
return(EOF);
c=(int) (*(*p)++);
(*length)--;
return(c);
}
static inline signed short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
static inline signed int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length)
{
signed int
value;
if (*length < 4)
return(0);
value=ReadProfileLong(MSBEndian,*p);
(*length)-=4;
*p+=4;
return(value);
}
static inline signed short ReadProfileMSBShort(unsigned char **p,
size_t *length)
{
signed short
value;
if (*length < 2)
return(0);
value=ReadProfileShort(MSBEndian,*p);
(*length)-=2;
*p+=2;
return(value);
}
static inline void WriteProfileLong(const EndianType endian,
const size_t value,unsigned char *p)
{
unsigned char
buffer[4];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
(void) memcpy(p,buffer,4);
return;
}
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
(void) memcpy(p,buffer,4);
}
static void WriteProfileShort(const EndianType endian,
const unsigned short value,unsigned char *p)
{
unsigned char
buffer[2];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
(void) memcpy(p,buffer,2);
return;
}
buffer[0]=(unsigned char) (value >> 8);
buffer[1]=(unsigned char) value;
(void) memcpy(p,buffer,2);
}
static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile)
{
size_t
length;
ssize_t
count;
unsigned char
*p;
unsigned short
id;
length=GetStringInfoLength(profile);
p=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadProfileByte(&p,&length) != 0x38)
continue;
if (ReadProfileByte(&p,&length) != 0x42)
continue;
if (ReadProfileByte(&p,&length) != 0x49)
continue;
if (ReadProfileByte(&p,&length) != 0x4D)
continue;
if (length < 7)
return(MagickFalse);
id=ReadProfileMSBShort(&p,&length);
count=(ssize_t) ReadProfileByte(&p,&length);
if ((count >= (ssize_t) length) || (count < 0))
return(MagickFalse);
p+=count;
length-=count;
if ((*p & 0x01) == 0)
(void) ReadProfileByte(&p,&length);
count=(ssize_t) ReadProfileMSBLong(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
if ((id == 0x3ED) && (count == 16))
{
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x*2.54*
65536.0),p);
else
WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x*
65536.0),p);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4);
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y*2.54*
65536.0),p+8);
else
WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y*
65536.0),p+8);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12);
}
p+=count;
length-=count;
}
return(MagickTrue);
}
MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
SplayTreeInfo
*exif_resources;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadProfileLong(endian,exif+4);
if ((offset < 0) || ((size_t) offset >= length))
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
int
components;
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
if (q > (exif+length-12))
break; /* corrupt EXIF */
if (GetValueFromSplayTree(exif_resources,q) == q)
break;
(void) AddValueToSplayTree(exif_resources,q,q);
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))
break;
components=(int) ReadProfileLong(endian,q+4);
if (components < 0)
break; /* corrupt EXIF */
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadProfileLong(endian,q+8);
if ((offset < 0) || ((size_t) (offset+number_bytes) > length))
continue;
if (~length < number_bytes)
continue; /* prevent overflow */
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p);
if (number_bytes == 8)
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p);
if (number_bytes == 8)
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
offset=(ssize_t) ReadProfileLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
exif_resources=DestroySplayTree(exif_resources);
return(MagickTrue);
}
MagickPrivate MagickBooleanType SyncImageProfiles(Image *image)
{
MagickBooleanType
status;
StringInfo
*profile;
status=MagickTrue;
profile=(StringInfo *) GetImageProfile(image,"8BIM");
if (profile != (StringInfo *) NULL)
if (Sync8BimProfile(image,profile) == MagickFalse)
status=MagickFalse;
profile=(StringInfo *) GetImageProfile(image,"EXIF");
if (profile != (StringInfo *) NULL)
if (SyncExifProfile(image,profile) == MagickFalse)
status=MagickFalse;
return(status);
}
static void UpdateClipPath(unsigned char *blob,size_t length,
const size_t old_columns,const size_t old_rows,
const RectangleInfo *new_geometry)
{
register ssize_t
i;
ssize_t
knot_count,
selector;
knot_count=0;
while (length != 0)
{
selector=(ssize_t) ReadProfileMSBShort(&blob,&length);
switch (selector)
{
case 0:
case 3:
{
if (knot_count != 0)
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Expected subpath length record.
*/
knot_count=(ssize_t) ReadProfileMSBShort(&blob,&length);
blob+=22;
length-=MagickMin(22,(ssize_t) length);
break;
}
case 1:
case 2:
case 4:
case 5:
{
if (knot_count == 0)
{
/*
Unexpected subpath knot.
*/
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Add sub-path knot
*/
for (i=0; i < 3; i++)
{
double
x,
y;
signed int
xx,
yy;
y=(double) ReadProfileMSBLong(&blob,&length);
y=y*old_rows/4096/4096;
y-=new_geometry->y;
yy=(signed int) ((y*4096*4096)/new_geometry->height);
WriteProfileLong(MSBEndian,(size_t) yy,blob-4);
x=(double) ReadProfileMSBLong(&blob,&length);
x=x*old_columns/4096/4096;
x-=new_geometry->x;
xx=(signed int) ((x*4096*4096)/new_geometry->width);
WriteProfileLong(MSBEndian,(size_t) xx,blob-4);
}
knot_count--;
break;
}
case 6:
case 7:
case 8:
default:
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
}
}
}
MagickPrivate void Update8BIMClipPath(const Image *image,
const size_t old_columns,const size_t old_rows,
const RectangleInfo *new_geometry)
{
const StringInfo
*profile;
size_t
length;
ssize_t
count,
id;
unsigned char
*info;
assert(image != (Image *) NULL);
assert(new_geometry != (RectangleInfo *) NULL);
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while (length > 0)
{
if (ReadProfileByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadProfileByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadProfileByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadProfileByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadProfileMSBShort(&info,&length);
count=(ssize_t) ReadProfileByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
info+=count;
length-=count;
}
if ((count & 0x01) == 0)
(void) ReadProfileByte(&info,&length);
count=(ssize_t) ReadProfileMSBLong(&info,&length);
if ((count < 0) || ((size_t) count > length))
{
length=0;
continue;
}
if ((id > 1999) && (id < 2999))
UpdateClipPath(info,(size_t) count,old_columns,old_rows,new_geometry);
info+=count;
length-=MagickMin(count,(ssize_t) length);
}
}
|
rgb_matrix.h
|
#ifndef RGB_MATRIX_H
#define RGB_MATRIX_H
#include <stdio.h>
#include <math.h>
#define PIX_MAX_NORM 1
#define PIX_MIN_NORM 0
/*
* Represents symetric 2x2 matrix that contains RGB values of the given pixel.
* Top left element represents R value, bottom left B value and other 2 elements G value.
*/
template<typename T>
struct RGBMatrix {
T r;
T g;
T b;
//Constructor of struct RGBmatrix
__host__ __device__ RGBMatrix(T r, T g, T b) : r(r), g(g), b(b) {}
//Default constructor of struct RGBMatrix. All values are set to 0.0
__host__ __device__ RGBMatrix() : RGBMatrix(0.0, 0.0, 0.0) {}
/*
* Converts the image vector containing rgb values to the vector containing
* rgb matrices. Memory for the new vector needs to be allocated and passed
* as a vector argument. It should be array of RGBMatrix values which size is equal
* as the size of the image. Pointers r, g and b are the pointers to the values
* of the red, green and blue
*/
static void __host__ __device__ rgb2matrix(T *r, T *g, T *b, RGBMatrix<T> *vector, int size);
/*
* Converts the vector containing RGBMatrices to vector containina RGB values.
*/
static void __host__ __device__ matrix2rgb(RGBMatrix<T> *vector, T *r, T *g, T *b, int size);
//Prints RGBMatrix
void __host__ __device__ print();
//Returns minimal RGBMatrix
static RGBMatrix __host__ __device__ min();
//Return maximal RGBMatrix
static RGBMatrix __host__ __device__ max();
//Represents operator <. Matrices are ordered in terms of lexicographic order due to the RGB values
template<typename U>
friend bool __host__ __device__ operator<(RGBMatrix<U> &a, RGBMatrix<U> &b);
//Represents operator >. Matrices are ordered in terms of lexicographic order due to the RGB values
template<typename U>
friend bool __host__ __device__ operator>(RGBMatrix<U> &a, RGBMatrix<U> &b);
};
template<typename T>
void __host__ __device__ RGBMatrix<T>::print() {
printf("(%f, %f, %f)", r, g, b);
}
template<typename T>
void __host__ __device__ RGBMatrix<T>::rgb2matrix(T *r, T *g, T *b, RGBMatrix<T> *vector, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
RGBMatrix *temp = vector + i;
temp->r = r[i];
temp->g = g[i];
temp->b = b[i];
}
}
template<typename T>
void __host__ __device__ RGBMatrix<T>::matrix2rgb(RGBMatrix<T> *vector, T *r, T *g, T *b, int size) {
#pragma omp parallel for
for (int i = 0; i < size; i++) {
RGBMatrix *temp = vector + i;
r[i] = temp->r;
g[i] = temp->g;
b[i] = temp->b;
}
}
template<typename T>
bool __host__ __device__ operator<(RGBMatrix<T> &a, RGBMatrix<T> &b) {
if (a.r < b.r) {
return true;
} else if (a.r == b.r) {
if (a.g < b.g) {
return true;
} else if (a.g == b.g) {
return (a.b < b.b);
} else {
return false;
}
} else {
return false;
}
}
template<typename T>
bool __host__ __device__ operator>(RGBMatrix<T> &a, RGBMatrix<T> &b) {
if (a.r > b.r) {
return true;
} else if (a.r == b.r) {
if (a.g > b.g) {
return true;
} else if (a.g == b.g) {
return (a.b > b.b);
} else {
return false;
}
} else {
return false;
}
}
template<typename T>
RGBMatrix<T> __host__ __device__ RGBMatrix<T>::max() {
return RGBMatrix<T>(PIX_MAX_NORM, PIX_MAX_NORM, PIX_MAX_NORM);
}
template<typename T>
RGBMatrix<T> __host__ __device__ RGBMatrix<T>::min() {
return RGBMatrix<T>(PIX_MIN_NORM, PIX_MIN_NORM, PIX_MIN_NORM);
}
#endif
|
r32x16b_avx2.c
|
/*
* AVX2 edition using 32 RANS states. This uses a shared pointer for the
* compressed buffer.
*
* TODO: implement SIMD version of the order-1 encoder (decoder is done).
*/
#ifdef _MSC_VER
#include <intrin.h>
#pragma warning(push)
#pragma warning(disable: 4752)
#if _MSC_VER < 1910
inline __forceinline __int64 _mm256_extract_epi64(__m256i a, const int index)
{
return ((__int64 *)&a)[index];
}
#endif
#else
#include <x86intrin.h>
#endif
#define NX 32
/*-------------------------------------------------------------------------- */
/* rans_byte.h from https://github.com/rygorous/ryg_rans */
// Simple byte-aligned rANS encoder/decoder - public domain - Fabian 'ryg' Giesen 2014
//
// Not intended to be "industrial strength"; just meant to illustrate the general
// idea.
#ifndef RANS_BYTE_HEADER
#define RANS_BYTE_HEADER
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <immintrin.h>
#ifdef assert
#define RansAssert assert
#else
#define RansAssert(x)
#endif
// READ ME FIRST:
//
// This is designed like a typical arithmetic coder API, but there's three
// twists you absolutely should be aware of before you start hacking:
//
// 1. You need to encode data in *reverse* - last symbol first. rANS works
// like a stack: last in, first out.
// 2. Likewise, the encoder outputs bytes *in reverse* - that is, you give
// it a pointer to the *end* of your buffer (exclusive), and it will
// slowly move towards the beginning as more bytes are emitted.
// 3. Unlike basically any other entropy coder implementation you might
// have used, you can interleave data from multiple independent rANS
// encoders into the same bytestream without any extra signaling;
// you can also just write some bytes by yourself in the middle if
// you want to. This is in addition to the usual arithmetic encoder
// property of being able to switch models on the fly. Writing raw
// bytes can be useful when you have some data that you know is
// incompressible, and is cheaper than going through the rANS encode
// function. Using multiple rANS coders on the same byte stream wastes
// a few bytes compared to using just one, but execution of two
// independent encoders can happen in parallel on superscalar and
// Out-of-Order CPUs, so this can be *much* faster in tight decoding
// loops.
//
// This is why all the rANS functions take the write pointer as an
// argument instead of just storing it in some context struct.
// --------------------------------------------------------------------------
// L ('l' in the paper) is the lower bound of our normalization interval.
// Between this and our byte-aligned emission, we use 31 (not 32!) bits.
// This is done intentionally because exact reciprocals for 31-bit uints
// fit in 32-bit uints: this permits some optimizations during encoding.
#define RANS_BYTE_L (1u << 15) // lower bound of our normalization interval
// State for a rANS encoder. Yep, that's all there is to it.
typedef uint32_t RansState;
// Initialize a rANS encoder.
static inline void RansEncInit(RansState* r)
{
*r = RANS_BYTE_L;
}
#ifdef INACTIVE
// Renormalize the encoder. Internal function.
static inline RansState RansEncRenorm(RansState x, uint8_t** pptr, uint32_t freq, uint32_t scale_bits)
{
uint32_t x_max = ((RANS_BYTE_L >> scale_bits) << 8) * freq - 1; // this turns into a shift.
if (x > x_max) {
uint8_t* ptr = *pptr;
do {
*--ptr = (uint8_t)(x & 0xff);
x >>= 8;
} while (x > x_max);
*pptr = ptr;
}
return x;
}
// Encodes a single symbol with range start "start" and frequency "freq".
// All frequencies are assumed to sum to "1 << scale_bits", and the
// resulting bytes get written to ptr (which is updated).
//
// NOTE: With rANS, you need to encode symbols in *reverse order*, i.e. from
// beginning to end! Likewise, the output bytestream is written *backwards*:
// ptr starts pointing at the end of the output buffer and keeps decrementing.
static inline void RansEncPut(RansState* r, uint8_t** pptr, uint32_t start, uint32_t freq, uint32_t scale_bits)
{
// renormalize
RansState x = RansEncRenorm(*r, pptr, freq, scale_bits);
// x = C(s,x)
*r = ((x / freq) << scale_bits) + (x % freq) + start;
}
#endif
// Flushes the rANS encoder.
static inline void RansEncFlush(RansState* r, uint8_t** pptr)
{
uint32_t x = *r;
uint8_t* ptr = *pptr;
ptr -= 4;
ptr[0] = (uint8_t)(x >> 0);
ptr[1] = (uint8_t)(x >> 8);
ptr[2] = (uint8_t)(x >> 16);
ptr[3] = (uint8_t)(x >> 24);
*pptr = ptr;
}
// Initializes a rANS decoder.
// Unlike the encoder, the decoder works forwards as you'd expect.
static inline void RansDecInit(RansState* r, uint8_t** pptr)
{
uint32_t x;
uint8_t* ptr = *pptr;
x = ptr[0] << 0;
x |= ptr[1] << 8;
x |= ptr[2] << 16;
x |= ptr[3] << 24;
ptr += 4;
*pptr = ptr;
*r = x;
}
#ifdef INACTIVE
// Returns the current cumulative frequency (map it to a symbol yourself!)
static inline uint32_t RansDecGet(RansState* r, uint32_t scale_bits)
{
return *r & ((1u << scale_bits) - 1);
}
// Advances in the bit stream by "popping" a single symbol with range start
// "start" and frequency "freq". All frequencies are assumed to sum to "1 << scale_bits",
// and the resulting bytes get written to ptr (which is updated).
static inline void RansDecAdvance(RansState* r, uint8_t** pptr, uint32_t start, uint32_t freq, uint32_t scale_bits)
{
uint32_t mask = (1u << scale_bits) - 1;
// s, x = D(x)
uint32_t x = *r;
x = freq * (x >> scale_bits) + (x & mask) - start;
// renormalize
if (x < RANS_BYTE_L) {
uint8_t* ptr = *pptr;
do x = (x << 8) | *ptr++; while (x < RANS_BYTE_L);
*pptr = ptr;
}
*r = x;
}
#endif
// --------------------------------------------------------------------------
// That's all you need for a full encoder; below here are some utility
// functions with extra convenience or optimizations.
// Encoder symbol description
// This (admittedly odd) selection of parameters was chosen to make
// RansEncPutSymbol as cheap as possible.
typedef struct {
uint32_t x_max; // (Exclusive) upper bound of pre-normalization interval
uint32_t rcp_freq; // Fixed-point reciprocal frequency
uint32_t bias; // Bias
uint32_t SD; // combined cmpl_freq & shift
uint16_t cmpl_freq; // Complement of frequency: (1 << scale_bits) - freq
uint16_t rcp_shift; // Reciprocal shift
uint16_t freq;
uint16_t start;
uint32_t padding1;
//uint32_t padding2;
} RansEncSymbol;
// Decoder symbols are straightforward.
typedef struct {
uint16_t start; // Start of range.
uint16_t freq; // Symbol frequency.
} RansDecSymbol;
// Initializes an encoder symbol to start "start" and frequency "freq"
static inline void RansEncSymbolInit(RansEncSymbol* s, uint32_t start, uint32_t freq, uint32_t scale_bits)
{
RansAssert(scale_bits <= 16);
RansAssert(start <= (1u << scale_bits));
RansAssert(freq <= (1u << scale_bits) - start);
// Say M := 1 << scale_bits.
//
// The original encoder does:
// x_new = (x/freq)*M + start + (x%freq)
//
// The fast encoder does (schematically):
// q = mul_hi(x, rcp_freq) >> rcp_shift (division)
// r = x - q*freq (remainder)
// x_new = q*M + bias + r (new x)
// plugging in r into x_new yields:
// x_new = bias + x + q*(M - freq)
// =: bias + x + q*cmpl_freq (*)
//
// and we can just precompute cmpl_freq. Now we just need to
// set up our parameters such that the original encoder and
// the fast encoder agree.
#ifdef FP_DIV
//s->scale_bits = scale_bits;
s->freq = freq;
s->start = start;
#endif
s->x_max = ((RANS_BYTE_L >> scale_bits) << 16) * freq - 1;
s->cmpl_freq = (uint16_t)((1 << scale_bits) - freq);
if (freq < 2) {
// freq=0 symbols are never valid to encode, so it doesn't matter what
// we set our values to.
//
// freq=1 is tricky, since the reciprocal of 1 is 1; unfortunately,
// our fixed-point reciprocal approximation can only multiply by values
// smaller than 1.
//
// So we use the "next best thing": rcp_freq=0xffffffff, rcp_shift=0.
// This gives:
// q = mul_hi(x, rcp_freq) >> rcp_shift
// = mul_hi(x, (1<<32) - 1)) >> 0
// = floor(x - x/(2^32))
// = x - 1 if 1 <= x < 2^32
// and we know that x>0 (x=0 is never in a valid normalization interval).
//
// So we now need to choose the other parameters such that
// x_new = x*M + start
// plug it in:
// x*M + start (desired result)
// = bias + x + q*cmpl_freq (*)
// = bias + x + (x - 1)*(M - 1) (plug in q=x-1, cmpl_freq)
// = bias + 1 + (x - 1)*M
// = x*M + (bias + 1 - M)
//
// so we have start = bias + 1 - M, or equivalently
// bias = start + M - 1.
s->rcp_freq = ~0u;
s->rcp_shift = 0;
s->bias = start + (1 << scale_bits) - 1;
}
else {
// Alverson, "Integer Division using reciprocals"
// shift=ceil(log2(freq))
uint32_t shift = 0;
while (freq > (1u << shift))
shift++;
s->rcp_freq = (uint32_t)(((1ull << (shift + 31)) + freq - 1) / freq);
s->rcp_shift = (uint16_t)(shift - 1);
// With these values, 'q' is the correct quotient, so we
// have bias=start.
s->bias = start;
}
s->rcp_shift += 32; // Avoid the extra >>32 in RansEncPutSymbol
s->SD = s->cmpl_freq | (s->rcp_shift << 16);
}
#ifdef INACTIVE
// Initialize a decoder symbol to start "start" and frequency "freq"
static inline void RansDecSymbolInit(RansDecSymbol* s, uint32_t start, uint32_t freq)
{
RansAssert(start <= (1 << 16));
RansAssert(freq <= (1 << 16) - start);
s->start = (uint16_t)start;
s->freq = (uint16_t)freq;
}
#endif
// Encodes a given symbol. This is faster than straight RansEnc since we can do
// multiplications instead of a divide.
//
// See RansEncSymbolInit for a description of how this works.
static inline void RansEncPutSymbol(RansState* r, uint8_t** pptr, RansEncSymbol const* sym)
{
//RansAssert(sym->x_max != 0); // can't encode symbol with freq=0
// renormalize
uint32_t x = *r;
uint32_t x_max = sym->x_max;
if (x > x_max) {
uint16_t* ptr = *(uint16_t **)pptr;
*--ptr = (uint16_t)(x & 0xffff);
x >>= 16;
*pptr = (uint8_t *)ptr;
}
// x = C(s,x)
// NOTE: written this way so we get a 32-bit "multiply high" when
// available. If you're on a 64-bit platform with cheap multiplies
// (e.g. x64), just bake the +32 into rcp_shift.
//uint32_t q = (uint32_t) (((uint64_t)x * sym->rcp_freq) >> 32) >> sym->rcp_shift;
// Slow method, but robust
// *r = ((x / sym->freq) << sym->scale_bits) + (x % sym->freq) + sym->start;
// return;
// The extra >>32 has already been added to RansEncSymbolInit
uint32_t q = (uint32_t)(((uint64_t)x * sym->rcp_freq) >> sym->rcp_shift);
*r = x + sym->bias + q * sym->cmpl_freq;
// assert(((x / sym->freq) << sym->scale_bits) + (x % sym->freq) + sym->start == *r);
}
#ifdef INACTIVE
// Equivalent to RansDecAdvance that takes a symbol.
static inline void RansDecAdvanceSymbol(RansState* r, uint8_t** pptr, RansDecSymbol const* sym, uint32_t scale_bits)
{
RansDecAdvance(r, pptr, sym->start, sym->freq, scale_bits);
}
#endif
#ifdef INACTIVE
// Advances in the bit stream by "popping" a single symbol with range start
// "start" and frequency "freq". All frequencies are assumed to sum to "1 << scale_bits".
// No renormalization or output happens.
static inline void RansDecAdvanceStep(RansState* r, uint32_t start, uint32_t freq, uint32_t scale_bits)
{
uint32_t mask = (1u << scale_bits) - 1;
// s, x = D(x)
uint32_t x = *r;
*r = freq * (x >> scale_bits) + (x & mask) - start;
}
#endif
#ifdef INACTIVE
// Equivalent to RansDecAdvanceStep that takes a symbol.
static inline void RansDecAdvanceSymbolStep(RansState* r, RansDecSymbol const* sym, uint32_t scale_bits)
{
RansDecAdvanceStep(r, sym->start, sym->freq, scale_bits);
}
#endif
// Renormalize.
static inline void RansDecRenorm(RansState* r, uint8_t** pptr)
{
// renormalize
uint32_t x = *r;
#ifndef USE_ASM
// Better on Atom?
//
// clang 464, gcc 485
if (x >= RANS_BYTE_L) return;
uint16_t* ptr = *(uint16_t **)pptr;
x = (x << 16) | *ptr++;
*pptr = (uint8_t *)ptr;
// clang 335, gcc 687
// uint32_t c = x < RANS_BYTE_L;
// uint16_t* ptr = *(uint16_t **)pptr;
// uint32_t y = (x << 16) | *ptr;
// x = c ? y : x;
// ptr += c;
// *pptr = (uint8_t *)ptr;
#else
// clang 596, gcc 650
uint16_t *ptr = *(uint16_t **)pptr;
__asm__("movzwl (%0), %%eax\n\t"
"mov %1, %%edx\n\t"
"shl $0x10, %%edx\n\t"
"or %%eax, %%edx\n\t"
"xor %%eax, %%eax\n\t"
"cmp $0x8000,%1\n\t"
"cmovb %%edx, %1\n\t"
"lea 2(%0), %%rax\n\t"
"cmovb %%rax, %0\n\t"
: "=r" (ptr), "=r" (x)
: "0" (ptr), "1" (x)
: "eax", "edx"
);
*pptr = (uint8_t *)ptr;
*pptr = (uint8_t *)ptr;
#endif
*r = x;
}
#endif // RANS_BYTE_HEADER
/*-------------------------------------------------------------------------- */
/*
* Example wrapper to use the rans_byte.h functions included above.
*
* This demonstrates how to use, and unroll, an order-0 and order-1 frequency
* model.
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include "permute.h"
#ifndef TF_SHIFT
# define TF_SHIFT 12
#endif
#define TOTFREQ (1<<TF_SHIFT)
// 9 is considerably faster on some data sets due to reduced table size.
#ifndef TF_SHIFT_O1
# define TF_SHIFT_O1 9
#endif
#define TOTFREQ_O1 (1<<TF_SHIFT_O1)
/*-----------------------------------------------------------------------------
* Memory to memory compression functions.
*
* These are original versions without any manual loop unrolling. They
* are easier to understand, but can be up to 2x slower.
*/
#define MAGIC 8
#ifdef UNUSED
static void hist1(unsigned char *in, unsigned int in_size, int F0[256]) {
int i;
for (i = 0; i < in_size; i++)
F0[in[i]]++;
}
static void hist4p(unsigned char *in, unsigned int in_size, int *F0) {
int F1[256 + MAGIC] = { 0 }, F2[256 + MAGIC] = { 0 }, F3[256 + MAGIC] = { 0 };
int i;
unsigned char *in_end4 = in + (in_size & ~3);
unsigned char *in_end = in + in_size;
while (in < in_end4) {
F0[*in++]++;
F1[*in++]++;
F2[*in++]++;
F3[*in++]++;
}
while (in < in_end)
F0[*in++]++;
for (i = 0; i < 256; i++)
F0[i] += F1[i] + F2[i] + F3[i];
}
#endif
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
static void hist8(unsigned char *in, unsigned int in_size, int F0[256]) {
int F1[256 + MAGIC] = { 0 }, F2[256 + MAGIC] = { 0 }, F3[256 + MAGIC] = { 0 };
int F4[256 + MAGIC] = { 0 }, F5[256 + MAGIC] = { 0 }, F6[256 + MAGIC] = { 0 }, F7[256 + MAGIC] = { 0 };
size_t i, i4 = ((in_size - 4) & ~7) / 4; // permits vnext
uint32_t *in4 = (uint32_t *)in;
uint32_t vnext = i4 ? in4[0] : 0;
for (i = 0; i < i4; i += 2) {
uint32_t v = vnext; vnext = in4[i + 1];
F0[(unsigned char)(v >> 0)]++;
F1[(unsigned char)(v >> 8)]++;
F2[(unsigned char)(v >> 16)]++;
F3[(unsigned char)(v >> 24)]++;
v = vnext; vnext = in4[i + 2];
F4[(unsigned char)(v >> 0)]++;
F5[(unsigned char)(v >> 8)]++;
F6[(unsigned char)(v >> 16)]++;
F7[(unsigned char)(v >> 24)]++;
}
i *= 4;
while (i < in_size)
F0[in[i++]]++;
for (i = 0; i < 256; i++)
F0[i] += F1[i] + F2[i] + F3[i] + F4[i] + F5[i] + F6[i] + F7[i];
}
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned int rans_compress_bound_32x16_AVX2(unsigned int size, int order, int *tab) {
int tabsz = order == 0
? 257 * 3 + 4 + NX * 4 + NX * 4
: 257 * 257 * 3 + 4 + NX * 4 + NX * 4;
if (tab) *tab = tabsz;
return (int)(1.05*size + NX * 4 + tabsz);
}
// _mm256__mul_epu32 is:
// -b -d -f -h
//* -q -s -u -w
//= BQ DS FU HW where BQ=b*q etc
//
// We want
// abcd efgh (a)
// *pqrs tuvw (b)
// =ABCD EFGH
//
// a mul b => BQ DS FU HW
// >>= 8 => -B QD SF UH
// & => -B -D -F -H (1)
// a>>8 mul b>>8 => AP CR ET GV
// & => A- C- E- G-
// | with (1) => AB CD EF GH
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
#if 0
static __m256i _mm256_mulhi_epu32(__m256i a, __m256i b) {
__m256i ab_lm = _mm256_mul_epu32(a, b);
ab_lm = _mm256_srli_epi64(ab_lm, 32);
a = _mm256_srli_epi64(a, 32);
ab_lm = _mm256_and_si256(ab_lm, _mm256_set1_epi64x(0xffffffff));
b = _mm256_srli_epi64(b, 32);
__m256i ab_hm = _mm256_mul_epu32(a, b);
ab_hm = _mm256_and_si256(ab_hm, _mm256_set1_epi64x((uint64_t)0xffffffff00000000));
ab_hm = _mm256_or_si256(ab_hm, ab_lm);
return ab_hm;
}
#else
static __m256i _mm256_mulhi_epu32(__m256i a, __m256i b) {
// Multiply bottom 4 items and top 4 items together.
__m256i ab_hm = _mm256_mul_epu32(_mm256_srli_epi64(a, 32), _mm256_srli_epi64(b, 32));
__m256i ab_lm = _mm256_srli_epi64(_mm256_mul_epu32(a, b), 32);
// Shift to get hi 32-bit of each 64-bit product
ab_hm = _mm256_and_si256(ab_hm, _mm256_set1_epi64x((uint64_t)0xffffffff00000000));
return _mm256_or_si256(ab_lm, ab_hm);
}
#endif
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
#if 0
__m256i _mm256_div_epi32(__m256i a, __m256i b) {
return _mm256_cvttps_epi32(_mm256_div_ps(_mm256_cvtepi32_ps(a),
_mm256_cvtepi32_ps(b)));
}
#else
__m256i _mm256_div_epi32(__m256i a, __m256i b) {
__m256d a1 = _mm256_cvtepi32_pd(_mm256_extracti128_si256(a, 0));
__m256d b1 = _mm256_cvtepi32_pd(_mm256_extracti128_si256(b, 0));
__m128i ab1 = _mm256_cvttpd_epi32(_mm256_div_pd(a1, b1));
__m256d a2 = _mm256_cvtepi32_pd(_mm256_extracti128_si256(a, 1));
__m256d b2 = _mm256_cvtepi32_pd(_mm256_extracti128_si256(b, 1));
__m128i ab2 = _mm256_cvttpd_epi32(_mm256_div_pd(a2, b2));
return _mm256_inserti128_si256(_mm256_castsi128_si256(ab1), ab2, 1);
}
#endif
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
#if 1
// Simulated gather. This is sometimes faster as it can run on other ports.
static inline __m256i _mm256_i32gather_epi32x(int *b, __m256i idx, int size) {
(void)size;
#ifndef _MSC_VER
int c[8] __attribute__((aligned(32)));
#else
_declspec(align(32))
int c[8];
#endif
_mm256_store_si256((__m256i *)c, idx);
return _mm256_set_epi32(b[c[7]], b[c[6]], b[c[5]], b[c[4]], b[c[3]], b[c[2]], b[c[1]], b[c[0]]);
}
#else
#define _mm256_i32gather_epi32x _mm256_i32gather_epi32
#endif
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_compress_O0_32x16_AVX2(unsigned char *in, unsigned int in_size,
unsigned char *out, unsigned int *out_size) {
unsigned char *cp, *out_end;
RansEncSymbol syms[256];
#ifndef _MSC_VER
RansState ransN[NX] __attribute__((aligned(32)));
#else
_declspec(align(32))
RansState ransN[NX];
#endif
uint8_t* ptr;
int F[256 + MAGIC] = { 0 }, i, j, tab_size, rle, x, fsum = 0;
int m = 0, M = 0;
int tabsz;
int bound = rans_compress_bound_32x16_AVX2(in_size, 0, &tabsz), z;
//uint64_t sym_mf[256], sym_bfs[256];
//uint32_t SD[256], SC[256], SB[256], SA[256];
uint32_t SB[256], SA[256], SD[256], SC[256];
#ifdef FP_DIV
uint32_t FS[256];
#endif
if (!out) {
*out_size = bound;
out = malloc(*out_size);
}
if (!out || (int64_t)bound > (int64_t)*out_size) {
return NULL;
}
ptr = out_end = out + bound;
// Compute statistics
hist8(in, in_size, F);
double p = (double)TOTFREQ / (double)in_size;
// Normalise so T[i] == TOTFREQ
for (m = M = j = 0; j < 256; j++) {
if (!F[j])
continue;
if (m < F[j])
m = F[j], M = j;
if ((F[j] = (int)(F[j] * p + 0.499)) == 0)
F[j] = 1;
fsum += F[j];
}
fsum++; // not needed, but can't remove without removing assert x<TOTFREQ (in old code)
int adjust = TOTFREQ - fsum;
if (adjust > 0) {
F[M] += adjust;
}
else if (adjust < 0) {
if (F[M] > -adjust) {
F[M] += adjust;
}
else {
adjust += F[M] - 1;
F[M] = 1;
for (j = 0; adjust && j < 256; j++) {
if (F[j] < 2) continue;
int d = F[j] > -adjust;
int m_ = d ? adjust : 1 - F[j];
F[j] += m_;
adjust -= m_;
}
}
}
//printf("F[%d]=%d\n", M, F[M]);
assert(F[M]>0);
// Encode statistics.
cp = out + 4;
for (x = rle = j = 0; j < 256; j++) {
if (F[j]) {
// j
if (rle) {
rle--;
}
else {
*cp++ = (unsigned char)j;
if (!rle && j && F[j - 1]) {
for (rle = j + 1; rle<256 && F[rle]; rle++)
;
rle -= j + 1;
*cp++ = (unsigned char)rle;
}
//fprintf(stderr, "%d: %d %d\n", j, rle, N[j]);
}
// F[j]
if (F[j]<128) {
*cp++ = (unsigned char)F[j];
}
else {
*cp++ = (unsigned char)(128 | (F[j] >> 8));
*cp++ = (unsigned char)(F[j] & 0xff);
}
RansEncSymbolInit(&syms[j], x, F[j], TF_SHIFT);
//SB[j] = syms[j].x_max;
//SA[i] = syms[j].rcp_freq;
//SD[i] = (syms[j].cmpl_freq<<0) | (syms[j].rcp_shift<<16);
//SC[i] = syms[j].bias;
x += F[j];
}
}
*cp++ = (unsigned char)0;
//write(2, out+4, cp-(out+4));
tab_size = (int)(cp - out);
for (z = 0; z < NX; z++)
RansEncInit(&ransN[z]);
z = i = in_size & (NX - 1);
while (z-- > 0)
RansEncPutSymbol(&ransN[z], &ptr, &syms[in[in_size - (i - z)]]);
for (i = 0; i < 256; i++) {
//sym_mf[i] = syms[i].rcp_freq | (((uint64_t)syms[i].x_max)<<32);
#ifdef FP_DIV
SB[i] = syms[i].x_max;
FS[i] = (syms[i].freq) | (syms[i].start << 16);
#else
SB[i] = syms[i].x_max;
SA[i] = syms[i].rcp_freq;
SD[i] = (syms[i].cmpl_freq << 0) | (syms[i].rcp_shift << 16);
SC[i] = syms[i].bias;
#endif
}
uint16_t *ptr16 = (uint16_t *)ptr;
#define LOAD1(a,b) __m256i a##1 = _mm256_load_si256((__m256i *)&b[0]);
#define LOAD2(a,b) __m256i a##2 = _mm256_load_si256((__m256i *)&b[8]);
#define LOAD3(a,b) __m256i a##3 = _mm256_load_si256((__m256i *)&b[16]);
#define LOAD4(a,b) __m256i a##4 = _mm256_load_si256((__m256i *)&b[24]);
#define LOAD(a,b) LOAD1(a,b);LOAD2(a,b);LOAD3(a,b);LOAD4(a,b)
#define STORE1(a,b) _mm256_store_si256((__m256i *)&b[0], a##1);
#define STORE2(a,b) _mm256_store_si256((__m256i *)&b[8], a##2);
#define STORE3(a,b) _mm256_store_si256((__m256i *)&b[16], a##3);
#define STORE4(a,b) _mm256_store_si256((__m256i *)&b[24], a##4);
#define STORE(a,b) STORE1(a,b);STORE2(a,b);STORE3(a,b);STORE4(a,b)
LOAD(Rv, ransN);
for (i = (in_size &~(NX - 1)); i>0; i -= NX) {
uint8_t *c = &in[i - 32];
// Set vs gather methods of loading data.
// Gather is faster, but can only schedule a few to run in parallel.
#define SET1(a,b) __m256i a##1 = _mm256_set_epi32(b[c[ 7]], b[c[ 6]], b[c[ 5]], b[c[ 4]], b[c[ 3]], b[c[ 2]], b[c[ 1]], b[c[ 0]])
#define SET2(a,b) __m256i a##2 = _mm256_set_epi32(b[c[15]], b[c[14]], b[c[13]], b[c[12]], b[c[11]], b[c[10]], b[c[ 9]], b[c[ 8]])
#define SET3(a,b) __m256i a##3 = _mm256_set_epi32(b[c[23]], b[c[22]], b[c[21]], b[c[20]], b[c[19]], b[c[18]], b[c[17]], b[c[16]])
#define SET4(a,b) __m256i a##4 = _mm256_set_epi32(b[c[31]], b[c[30]], b[c[29]], b[c[28]], b[c[27]], b[c[26]], b[c[25]], b[c[24]])
#define SET(a,b) SET1(a,b);SET2(a,b);SET3(a,b);SET4(a,b)
// Renorm:
// if (x > x_max) {*--ptr16 = x & 0xffff; x >>= 16;}
SET(xmax, SB);
__m256i cv1 = _mm256_cmpgt_epi32(Rv1, xmax1);
__m256i cv2 = _mm256_cmpgt_epi32(Rv2, xmax2);
__m256i cv3 = _mm256_cmpgt_epi32(Rv3, xmax3);
__m256i cv4 = _mm256_cmpgt_epi32(Rv4, xmax4);
// Store bottom 16-bits at ptr16
unsigned int imask1 = _mm256_movemask_ps(*(__m256 *)&(cv1));
unsigned int imask2 = _mm256_movemask_ps(*(__m256 *)&(cv2));
unsigned int imask3 = _mm256_movemask_ps(*(__m256 *)&(cv3));
unsigned int imask4 = _mm256_movemask_ps(*(__m256 *)&(cv4));
__m256i idx1 = _mm256_load_si256((const __m256i*)permutec[imask1]);
__m256i idx2 = _mm256_load_si256((const __m256i*)permutec[imask2]);
__m256i idx3 = _mm256_load_si256((const __m256i*)permutec[imask3]);
__m256i idx4 = _mm256_load_si256((const __m256i*)permutec[imask4]);
// Permute; to gather together the rans states that need flushing
__m256i V1 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv1, cv1), idx1);
__m256i V2 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv2, cv2), idx2);
__m256i V3 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv3, cv3), idx3);
__m256i V4 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv4, cv4), idx4);
// We only flush bottom 16 bits, to squash 32-bit states into 16 bit.
V1 = _mm256_and_si256(V1, _mm256_set1_epi32(0xffff));
V2 = _mm256_and_si256(V2, _mm256_set1_epi32(0xffff));
V3 = _mm256_and_si256(V3, _mm256_set1_epi32(0xffff));
V4 = _mm256_and_si256(V4, _mm256_set1_epi32(0xffff));
__m256i V12 = _mm256_packus_epi32(V1, V2);
__m256i V34 = _mm256_packus_epi32(V3, V4);
// It's BAba order, want BbAa so shuffle.
V12 = _mm256_permute4x64_epi64(V12, 0xd8);
V34 = _mm256_permute4x64_epi64(V34, 0xd8);
// Now we have bottom N 16-bit values in each V12/V34 to flush
__m128i f = _mm256_extractf128_si256(V34, 1);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask4);
f = _mm256_extractf128_si256(V34, 0);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask3);
f = _mm256_extractf128_si256(V12, 1);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask2);
f = _mm256_extractf128_si256(V12, 0);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask1);
__m256i Rs;
Rs = _mm256_srli_epi32(Rv1, 16); Rv1 = _mm256_blendv_epi8(Rv1, Rs, cv1);
Rs = _mm256_srli_epi32(Rv2, 16); Rv2 = _mm256_blendv_epi8(Rv2, Rs, cv2);
Rs = _mm256_srli_epi32(Rv3, 16); Rv3 = _mm256_blendv_epi8(Rv3, Rs, cv3);
Rs = _mm256_srli_epi32(Rv4, 16); Rv4 = _mm256_blendv_epi8(Rv4, Rs, cv4);
// Cannot trivially replace the multiply as mulhi_epu32 doesn't exist (only mullo).
// However we can use _mm256_mul_epu32 twice to get 64bit results (half our lanes)
// and shift/or to get the answer.
//
// (AVX512 allows us to hold it all in 64-bit lanes and use mullo_epi64
// plus a shift. KNC has mulhi_epi32, but not sure if this is available.)
#ifndef FP_DIV
SET(rfv, SA);
rfv1 = _mm256_mulhi_epu32(Rv1, rfv1);
rfv2 = _mm256_mulhi_epu32(Rv2, rfv2);
rfv3 = _mm256_mulhi_epu32(Rv3, rfv3);
rfv4 = _mm256_mulhi_epu32(Rv4, rfv4);
SET(SDv, SD);
__m256i shiftv1 = _mm256_srli_epi32(SDv1, 16);
__m256i shiftv2 = _mm256_srli_epi32(SDv2, 16);
__m256i shiftv3 = _mm256_srli_epi32(SDv3, 16);
__m256i shiftv4 = _mm256_srli_epi32(SDv4, 16);
shiftv1 = _mm256_sub_epi32(shiftv1, _mm256_set1_epi32(32));
shiftv2 = _mm256_sub_epi32(shiftv2, _mm256_set1_epi32(32));
shiftv3 = _mm256_sub_epi32(shiftv3, _mm256_set1_epi32(32));
shiftv4 = _mm256_sub_epi32(shiftv4, _mm256_set1_epi32(32));
__m256i qv1 = _mm256_srlv_epi32(rfv1, shiftv1);
__m256i qv2 = _mm256_srlv_epi32(rfv2, shiftv2);
__m256i freqv1 = _mm256_and_si256(SDv1, _mm256_set1_epi32(0xffff));
__m256i freqv2 = _mm256_and_si256(SDv2, _mm256_set1_epi32(0xffff));
qv1 = _mm256_mullo_epi32(qv1, freqv1);
qv2 = _mm256_mullo_epi32(qv2, freqv2);
__m256i qv3 = _mm256_srlv_epi32(rfv3, shiftv3);
__m256i qv4 = _mm256_srlv_epi32(rfv4, shiftv4);
__m256i freqv3 = _mm256_and_si256(SDv3, _mm256_set1_epi32(0xffff));
__m256i freqv4 = _mm256_and_si256(SDv4, _mm256_set1_epi32(0xffff));
qv3 = _mm256_mullo_epi32(qv3, freqv3);
qv4 = _mm256_mullo_epi32(qv4, freqv4);
SET(biasv, SC);
qv1 = _mm256_add_epi32(qv1, biasv1);
qv2 = _mm256_add_epi32(qv2, biasv2);
qv3 = _mm256_add_epi32(qv3, biasv3);
qv4 = _mm256_add_epi32(qv4, biasv4);
Rv1 = _mm256_add_epi32(Rv1, qv1);
Rv2 = _mm256_add_epi32(Rv2, qv2);
Rv3 = _mm256_add_epi32(Rv3, qv3);
Rv4 = _mm256_add_epi32(Rv4, qv4);
#else
// slow method:
// *r = ((x / sym->freq) << sym->scale_bits) + (x % sym->freq) + sym->start;
// xdiv = x/freq;
// xmod = x - xd * f;
// R = xdiv << TF_SHIFT;
// R += xmod;
// R += start;
SET(FSv, FS);
__m256i Fv1 = _mm256_and_si256(FSv1, _mm256_set1_epi32(0xffff));
__m256i Fv2 = _mm256_and_si256(FSv2, _mm256_set1_epi32(0xffff));
__m256i Fv3 = _mm256_and_si256(FSv3, _mm256_set1_epi32(0xffff));
__m256i Fv4 = _mm256_and_si256(FSv4, _mm256_set1_epi32(0xffff));
__m256i Sv1 = _mm256_srli_epi32(FSv1, 16);
__m256i Sv2 = _mm256_srli_epi32(FSv2, 16);
__m256i Sv3 = _mm256_srli_epi32(FSv3, 16);
__m256i Sv4 = _mm256_srli_epi32(FSv4, 16);
__m256i Rdiv1 = _mm256_div_epi32(Rv1, Fv1);
__m256i Rdiv2 = _mm256_div_epi32(Rv2, Fv2);
__m256i Rdiv3 = _mm256_div_epi32(Rv3, Fv3);
__m256i Rdiv4 = _mm256_div_epi32(Rv4, Fv4);
__m256i Rmod1 = _mm256_sub_epi32(Rv1, _mm256_mullo_epi32(Rdiv1, Fv1));
__m256i Rmod2 = _mm256_sub_epi32(Rv2, _mm256_mullo_epi32(Rdiv2, Fv2));
__m256i Rmod3 = _mm256_sub_epi32(Rv3, _mm256_mullo_epi32(Rdiv3, Fv3));
__m256i Rmod4 = _mm256_sub_epi32(Rv4, _mm256_mullo_epi32(Rdiv4, Fv4));
Rv1 = _mm256_slli_epi32(Rdiv1, TF_SHIFT);
Rv2 = _mm256_slli_epi32(Rdiv2, TF_SHIFT);
Rv3 = _mm256_slli_epi32(Rdiv3, TF_SHIFT);
Rv4 = _mm256_slli_epi32(Rdiv4, TF_SHIFT);
Rv1 = _mm256_add_epi32(Rv1, Rmod1);
Rv2 = _mm256_add_epi32(Rv2, Rmod2);
Rv3 = _mm256_add_epi32(Rv3, Rmod3);
Rv4 = _mm256_add_epi32(Rv4, Rmod4);
Rv1 = _mm256_add_epi32(Rv1, Sv1);
Rv2 = _mm256_add_epi32(Rv2, Sv2);
Rv3 = _mm256_add_epi32(Rv3, Sv3);
Rv4 = _mm256_add_epi32(Rv4, Sv4);
#endif
}
STORE(Rv, ransN);
ptr = (uint8_t *)ptr16;
for (z = NX - 1; z >= 0; z--)
RansEncFlush(&ransN[z], &ptr);
// Finalise block size and return it
*out_size = (unsigned int)((out_end - ptr) + tab_size);
cp = out;
*cp++ = (in_size >> 0) & 0xff;
*cp++ = (in_size >> 8) & 0xff;
*cp++ = (in_size >> 16) & 0xff;
*cp++ = (in_size >> 24) & 0xff;
memmove(out + tab_size, ptr, out_end - ptr);
return out;
}
typedef struct {
unsigned char R[TOTFREQ];
} ari_decoder;
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_uncompress_O0_32x16_AVX2(unsigned char *in, unsigned int in_size,
unsigned char *out, unsigned int *out_size) {
(void)in_size;
/* Load in the static tables */
unsigned char *cp = in + 4;
int i, j, x, y, out_sz, rle;
//uint16_t sfreq[TOTFREQ+32];
//uint16_t sbase[TOTFREQ+32]; // faster to use 32-bit on clang
uint8_t ssym[TOTFREQ + 64]; // faster to use 16-bit on clang
#ifndef _MSC_VER
uint32_t s3[TOTFREQ] __attribute__((aligned(32))); // For TF_SHIFT <= 12
#else
_declspec(align(32))
uint32_t s3[TOTFREQ]; // For TF_SHIFT <= 12
#endif
out_sz = ((in[0]) << 0) | ((in[1]) << 8) | ((in[2]) << 16) | ((in[3]) << 24);
if (!out) {
out = malloc(out_sz);
*out_size = out_sz;
}
if (!out || (int64_t)out_sz > (int64_t)*out_size)
return NULL;
// Precompute reverse lookup of frequency.
rle = x = y = 0;
j = *cp++;
do {
int F, C;
if ((F = *cp++) >= 128) {
F &= ~128;
F = ((F & 127) << 8) | *cp++;
}
C = x;
for (y = 0; y < F; y++) {
ssym[y + C] = (uint8_t)j;
//sfreq[y + C] = F;
//sbase[y + C] = y;
s3[y + C] = (((uint32_t)F) << (TF_SHIFT + 8)) | (y << 8) | j;
}
x += F;
if (!rle && j + 1 == *cp) {
j = *cp++;
rle = *cp++;
}
else if (rle) {
rle--;
j++;
}
else {
j = *cp++;
}
} while (j);
assert(x < TOTFREQ);
int z;
#ifndef _MSC_VER
RansState R[NX] __attribute__((aligned(32)));
#else
_declspec(align(32))
RansState R[NX];
#endif
for (z = 0; z < NX; z++)
RansDecInit(&R[z], &cp);
uint16_t *sp = (uint16_t *)cp;
int out_end = (out_sz&~(NX - 1));
const uint32_t mask = (1u << TF_SHIFT) - 1;
__m256i maskv = _mm256_set1_epi32(mask); // set mask in all lanes
LOAD(Rv, R);
for (i = 0; i < out_end; i += NX) {
//for (z = 0; z < NX; z++)
// m[z] = R[z] & mask;
__m256i masked1 = _mm256_and_si256(Rv1, maskv);
__m256i masked2 = _mm256_and_si256(Rv2, maskv);
// S[z] = s3[m[z]];
__m256i Sv1 = _mm256_i32gather_epi32x((int *)s3, masked1, sizeof(*s3));
__m256i Sv2 = _mm256_i32gather_epi32x((int *)s3, masked2, sizeof(*s3));
// f[z] = S[z]>>(TF_SHIFT+8);
__m256i fv1 = _mm256_srli_epi32(Sv1, TF_SHIFT + 8);
__m256i fv2 = _mm256_srli_epi32(Sv2, TF_SHIFT + 8);
// b[z] = (S[z]>>8) & mask;
__m256i bv1 = _mm256_and_si256(_mm256_srli_epi32(Sv1, 8), maskv);
__m256i bv2 = _mm256_and_si256(_mm256_srli_epi32(Sv2, 8), maskv);
// s[z] = S[z] & 0xff;
__m256i sv1 = _mm256_and_si256(Sv1, _mm256_set1_epi32(0xff));
__m256i sv2 = _mm256_and_si256(Sv2, _mm256_set1_epi32(0xff));
// R[z] = f[z] * (R[z] >> TF_SHIFT) + b[z];
Rv1 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv1, TF_SHIFT), fv1), bv1);
Rv2 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv2, TF_SHIFT), fv2), bv2);
// Tricky one: out[i+z] = s[z];
// ---h---g ---f---e ---d---c ---b---a
// ---p---o ---n---m ---l---k ---j---i
// packs_epi32 -p-o-n-m -h-g-f-e -l-k-j-i -d-c-b-a
// permute4x64 -p-o-n-m -l-k-j-i -h-g-f-e -d-c-b-a
// packs_epi16 ponmlkji ponmlkji hgfedcba hgfedcba
sv1 = _mm256_packus_epi32(sv1, sv2);
sv1 = _mm256_permute4x64_epi64(sv1, 0xd8);
__m256i Vv1 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
sv1 = _mm256_packus_epi16(sv1, sv1);
// c = R[z] < RANS_BYTE_L;
__m256i renorm_mask1 = _mm256_xor_si256(Rv1, _mm256_set1_epi32(0x80000000));
__m256i renorm_mask2 = _mm256_xor_si256(Rv2, _mm256_set1_epi32(0x80000000));
renorm_mask1 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask1);
renorm_mask2 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask2);
// y = (R[z] << 16) | V[z];
unsigned int imask1 = _mm256_movemask_ps(*(__m256 *)&renorm_mask1);
__m256i idx1 = _mm256_load_si256((const __m256i*)permute[imask1]);
__m256i Yv1 = _mm256_slli_epi32(Rv1, 16);
Vv1 = _mm256_permutevar8x32_epi32(Vv1, idx1);
__m256i Yv2 = _mm256_slli_epi32(Rv2, 16);
// Shuffle the renorm values to correct lanes and incr sp pointer
unsigned int imask2 = _mm256_movemask_ps(*(__m256 *)&renorm_mask2);
sp += _mm_popcnt_u32(imask1);
__m256i idx2 = _mm256_load_si256((const __m256i*)permute[imask2]);
__m256i Vv2 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
sp += _mm_popcnt_u32(imask2);
Yv1 = _mm256_or_si256(Yv1, Vv1);
Vv2 = _mm256_permutevar8x32_epi32(Vv2, idx2);
Yv2 = _mm256_or_si256(Yv2, Vv2);
// R[z] = c ? Y[z] : R[z];
Rv1 = _mm256_blendv_epi8(Rv1, Yv1, renorm_mask1);
Rv2 = _mm256_blendv_epi8(Rv2, Yv2, renorm_mask2);
// ------------------------------------------------------------
// m[z] = R[z] & mask;
// S[z] = s3[m[z]];
__m256i masked3 = _mm256_and_si256(Rv3, maskv);
__m256i Sv3 = _mm256_i32gather_epi32x((int *)s3, masked3, sizeof(*s3));
*(uint64_t *)&out[i + 0] = _mm256_extract_epi64(sv1, 0);
*(uint64_t *)&out[i + 8] = _mm256_extract_epi64(sv1, 2);
__m256i masked4 = _mm256_and_si256(Rv4, maskv);
__m256i Sv4 = _mm256_i32gather_epi32x((int *)s3, masked4, sizeof(*s3));
// f[z] = S[z]>>(TF_SHIFT+8);
__m256i fv3 = _mm256_srli_epi32(Sv3, TF_SHIFT + 8);
__m256i fv4 = _mm256_srli_epi32(Sv4, TF_SHIFT + 8);
// b[z] = (S[z]>>8) & mask;
__m256i bv3 = _mm256_and_si256(_mm256_srli_epi32(Sv3, 8), maskv);
__m256i bv4 = _mm256_and_si256(_mm256_srli_epi32(Sv4, 8), maskv);
// s[z] = S[z] & 0xff;
__m256i sv3 = _mm256_and_si256(Sv3, _mm256_set1_epi32(0xff));
__m256i sv4 = _mm256_and_si256(Sv4, _mm256_set1_epi32(0xff));
// R[z] = f[z] * (R[z] >> TF_SHIFT) + b[z];
Rv3 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv3, TF_SHIFT), fv3), bv3);
Rv4 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv4, TF_SHIFT), fv4), bv4);
// Tricky one: out[i+z] = s[z];
// ---h---g ---f---e ---d---c ---b---a
// ---p---o ---n---m ---l---k ---j---i
// packs_epi32 -p-o-n-m -h-g-f-e -l-k-j-i -d-c-b-a
// permute4x64 -p-o-n-m -l-k-j-i -h-g-f-e -d-c-b-a
// packs_epi16 ponmlkji ponmlkji hgfedcba hgfedcba
sv3 = _mm256_packus_epi32(sv3, sv4);
sv3 = _mm256_permute4x64_epi64(sv3, 0xd8);
__m256i renorm_mask3 = _mm256_xor_si256(Rv3, _mm256_set1_epi32(0x80000000));
__m256i renorm_mask4 = _mm256_xor_si256(Rv4, _mm256_set1_epi32(0x80000000));
sv3 = _mm256_packus_epi16(sv3, sv3);
// c = R[z] < RANS_BYTE_L;
renorm_mask3 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask3);
renorm_mask4 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask4);
*(uint64_t *)&out[i + 16] = _mm256_extract_epi64(sv3, 0);
*(uint64_t *)&out[i + 24] = _mm256_extract_epi64(sv3, 2);
// y = (R[z] << 16) | V[z];
__m256i Vv3 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
__m256i Yv3 = _mm256_slli_epi32(Rv3, 16);
unsigned int imask3 = _mm256_movemask_ps(*(__m256 *)&renorm_mask3);
__m256i idx3 = _mm256_load_si256((const __m256i*)permute[imask3]);
// Shuffle the renorm values to correct lanes and incr sp pointer
Vv3 = _mm256_permutevar8x32_epi32(Vv3, idx3);
__m256i Yv4 = _mm256_slli_epi32(Rv4, 16);
unsigned int imask4 = _mm256_movemask_ps(*(__m256 *)&renorm_mask4);
sp += _mm_popcnt_u32(imask3);
__m256i idx4 = _mm256_load_si256((const __m256i*)permute[imask4]);
__m256i Vv4 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
//Vv = _mm256_and_si256(Vv, renorm_mask); (blend does the AND anyway)
Yv3 = _mm256_or_si256(Yv3, Vv3);
Vv4 = _mm256_permutevar8x32_epi32(Vv4, idx4);
Yv4 = _mm256_or_si256(Yv4, Vv4);
sp += _mm_popcnt_u32(imask4);
// R[z] = c ? Y[z] : R[z];
Rv3 = _mm256_blendv_epi8(Rv3, Yv3, renorm_mask3);
Rv4 = _mm256_blendv_epi8(Rv4, Yv4, renorm_mask4);
}
STORE(Rv, R);
//_mm256_store_si256((__m256i *)&R[0], Rv1);
//_mm256_store_si256((__m256i *)&R[8], Rv2);
//_mm256_store_si256((__m256i *)&R[16], Rv3);
//_mm256_store_si256((__m256i *)&R[24], Rv4);
//#pragma omp simd
// for (z = 0; z < NX; z++) {
// uint32_t m = R[z] & mask;
// R[z] = sfreq[m] * (R[z] >> TF_SHIFT) + sbase[m];
// out[i+z] = ssym[m];
// uint32_t c = R[z] < RANS_BYTE_L; // NX16=>166MB/s
// uint32_t y = (R[z] << 16) | *spN[z];
// spN[z] += c ? 1 : 0;
// R[z] = c ? y : R[z];
//
// }
// }
for (z = out_sz & (NX - 1); z-- > 0; )
out[out_end + z] = ssym[R[z] & mask];
*out_size = out_sz;
return out;
}
#ifdef UNUSED
static void hist1_1(unsigned char *in, unsigned int in_size,
int F0[256][256], int T0[256]) {
unsigned int last_i, i;
unsigned char c;
for (last_i = i = 0; i<in_size; i++) {
F0[last_i][c = in[i]]++;
T0[last_i]++;
last_i = c;
}
}
#endif
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
static void hist1_4(unsigned char *in, unsigned int in_size,
int F0[256][256], int *T0) {
int T1[256 + MAGIC] = { 0 }, T2[256 + MAGIC] = { 0 }, T3[256 + MAGIC] = { 0 };
unsigned int idiv4 = in_size / 4;
int i;
unsigned char c0, c1, c2, c3;
unsigned char *in0 = in + 0;
unsigned char *in1 = in + idiv4;
unsigned char *in2 = in + idiv4 * 2;
unsigned char *in3 = in + idiv4 * 3;
unsigned char last_0 = 0, last_1 = in1[-1], last_2 = in2[-1], last_3 = in3[-1];
//unsigned char last_0 = 0, last_1 = 0, last_2 = 0, last_3 = 0;
unsigned char *in0_end = in1;
while (in0 < in0_end) {
F0[last_0][c0 = *in0++]++;
T0[last_0]++;
last_0 = c0;
F0[last_1][c1 = *in1++]++;
T1[last_1]++;
last_1 = c1;
F0[last_2][c2 = *in2++]++;
T2[last_2]++;
last_2 = c2;
F0[last_3][c3 = *in3++]++;
T3[last_3]++;
last_3 = c3;
}
while (in3 < in + in_size) {
F0[last_3][c3 = *in3++]++;
T3[last_3]++;
last_3 = c3;
}
for (i = 0; i < 256; i++) {
T0[i] += T1[i] + T2[i] + T3[i];
}
}
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_compress_O1_32x16_AVX2(unsigned char *in, unsigned int in_size,
unsigned char *out, unsigned int *out_size) {
unsigned char *cp, *out_end;
unsigned int tab_size, rle_i, rle_j;
RansEncSymbol syms[256][256];
int bound = rans_compress_bound_32x16_AVX2(in_size, 1, NULL), z;
#ifndef _MSC_VER
RansState ransN[NX] __attribute__((aligned(32)));
#else
_declspec(align(32))
RansState ransN[NX];
#endif
if (!out) {
*out_size = bound;
out = malloc(*out_size);
}
if (!out || (int64_t)bound > (int64_t)*out_size)
return NULL;
out_end = out + bound;
cp = out + 4;
int F[256][256] = { { 0 } }, T[256 + MAGIC] = { 0 }, i, j;
//memset(F, 0, 256*256*sizeof(int));
//memset(T, 0, 256*sizeof(int));
hist1_4(in, in_size, F, T);
for (z = 1; z < NX; z++)
F[0][in[z*(in_size / NX)]]++;
T[0] += NX - 1;
// Normalise so T[i] == TOTFREQ
for (rle_i = i = 0; i < 256; i++) {
int t2, m, M;
unsigned int x;
if (T[i] == 0)
continue;
//uint64_t p = (TOTFREQ * TOTFREQ) / t;
double p = ((double)TOTFREQ_O1) / T[i];
for (t2 = m = M = j = 0; j < 256; j++) {
if (!F[i][j])
continue;
if (m < F[i][j])
m = F[i][j], M = j;
if ((F[i][j] = (int)(F[i][j] * p)) <= 0)
F[i][j] = 1;
t2 += F[i][j];
}
//t2++;
int adjust = TOTFREQ_O1 - t2;
if (adjust > 0) {
// Boost most common
F[i][M] += adjust;
}
else if (adjust < 0) {
// Reduce highest and distribute remainder
if (F[i][M] > -adjust) {
F[i][M] += adjust;
}
else {
adjust += F[i][M] - 1;
F[i][M] = 1;
for (j = 0; adjust && j < 256; j++) {
if (F[i][j] < 2) continue;
int d = F[i][j] > -adjust;
int m_ = d ? adjust : 1 - F[i][j];
F[i][j] += m_;
adjust -= m_;
}
}
}
// Store frequency table
// i
if (rle_i) {
rle_i--;
}
else {
*cp++ = (unsigned char)i;
// FIXME: could use order-0 statistics to observe which alphabet
// symbols are present and base RLE on that ordering instead.
if (i && T[i - 1]) {
for (rle_i = i + 1; rle_i<256 && T[rle_i]; rle_i++)
;
rle_i -= i + 1;
*cp++ = (unsigned char)rle_i;
}
}
int *F_i_ = F[i];
x = 0;
rle_j = 0;
for (j = 0; j < 256; j++) {
if (F_i_[j]) {
//fprintf(stderr, "F[%d][%d]=%d, x=%d\n", i, j, F_i_[j], x);
// j
if (rle_j) {
rle_j--;
}
else {
*cp++ = (unsigned char)j;
if (!rle_j && j && F_i_[j - 1]) {
for (rle_j = j + 1; rle_j<256 && F_i_[rle_j]; rle_j++)
;
rle_j -= j + 1;
*cp++ = (unsigned char)rle_j;
}
}
// F_i_[j]
if (F_i_[j]<128) {
*cp++ = (unsigned char)F_i_[j];
}
else {
*cp++ = (unsigned char)(128 | (F_i_[j] >> 8));
*cp++ = (unsigned char)(F_i_[j] & 0xff);
}
RansEncSymbolInit(&syms[i][j], x, F_i_[j], TF_SHIFT_O1);
x += F_i_[j];
}
}
*cp++ = (unsigned char)0;
}
*cp++ = (unsigned char)0;
//write(2, out+4, cp-(out+4));
tab_size = (unsigned int)(cp - out);
assert(tab_size < 257 * 257 * 3);
for (z = 0; z < NX; z++)
RansEncInit(&ransN[z]);
uint8_t* ptr = out_end;
int isz4 = in_size / NX;
int iN[NX];
for (z = 0; z < NX; z++)
iN[z] = (z + 1)*isz4 - 2;
unsigned char lN[NX];
for (z = 0; z < NX; z++)
lN[z] = in[iN[z] + 1];
// Deal with the remainder
z = NX - 1;
lN[z] = in[in_size - 1];
for (iN[z] = in_size - 2; iN[z] > NX*isz4 - 2; iN[z]--) {
unsigned char c = in[iN[z]];
RansEncPutSymbol(&ransN[z], &ptr, &syms[c][lN[z]]);
lN[z] = c;
}
#if 0
for (; iN[0] >= 0; ) {
uint32_t c[NX];
RansEncSymbol *sN[NX];
for (z = 0; z < NX; z++)
sN[z] = &syms[c[z] = in[iN[z]]][lN[z]];
for (z = NX - 1; z >= 0; z--)
RansEncPutSymbol(&ransN[z], &ptr, sN[z]);
for (z = 0; z < NX; z++) {
lN[z] = c[z];
iN[z]--;
}
}
#else
uint16_t *ptr16 = (uint16_t *)ptr;
LOAD(Rv, ransN);
for (; iN[0] >= 0; ) {
uint32_t c[NX];
// Gather all the symbol values together in adjacent arrays.
// Better to just use raw set?
RansEncSymbol *sN[NX];
for (z = 0; z < NX; z++)
sN[z] = &syms[c[z] = in[iN[z]]][lN[z]];
#define SET1x(a,b,x) __m256i a##1 = _mm256_set_epi32(b[ 7]->x, b[ 6]->x, b[ 5]->x, b[ 4]->x, b[ 3]->x, b[ 2]->x, b[ 1]->x, b[ 0]->x)
#define SET2x(a,b,x) __m256i a##2 = _mm256_set_epi32(b[15]->x, b[14]->x, b[13]->x, b[12]->x, b[11]->x, b[10]->x, b[ 9]->x, b[ 8]->x)
#define SET3x(a,b,x) __m256i a##3 = _mm256_set_epi32(b[23]->x, b[22]->x, b[21]->x, b[20]->x, b[19]->x, b[18]->x, b[17]->x, b[16]->x)
#define SET4x(a,b,x) __m256i a##4 = _mm256_set_epi32(b[31]->x, b[30]->x, b[29]->x, b[28]->x, b[27]->x, b[26]->x, b[25]->x, b[24]->x)
#define SETx(a,b,x) SET1x(a,b,x);SET2x(a,b,x);SET3x(a,b,x);SET4x(a,b,x)
// ------------------------------------------------------------
// for (z = NX-1; z >= 0; z--) {
// if (ransN[z] >= x_max[z]) {
// *--ptr16 = ransN[z] & 0xffff;
// ransN[z] >>= 16;
// }
// }
//LOAD(xmax,x_max);
SETx(xmax, sN, x_max);
__m256i cv1 = _mm256_cmpgt_epi32(Rv1, xmax1);
__m256i cv2 = _mm256_cmpgt_epi32(Rv2, xmax2);
__m256i cv3 = _mm256_cmpgt_epi32(Rv3, xmax3);
__m256i cv4 = _mm256_cmpgt_epi32(Rv4, xmax4);
// Store bottom 16-bits at ptr16
//
// for (z = NX-1; z >= 0; z--) {
// if (cond[z]) *--ptr16 = (uint16_t )(ransN[z] & 0xffff);
// }
unsigned int imask1 = _mm256_movemask_ps(*(__m256 *)&cv1);
unsigned int imask2 = _mm256_movemask_ps(*(__m256 *)&cv2);
unsigned int imask3 = _mm256_movemask_ps(*(__m256 *)&cv3);
unsigned int imask4 = _mm256_movemask_ps(*(__m256 *)&cv4);
__m256i idx1 = _mm256_load_si256((const __m256i*)permutec[imask1]);
__m256i idx2 = _mm256_load_si256((const __m256i*)permutec[imask2]);
__m256i idx3 = _mm256_load_si256((const __m256i*)permutec[imask3]);
__m256i idx4 = _mm256_load_si256((const __m256i*)permutec[imask4]);
// Permute; to gather together the rans states that need flushing
__m256i V1 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv1, cv1), idx1);
__m256i V2 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv2, cv2), idx2);
__m256i V3 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv3, cv3), idx3);
__m256i V4 = _mm256_permutevar8x32_epi32(_mm256_and_si256(Rv4, cv4), idx4);
// We only flush bottom 16 bits, to squash 32-bit states into 16 bit.
V1 = _mm256_and_si256(V1, _mm256_set1_epi32(0xffff));
V2 = _mm256_and_si256(V2, _mm256_set1_epi32(0xffff));
V3 = _mm256_and_si256(V3, _mm256_set1_epi32(0xffff));
V4 = _mm256_and_si256(V4, _mm256_set1_epi32(0xffff));
__m256i V12 = _mm256_packus_epi32(V1, V2);
__m256i V34 = _mm256_packus_epi32(V3, V4);
// It's BAba order, want BbAa so shuffle.
V12 = _mm256_permute4x64_epi64(V12, 0xd8);
V34 = _mm256_permute4x64_epi64(V34, 0xd8);
// Now we have bottom N 16-bit values in each V12/V34 to flush
__m128i f = _mm256_extractf128_si256(V34, 1);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask4);
f = _mm256_extractf128_si256(V34, 0);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask3);
f = _mm256_extractf128_si256(V12, 1);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask2);
f = _mm256_extractf128_si256(V12, 0);
_mm_storeu_si128((__m128i *)(ptr16 - 8), f);
ptr16 -= _mm_popcnt_u32(imask1);
__m256i Rs;
Rs = _mm256_srli_epi32(Rv1, 16); Rv1 = _mm256_blendv_epi8(Rv1, Rs, cv1);
Rs = _mm256_srli_epi32(Rv2, 16); Rv2 = _mm256_blendv_epi8(Rv2, Rs, cv2);
Rs = _mm256_srli_epi32(Rv3, 16); Rv3 = _mm256_blendv_epi8(Rv3, Rs, cv3);
Rs = _mm256_srli_epi32(Rv4, 16); Rv4 = _mm256_blendv_epi8(Rv4, Rs, cv4);
// ------------------------------------------------------------
// uint32_t q = (uint32_t) (((uint64_t)ransN[z] * rcp_freq[z]) >> rcp_shift[z]);
// ransN[z] = ransN[z] + bias[z] + q * cmpl_freq[z];
// Cannot trivially replace the multiply as mulhi_epu32 doesn't exist (only mullo).
// However we can use _mm256_mul_epu32 twice to get 64bit results (half our lanes)
// and shift/or to get the answer.
//
// (AVX512 allows us to hold it all in 64-bit lanes and use mullo_epi64
// plus a shift. KNC has mulhi_epi32, but not sure if this is available.)
SETx(rfv, sN, rcp_freq);
rfv1 = _mm256_mulhi_epu32(Rv1, rfv1);
rfv2 = _mm256_mulhi_epu32(Rv2, rfv2);
rfv3 = _mm256_mulhi_epu32(Rv3, rfv3);
rfv4 = _mm256_mulhi_epu32(Rv4, rfv4);
SETx(SDv, sN, SD);
__m256i shiftv1 = _mm256_srli_epi32(SDv1, 16);
__m256i shiftv2 = _mm256_srli_epi32(SDv2, 16);
__m256i shiftv3 = _mm256_srli_epi32(SDv3, 16);
__m256i shiftv4 = _mm256_srli_epi32(SDv4, 16);
shiftv1 = _mm256_sub_epi32(shiftv1, _mm256_set1_epi32(32));
shiftv2 = _mm256_sub_epi32(shiftv2, _mm256_set1_epi32(32));
shiftv3 = _mm256_sub_epi32(shiftv3, _mm256_set1_epi32(32));
shiftv4 = _mm256_sub_epi32(shiftv4, _mm256_set1_epi32(32));
__m256i qv1 = _mm256_srlv_epi32(rfv1, shiftv1);
__m256i qv2 = _mm256_srlv_epi32(rfv2, shiftv2);
__m256i freqv1 = _mm256_and_si256(SDv1, _mm256_set1_epi32(0xffff));
__m256i freqv2 = _mm256_and_si256(SDv2, _mm256_set1_epi32(0xffff));
qv1 = _mm256_mullo_epi32(qv1, freqv1);
qv2 = _mm256_mullo_epi32(qv2, freqv2);
__m256i qv3 = _mm256_srlv_epi32(rfv3, shiftv3);
__m256i qv4 = _mm256_srlv_epi32(rfv4, shiftv4);
__m256i freqv3 = _mm256_and_si256(SDv3, _mm256_set1_epi32(0xffff));
__m256i freqv4 = _mm256_and_si256(SDv4, _mm256_set1_epi32(0xffff));
qv3 = _mm256_mullo_epi32(qv3, freqv3);
qv4 = _mm256_mullo_epi32(qv4, freqv4);
SETx(biasv, sN, bias);
qv1 = _mm256_add_epi32(qv1, biasv1);
qv2 = _mm256_add_epi32(qv2, biasv2);
qv3 = _mm256_add_epi32(qv3, biasv3);
qv4 = _mm256_add_epi32(qv4, biasv4);
Rv1 = _mm256_add_epi32(Rv1, qv1);
Rv2 = _mm256_add_epi32(Rv2, qv2);
Rv3 = _mm256_add_epi32(Rv3, qv3);
Rv4 = _mm256_add_epi32(Rv4, qv4);
for (z = 0; z < NX; z++) {
//uint32_t q = (uint32_t) (((uint64_t)ransN[z] * rcp_freq[z]) >> rcp_shift[z]);
//ransN[z] = ransN[z] + bias[z] + q * cmpl_freq[z];
lN[z] = (unsigned char)c[z];
iN[z]--;
}
}
STORE(Rv, ransN);
ptr = (uint8_t *)ptr16;
#endif
for (z = NX - 1; z >= 0; z--)
RansEncPutSymbol(&ransN[z], &ptr, &syms[0][lN[z]]);
for (z = NX - 1; z >= 0; z--)
RansEncFlush(&ransN[z], &ptr);
*out_size = (unsigned int)((out_end - ptr) + tab_size);
cp = out;
*cp++ = (in_size >> 0) & 0xff;
*cp++ = (in_size >> 8) & 0xff;
*cp++ = (in_size >> 16) & 0xff;
*cp++ = (in_size >> 24) & 0xff;
memmove(out + tab_size, ptr, out_end - ptr);
return out;
}
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_uncompress_O1_32x16_AVX2(unsigned char *in, unsigned int in_size,
unsigned char *out, unsigned int *out_size) {
(void)in_size;
/* Load in the static tables */
unsigned char *cp = in + 4;
int i, j = -999, x, y, out_sz, rle_i, rle_j;
#ifndef _MSC_VER
uint32_t s3[256][TOTFREQ_O1] __attribute__((aligned(32)));
#else
_declspec(align(32))
uint32_t s3[256][TOTFREQ_O1];
#endif
//memset(D, 0, 256*sizeof(*D));
out_sz = ((in[0]) << 0) | ((in[1]) << 8) | ((in[2]) << 16) | ((in[3]) << 24);
if (!out) {
out = malloc(out_sz);
*out_size = out_sz;
}
if (!out || (int64_t)out_sz > (int64_t)*out_size)
return NULL;
//fprintf(stderr, "out_sz=%d\n", out_sz);
//i = *cp++;
rle_i = 0;
i = *cp++;
do {
rle_j = x = y = 0;
j = *cp++;
do {
int F, C;
if ((F = *cp++) >= 128) {
F &= ~128;
F = ((F & 127) << 8) | *cp++;
}
C = x;
//fprintf(stderr, "i=%d j=%d F=%d C=%d\n", i, j, D[i].F[j], D[i].C[j]);
if (!F)
F = TOTFREQ_O1;
for (y = 0; y < F; y++) {
s3[i][y + C] = (((uint32_t)F) << (TF_SHIFT_O1 + 8)) | (y << 8) | j;
}
x += F;
assert(x <= TOTFREQ_O1);
if (!rle_j && j + 1 == *cp) {
j = *cp++;
rle_j = *cp++;
}
else if (rle_j) {
rle_j--;
j++;
}
else {
j = *cp++;
}
} while (j);
if (!rle_i && i + 1 == *cp) {
i = *cp++;
rle_i = *cp++;
}
else if (rle_i) {
rle_i--;
i++;
}
else {
i = *cp++;
}
} while (i);
// Precompute reverse lookup of frequency.
#ifndef _MSC_VER
RansState ransN[NX] __attribute__((aligned(32)));
#else
_declspec(align(32))
RansState ransN[NX];
#endif
int z;
uint8_t *ptr = cp;
for (z = 0; z < NX; z++)
RansDecInit(&ransN[z], &ptr);
int isz4 = out_sz / NX;
int lN[NX] = { 0 }, iN[NX];
for (z = 0; z < NX; z++)
iN[z] = z * isz4;
uint16_t *sp = (uint16_t *)ptr;
const uint32_t mask = (1u << TF_SHIFT_O1) - 1;
__m256i maskv = _mm256_set1_epi32(mask);
LOAD(Rv, ransN);
LOAD(Lv, lN);
union {
unsigned char tbuf[32][32];
uint64_t tbuf64[32][4];
} u;
int tidx = 0;
for (; iN[0] < isz4; ) {
// m[z] = ransN[z] & mask;
__m256i masked1 = _mm256_and_si256(Rv1, maskv);
__m256i masked2 = _mm256_and_si256(Rv2, maskv);
// S[z] = s3[lN[z]][m[z]];
Lv1 = _mm256_slli_epi32(Lv1, TF_SHIFT_O1);
masked1 = _mm256_add_epi32(masked1, Lv1);
Lv2 = _mm256_slli_epi32(Lv2, TF_SHIFT_O1);
masked2 = _mm256_add_epi32(masked2, Lv2);
__m256i masked3 = _mm256_and_si256(Rv3, maskv);
__m256i masked4 = _mm256_and_si256(Rv4, maskv);
Lv3 = _mm256_slli_epi32(Lv3, TF_SHIFT_O1);
masked3 = _mm256_add_epi32(masked3, Lv3);
Lv4 = _mm256_slli_epi32(Lv4, TF_SHIFT_O1);
masked4 = _mm256_add_epi32(masked4, Lv4);
__m256i Sv1 = _mm256_i32gather_epi32x((int *)&s3[0][0], masked1, sizeof(s3[0][0]));
__m256i Sv2 = _mm256_i32gather_epi32x((int *)&s3[0][0], masked2, sizeof(s3[0][0]));
// f[z] = S[z]>>(TF_SHIFT_O1+8);
__m256i fv1 = _mm256_srli_epi32(Sv1, TF_SHIFT_O1 + 8);
__m256i fv2 = _mm256_srli_epi32(Sv2, TF_SHIFT_O1 + 8);
__m256i Sv3 = _mm256_i32gather_epi32x((int *)&s3[0][0], masked3, sizeof(s3[0][0]));
__m256i Sv4 = _mm256_i32gather_epi32x((int *)&s3[0][0], masked4, sizeof(s3[0][0]));
__m256i fv3 = _mm256_srli_epi32(Sv3, TF_SHIFT_O1 + 8);
__m256i fv4 = _mm256_srli_epi32(Sv4, TF_SHIFT_O1 + 8);
// b[z] = (S[z]>>8) & mask;
__m256i bv1 = _mm256_and_si256(_mm256_srli_epi32(Sv1, 8), maskv);
__m256i bv2 = _mm256_and_si256(_mm256_srli_epi32(Sv2, 8), maskv);
__m256i bv3 = _mm256_and_si256(_mm256_srli_epi32(Sv3, 8), maskv);
__m256i bv4 = _mm256_and_si256(_mm256_srli_epi32(Sv4, 8), maskv);
// s[z] = S[z] & 0xff;
__m256i sv1 = _mm256_and_si256(Sv1, _mm256_set1_epi32(0xff));
__m256i sv2 = _mm256_and_si256(Sv2, _mm256_set1_epi32(0xff));
__m256i sv3 = _mm256_and_si256(Sv3, _mm256_set1_epi32(0xff));
__m256i sv4 = _mm256_and_si256(Sv4, _mm256_set1_epi32(0xff));
// R[z] = f[z] * (R[z] >> TF_SHIFT_O1) + b[z];
Rv1 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv1, TF_SHIFT_O1), fv1), bv1);
Rv2 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv2, TF_SHIFT_O1), fv2), bv2);
//for (z = 0; z < NX; z++) lN[z] = c[z];
Lv1 = sv1;
Lv2 = sv2;
sv1 = _mm256_packus_epi32(sv1, sv2);
sv1 = _mm256_permute4x64_epi64(sv1, 0xd8);
// Start loading next batch of normalised states
__m256i Vv1 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
sv1 = _mm256_packus_epi16(sv1, sv1);
// out[iN[z]] = c[z]; // simulate scatter
// RansDecRenorm(&ransN[z], &ptr);
__m256i renorm_mask1 = _mm256_xor_si256(Rv1, _mm256_set1_epi32(0x80000000));
__m256i renorm_mask2 = _mm256_xor_si256(Rv2, _mm256_set1_epi32(0x80000000));
renorm_mask1 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask1);
renorm_mask2 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask2);
unsigned int imask1 = _mm256_movemask_ps(*(__m256 *)&renorm_mask1);
__m256i idx1 = _mm256_load_si256((const __m256i*)permute[imask1]);
__m256i Yv1 = _mm256_slli_epi32(Rv1, 16);
__m256i Yv2 = _mm256_slli_epi32(Rv2, 16);
unsigned int imask2 = _mm256_movemask_ps(*(__m256 *)&renorm_mask2);
Vv1 = _mm256_permutevar8x32_epi32(Vv1, idx1);
sp += _mm_popcnt_u32(imask1);
u.tbuf64[tidx][0] = _mm256_extract_epi64(sv1, 0);
u.tbuf64[tidx][1] = _mm256_extract_epi64(sv1, 2);
__m256i idx2 = _mm256_load_si256((const __m256i*)permute[imask2]);
__m256i Vv2 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
sp += _mm_popcnt_u32(imask2);
Vv2 = _mm256_permutevar8x32_epi32(Vv2, idx2);
//Vv = _mm256_and_si256(Vv, renorm_mask); (blend does the AND anyway)
Yv1 = _mm256_or_si256(Yv1, Vv1);
Yv2 = _mm256_or_si256(Yv2, Vv2);
Rv1 = _mm256_blendv_epi8(Rv1, Yv1, renorm_mask1);
Rv2 = _mm256_blendv_epi8(Rv2, Yv2, renorm_mask2);
/////////////////////////////////////////////////////////////////////
// Start loading next batch of normalised states
__m256i Vv3 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
// R[z] = f[z] * (R[z] >> TF_SHIFT_O1) + b[z];
Rv3 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv3, TF_SHIFT_O1), fv3), bv3);
Rv4 = _mm256_add_epi32(_mm256_mullo_epi32(_mm256_srli_epi32(Rv4, TF_SHIFT_O1), fv4), bv4);
//for (z = 0; z < NX; z++) lN[z] = c[z];
Lv3 = sv3;
Lv4 = sv4;
// out[iN[z]] = c[z]; // simulate scatter
// RansDecRenorm(&ransN[z], &ptr);
__m256i renorm_mask3 = _mm256_xor_si256(Rv3, _mm256_set1_epi32(0x80000000));
__m256i renorm_mask4 = _mm256_xor_si256(Rv4, _mm256_set1_epi32(0x80000000));
renorm_mask3 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask3);
renorm_mask4 = _mm256_cmpgt_epi32(_mm256_set1_epi32(RANS_BYTE_L - 0x80000000), renorm_mask4);
__m256i Yv3 = _mm256_slli_epi32(Rv3, 16);
__m256i Yv4 = _mm256_slli_epi32(Rv4, 16);
unsigned int imask3 = _mm256_movemask_ps(*(__m256 *)&renorm_mask3);
unsigned int imask4 = _mm256_movemask_ps(*(__m256 *)&renorm_mask4);
__m256i idx3 = _mm256_load_si256((const __m256i*)permute[imask3]);
sp += _mm_popcnt_u32(imask3);
Vv3 = _mm256_permutevar8x32_epi32(Vv3, idx3);
sv3 = _mm256_packus_epi32(sv3, sv4);
sv3 = _mm256_permute4x64_epi64(sv3, 0xd8);
sv3 = _mm256_packus_epi16(sv3, sv3);
u.tbuf64[tidx][2] = _mm256_extract_epi64(sv3, 0);
u.tbuf64[tidx][3] = _mm256_extract_epi64(sv3, 2);
iN[0]++;
if (++tidx == 32) {
iN[0] -= 32;
for (z = 0; z < NX; z++) {
// replace by gathers?
*(uint64_t *)&out[iN[z]] =
((uint64_t)(u.tbuf[0][z]) << 0) + ((uint64_t)(u.tbuf[1][z]) << 8) +
((uint64_t)(u.tbuf[2][z]) << 16) + ((uint64_t)(u.tbuf[3][z]) << 24) +
((uint64_t)(u.tbuf[4][z]) << 32) + ((uint64_t)(u.tbuf[5][z]) << 40) +
((uint64_t)(u.tbuf[6][z]) << 48) + ((uint64_t)(u.tbuf[7][z]) << 56);
*(uint64_t *)&out[iN[z] + 8] =
((uint64_t)(u.tbuf[8 + 0][z]) << 0) + ((uint64_t)(u.tbuf[8 + 1][z]) << 8) +
((uint64_t)(u.tbuf[8 + 2][z]) << 16) + ((uint64_t)(u.tbuf[8 + 3][z]) << 24) +
((uint64_t)(u.tbuf[8 + 4][z]) << 32) + ((uint64_t)(u.tbuf[8 + 5][z]) << 40) +
((uint64_t)(u.tbuf[8 + 6][z]) << 48) + ((uint64_t)(u.tbuf[8 + 7][z]) << 56);
*(uint64_t *)&out[iN[z] + 16] =
((uint64_t)(u.tbuf[16 + 0][z]) << 0) + ((uint64_t)(u.tbuf[16 + 1][z]) << 8) +
((uint64_t)(u.tbuf[16 + 2][z]) << 16) + ((uint64_t)(u.tbuf[16 + 3][z]) << 24) +
((uint64_t)(u.tbuf[16 + 4][z]) << 32) + ((uint64_t)(u.tbuf[16 + 5][z]) << 40) +
((uint64_t)(u.tbuf[16 + 6][z]) << 48) + ((uint64_t)(u.tbuf[16 + 7][z]) << 56);
*(uint64_t *)&out[iN[z] + 24] =
((uint64_t)(u.tbuf[24 + 0][z]) << 0) + ((uint64_t)(u.tbuf[24 + 1][z]) << 8) +
((uint64_t)(u.tbuf[24 + 2][z]) << 16) + ((uint64_t)(u.tbuf[24 + 3][z]) << 24) +
((uint64_t)(u.tbuf[24 + 4][z]) << 32) + ((uint64_t)(u.tbuf[24 + 5][z]) << 40) +
((uint64_t)(u.tbuf[24 + 6][z]) << 48) + ((uint64_t)(u.tbuf[24 + 7][z]) << 56);
iN[z] += 32;
}
tidx = 0;
}
__m256i idx4 = _mm256_load_si256((const __m256i*)permute[imask4]);
__m256i Vv4 = _mm256_cvtepu16_epi32(_mm_loadu_si128((__m128i *)sp));
//Vv = _mm256_and_si256(Vv, renorm_mask); (blend does the AND anyway)
Yv3 = _mm256_or_si256(Yv3, Vv3);
Vv4 = _mm256_permutevar8x32_epi32(Vv4, idx4);
Yv4 = _mm256_or_si256(Yv4, Vv4);
sp += _mm_popcnt_u32(imask4);
Rv3 = _mm256_blendv_epi8(Rv3, Yv3, renorm_mask3);
Rv4 = _mm256_blendv_epi8(Rv4, Yv4, renorm_mask4);
}
STORE(Rv, ransN);
//_mm256_store_si256((__m256i *)&ransN[ 0], Rv1);
//_mm256_store_si256((__m256i *)&ransN[ 8], Rv2);
//_mm256_store_si256((__m256i *)&ransN[16], Rv3);
//_mm256_store_si256((__m256i *)&ransN[24], Rv4);
STORE(Lv, lN);
//_mm256_store_si256((__m256i *)&lN[ 0], Lv1);
//_mm256_store_si256((__m256i *)&lN[ 8], Lv2);
//_mm256_store_si256((__m256i *)&lN[16], Lv3);
//_mm256_store_si256((__m256i *)&lN[24], Lv4);
ptr = (uint8_t *)sp;
if (1) {
iN[0] -= tidx;
int T;
for (z = 0; z < NX; z++)
for (T = 0; T < tidx; T++)
out[iN[z]++] = u.tbuf[T][z];
}
// Remainder
z = NX - 1;
for (; iN[z] < out_sz; ) {
uint32_t m = ransN[z] & ((1u << TF_SHIFT_O1) - 1);
uint32_t S = s3[lN[z]][m];
unsigned char c = S & 0xff;
out[iN[z]++] = c;
ransN[z] = (S >> (TF_SHIFT_O1 + 8)) * (ransN[z] >> TF_SHIFT_O1) +
((S >> 8) & ((1u << TF_SHIFT_O1) - 1));
RansDecRenorm(&ransN[z], &ptr);
lN[z] = c;
}
*out_size = out_sz;
return out;
}
/*-----------------------------------------------------------------------------
* Simple interface to the order-0 vs order-1 encoders and decoders.
*/
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_compress_to_32x16_AVX2(unsigned char *in, unsigned int in_size,
unsigned char *out, unsigned int *out_size,
int order) {
return order
? rans_compress_O1_32x16_AVX2(in, in_size, out, out_size)
: rans_compress_O0_32x16_AVX2(in, in_size, out, out_size);
}
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_compress_32x16(unsigned char *in, unsigned int in_size,
unsigned int *out_size, int order) {
return rans_compress_to_32x16_AVX2(in, in_size, NULL, out_size, order);
}
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_uncompress_to_32x16_AVX2(unsigned char *in, unsigned int in_size,
unsigned char *out, unsigned int *out_size,
int order) {
return order
? rans_uncompress_O1_32x16_AVX2(in, in_size, out, out_size)
: rans_uncompress_O0_32x16_AVX2(in, in_size, out, out_size);
}
#ifndef _MSC_VER
__attribute__((target("avx2")))
#endif
unsigned char *rans_uncompress_32x16_AVX2(unsigned char *in, unsigned int in_size,
unsigned int *out_size, int order) {
return rans_uncompress_to_32x16_AVX2(in, in_size, NULL, out_size, order);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
|
block-2.c
|
// { dg-do compile }
void foo()
{
int i, j;
#pragma omp for
for (i = 0; i < 10; ++i)
break; // { dg-error "break" }
bad1:
#pragma omp for
for (i = 0; i < 10; ++i)
goto bad1; // { dg-error "invalid exit" }
goto bad2; // { dg-error "invalid entry" }
#pragma omp for
for (i = 0; i < 10; ++i)
{
bad2: ;
}
#pragma omp for
for (i = 0; i < 10; ++i)
for (j = 0; j < 10; ++j)
if (i == j)
break;
#pragma omp for
for (i = 0; i < 10; ++i)
continue;
}
|
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] = 4;
tile_size[3] = 128;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* 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+2,2),ceild(4*t2-Nz+9,4));t3<=min(min(floord(4*Nt+Ny-9,4),floord(2*t1+Ny-3,4)),floord(4*t2+Ny-9,4));t3++) {
for (t4=max(max(ceild(t1-60,64),ceild(4*t2-Nz-115,128)),ceild(4*t3-Ny-115,128));t4<=min(min(min(floord(4*Nt+Nx-9,128),floord(2*t1+Nx-3,128)),floord(4*t2+Nx-9,128)),floord(4*t3+Nx-9,128));t4++) {
for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(4*t3-Ny+5,4)),ceild(128*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=4*t3;t7<=min(4*t3+3,4*t5+Ny-5);t7++) {
lbv=max(128*t4,4*t5+4);
ubv=min(128*t4+127,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;
}
|
mutation.h
|
/*!
* Functions to determine the number of fit mutated genomes that exist
* a Hamming distance m (or h) away from a given, fit genome.
*/
#ifndef _MUTATION_H_
#define _MUTATION_H_
#include <math.h>
#ifndef __FITNESS_FUNCTION__
#error "#include a fitness.h before #including mutations.h to ensure evaluate_fitness() is available"
#endif
/*!
* Return the number of fit mutations of genome at a Hamming
* distance of h. Exponentially costly in h, I think.
*/
pair<unsigned int, double>
num_fit_mutations (const array<genosect_t, N_Genes>& genome, unsigned int h)
{
// Return variables
unsigned int numfit = 0;
double fitness_sum = 0.0;
// The length of the genome
unsigned int l_genome = N_Genes * (1<<N_Ins);
// A genome that gets flipped from the original genome and then evaluated.
array<genosect_t, N_Genes> flipped_genome;
// This makes combo long enough for h all the way up to the full
// width of the genome. combo[i] is the index of the i-th element
// in the combination
int combo[N_Genes * (1<<N_Ins)];
// Setup combo for the initial combination - first h bits set to
// 1. Set everything else to 0
for (int i = 0; i < static_cast<int>(h); ++i) { combo[static_cast<unsigned int>(i)] = i; }
for (unsigned int i = h; i < l_genome; ++i) { combo[i] = 0; }
// Generate and evaluate all the combinations
bool finished = false;
while (!finished) {
// printc (combo, h);
// Initialise flipped_genome
copy_genome (genome, flipped_genome);
// Work out flipped_genome[i]s and then compute fitness
for (unsigned int i = 0; i < N_Genes; ++i) {
for (unsigned int j = 0; j < h; ++j) {
if (combo[j] >= static_cast<int>(i*(1<<N_Ins))
&& combo[j] < static_cast<int>((i+1)*(1<<N_Ins))) {
// Then combo[j] is an index that is in genosect[i] so flip this bit.
unsigned int bit_to_flip = combo[j] - (i*(1<<N_Ins));
flipped_genome[i] ^= (0x1 << bit_to_flip);
}
}
}
double f = evaluate_fitness (flipped_genome);
if (f > 0.0) {
++numfit;
fitness_sum += f;
}
if (!next_combination (combo, h, l_genome)) {
finished = true;
}
}
DBG ("Numfit:" << numfit << " sum of fitness: " << fitness_sum);
return make_pair(numfit, fitness_sum);
}
/*!
* Compute an estimate of the number of fit mutations at a given
* Hamming distance, hd, by making a number of samples, num_samples.
*/
pair<unsigned int, double>
num_fit_mutations_sample (const array<genosect_t, N_Genes>& genome,
unsigned int hd, unsigned int num_samples)
{
unsigned int numfit = 0;
double fitness_sum = 0.0;
unsigned int n_in_gs = (1 << N_Ins);
vector<unsigned int> flipbit (hd, 0);
array<genosect_t, N_Genes> flip_mask;
array<genosect_t, N_Genes> flipped_genome;
set<array<genosect_t, N_Genes> > masks;
for (unsigned int s = 0; s < num_samples; ++s) {
copy_genome (genome, flipped_genome);
zero_genome (flip_mask);
// Get random numbers to determine flipping
//for (unsigned int h = 0; h < hd; ++h) {
unsigned int h = 0;
unsigned int num_miss = 0;
while (h<hd) {
// Should be in range 0 to 80 for N_Genes==5
float f = randFloat() * N_Genes * n_in_gs;
flipbit[h] = (unsigned int)floorf (f);
DBG2 ("flipbit[" << h << "]: " << flipbit[h]);
unsigned int fb = (unsigned int)floorf (f);
unsigned int fb_genosect = fb / n_in_gs;
unsigned int fb_offset = fb % n_in_gs;
// mask_part is the new part of the mask to flip
genosect_t mask_part = 0x1 << fb_offset;
// Make sure we didn't already flip this one!
if ((flip_mask[fb_genosect] & mask_part) != mask_part) {
// Set bit fb_offset in flip_mask[fb_genosect];
flip_mask[fb_genosect] |= mask_part;
++h;
DBG2 ("Added to flip_mask...");
} else {
// Do nothing, make another sample from the RNG to flip another bit.
DBG2("It's a miss.");
++num_miss;
}
}
#ifdef DEBUG2
if (num_miss > 0) {
DBG ("Number of misses creating flip_mask was: " << num_miss);
}
#endif
// Check we didn't already choose this one.
DBG2 ("Check if flip_mask already seen...");
if (masks.count(flip_mask) == 0) {
masks.insert(flip_mask);
// Now do the flipping, genome section by genome section
#pragma omp simd
for (unsigned int i=0; i<N_Genes; ++i) {
flipped_genome[i] ^= flip_mask[i];
}
// Now evaluate the fitness
double f = evaluate_fitness (flipped_genome);
if (f > 0.0) {
++numfit;
fitness_sum += f;
}
} else {
// We found a duplicate mask, so decrement s to make sure we do one more random sample.
DBG2 ("Flip mask seen :(");
--s;
}
}
DBG ("Numfit:" << numfit << " sum of fitness: " << fitness_sum);
return make_pair (numfit, fitness_sum);
}
/*!
* Create a random genome and evolve it into a maximally fit genome.
*/
array<genosect_t, N_Genes>
evolve_new_genome (void)
{
// Holds the genome and a copy of it.
array<genosect_t, N_Genes> refg;
array<genosect_t, N_Genes> newg;
random_genome (refg);
double a = evaluate_fitness (refg);
unsigned int gen = 0;
// Test fitness to determine whether we should evolve.
while (a < 1.0) {
copy_genome (refg, newg);
evolve_genome (newg);
++gen;
double b = evaluate_fitness (newg);
if (a > b) {
// New fitness <= old fitness
} else {
// Copy new fitness to ref
a = b;
// Copy new to reference
copy_genome (newg, refg);
}
}
DBG ("It took " << gen << " generations to evolve this genome");
return refg;
}
#endif // _MUTATION_H_
|
1body.h
|
/*
* Copyright (C) 2004-2020 Edward F. Valeev
*
* This file is part of Libint.
*
* Libint 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 3 of the License, or
* (at your option) any later version.
*
* Libint 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 Libint. If not, see <http://www.gnu.org/licenses/>.
*
*/
// standard C++ headers
#include <atomic>
#include <chrono>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <memory>
#include <mutex>
#include <sstream>
#include <thread>
#include <unordered_map>
#include <vector>
// have BTAS library?
#ifdef LIBINT2_HAVE_BTAS
# include <btas/btas.h>
#else // LIBINT2_HAVE_BTAS
# error "libint2::lcao requires BTAS"
#endif
// Libint Gaussian integrals library
#include <libint2/diis.h>
#include <libint2/util/intpart_iter.h>
#include <libint2/chemistry/sto3g_atomic_density.h>
#include <libint2.hpp>
#if defined(_OPENMP)
#include <omp.h>
#endif
typedef btas::RangeNd<CblasRowMajor, std::array<long, 2>> Range2;
typedef btas::RangeNd<CblasRowMajor, std::array<long, 3>> Range3;
typedef btas::RangeNd<CblasRowMajor, std::array<long, 4>> Range4;
typedef btas::Tensor<double, Range2> Tensor2d;
typedef btas::Tensor<double, Range3> Tensor3d;
typedef btas::Tensor<double, Range3> Tensor4d;
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
Matrix; // import dense, dynamically sized Matrix type from Eigen;
// this is a matrix with row-major storage
// (http://en.wikipedia.org/wiki/Row-major_order)
// to meet the layout of the integrals returned by the Libint integral library
typedef Eigen::DiagonalMatrix<double, Eigen::Dynamic, Eigen::Dynamic>
DiagonalMatrix;
using libint2::Shell;
using libint2::libint2::Atom;
using libint2::BasisSet;
using libint2::Operator;
using libint2::BraKet;
std::vector<libint2::Atom> read_geometry(const std::string& filename);
Matrix compute_soad(const std::vector<libint2::Atom>& atoms);
// computes norm of shell-blocks of A
Matrix compute_shellblock_norm(const BasisSet& obs, const Matrix& A);
template <Operator obtype>
std::array<Matrix, libint2::operator_traits<obtype>::nopers> compute_1body_ints(
const BasisSet& obs, const std::vector<libint2::Atom>& atoms = std::vector<libint2::Atom>());
#if LIBINT2_DERIV_ONEBODY_ORDER
template <Operator obtype>
std::vector<Matrix> compute_1body_ints_deriv(unsigned deriv_order,
const BasisSet& obs,
const std::vector<libint2::Atom>& atoms);
#endif // LIBINT2_DERIV_ONEBODY_ORDER
template <libint2::Operator Kernel = libint2::Operator::coulomb>
Matrix compute_schwarz_ints(
const BasisSet& bs1, const BasisSet& bs2 = BasisSet(),
bool use_2norm = false, // use infty norm by default
typename libint2::operator_traits<Kernel>::oper_params_type params =
libint2::operator_traits<Kernel>::default_params());
Matrix compute_do_ints(const BasisSet& bs1, const BasisSet& bs2 = BasisSet(),
bool use_2norm = false // use infty norm by default
);
using shellpair_list_t = std::unordered_map<size_t, std::vector<size_t>>;
shellpair_list_t obs_shellpair_list; // shellpair list for OBS
/// computes non-negligible shell pair list; shells \c i and \c j form a
/// non-negligible
/// pair if they share a center or the Frobenius norm of their overlap is
/// greater than threshold
shellpair_list_t compute_shellpair_list(const BasisSet& bs1,
const BasisSet& bs2 = BasisSet(),
double threshold = 1e-12);
Matrix compute_2body_fock(
const BasisSet& obs, const Matrix& D,
double precision = std::numeric_limits<
double>::epsilon(), // discard contributions smaller than this
const Matrix& Schwarz = Matrix() // K_ij = sqrt(||(ij|ij)||_\infty); if
// empty, do not Schwarz screen
);
// an Fock builder that can accept densities expressed a separate basis
Matrix compute_2body_fock_general(
const BasisSet& obs, const Matrix& D, const BasisSet& D_bs,
bool D_is_sheldiagonal = false, // set D_is_shelldiagonal if doing SOAD
double precision = std::numeric_limits<
double>::epsilon() // discard contributions smaller than this
);
#if LIBINT2_DERIV_ERI_ORDER
template <unsigned deriv_order>
std::vector<Matrix> compute_2body_fock_deriv(
const BasisSet& obs, const std::vector<libint2::Atom>& atoms,
const Matrix& D,
double precision = std::numeric_limits<
double>::epsilon(), // discard contributions smaller than this
const Matrix& Schwarz = Matrix() // K_ij = sqrt(||(ij|ij)||_\infty); if
// empty, do not Schwarz screen
);
#endif // LIBINT2_DERIV_ERI_ORDER
// returns {X,X^{-1},S_condition_number_after_conditioning}, where
// X is the generalized square-root-inverse such that X.transpose() * S * X = I
// columns of Xinv is the basis conditioned such that
// the condition number of its metric (Xinv.transpose . Xinv) <
// S_condition_number_threshold
std::tuple<Matrix, Matrix, double> conditioning_orthogonalizer(
const Matrix& S, double S_condition_number_threshold);
#ifdef LIBINT2_HAVE_BTAS
#define HAVE_DENSITY_FITTING 1
struct DFFockEngine {
const BasisSet& obs;
const BasisSet& dfbs;
DFFockEngine(const BasisSet& _obs, const BasisSet& _dfbs)
: obs(_obs), dfbs(_dfbs) {}
typedef btas::RangeNd<CblasRowMajor, std::array<long, 3>> Range3d;
typedef btas::Tensor<double, Range3d> Tensor3d;
Tensor3d xyK;
// a DF-based builder, using coefficients of occupied MOs
Matrix compute_2body_fock_dfC(const Matrix& Cocc);
};
#endif // HAVE_DENSITY_FITTING
namespace libint2 {
int nthreads;
/// fires off \c nthreads instances of lambda in parallel
template <typename Lambda>
void parallel_do(Lambda& lambda) {
#ifdef _OPENMP
#pragma omp parallel
{
auto thread_id = omp_get_thread_num();
lambda(thread_id);
}
#else // use C++11 threads
std::vector<std::thread> threads;
for (int thread_id = 0; thread_id != libint2::nthreads; ++thread_id) {
if (thread_id != nthreads - 1)
threads.push_back(std::thread(lambda, thread_id));
else
lambda(thread_id);
} // threads_id
for (int thread_id = 0; thread_id < nthreads - 1; ++thread_id)
threads[thread_id].join();
#endif
}
}
int main(int argc, char* argv[]) {
using std::cout;
using std::cerr;
using std::endl;
try {
/*** =========================== ***/
/*** initialize molecule ***/
/*** =========================== ***/
// read geometry from a file; by default read from h2o.xyz, else take
// filename (.xyz) from the command line
const auto filename = (argc > 1) ? argv[1] : "h2o.xyz";
const auto basisname = (argc > 2) ? argv[2] : "aug-cc-pVDZ";
bool do_density_fitting = false;
#ifdef HAVE_DENSITY_FITTING
do_density_fitting = (argc > 3);
const auto dfbasisname = do_density_fitting ? argv[3] : "";
#endif
std::vector<libint2::Atom> atoms = read_geometry(filename);
// set up thread pool
{
using libint2::nthreads;
auto nthreads_cstr = getenv("LIBINT_NUM_THREADS");
nthreads = 1;
if (nthreads_cstr && strcmp(nthreads_cstr, "")) {
std::istringstream iss(nthreads_cstr);
iss >> nthreads;
if (nthreads > 1 << 16 || nthreads <= 0) nthreads = 1;
}
#if defined(_OPENMP)
omp_set_num_threads(nthreads);
#endif
std::cout << "Will scale over " << nthreads
#if defined(_OPENMP)
<< " OpenMP"
#else
<< " C++11"
#endif
<< " threads" << std::endl;
}
// count the number of electrons
auto nelectron = 0;
for (auto i = 0; i < atoms.size(); ++i) nelectron += atoms[i].atomic_number;
const auto ndocc = nelectron / 2;
cout << "# of electrons = " << nelectron << endl;
// compute the nuclear repulsion energy
auto enuc = 0.0;
for (auto i = 0; i < atoms.size(); i++)
for (auto j = i + 1; j < atoms.size(); j++) {
auto xij = atoms[i].x - atoms[j].x;
auto yij = atoms[i].y - atoms[j].y;
auto zij = atoms[i].z - atoms[j].z;
auto r2 = xij * xij + yij * yij + zij * zij;
auto r = sqrt(r2);
enuc += atoms[i].atomic_number * atoms[j].atomic_number / r;
}
cout << "Nuclear repulsion energy = " << std::setprecision(15) << enuc
<< endl;
libint2::Shell::do_enforce_unit_normalization(false);
cout << "libint2::Atomic Cartesian coordinates (a.u.):" << endl;
for (const auto& a : atoms)
std::cout << a.atomic_number << " " << a.x << " " << a.y << " " << a.z
<< std::endl;
BasisSet obs(basisname, atoms);
cout << "orbital basis set rank = " << obs.nbf() << endl;
#ifdef HAVE_DENSITY_FITTING
BasisSet dfbs;
if (do_density_fitting) {
dfbs = BasisSet(dfbasisname, atoms);
cout << "density-fitting basis set rank = " << dfbs.nbf() << endl;
}
#endif // HAVE_DENSITY_FITTING
/*** =========================== ***/
/*** compute 1-e integrals ***/
/*** =========================== ***/
// initializes the Libint integrals library ... now ready to compute
libint2::initialize();
// compute OBS non-negligible shell-pair list
{
obs_shellpair_list = compute_shellpair_list(obs);
size_t nsp = 0;
for (auto& sp : obs_shellpair_list) {
nsp += sp.second.size();
}
std::cout << "# of {all,non-negligible} shell-pairs = {"
<< obs.size() * (obs.size() + 1) / 2 << "," << nsp << "}"
<< std::endl;
}
// compute one-body integrals
auto S = compute_1body_ints<Operator::overlap>(obs)[0];
auto T = compute_1body_ints<Operator::kinetic>(obs)[0];
auto V = compute_1body_ints<Operator::nuclear>(obs, libint2::make_point_charges(atoms))[0];
Matrix H = T + V;
T.resize(0, 0);
V.resize(0, 0);
// compute orthogonalizer X such that X.transpose() . S . X = I
Matrix X, Xinv;
double XtX_condition_number; // condition number of "re-conditioned"
// overlap obtained as Xinv.transpose() . Xinv
// one should think of columns of Xinv as the conditioned basis
// Re: name ... cond # (Xinv.transpose() . Xinv) = cond # (X.transpose() .
// X)
// by default assume can manage to compute with condition number of S <=
// 1/eps
// this is probably too optimistic, but in well-behaved cases even 10^11 is
// OK
double S_condition_number_threshold =
1.0 / std::numeric_limits<double>::epsilon();
std::tie(X, Xinv, XtX_condition_number) =
conditioning_orthogonalizer(S, S_condition_number_threshold);
Matrix D;
Matrix C_occ;
Matrix evals;
{ // use SOAD as the guess density
const auto tstart = std::chrono::high_resolution_clock::now();
auto D_minbs = compute_soad(atoms); // compute guess in minimal basis
BasisSet minbs("STO-3G", atoms);
if (minbs == obs)
D = D_minbs;
else { // if basis != minimal basis, map non-representable SOAD guess
// into the AO basis
// by diagonalizing a Fock matrix
std::cout << "projecting SOAD into AO basis ... ";
auto F = H;
F += compute_2body_fock_general(
obs, D_minbs, minbs, true /* SOAD_D_is_shelldiagonal */,
std::numeric_limits<double>::epsilon() // this is cheap, no reason
// to be cheaper
);
// solve F C = e S C by (conditioned) transformation to F' C' = e C',
// where
// F' = X.transpose() . F . X; the original C is obtained as C = X . C'
Eigen::SelfAdjointEigenSolver<Matrix> eig_solver(X.transpose() * F * X);
auto C = X * eig_solver.eigenvectors();
// compute density, D = C(occ) . C(occ)T
C_occ = C.leftCols(ndocc);
D = C_occ * C_occ.transpose();
const auto tstop = std::chrono::high_resolution_clock::now();
const std::chrono::duration<double> time_elapsed = tstop - tstart;
std::cout << "done (" << time_elapsed.count() << " s)" << std::endl;
}
}
// pre-compute data for Schwarz bounds
auto K = compute_schwarz_ints<>(obs, BasisSet(), true);
// prepare for density fitting
#ifdef HAVE_DENSITY_FITTING
std::unique_ptr<DFFockEngine> dffockengine(
do_density_fitting ? new DFFockEngine(obs, dfbs) : nullptr);
#endif // HAVE_DENSITY_FITTING
/*** =========================== ***/
/*** SCF loop ***/
/*** =========================== ***/
const auto maxiter = 100;
const auto conv = 1e-12;
auto iter = 0;
auto rms_error = 1.0;
auto ediff_rel = 0.0;
auto ehf = 0.0;
auto n2 = D.cols() * D.rows();
libint2::DIIS<Matrix> diis(2); // start DIIS on second iteration
// prepare for incremental Fock build ...
Matrix D_diff = D;
Matrix F = H;
bool reset_incremental_fock_formation = false;
bool incremental_Fbuild_started = false;
double start_incremental_F_threshold = 1e-5;
double next_reset_threshold = 0.0;
size_t last_reset_iteration = 0;
// ... unless doing DF, then use MO coefficients, hence not "incremental"
if (do_density_fitting) start_incremental_F_threshold = 0.0;
do {
const auto tstart = std::chrono::high_resolution_clock::now();
++iter;
// Last iteration's energy and density
auto ehf_last = ehf;
Matrix D_last = D;
if (not incremental_Fbuild_started &&
rms_error < start_incremental_F_threshold) {
incremental_Fbuild_started = true;
reset_incremental_fock_formation = false;
last_reset_iteration = iter - 1;
next_reset_threshold = rms_error / 1e1;
std::cout << "== started incremental fock build" << std::endl;
}
if (reset_incremental_fock_formation || not incremental_Fbuild_started) {
F = H;
D_diff = D;
}
if (reset_incremental_fock_formation && incremental_Fbuild_started) {
reset_incremental_fock_formation = false;
last_reset_iteration = iter;
next_reset_threshold = rms_error / 1e1;
std::cout << "== reset incremental fock build" << std::endl;
}
// build a new Fock matrix
if (not do_density_fitting) {
// totally empirical precision variation, involves the condition number
const auto precision_F = std::min(
std::min(1e-3 / XtX_condition_number, 1e-7),
std::max(rms_error / 1e4, std::numeric_limits<double>::epsilon()));
F += compute_2body_fock(obs, D_diff, precision_F, K);
}
#if HAVE_DENSITY_FITTING
else { // do DF
F = H + dffockengine->compute_2body_fock_dfC(C_occ);
}
#else
else {
assert(false);
} // do_density_fitting is true but HAVE_DENSITY_FITTING is not defined!
// should not happen
#endif // HAVE_DENSITY_FITTING
// compute HF energy with the non-extrapolated Fock matrix
ehf = D.cwiseProduct(H + F).sum();
ediff_rel = std::abs((ehf - ehf_last) / ehf);
// compute SCF error
Matrix FD_comm = F * D * S - S * D * F;
rms_error = FD_comm.norm() / n2;
if (rms_error < next_reset_threshold || iter - last_reset_iteration >= 8)
reset_incremental_fock_formation = true;
// DIIS extrapolate F
Matrix F_diis = F; // extrapolated F cannot be used in incremental Fock
// build; only used to produce the density
// make a copy of the unextrapolated matrix
diis.extrapolate(F_diis, FD_comm);
// solve F C = e S C by (conditioned) transformation to F' C' = e C',
// where
// F' = X.transpose() . F . X; the original C is obtained as C = X . C'
Eigen::SelfAdjointEigenSolver<Matrix> eig_solver(X.transpose() * F_diis *
X);
evals = eig_solver.eigenvalues();
auto C = X * eig_solver.eigenvectors();
// compute density, D = C(occ) . C(occ)T
C_occ = C.leftCols(ndocc);
D = C_occ * C_occ.transpose();
D_diff = D - D_last;
const auto tstop = std::chrono::high_resolution_clock::now();
const std::chrono::duration<double> time_elapsed = tstop - tstart;
if (iter == 1)
std::cout << "\n\nIter E(HF) D(E)/E "
"RMS([F,D])/nn Time(s)\n";
printf(" %02d %20.12f %20.12e %20.12e %10.5lf\n", iter, ehf + enuc,
ediff_rel, rms_error, time_elapsed.count());
} while (((ediff_rel > conv) || (rms_error > conv)) && (iter < maxiter));
printf("** Hartree-Fock energy = %20.12f\n", ehf + enuc);
auto Mu = compute_1body_ints<Operator::emultipole2>(obs);
std::array<double, 3> mu;
std::array<double, 6> qu;
for (int xyz = 0; xyz != 3; ++xyz)
mu[xyz] = -2 *
D.cwiseProduct(Mu[xyz + 1])
.sum(); // 2 = alpha + beta, -1 = electron charge
for (int k = 0; k != 6; ++k)
qu[k] = -2 *
D.cwiseProduct(Mu[k + 4])
.sum(); // 2 = alpha + beta, -1 = electron charge
std::cout << "** edipole = ";
std::copy(mu.begin(), mu.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
std::cout << "** equadrupole = ";
std::copy(qu.begin(), qu.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
{ // compute force
#if LIBINT2_DERIV_ONEBODY_ORDER
// compute 1-e forces
Matrix F1 = Matrix::Zero(atoms.size(), 3);
Matrix F_Pulay = Matrix::Zero(atoms.size(), 3);
//////////
// one-body contributions to the forces
//////////
auto T1 = compute_1body_ints_deriv<Operator::kinetic>(1, obs, atoms);
auto V1 = compute_1body_ints_deriv<Operator::nuclear>(1, obs, atoms);
for (auto atom = 0, i = 0; atom != atoms.size(); ++atom) {
for (auto xyz = 0; xyz != 3; ++xyz, ++i) {
auto force = 2 * (T1[i] + V1[i]).cwiseProduct(D).sum();
F1(atom, xyz) += force;
}
}
//////////
// Pulay force
//////////
// orbital energy density
DiagonalMatrix evals_occ(evals.topRows(ndocc));
Matrix W = C_occ * evals_occ * C_occ.transpose();
auto S1 = compute_1body_ints_deriv<Operator::overlap>(1, obs, atoms);
for (auto atom = 0, i = 0; atom != atoms.size(); ++atom) {
for (auto xyz = 0; xyz != 3; ++xyz, ++i) {
auto force = 2 * S1[i].cwiseProduct(W).sum();
F_Pulay(atom, xyz) -= force;
}
}
std::cout << "** 1-body forces = ";
for (int atom = 0; atom != atoms.size(); ++atom)
for (int xyz = 0; xyz != 3; ++xyz) std::cout << F1(atom, xyz) << " ";
std::cout << std::endl;
std::cout << "** Pulay forces = ";
for (int atom = 0; atom != atoms.size(); ++atom)
for (int xyz = 0; xyz != 3; ++xyz)
std::cout << F_Pulay(atom, xyz) << " ";
std::cout << std::endl;
#endif // LIBINT2_DERIV_ONEBODY_ORDER
#if LIBINT2_DERIV_ERI_ORDER
// compute 2-e forces
Matrix F2 = Matrix::Zero(atoms.size(), 3);
//////////
// two-body contributions to the forces
//////////
auto G1 = compute_2body_fock_deriv<1>(obs, atoms, D);
for (auto atom = 0, i = 0; atom != atoms.size(); ++atom) {
for (auto xyz = 0; xyz != 3; ++xyz, ++i) {
// identity prefactor since E(HF) = trace(H + F, D) = trace(2H + G, D)
auto force = G1[i].cwiseProduct(D).sum();
F2(atom, xyz) += force;
}
}
std::cout << "** 2-body forces = ";
for (int atom = 0; atom != atoms.size(); ++atom)
for (int xyz = 0; xyz != 3; ++xyz) std::cout << F2(atom, xyz) << " ";
std::cout << std::endl;
#endif
// if support 1-e and 2-e derivatives compute nuclear repulsion force and the
// total force
#if LIBINT2_DERIV_ONEBODY_ORDER && LIBINT2_DERIV_ERI_ORDER
// compute nuclear repulsion forces
Matrix FN = Matrix::Zero(atoms.size(), 3);
//////////
// nuclear repulsion contribution to the forces
//////////
for (auto a1 = 1; a1 != atoms.size(); ++a1) {
const auto& atom1 = atoms[a1];
for (auto a2 = 0; a2 < a1; ++a2) {
const auto& atom2 = atoms[a2];
auto x12 = atom1.x - atom2.x;
auto y12 = atom1.y - atom2.y;
auto z12 = atom1.z - atom2.z;
auto r12_2 = x12 * x12 + y12 * y12 + z12 * z12;
auto r12 = sqrt(r12_2);
auto r12_3 = r12 * r12_2;
auto z1z2_over_r12_3 =
atom1.atomic_number * atom2.atomic_number / r12_3;
auto fx = -x12 * z1z2_over_r12_3;
auto fy = -y12 * z1z2_over_r12_3;
auto fz = -z12 * z1z2_over_r12_3;
FN(a1, 0) += fx;
FN(a1, 1) += fy;
FN(a1, 2) += fz;
FN(a2, 0) -= fx;
FN(a2, 1) -= fy;
FN(a2, 2) -= fz;
}
}
std::cout << "** nuclear repulsion forces = ";
for (int atom = 0; atom != atoms.size(); ++atom)
for (int xyz = 0; xyz != 3; ++xyz) std::cout << FN(atom, xyz) << " ";
std::cout << std::endl;
auto F = F1 + F_Pulay + F2 + FN;
std::cout << "** Hartree-Fock forces = ";
for (int atom = 0; atom != atoms.size(); ++atom)
for (int xyz = 0; xyz != 3; ++xyz) std::cout << F(atom, xyz) << " ";
std::cout << std::endl;
#endif
}
{ // compute hessian
const auto ncoords = 3 * atoms.size();
// # of elems in upper triangle
const auto nelem = ncoords * (ncoords+1) / 2;
#if LIBINT2_DERIV_ONEBODY_ORDER > 1
// compute 1-e hessian
Matrix H1 = Matrix::Zero(ncoords, ncoords);
Matrix H_Pulay = Matrix::Zero(ncoords, ncoords);
//////////
// one-body contributions to the hessian
//////////
auto T2 = compute_1body_ints_deriv<Operator::kinetic>(2, obs, atoms);
auto V2 = compute_1body_ints_deriv<Operator::nuclear>(2, obs, atoms);
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col, ++i) {
auto hess = 2 * (T2[i] + V2[i]).cwiseProduct(D).sum();
H1(row, col) += hess;
}
}
//////////
// Pulay hessian
//////////
// orbital energy density
DiagonalMatrix evals_occ(evals.topRows(ndocc));
Matrix W = C_occ * evals_occ * C_occ.transpose();
auto S2 = compute_1body_ints_deriv<Operator::overlap>(2, obs, atoms);
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col, ++i) {
auto hess = 2 * S2[i].cwiseProduct(W).sum();
H_Pulay(row, col) -= hess;
}
}
std::cout << "** 1-body hessian = ";
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col) {
std::cout << H1(row, col) << " ";
}
}
std::cout << std::endl;
std::cout << "** Pulay hessian = ";
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col) {
std::cout << H_Pulay(row, col) << " ";
}
}
std::cout << std::endl;
#endif // LIBINT2_DERIV_ONEBODY_ORDER > 1
#if LIBINT2_DERIV_ERI_ORDER > 1
// compute 2-e forces
Matrix H2 = Matrix::Zero(ncoords, ncoords);
//////////
// two-body contributions to the forces
//////////
auto G2 = compute_2body_fock_deriv<2>(obs, atoms, D);
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col, ++i) {
// identity prefactor since E(HF) = trace(H + F, D) = trace(2H + G, D)
auto hess = G2[i].cwiseProduct(D).sum();
H2(row, col) += hess;
}
}
std::cout << "** 2-body hessian = ";
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col) {
std::cout << H2(row, col) << " ";
}
}
std::cout << std::endl;
#endif
// if support 1-e and 2-e 2nd derivatives compute nuclear repulsion hessian and
// the total hessian
#if LIBINT2_DERIV_ONEBODY_ORDER > 1 && LIBINT2_DERIV_ERI_ORDER > 1
// compute nuclear repulsion hessian
// NB only the upper triangle is computed!!!
Matrix HN = Matrix::Zero(ncoords, ncoords);
//////////
// nuclear repulsion contribution to the hessian
//////////
for (auto a1 = 1; a1 != atoms.size(); ++a1) {
const auto& atom1 = atoms[a1];
for (auto a2 = 0; a2 < a1; ++a2) {
const auto& atom2 = atoms[a2];
auto x12 = atom1.x - atom2.x;
auto y12 = atom1.y - atom2.y;
auto z12 = atom1.z - atom2.z;
auto x12_2 = x12 * x12;
auto y12_2 = y12 * y12;
auto z12_2 = z12 * z12;
auto r12_2 = x12 * x12 + y12 * y12 + z12 * z12;
auto r12 = sqrt(r12_2);
auto r12_5 = r12 * r12_2 * r12_2;
auto z1z2_over_r12_5 =
atom1.atomic_number * atom2.atomic_number / r12_5;
HN(3*a1 + 0, 3*a1 + 0) += z1z2_over_r12_5 * (3*x12_2 - r12_2);
HN(3*a1 + 1, 3*a1 + 1) += z1z2_over_r12_5 * (3*y12_2 - r12_2);
HN(3*a1 + 2, 3*a1 + 2) += z1z2_over_r12_5 * (3*z12_2 - r12_2);
HN(3*a1 + 0, 3*a1 + 1) += z1z2_over_r12_5 * (3*x12*y12);
HN(3*a1 + 0, 3*a1 + 2) += z1z2_over_r12_5 * (3*x12*z12);
HN(3*a1 + 1, 3*a1 + 2) += z1z2_over_r12_5 * (3*y12*z12);
HN(3*a2 + 0, 3*a2 + 0) += z1z2_over_r12_5 * (3*x12_2 - r12_2);
HN(3*a2 + 1, 3*a2 + 1) += z1z2_over_r12_5 * (3*y12_2 - r12_2);
HN(3*a2 + 2, 3*a2 + 2) += z1z2_over_r12_5 * (3*z12_2 - r12_2);
HN(3*a2 + 0, 3*a2 + 1) += z1z2_over_r12_5 * (3*x12*y12);
HN(3*a2 + 0, 3*a2 + 2) += z1z2_over_r12_5 * (3*x12*z12);
HN(3*a2 + 1, 3*a2 + 2) += z1z2_over_r12_5 * (3*y12*z12);
HN(3*a2 + 0, 3*a1 + 0) -= z1z2_over_r12_5 * (3*x12_2 - r12_2);
HN(3*a2 + 1, 3*a1 + 1) -= z1z2_over_r12_5 * (3*y12_2 - r12_2);
HN(3*a2 + 2, 3*a1 + 2) -= z1z2_over_r12_5 * (3*z12_2 - r12_2);
HN(3*a2 + 1, 3*a1 + 0) -= z1z2_over_r12_5 * (3*y12*x12);
HN(3*a2 + 2, 3*a1 + 0) -= z1z2_over_r12_5 * (3*z12*x12);
HN(3*a2 + 2, 3*a1 + 1) -= z1z2_over_r12_5 * (3*z12*y12);
HN(3*a2 + 0, 3*a1 + 1) -= z1z2_over_r12_5 * (3*x12*y12);
HN(3*a2 + 0, 3*a1 + 2) -= z1z2_over_r12_5 * (3*x12*z12);
HN(3*a2 + 1, 3*a1 + 2) -= z1z2_over_r12_5 * (3*y12*z12);
}
}
std::cout << "** nuclear repulsion hessian = ";
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col) {
std::cout << HN(row, col) << " ";
}
}
std::cout << std::endl;
auto H = H1 + H_Pulay + H2 + HN;
std::cout << "** Hartree-Fock hessian = ";
for (auto row = 0, i = 0; row != ncoords; ++row) {
for (auto col = row; col != ncoords; ++col) {
std::cout << H(row, col) << " ";
}
}
std::cout << std::endl;
#endif
}
libint2::finalize(); // done with libint
} // end of try block; if any exceptions occurred, report them and exit
// cleanly
catch (const char* ex) {
cerr << "caught exception: " << ex << endl;
return 1;
} catch (std::string& ex) {
cerr << "caught exception: " << ex << endl;
return 1;
} catch (std::exception& ex) {
cerr << ex.what() << endl;
return 1;
} catch (...) {
cerr << "caught unknown exception\n";
return 1;
}
return 0;
}
std::vector<libint2::Atom> read_geometry(const std::string& filename) {
std::cout << "Will read geometry from " << filename << std::endl;
std::ifstream is(filename);
if (not is.good()) {
char errmsg[256] = "Could not open file ";
strncpy(errmsg + 20, filename.c_str(), 235);
errmsg[255] = '\0';
throw std::ios_base::failure(errmsg);
}
// to prepare for MPI parallelization, we will read the entire file into a
// string that can be
// broadcast to everyone, then converted to an std::istringstream object that
// can be used just like std::ifstream
std::ostringstream oss;
oss << is.rdbuf();
// use ss.str() to get the entire contents of the file as an std::string
// broadcast
// then make an std::istringstream in each process
std::istringstream iss(oss.str());
// check the extension: if .xyz, assume the standard XYZ format, otherwise
// throw an exception
if (filename.rfind(".xyz") != std::string::npos)
return libint2::read_dotxyz(iss);
else
throw "only .xyz files are accepted";
}
// computes Superposition-Of-libint2::Atomic-Densities guess for the molecular density
// matrix
// in minimal basis; occupies subshells by smearing electrons evenly over the
// orbitals
Matrix compute_soad(const std::vector<libint2::Atom>& atoms) {
// compute number of atomic orbitals
size_t nao = 0;
for (const auto& atom : atoms) {
const auto Z = atom.atomic_number;
nao += libint2::sto3g_num_ao(Z);
}
// compute the minimal basis density
Matrix D = Matrix::Zero(nao, nao);
size_t ao_offset = 0; // first AO of this atom
for (const auto& atom : atoms) {
const auto Z = atom.atomic_number;
const auto& occvec = libint2::sto3g_ao_occupation_vector(Z);
for(const auto& occ: occvec) {
D(ao_offset, ao_offset) = occ;
++ao_offset;
}
}
return D * 0.5; // we use densities normalized to # of electrons/2
}
Matrix compute_shellblock_norm(const BasisSet& obs, const Matrix& A) {
const auto nsh = obs.size();
Matrix Ash(nsh, nsh);
auto shell2bf = obs.shell2bf();
for (size_t s1 = 0; s1 != nsh; ++s1) {
const auto& s1_first = shell2bf[s1];
const auto& s1_size = obs[s1].size();
for (size_t s2 = 0; s2 != nsh; ++s2) {
const auto& s2_first = shell2bf[s2];
const auto& s2_size = obs[s2].size();
Ash(s1, s2) = A.block(s1_first, s2_first, s1_size, s2_size)
.lpNorm<Eigen::Infinity>();
}
}
return Ash;
}
template <Operator obtype, typename OperatorParams>
std::array<Matrix, libint2::operator_traits<obtype>::nopers> compute_1body_ints(
const BasisSet& obs, OperatorParams params) {
const auto n = obs.nbf();
const auto nshells = obs.size();
using libint2::nthreads;
typedef std::array<Matrix, libint2::operator_traits<obtype>::nopers>
result_type;
const unsigned int nopers = libint2::operator_traits<obtype>::nopers;
result_type result;
for (auto& r : result) r = Matrix::Zero(n, n);
// construct the 1-body integrals engine
std::vector<libint2::Engine> engines(nthreads);
engines[0] = libint2::Engine(obtype, obs.max_nprim(), obs.max_l(), 0);
// nuclear attraction ints engine needs to know where the charges sit ...
// the nuclei are charges in this case; in QM/MM there will also be classical
// charges
if (obtype == Operator::nuclear || obtype == Operator::erf_nuclear ||
obtype == Operator::erfc_nuclear) {
engines[0].set_params(params);
}
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
auto shell2bf = obs.shell2bf();
auto compute = [&](int thread_id) {
const auto& buf = engines[thread_id].results();
// loop over unique shell pairs, {s1,s2} such that s1 >= s2
// this is due to the permutational symmetry of the real integrals over
// Hermitian operators: (1|2) = (2|1)
for (auto s1 = 0l, s12 = 0l; s1 != nshells; ++s1) {
auto bf1 = shell2bf[s1]; // first basis function in this shell
auto n1 = obs[s1].size();
auto s1_offset = s1 * (s1+1) / 2;
for(auto s2: obs_shellpair_list[s1]) {
auto s12 = s1_offset + s2;
if (s12 % nthreads != thread_id) continue;
auto bf2 = shell2bf[s2];
auto n2 = obs[s2].size();
auto n12 = n1 * n2;
// compute shell pair; return is the pointer to the buffer
engines[thread_id].compute(obs[s1], obs[s2]);
for (unsigned int op = 0; op != nopers; ++op) {
// "map" buffer to a const Eigen Matrix, and copy it to the
// corresponding blocks of the result
Eigen::Map<const Matrix> buf_mat(buf[op], n1, n2);
result[op].block(bf1, bf2, n1, n2) = buf_mat;
if (s1 != s2) // if s1 >= s2, copy {s1,s2} to the corresponding
// {s2,s1} block, note the transpose!
result[op].block(bf2, bf1, n2, n1) = buf_mat.transpose();
}
}
}
}; // compute lambda
libint2::parallel_do(compute);
return result;
}
#if LIBINT2_DERIV_ONEBODY_ORDER
template <Operator obtype>
std::vector<Matrix> compute_1body_ints_deriv(unsigned deriv_order,
const BasisSet& obs,
const std::vector<libint2::Atom>& atoms) {
using libint2::nthreads;
const auto n = obs.nbf();
const auto nshells = obs.size();
constexpr auto nopers = libint2::operator_traits<obtype>::nopers;
const auto nresults =
nopers * libint2::num_geometrical_derivatives(atoms.size(), deriv_order);
typedef std::vector<Matrix> result_type;
result_type result(nresults);
for (auto& r : result) r = Matrix::Zero(n, n);
// construct the 1-body integrals engine
std::vector<libint2::Engine> engines(nthreads);
engines[0] =
libint2::Engine(obtype, obs.max_nprim(), obs.max_l(), deriv_order);
// nuclear attraction ints engine needs to know where the charges sit ...
// the nuclei are charges in this case; in QM/MM there will also be classical
// charges
if (obtype == Operator::nuclear) {
std::vector<std::pair<double, std::array<double, 3>>> q;
for (const auto& atom : atoms) {
q.push_back({static_cast<double>(atom.atomic_number),
{{atom.x, atom.y, atom.z}}});
}
engines[0].set_params(q);
}
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
auto shell2bf = obs.shell2bf();
auto shell2atom = obs.shell2atom(atoms);
const auto natoms = atoms.size();
const auto two_times_ncoords = 6*natoms;
const auto nderivcenters_shset =
2 + ((obtype == Operator::nuclear) ? natoms : 0);
auto compute = [&](int thread_id) {
const auto& buf = engines[thread_id].results();
// loop over unique shell pairs, {s1,s2} such that s1 >= s2
// this is due to the permutational symmetry of the real integrals over
// Hermitian operators: (1|2) = (2|1)
for (auto s1 = 0l, s12 = 0l; s1 != nshells; ++s1) {
auto bf1 = shell2bf[s1]; // first basis function in this shell
auto n1 = obs[s1].size();
auto atom1 = shell2atom[s1];
assert(atom1 != -1);
auto s1_offset = s1 * (s1+1) / 2;
for(auto s2: obs_shellpair_list[s1]) {
auto s12 = s1_offset + s2;
if (s12 % nthreads != thread_id) continue;
auto bf2 = shell2bf[s2];
auto n2 = obs[s2].size();
auto atom2 = shell2atom[s2];
auto n12 = n1 * n2;
// compute shell pair; return is the pointer to the buffer
engines[thread_id].compute(obs[s1], obs[s2]);
// "copy" lambda copies shell set \c idx to the operator matrix with
// index \c op
auto add_shellset_to_dest = [&](std::size_t op, std::size_t idx,
double scale = 1.0) {
// "map" buffer to a const Eigen Matrix, and copy it to the
// corresponding blocks of the result
Eigen::Map<const Matrix> buf_mat(buf[idx], n1, n2);
if (scale == 1.0)
result[op].block(bf1, bf2, n1, n2) += buf_mat;
else
result[op].block(bf1, bf2, n1, n2) += scale * buf_mat;
if (s1 != s2) { // if s1 >= s2, copy {s1,s2} to the corresponding
// {s2,s1} block, note the transpose!
if (scale == 1.0)
result[op].block(bf2, bf1, n2, n1) += buf_mat.transpose();
else
result[op].block(bf2, bf1, n2, n1) += scale * buf_mat.transpose();
}
};
switch (deriv_order) {
case 0:
for (std::size_t op = 0; op != nopers; ++op) {
add_shellset_to_dest(op, op);
}
break;
// map deriv quanta for this shell pair to the overall deriv quanta
//
// easiest to explain with example:
// in sto-3g water shells 0 1 2 sit on atom 0, shells 3 and 4 on atoms
// 1 and 2 respectively
// each call to engine::compute for nuclear ints will return
// derivatives
// with respect to 15 coordinates, obtained as 3 (x,y,z) times 2 + 3 =
// 5 centers
// (2 centers on which shells sit + 3 nuclear charges)
// (for overlap, kinetic, and emultipole ints we there are only 6
// coordinates
// since the operator is coordinate-independent, or derivatives with
// respect to
// the operator coordinates are not computed)
//
case 1: {
std::size_t shellset_idx = 0;
for (auto c = 0; c != nderivcenters_shset; ++c) {
auto atom = (c == 0) ? atom1 : ((c == 1) ? atom2 : c - 2);
auto op_start = 3 * atom * nopers;
auto op_fence = op_start + nopers;
for (auto xyz = 0; xyz != 3;
++xyz, op_start += nopers, op_fence += nopers) {
for (unsigned int op = op_start; op != op_fence;
++op, ++shellset_idx) {
add_shellset_to_dest(op, shellset_idx);
}
}
}
} break;
case 2: {
//
// must pay attention to symmetry when computing 2nd and higher-order derivs
// e.g. d2 (s1|s2) / dX dY involves several cases:
// 1. only s1 (or only s2) depends on X AND Y (i.e. X and Y refer to same atom) =>
// d2 (s1|s2) / dX dY = (d2 s1 / dX dY | s2)
// 2. s1 depends on X only, s2 depends on Y only (or vice versa) =>
// d2 (s1|s2) / dX dY = (d s1 / dX | d s2 / dY)
// 3. s1 AND s2 depend on X AND Y (i.e. X and Y refer to same atom) =>
// case A: X != Y
// d2 (s1|s2) / dX dY = (d2 s1 / dX dY | s2) + (d s1 / dX | d s2 / dY)
// + (d s1 / dY | d s2 / dX) + (s1| d2 s2 / dX dY )
// case B: X == Y
// d2 (s1|s2) / dX2 = (d2 s1 / dX2 | s2) + 2 (d s1 / dX | d s2 / dX)
// + (s1| d2 s2 / dX2 )
// computes upper triangle index
// n2 = matrix size times 2
// i,j = (unordered) indices
#define upper_triangle_index(n2, i, j) \
(std::min((i), (j))) * ((n2) - (std::min((i), (j))) - 1) / 2 + \
(std::max((i), (j)))
// look over shellsets in the order in which they appear
std::size_t shellset_idx = 0;
for (auto c1 = 0; c1 != nderivcenters_shset; ++c1) {
auto a1 = (c1 == 0) ? atom1 : ((c1 == 1) ? atom2 : c1 - 2);
auto coord1 = 3 * a1;
for (auto xyz1 = 0; xyz1 != 3; ++xyz1, ++coord1) {
for (auto c2 = c1; c2 != nderivcenters_shset; ++c2) {
auto a2 = (c2 == 0) ? atom1 : ((c2 == 1) ? atom2 : c2 - 2);
auto xyz2_start = (c1 == c2) ? xyz1 : 0;
auto coord2 = 3 * a2 + xyz2_start;
for (auto xyz2 = xyz2_start; xyz2 != 3;
++xyz2, ++coord2) {
double scale = (coord1 == coord2 && c1 != c2) ? 2.0 : 1.0;
const auto coord12 =
upper_triangle_index(two_times_ncoords, coord1, coord2);
auto op_start = coord12 * nopers;
auto op_fence = op_start + nopers;
for (auto op = op_start; op != op_fence;
++op, ++shellset_idx) {
add_shellset_to_dest(op, shellset_idx, scale);
}
}
}
}
}
} break;
#undef upper_triangle_index
default: {
assert(false && "not yet implemented");
using ShellSetDerivIterator =
libint2::FixedOrderedIntegerPartitionIterator<
std::vector<unsigned int>>;
ShellSetDerivIterator shellset_diter(deriv_order,
nderivcenters_shset);
while (shellset_diter) {
const auto& deriv = *shellset_diter;
}
}
} // copy shell block switch
} // s2 <= s1
} // s1
}; // compute lambda
libint2::parallel_do(compute);
return result;
}
#endif
template <libint2::Operator Kernel>
Matrix compute_schwarz_ints(
const BasisSet& bs1, const BasisSet& _bs2, bool use_2norm,
typename libint2::operator_traits<Kernel>::oper_params_type params) {
const BasisSet& bs2 = (_bs2.empty() ? bs1 : _bs2);
const auto nsh1 = bs1.size();
const auto nsh2 = bs2.size();
const auto bs1_equiv_bs2 = (&bs1 == &bs2);
Matrix K = Matrix::Zero(nsh1, nsh2);
// construct the 2-electron repulsion integrals engine
using libint2::Engine;
using libint2::nthreads;
std::vector<Engine> engines(nthreads);
// !!! very important: cannot screen primitives in Schwarz computation !!!
auto epsilon = 0.;
engines[0] = Engine(Kernel, std::max(bs1.max_nprim(), bs2.max_nprim()),
std::max(bs1.max_l(), bs2.max_l()), 0, epsilon, params);
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
std::cout << "computing Schwarz bound prerequisites (kernel=" << (int)Kernel
<< ") ... ";
libint2::Timers<1> timer;
timer.set_now_overhead(25);
timer.start(0);
auto compute = [&](int thread_id) {
const auto& buf = engines[thread_id].results();
// loop over permutationally-unique set of shells
for (auto s1 = 0l, s12 = 0l; s1 != nsh1; ++s1) {
auto n1 = bs1[s1].size(); // number of basis functions in this shell
auto s2_max = bs1_equiv_bs2 ? s1 : nsh2 - 1;
for (auto s2 = 0; s2 <= s2_max; ++s2, ++s12) {
if (s12 % nthreads != thread_id) continue;
auto n2 = bs2[s2].size();
auto n12 = n1 * n2;
engines[thread_id].compute2<Kernel, BraKet::xx_xx, 0>(bs1[s1], bs2[s2],
bs1[s1], bs2[s2]);
assert(buf[0] != nullptr &&
"to compute Schwarz ints turn off primitive screening");
// the diagonal elements are the Schwarz ints ... use Map.diagonal()
Eigen::Map<const Matrix> buf_mat(buf[0], n12, n12);
auto norm2 = use_2norm ? buf_mat.diagonal().norm()
: buf_mat.diagonal().lpNorm<Eigen::Infinity>();
K(s1, s2) = std::sqrt(norm2);
if (bs1_equiv_bs2) K(s2, s1) = K(s1, s2);
}
}
}; // thread lambda
libint2::parallel_do(compute);
timer.stop(0);
std::cout << "done (" << timer.read(0) << " s)" << std::endl;
return K;
}
Matrix compute_do_ints(const BasisSet& bs1, const BasisSet& bs2,
bool use_2norm) {
return compute_schwarz_ints<libint2::Operator::delta>(bs1, bs2, use_2norm);
}
shellpair_list_t compute_shellpair_list(const BasisSet& bs1,
const BasisSet& _bs2,
const double threshold) {
const BasisSet& bs2 = (_bs2.empty() ? bs1 : _bs2);
const auto nsh1 = bs1.size();
const auto nsh2 = bs2.size();
const auto bs1_equiv_bs2 = (&bs1 == &bs2);
using libint2::nthreads;
// construct the 2-electron repulsion integrals engine
using libint2::Engine;
std::vector<Engine> engines;
engines.reserve(nthreads);
engines.emplace_back(Operator::overlap,
std::max(bs1.max_nprim(), bs2.max_nprim()),
std::max(bs1.max_l(), bs2.max_l()), 0);
for (size_t i = 1; i != nthreads; ++i) {
engines.push_back(engines[0]);
}
std::cout << "computing non-negligible shell-pair list ... ";
libint2::Timers<1> timer;
timer.set_now_overhead(25);
timer.start(0);
shellpair_list_t result;
std::mutex mx;
auto compute = [&](int thread_id) {
auto& engine = engines[thread_id];
const auto& buf = engine.results();
// loop over permutationally-unique set of shells
for (auto s1 = 0l, s12 = 0l; s1 != nsh1; ++s1) {
mx.lock();
if (result.find(s1) == result.end())
result.insert(std::make_pair(s1, std::vector<size_t>()));
mx.unlock();
auto n1 = bs1[s1].size(); // number of basis functions in this shell
auto s2_max = bs1_equiv_bs2 ? s1 : nsh2 - 1;
for (auto s2 = 0; s2 <= s2_max; ++s2, ++s12) {
if (s12 % nthreads != thread_id) continue;
auto on_same_center = (bs1[s1].O == bs2[s2].O);
bool significant = on_same_center;
if (not on_same_center) {
auto n2 = bs2[s2].size();
engines[thread_id].compute(bs1[s1], bs2[s2]);
Eigen::Map<const Matrix> buf_mat(buf[0], n1, n2);
auto norm = buf_mat.norm();
significant = (norm >= threshold);
}
if (significant) {
mx.lock();
result[s1].emplace_back(s2);
mx.unlock();
}
}
}
}; // end of compute
libint2::parallel_do(compute);
// resort shell list in increasing order, i.e. result[s][s1] < result[s][s2]
// if s1 < s2
auto sort = [&](int thread_id) {
for (auto s1 = 0l; s1 != nsh1; ++s1) {
if (s1 % nthreads == thread_id) {
auto& list = result[s1];
std::sort(list.begin(), list.end());
}
}
}; // end of sort
libint2::parallel_do(sort);
timer.stop(0);
std::cout << "done (" << timer.read(0) << " s)" << std::endl;
return result;
}
// returns {X,X^{-1},rank,A_condition_number,result_A_condition_number}, where
// X is the generalized square-root-inverse such that X.transpose() * A * X = I
//
// if symmetric is true, produce "symmetric" sqrtinv: X = U . A_evals_sqrtinv .
// U.transpose()),
// else produce "canonical" sqrtinv: X = U . A_evals_sqrtinv
// where U are eigenvectors of A
// rows and cols of symmetric X are equivalent; for canonical X the rows are
// original basis (AO),
// cols are transformed basis ("orthogonal" AO)
//
// A is conditioned to max_condition_number
std::tuple<Matrix, Matrix, size_t, double, double> gensqrtinv(
const Matrix& S, bool symmetric = false,
double max_condition_number = 1e8) {
Eigen::SelfAdjointEigenSolver<Matrix> eig_solver(S);
auto U = eig_solver.eigenvectors();
auto s = eig_solver.eigenvalues();
auto s_max = s.maxCoeff();
auto condition_number = std::min(
s_max / std::max(s.minCoeff(), std::numeric_limits<double>::min()),
1.0 / std::numeric_limits<double>::epsilon());
auto threshold = s_max / max_condition_number;
long n = s.rows();
long n_cond = 0;
for (long i = n - 1; i >= 0; --i) {
if (s(i) >= threshold) {
++n_cond;
} else
i = 0; // skip rest since eigenvalues are in ascending order
}
auto sigma = s.bottomRows(n_cond);
auto result_condition_number = sigma.maxCoeff() / sigma.minCoeff();
auto sigma_sqrt = sigma.array().sqrt().matrix().asDiagonal();
auto sigma_invsqrt = sigma.array().sqrt().inverse().matrix().asDiagonal();
// make canonical X/Xinv
auto U_cond = U.block(0, n - n_cond, n, n_cond);
Matrix X = U_cond * sigma_invsqrt;
Matrix Xinv = U_cond * sigma_sqrt;
// convert to symmetric, if needed
if (symmetric) {
X = X * U_cond.transpose();
Xinv = Xinv * U_cond.transpose();
}
return std::make_tuple(X, Xinv, size_t(n_cond), condition_number,
result_condition_number);
}
std::tuple<Matrix, Matrix, double> conditioning_orthogonalizer(
const Matrix& S, double S_condition_number_threshold) {
size_t obs_rank;
double S_condition_number;
double XtX_condition_number;
Matrix X, Xinv;
assert(S.rows() == S.cols());
std::tie(X, Xinv, obs_rank, S_condition_number, XtX_condition_number) =
gensqrtinv(S, false, S_condition_number_threshold);
auto obs_nbf_omitted = (long)S.rows() - (long)obs_rank;
std::cout << "overlap condition number = " << S_condition_number;
if (obs_nbf_omitted > 0)
std::cout << " (dropped " << obs_nbf_omitted << " "
<< (obs_nbf_omitted > 1 ? "fns" : "fn") << " to reduce to "
<< XtX_condition_number << ")";
std::cout << std::endl;
if (obs_nbf_omitted > 0) {
Matrix should_be_I = X.transpose() * S * X;
Matrix I = Matrix::Identity(should_be_I.rows(), should_be_I.cols());
std::cout << "||X^t * S * X - I||_2 = " << (should_be_I - I).norm()
<< " (should be 0)" << std::endl;
}
return std::make_tuple(X, Xinv, XtX_condition_number);
}
Matrix compute_2body_2index_ints(const BasisSet& bs) {
using libint2::nthreads;
const auto n = bs.nbf();
const auto nshells = bs.size();
Matrix result = Matrix::Zero(n, n);
// build engines for each thread
using libint2::Engine;
std::vector<Engine> engines(nthreads);
engines[0] =
Engine(libint2::Operator::coulomb, bs.max_nprim(), bs.max_l(), 0);
engines[0].set(BraKet::xs_xs);
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
auto shell2bf = bs.shell2bf();
auto unitshell = Shell::unit();
auto compute = [&](int thread_id) {
auto& engine = engines[thread_id];
const auto& buf = engine.results();
// loop over unique shell pairs, {s1,s2} such that s1 >= s2
// this is due to the permutational symmetry of the real integrals over
// Hermitian operators: (1|2) = (2|1)
for (auto s1 = 0l, s12 = 0l; s1 != nshells; ++s1) {
auto bf1 = shell2bf[s1]; // first basis function in this shell
auto n1 = bs[s1].size();
for (auto s2 = 0; s2 <= s1; ++s2, ++s12) {
if (s12 % nthreads != thread_id) continue;
auto bf2 = shell2bf[s2];
auto n2 = bs[s2].size();
// compute shell pair; return is the pointer to the buffer
engine.compute(bs[s1], bs[s2]);
if (buf[0] == nullptr)
continue; // if all integrals screened out, skip to next shell set
// "map" buffer to a const Eigen Matrix, and copy it to the
// corresponding blocks of the result
Eigen::Map<const Matrix> buf_mat(buf[0], n1, n2);
result.block(bf1, bf2, n1, n2) = buf_mat;
if (s1 != s2) // if s1 >= s2, copy {s1,s2} to the corresponding {s2,s1}
// block, note the transpose!
result.block(bf2, bf1, n2, n1) = buf_mat.transpose();
}
}
}; // compute lambda
libint2::parallel_do(compute);
return result;
}
Matrix compute_2body_fock(const BasisSet& obs, const Matrix& D,
double precision, const Matrix& Schwarz) {
const auto n = obs.nbf();
const auto nshells = obs.size();
using libint2::nthreads;
std::vector<Matrix> G(nthreads, Matrix::Zero(n, n));
const auto do_schwarz_screen = Schwarz.cols() != 0 && Schwarz.rows() != 0;
Matrix D_shblk_norm =
compute_shellblock_norm(obs, D); // matrix of infty-norms of shell blocks
auto fock_precision = precision;
// engine precision controls primitive truncation, assume worst-case scenario
// (all primitive combinations add up constructively)
auto max_nprim = obs.max_nprim();
auto max_nprim4 = max_nprim * max_nprim * max_nprim * max_nprim;
auto engine_precision = std::min(fock_precision / D_shblk_norm.maxCoeff(),
std::numeric_limits<double>::epsilon()) /
max_nprim4;
// construct the 2-electron repulsion integrals engine pool
using libint2::Engine;
std::vector<Engine> engines(nthreads);
engines[0] = Engine(Operator::coulomb, obs.max_nprim(), obs.max_l(), 0);
engines[0].set_precision(engine_precision); // shellset-dependent precision
// control will likely break
// positive definiteness
// stick with this simple recipe
std::cout << "compute_2body_fock:precision = " << precision << std::endl;
std::cout << "Engine::precision = " << engines[0].precision() << std::endl;
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
std::atomic<size_t> num_ints_computed{0};
#if defined(REPORT_INTEGRAL_TIMINGS)
std::vector<libint2::Timers<1>> timers(nthreads);
#endif
auto shell2bf = obs.shell2bf();
auto lambda = [&](int thread_id) {
auto& engine = engines[thread_id];
auto& g = G[thread_id];
const auto& buf = engine.results();
#if defined(REPORT_INTEGRAL_TIMINGS)
auto& timer = timers[thread_id];
timer.clear();
timer.set_now_overhead(25);
#endif
// loop over permutationally-unique set of shells
for (auto s1 = 0l, s1234 = 0l; s1 != nshells; ++s1) {
auto bf1_first = shell2bf[s1]; // first basis function in this shell
auto n1 = obs[s1].size(); // number of basis functions in this shell
for (const auto& s2 : obs_shellpair_list[s1]) {
auto bf2_first = shell2bf[s2];
auto n2 = obs[s2].size();
const auto Dnorm12 = do_schwarz_screen ? D_shblk_norm(s1, s2) : 0.;
for (auto s3 = 0; s3 <= s1; ++s3) {
auto bf3_first = shell2bf[s3];
auto n3 = obs[s3].size();
const auto Dnorm123 =
do_schwarz_screen
? std::max(D_shblk_norm(s1, s3),
std::max(D_shblk_norm(s2, s3), Dnorm12))
: 0.;
const auto s4_max = (s1 == s3) ? s2 : s3;
for (const auto& s4 : obs_shellpair_list[s3]) {
if (s4 > s4_max)
break; // for each s3, s4 are stored in monotonically increasing
// order
if ((s1234++) % nthreads != thread_id) continue;
const auto Dnorm1234 =
do_schwarz_screen
? std::max(
D_shblk_norm(s1, s4),
std::max(D_shblk_norm(s2, s4),
std::max(D_shblk_norm(s3, s4), Dnorm123)))
: 0.;
if (do_schwarz_screen &&
Dnorm1234 * Schwarz(s1, s2) * Schwarz(s3, s4) <
fock_precision)
continue;
auto bf4_first = shell2bf[s4];
auto n4 = obs[s4].size();
num_ints_computed += n1 * n2 * n3 * n4;
// compute the permutational degeneracy (i.e. # of equivalents) of
// the given shell set
auto s12_deg = (s1 == s2) ? 1.0 : 2.0;
auto s34_deg = (s3 == s4) ? 1.0 : 2.0;
auto s12_34_deg = (s1 == s3) ? (s2 == s4 ? 1.0 : 2.0) : 2.0;
auto s1234_deg = s12_deg * s34_deg * s12_34_deg;
#if defined(REPORT_INTEGRAL_TIMINGS)
timer.start(0);
#endif
engine.compute2<Operator::coulomb, BraKet::xx_xx, 0>(
obs[s1], obs[s2], obs[s3], obs[s4]);
const auto* buf_1234 = buf[0];
if (buf_1234 == nullptr)
continue; // if all integrals screened out, skip to next quartet
#if defined(REPORT_INTEGRAL_TIMINGS)
timer.stop(0);
#endif
Eigen::Map<MatrixXd> buf_1234_map(buf_1234, n12, n34);
assert(buf_1234_map.norm() < Schwarz(s1, s2) * Schwarz(s3, s4));
// 1) each shell set of integrals contributes up to 6 shell sets of
// the Fock matrix:
// F(a,b) += (ab|cd) * D(c,d)
// F(c,d) += (ab|cd) * D(a,b)
// F(b,d) -= 1/4 * (ab|cd) * D(a,c)
// F(b,c) -= 1/4 * (ab|cd) * D(a,d)
// F(a,c) -= 1/4 * (ab|cd) * D(b,d)
// F(a,d) -= 1/4 * (ab|cd) * D(b,c)
// 2) each permutationally-unique integral (shell set) must be
// scaled by its degeneracy,
// i.e. the number of the integrals/sets equivalent to it
// 3) the end result must be symmetrized
for (auto f1 = 0, f1234 = 0; f1 != n1; ++f1) {
const auto bf1 = f1 + bf1_first;
for (auto f2 = 0; f2 != n2; ++f2) {
const auto bf2 = f2 + bf2_first;
for (auto f3 = 0; f3 != n3; ++f3) {
const auto bf3 = f3 + bf3_first;
for (auto f4 = 0; f4 != n4; ++f4, ++f1234) {
const auto bf4 = f4 + bf4_first;
const auto value = buf_1234[f1234];
const auto value_scal_by_deg = value * s1234_deg;
g(bf1, bf2) += D(bf3, bf4) * value_scal_by_deg;
g(bf3, bf4) += D(bf1, bf2) * value_scal_by_deg;
g(bf1, bf3) -= 0.25 * D(bf2, bf4) * value_scal_by_deg;
g(bf2, bf4) -= 0.25 * D(bf1, bf3) * value_scal_by_deg;
g(bf1, bf4) -= 0.25 * D(bf2, bf3) * value_scal_by_deg;
g(bf2, bf3) -= 0.25 * D(bf1, bf4) * value_scal_by_deg;
}
}
}
}
}
}
}
}
}; // end of lambda
libint2::parallel_do(lambda);
// accumulate contributions from all threads
for (size_t i = 1; i != nthreads; ++i) {
G[0] += G[i];
}
#if defined(REPORT_INTEGRAL_TIMINGS)
double time_for_ints = 0.0;
for (auto& t : timers) {
time_for_ints += t.read(0);
}
std::cout << "time for integrals = " << time_for_ints << std::endl;
for (int t = 0; t != nthreads; ++t) engines[t].print_timers();
#endif
Matrix GG = 0.5 * (G[0] + G[0].transpose());
std::cout << "# of integrals = " << num_ints_computed << std::endl;
// symmetrize the result and return
return GG;
}
#if LIBINT2_DERIV_ERI_ORDER
template <unsigned deriv_order>
std::vector<Matrix> compute_2body_fock_deriv(const BasisSet& obs,
const std::vector<libint2::Atom>& atoms,
const Matrix& D, double precision,
const Matrix& Schwarz) {
const auto n = obs.nbf();
const auto nshells = obs.size();
const auto nderiv_shellset =
libint2::num_geometrical_derivatives(4, deriv_order); // # of derivs for each shell quartet
const auto nderiv = libint2::num_geometrical_derivatives(
atoms.size(), deriv_order); // total # of derivs
const auto ncoords_times_two = (atoms.size() * 3) * 2;
using libint2::nthreads;
std::vector<Matrix> G(nthreads * nderiv, Matrix::Zero(n, n));
const auto do_schwarz_screen = Schwarz.cols() != 0 && Schwarz.rows() != 0;
Matrix D_shblk_norm =
compute_shellblock_norm(obs, D); // matrix of infty-norms of shell blocks
auto fock_precision = precision;
// engine precision controls primitive truncation, assume worst-case scenario
// (all primitive combinations add up constructively)
auto max_nprim = obs.max_nprim();
auto max_nprim4 = max_nprim * max_nprim * max_nprim * max_nprim;
auto engine_precision = std::min(fock_precision / D_shblk_norm.maxCoeff(),
std::numeric_limits<double>::epsilon()) /
max_nprim4;
// construct the 2-electron repulsion integrals engine pool
using libint2::Engine;
std::vector<Engine> engines(nthreads);
engines[0] =
Engine(Operator::coulomb, obs.max_nprim(), obs.max_l(), deriv_order);
engines[0].set_precision(engine_precision); // shellset-dependent precision
// control will likely break
// positive definiteness
// stick with this simple recipe
std::cout << "compute_2body_fock:precision = " << precision << std::endl;
std::cout << "Engine::precision = " << engines[0].precision() << std::endl;
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
std::atomic<size_t> num_ints_computed{0};
#if defined(REPORT_INTEGRAL_TIMINGS)
std::vector<libint2::Timers<1>> timers(nthreads);
#endif
auto shell2bf = obs.shell2bf();
auto shell2atom = obs.shell2atom(atoms);
auto lambda = [&](int thread_id) {
auto& engine = engines[thread_id];
const auto& buf = engine.results();
#if defined(REPORT_INTEGRAL_TIMINGS)
auto& timer = timers[thread_id];
timer.clear();
timer.set_now_overhead(25);
#endif
size_t shell_atoms[4];
// loop over permutationally-unique set of shells
for (auto s1 = 0l, s1234 = 0l; s1 != nshells; ++s1) {
auto bf1_first = shell2bf[s1]; // first basis function in this shell
auto n1 = obs[s1].size(); // number of basis functions in this shell
shell_atoms[0] = shell2atom[s1];
for (const auto& s2 : obs_shellpair_list[s1]) {
auto bf2_first = shell2bf[s2];
auto n2 = obs[s2].size();
shell_atoms[1] = shell2atom[s2];
const auto Dnorm12 = do_schwarz_screen ? D_shblk_norm(s1, s2) : 0.;
for (auto s3 = 0; s3 <= s1; ++s3) {
auto bf3_first = shell2bf[s3];
auto n3 = obs[s3].size();
shell_atoms[2] = shell2atom[s3];
const auto Dnorm123 =
do_schwarz_screen
? std::max(D_shblk_norm(s1, s3),
std::max(D_shblk_norm(s2, s3), Dnorm12))
: 0.;
const auto s4_max = (s1 == s3) ? s2 : s3;
for (const auto& s4 : obs_shellpair_list[s3]) {
if (s4 > s4_max)
break; // for each s3, s4 are stored in monotonically increasing
// order
if ((s1234++) % nthreads != thread_id) continue;
const auto Dnorm1234 =
do_schwarz_screen
? std::max(
D_shblk_norm(s1, s4),
std::max(D_shblk_norm(s2, s4),
std::max(D_shblk_norm(s3, s4), Dnorm123)))
: 0.;
if (do_schwarz_screen &&
Dnorm1234 * Schwarz(s1, s2) * Schwarz(s3, s4) <
fock_precision)
continue;
auto bf4_first = shell2bf[s4];
auto n4 = obs[s4].size();
shell_atoms[3] = shell2atom[s4];
const auto n1234 = n1 * n2 * n3 * n4;
// compute the permutational degeneracy (i.e. # of equivalents) of
// the given shell set
auto s12_deg = (s1 == s2) ? 1.0 : 2.0;
auto s34_deg = (s3 == s4) ? 1.0 : 2.0;
auto s12_34_deg = (s1 == s3) ? (s2 == s4 ? 1.0 : 2.0) : 2.0;
auto s1234_deg = s12_deg * s34_deg * s12_34_deg;
// computes contribution from shell set \c idx to the operator matrix with
// index \c op
auto add_shellset_to_dest = [&](
std::size_t op, std::size_t idx, int coord1, int coord2, double scale = 1.0) {
auto& g = G[op];
auto shset = buf[idx];
const auto weight = scale * s1234_deg;
for (auto f1 = 0, f1234 = 0; f1 != n1; ++f1) {
const auto bf1 = f1 + bf1_first;
for (auto f2 = 0; f2 != n2; ++f2) {
const auto bf2 = f2 + bf2_first;
for (auto f3 = 0; f3 != n3; ++f3) {
const auto bf3 = f3 + bf3_first;
for (auto f4 = 0; f4 != n4; ++f4, ++f1234) {
const auto bf4 = f4 + bf4_first;
const auto value = shset[f1234];
const auto wvalue = value * weight;
g(bf1, bf2) += D(bf3, bf4) * wvalue;
g(bf3, bf4) += D(bf1, bf2) * wvalue;
g(bf1, bf3) -= 0.25 * D(bf2, bf4) * wvalue;
g(bf2, bf4) -= 0.25 * D(bf1, bf3) * wvalue;
g(bf1, bf4) -= 0.25 * D(bf2, bf3) * wvalue;
g(bf2, bf3) -= 0.25 * D(bf1, bf4) * wvalue;
}
}
}
}
};
#if defined(REPORT_INTEGRAL_TIMINGS)
timer.start(0);
#endif
engine.compute2<Operator::coulomb, BraKet::xx_xx, deriv_order>(
obs[s1], obs[s2], obs[s3], obs[s4]);
if (buf[0] == nullptr)
continue; // if all integrals screened out, skip to next quartet
num_ints_computed += nderiv_shellset * n1234;
#if defined(REPORT_INTEGRAL_TIMINGS)
timer.stop(0);
#endif
switch (deriv_order) {
case 0: {
int coord1 = 0, coord2 = 0;
add_shellset_to_dest(thread_id, 0, coord1, coord2);
} break;
case 1: {
for (auto d = 0; d != 12; ++d) {
const int a = d / 3;
const int xyz = d % 3;
auto coord = shell_atoms[a] * 3 + xyz;
auto& g = G[thread_id * nderiv + coord];
int coord1 = 0, coord2 = 0;
add_shellset_to_dest(thread_id * nderiv + coord, d, coord1, coord2);
} // d \in [0,12)
} break;
case 2: {
// computes upper triangle index
// n2 = matrix size times 2
// i,j = (unordered) indices
#define upper_triangle_index(n2, i, j) \
(std::min((i), (j))) * ((n2) - (std::min((i), (j))) - 1) / 2 + \
(std::max((i), (j)))
// look over shellsets in the order in which they appear
std::size_t shellset_idx = 0;
for (auto c1 = 0; c1 != 4; ++c1) {
auto a1 = shell_atoms[c1];
auto coord1 = 3 * a1;
for (auto xyz1 = 0; xyz1 != 3; ++xyz1, ++coord1) {
for (auto c2 = c1; c2 != 4; ++c2) {
auto a2 = shell_atoms[c2];
auto xyz2_start = (c1 == c2) ? xyz1 : 0;
auto coord2 = 3 * a2 + xyz2_start;
for (auto xyz2 = xyz2_start; xyz2 != 3;
++xyz2, ++coord2) {
double scale =
(coord1 == coord2 && c1 != c2) ? 2.0 : 1.0;
const auto coord12 = upper_triangle_index(
ncoords_times_two, coord1, coord2);
auto op = thread_id * nderiv + coord12;
add_shellset_to_dest(op, shellset_idx, coord1, coord2, scale);
++shellset_idx;
}
}
}
}
} break;
#undef upper_triangle_index
default:
assert(deriv_order <= 2 &&
"support for 3rd and higher derivatives of the Fock "
"matrix not yet implemented");
}
}
}
}
}
}; // end of lambda
libint2::parallel_do(lambda);
// accumulate contributions from all threads
for (size_t t = 1; t != nthreads; ++t) {
for (auto d = 0; d != nderiv; ++d) {
G[d] += G[t * nderiv + d];
}
}
#if defined(REPORT_INTEGRAL_TIMINGS)
double time_for_ints = 0.0;
for (auto& t : timers) {
time_for_ints += t.read(0);
}
std::cout << "time for integrals = " << time_for_ints << std::endl;
for (int t = 0; t != nthreads; ++t) engines[t].print_timers();
#endif
std::vector<Matrix> GG(nderiv);
for (auto d = 0; d != nderiv; ++d) {
GG[d] = 0.5 * (G[d] + G[d].transpose());
}
std::cout << "# of integrals = " << num_ints_computed << std::endl;
// symmetrize the result and return
return GG;
}
#endif
Matrix compute_2body_fock_general(const BasisSet& obs, const Matrix& D,
const BasisSet& D_bs, bool D_is_shelldiagonal,
double precision) {
const auto n = obs.nbf();
const auto nshells = obs.size();
const auto n_D = D_bs.nbf();
assert(D.cols() == D.rows() && D.cols() == n_D);
using libint2::nthreads;
std::vector<Matrix> G(nthreads, Matrix::Zero(n, n));
// construct the 2-electron repulsion integrals engine
using libint2::Engine;
std::vector<Engine> engines(nthreads);
engines[0] = Engine(libint2::Operator::coulomb,
std::max(obs.max_nprim(), D_bs.max_nprim()),
std::max(obs.max_l(), D_bs.max_l()), 0);
engines[0].set_precision(precision); // shellset-dependent precision control
// will likely break positive
// definiteness
// stick with this simple recipe
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
auto shell2bf = obs.shell2bf();
auto shell2bf_D = D_bs.shell2bf();
auto lambda = [&](int thread_id) {
auto& engine = engines[thread_id];
auto& g = G[thread_id];
const auto& buf = engine.results();
// loop over permutationally-unique set of shells
for (auto s1 = 0l, s1234 = 0l; s1 != nshells; ++s1) {
auto bf1_first = shell2bf[s1]; // first basis function in this shell
auto n1 = obs[s1].size(); // number of basis functions in this shell
for (auto s2 = 0; s2 <= s1; ++s2) {
auto bf2_first = shell2bf[s2];
auto n2 = obs[s2].size();
for (auto s3 = 0; s3 < D_bs.size(); ++s3) {
auto bf3_first = shell2bf_D[s3];
auto n3 = D_bs[s3].size();
auto s4_begin = D_is_shelldiagonal ? s3 : 0;
auto s4_fence = D_is_shelldiagonal ? s3 + 1 : D_bs.size();
for (auto s4 = s4_begin; s4 != s4_fence; ++s4, ++s1234) {
if (s1234 % nthreads != thread_id) continue;
auto bf4_first = shell2bf_D[s4];
auto n4 = D_bs[s4].size();
// compute the permutational degeneracy (i.e. # of equivalents) of
// the given shell set
auto s12_deg = (s1 == s2) ? 1.0 : 2.0;
if (s3 >= s4) {
auto s34_deg = (s3 == s4) ? 1.0 : 2.0;
auto s1234_deg = s12_deg * s34_deg;
// auto s1234_deg = s12_deg;
engine.compute2<Operator::coulomb, BraKet::xx_xx, 0>(
obs[s1], obs[s2], D_bs[s3], D_bs[s4]);
const auto* buf_1234 = buf[0];
if (buf_1234 != nullptr) {
for (auto f1 = 0, f1234 = 0; f1 != n1; ++f1) {
const auto bf1 = f1 + bf1_first;
for (auto f2 = 0; f2 != n2; ++f2) {
const auto bf2 = f2 + bf2_first;
for (auto f3 = 0; f3 != n3; ++f3) {
const auto bf3 = f3 + bf3_first;
for (auto f4 = 0; f4 != n4; ++f4, ++f1234) {
const auto bf4 = f4 + bf4_first;
const auto value = buf_1234[f1234];
const auto value_scal_by_deg = value * s1234_deg;
g(bf1, bf2) += 2.0 * D(bf3, bf4) * value_scal_by_deg;
}
}
}
}
}
}
engine.compute2<Operator::coulomb, BraKet::xx_xx, 0>(
obs[s1], D_bs[s3], obs[s2], D_bs[s4]);
const auto* buf_1324 = buf[0];
if (buf_1324 == nullptr)
continue; // if all integrals screened out, skip to next quartet
for (auto f1 = 0, f1324 = 0; f1 != n1; ++f1) {
const auto bf1 = f1 + bf1_first;
for (auto f3 = 0; f3 != n3; ++f3) {
const auto bf3 = f3 + bf3_first;
for (auto f2 = 0; f2 != n2; ++f2) {
const auto bf2 = f2 + bf2_first;
for (auto f4 = 0; f4 != n4; ++f4, ++f1324) {
const auto bf4 = f4 + bf4_first;
const auto value = buf_1324[f1324];
const auto value_scal_by_deg = value * s12_deg;
g(bf1, bf2) -= D(bf3, bf4) * value_scal_by_deg;
}
}
}
}
}
}
}
}
}; // thread lambda
libint2::parallel_do(lambda);
// accumulate contributions from all threads
for (size_t i = 1; i != nthreads; ++i) {
G[0] += G[i];
}
// symmetrize the result and return
return 0.5 * (G[0] + G[0].transpose());
}
#ifdef HAVE_DENSITY_FITTING
Matrix DFFockEngine::compute_2body_fock_dfC(const Matrix& Cocc) {
using libint2::nthreads;
const auto n = obs.nbf();
const auto ndf = dfbs.nbf();
libint2::Timers<1> wall_timer;
wall_timer.set_now_overhead(25);
std::vector<libint2::Timers<5>> timers(nthreads);
for(auto& timer: timers) timer.set_now_overhead(25);
typedef btas::RangeNd<CblasRowMajor, std::array<long, 1>> Range1d;
typedef btas::RangeNd<CblasRowMajor, std::array<long, 2>> Range2d;
typedef btas::Tensor<double, Range1d> Tensor1d;
typedef btas::Tensor<double, Range2d> Tensor2d;
// using first time? compute 3-center ints and transform to inv sqrt
// representation
if (xyK.size() == 0) {
wall_timer.start(0);
const auto nshells = obs.size();
const auto nshells_df = dfbs.size();
const auto& unitshell = libint2::Shell::unit();
// construct the 2-electron 3-center repulsion integrals engine
// since the code assumes (xx|xs) braket, and Engine/libint only produces
// (xs|xx), use 4-center engine
std::vector<libint2::Engine> engines(nthreads);
engines[0] = libint2::Engine(libint2::Operator::coulomb,
std::max(obs.max_nprim(), dfbs.max_nprim()),
std::max(obs.max_l(), dfbs.max_l()), 0);
engines[0].set(BraKet::xs_xx);
for (size_t i = 1; i != nthreads; ++i) {
engines[i] = engines[0];
}
auto shell2bf = obs.shell2bf();
auto shell2bf_df = dfbs.shell2bf();
Tensor3d Zxy{ndf, n, n};
auto lambda = [&](int thread_id) {
auto& engine = engines[thread_id];
auto& timer = timers[thread_id];
const auto& results = engine.results();
// loop over permutationally-unique set of shells
for (auto s1 = 0l, s123 = 0l; s1 != nshells_df; ++s1) {
auto bf1_first = shell2bf_df[s1]; // first basis function in this shell
auto n1 = dfbs[s1].size(); // number of basis functions in this shell
for (auto s2 = 0; s2 != nshells; ++s2) {
auto bf2_first = shell2bf[s2];
auto n2 = obs[s2].size();
const auto n12 = n1 * n2;
for (auto s3 = 0; s3 != nshells; ++s3, ++s123) {
if (s123 % nthreads != thread_id) continue;
auto bf3_first = shell2bf[s3];
auto n3 = obs[s3].size();
const auto n123 = n12 * n3;
timer.start(0);
engine.compute2<Operator::coulomb, BraKet::xs_xx, 0>(
dfbs[s1], unitshell, obs[s2], obs[s3]);
const auto* buf = results[0];
if (buf == nullptr)
continue;
timer.stop(0);
timer.start(1);
auto lower_bound = {bf1_first, bf2_first, bf3_first};
auto upper_bound = {bf1_first + n1, bf2_first + n2, bf3_first + n3};
auto view = btas::make_view(
Zxy.range().slice(lower_bound, upper_bound), Zxy.storage());
std::copy(buf, buf + n123, view.begin());
timer.stop(1);
} // s3
} // s2
} // s1
}; // lambda
libint2::parallel_do(lambda);
wall_timer.stop(0);
double ints_time = 0;
for(const auto& timer: timers) ints_time += timer.read(0);
std::cout << "time for Zxy integrals = " << ints_time << " (total from all threads)" << std::endl;
double copy_time = 0;
for(const auto& timer: timers) copy_time += timer.read(1);
std::cout << "time for copying into BTAS = " << copy_time << " (total from all threads)"<< std::endl;
std::cout << "wall time for Zxy integrals + copy = " << wall_timer.read(0) << std::endl;
timers[0].start(2);
Matrix V = compute_2body_2index_ints(dfbs);
Eigen::LLT<Matrix> V_LLt(V);
Matrix I = Matrix::Identity(ndf, ndf);
auto L = V_LLt.matrixL();
Matrix V_L = L;
Matrix Linv = L.solve(I).transpose();
// check
// std::cout << "||V - L L^t|| = " << (V - V_L * V_L.transpose()).norm() <<
// std::endl;
// std::cout << "||I - L L^-1^t|| = " << (I - V_L *
// Linv.transpose()).norm() << std::endl;
// std::cout << "||V^-1 - L^-1 L^-1^t|| = " << (V.inverse() - Linv *
// Linv.transpose()).norm() << std::endl;
Tensor2d K{ndf, ndf};
std::copy(Linv.data(), Linv.data() + ndf * ndf, K.begin());
xyK = Tensor3d{n, n, ndf};
btas::contract(1.0, Zxy, {1, 2, 3}, K, {1, 4}, 0.0, xyK, {2, 3, 4});
Zxy = Tensor3d{0, 0, 0}; // release memory
timers[0].stop(2);
std::cout << "time for integrals metric tform = " << timers[0].read(2)
<< std::endl;
} // if (xyK.size() == 0)
// compute exchange
timers[0].start(3);
const auto nocc = Cocc.cols();
Tensor2d Co{n, nocc};
std::copy(Cocc.data(), Cocc.data() + n * nocc, Co.begin());
Tensor3d xiK{n, nocc, ndf};
btas::contract(1.0, xyK, {1, 2, 3}, Co, {2, 4}, 0.0, xiK, {1, 4, 3});
Tensor2d G{n, n};
btas::contract(1.0, xiK, {1, 2, 3}, xiK, {4, 2, 3}, 0.0, G, {1, 4});
timers[0].stop(3);
std::cout << "time for exchange = " << timers[0].read(3) << std::endl;
// compute Coulomb
timers[0].start(4);
Tensor1d Jtmp{ndf};
btas::contract(1.0, xiK, {1, 2, 3}, Co, {1, 2}, 0.0, Jtmp, {3});
xiK = Tensor3d{0, 0, 0};
btas::contract(2.0, xyK, {1, 2, 3}, Jtmp, {3}, -1.0, G, {1, 2});
timers[0].stop(4);
std::cout << "time for coulomb = " << timers[0].read(4) << std::endl;
// copy result to an Eigen::Matrix
Matrix result(n, n);
std::copy(G.cbegin(), G.cend(), result.data());
return result;
}
#endif // HAVE_DENSITY_FITTING
// should be a unit test somewhere
void api_basic_compile_test(const BasisSet& obs) {
using namespace libint2;
Engine onebody_engine(
Operator::overlap, // will compute overlap ints
obs.max_nprim(), // max # of primitives in shells this engine will
// accept
obs.max_l() // max angular momentum of shells this engine will accept
);
auto shell2bf = obs.shell2bf();
const auto& results = onebody_engine.results();
for (auto s1 = 0; s1 != obs.size(); ++s1) {
for (auto s2 = 0; s2 != obs.size(); ++s2) {
std::cout << "compute shell set {" << s1 << "," << s2 << "} ... ";
onebody_engine.compute(obs[s1], obs[s2]);
const auto* ints_shellset = results[0];
std::cout << "done" << std::endl;
auto bf1 = shell2bf[s1]; // first basis function in first shell
auto n1 = obs[s1].size(); // number of basis functions in first shell
auto bf2 = shell2bf[s2]; // first basis function in second shell
auto n2 = obs[s2].size(); // number of basis functions in second shell
// this iterates over integrals in the order they are packed in array
// ints_shellset
for (auto f1 = 0; f1 != n1; ++f1)
for (auto f2 = 0; f2 != n2; ++f2)
std::cout << " " << bf1 + f1 << " " << bf2 + f2 << " "
<< ints_shellset[f1 * n2 + f2] << std::endl;
}
}
using libint2::Operator;
std::vector<std::pair<double, double>> cgtg_params{
{0.1, 0.2}, {0.3, 0.4}, {0.5, 0.6}};
{
auto K =
compute_schwarz_ints<Operator::cgtg>(obs, obs, false, cgtg_params);
std::cout << "cGTG Schwarz ints\n" << K << std::endl;
}
{
auto K = compute_schwarz_ints<Operator::cgtg_x_coulomb>(obs, obs, false,
cgtg_params);
std::cout << "cGTG/r12 Schwarz ints\n" << K << std::endl;
}
{
auto K =
compute_schwarz_ints<Operator::delcgtg2>(obs, obs, false, cgtg_params);
std::cout << "||Del.cGTG||^2 Schwarz ints\n" << K << std::endl;
}
{ // test 2-index ints
Engine eri4_engine(Operator::coulomb, obs.max_nprim(), obs.max_l());
Engine eri2_engine = eri4_engine;
eri2_engine.set(BraKet::xs_xs);
auto shell2bf = obs.shell2bf();
const auto& results4 = eri4_engine.results();
const auto& results2 = eri2_engine.results();
for (auto s1 = 0; s1 != obs.size(); ++s1) {
for (auto s2 = 0; s2 != obs.size(); ++s2) {
eri4_engine.compute(obs[s1], Shell::unit(), obs[s2], Shell::unit());
eri2_engine.compute(obs[s1], obs[s2]);
auto bf1 = shell2bf[s1]; // first basis function in first shell
auto n1 = obs[s1].size(); // number of basis functions in first shell
auto bf2 = shell2bf[s2]; // first basis function in second shell
auto n2 = obs[s2].size(); // number of basis functions in second shell
const auto* buf4 = results4[0];
const auto* buf2 = results2[0];
// this iterates over integrals in the order they are packed in array
// ints_shellset
for (auto f1 = 0, f12 = 0; f1 != n1; ++f1)
for (auto f2 = 0; f2 != n2; ++f2, ++f12)
assert(std::abs(buf4[f12] - buf2[f12]) < 1e-12 &&
"2-center ints test failed");
}
}
}
{ // test 3-index ints
Engine eri4_engine(Operator::coulomb, obs.max_nprim(), obs.max_l());
Engine eri3_engine = eri4_engine;
eri3_engine.set(BraKet::xs_xx);
auto shell2bf = obs.shell2bf();
const auto& results4 = eri4_engine.results();
const auto& results3 = eri3_engine.results();
for (auto s1 = 0; s1 != obs.size(); ++s1) {
for (auto s2 = 0; s2 != obs.size(); ++s2) {
for (auto s3 = 0; s3 != obs.size(); ++s3) {
eri4_engine.compute(obs[s1], Shell::unit(), obs[s2], obs[s3]);
eri3_engine.compute(obs[s1], obs[s2], obs[s3]);
auto bf1 = shell2bf[s1]; // first basis function in first shell
auto n1 = obs[s1].size(); // number of basis functions in first shell
auto bf2 = shell2bf[s2]; // first basis function in second shell
auto n2 =
obs[s2].size(); // number of basis functions in second shell
auto bf3 = shell2bf[s3]; // first basis function in third shell
auto n3 = obs[s3].size(); // number of basis functions in third shell
const auto* buf4 = results4[0];
const auto* buf3 = results3[0];
// this iterates over integrals in the order they are packed in array
// ints_shellset
for (auto f1 = 0, f123 = 0; f1 != n1; ++f1)
for (auto f2 = 0; f2 != n2; ++f2)
for (auto f3 = 0; f3 != n3; ++f3, ++f123)
assert(std::abs(buf4[f123] - buf3[f123]) < 1e-12 &&
"3-center ints test failed");
}
}
}
}
#if LIBINT2_DERIV_ERI_ORDER
{ // test deriv 2-index ints
Engine eri4_engine(Operator::coulomb, obs.max_nprim(), obs.max_l(), 1);
Engine eri2_engine = eri4_engine;
eri2_engine.set(BraKet::xs_xs);
auto shell2bf = obs.shell2bf();
const auto& results4 = eri4_engine.results();
const auto& results2 = eri2_engine.results();
for (auto s1 = 0; s1 != obs.size(); ++s1) {
for (auto s2 = 0; s2 != obs.size(); ++s2) {
eri4_engine.compute(obs[s1], Shell::unit(), obs[s2], Shell::unit());
eri2_engine.compute(obs[s1], obs[s2]);
auto bf1 = shell2bf[s1]; // first basis function in first shell
auto n1 = obs[s1].size(); // number of basis functions in first shell
auto bf2 = shell2bf[s2]; // first basis function in second shell
auto n2 = obs[s2].size(); // number of basis functions in second shell
// loop over derivative shell sets
for(auto d=0; d!=6; ++d) {
const auto* buf4 = results4[d<3 ? d : d+3];
const auto* buf2 = results2[d];
// this iterates over integrals in the order they are packed in array
// ints_shellset
for (auto f1 = 0, f12 = 0; f1 != n1; ++f1)
for (auto f2 = 0; f2 != n2; ++f2, ++f12)
assert(std::abs(buf4[f12] - buf2[f12]) < 1e-12 &&
"deriv 2-center ints test failed");
}
}
}
}
#endif
#if LIBINT2_DERIV_ERI_ORDER > 1
{ // test 2nd deriv 2-index ints
Engine eri4_engine(Operator::coulomb, obs.max_nprim(), obs.max_l(), 2);
Engine eri2_engine = eri4_engine;
eri2_engine.set(BraKet::xs_xs);
auto shell2bf = obs.shell2bf();
const auto& results4 = eri4_engine.results();
const auto& results2 = eri2_engine.results();
for (auto s1 = 0; s1 != obs.size(); ++s1) {
for (auto s2 = 0; s2 != obs.size(); ++s2) {
eri4_engine.compute(obs[s1], Shell::unit(), obs[s2], Shell::unit());
eri2_engine.compute(obs[s1], obs[s2]);
auto bf1 = shell2bf[s1]; // first basis function in first shell
auto n1 = obs[s1].size(); // number of basis functions in first shell
auto bf2 = shell2bf[s2]; // first basis function in second shell
auto n2 = obs[s2].size(); // number of basis functions in second shell
// loop over derivative shell sets
for (auto d1 = 0, d12 = 0; d1 != 6; ++d1) {
const auto dd1 = d1 < 3 ? d1 : d1 + 3;
for (auto d2 = d1; d2 != 6; ++d2, ++d12) {
const auto dd2 = d2 < 3 ? d2 : d2 + 3;
const auto dd12 = dd1 * (24 - dd1 - 1) / 2 + dd2;
const auto* buf4 = results4[dd12];
const auto* buf2 = results2[d12];
// this iterates over integrals in the order they are packed in
// array
// ints_shellset
for (auto f1 = 0, f12 = 0; f1 != n1; ++f1)
for (auto f2 = 0; f2 != n2; ++f2, ++f12)
assert(std::abs(buf4[f12] - buf2[f12]) < 1e-12 &&
"2nd deriv 2-center ints test failed");
}
}
}
}
}
#endif
}
|
parte2.c
|
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <unistd.h>
static unsigned long num_steps;
double step;
int main (int argc, char **argv)
{
unsigned long int i, cores;
double x, pi, sum = 0.0;
cores = sysconf( _SC_NPROCESSORS_ONLN );
num_steps = atol(argv[1]);
step = 1.0/(double) num_steps;
omp_set_num_threads(cores);
/*
* a linha abaixo diz para paralelizar o for subsequente (openmp
* trata de quebrar o for e repartir entre as threads seguindo
* o agendamento guiado, schedule(guided)).
* reduction(+:sum) faz com que a variavel sum seja tratada como
* privada em cada thread evitando que haja concorrencia e
* a thread principal cuida, apos o laco, de atualizar o conteudo
* de sum realizando a operacao de adicao (op:var) entre a sum
* de todas as threads.
*
* private(x) faz com que cada thread tenha sua propria variavel x
* e que nao e' compartilhada. Isto pode ser feito pois x e' uma
* variavel independente a cada laco; auxiliar e temporaria.
*
* */
#pragma omp parallel for reduction(+:sum) private(x) schedule(guided)
for (i=1;i<= num_steps; i++)
{
x = (i-0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step * sum;
printf("Pi = %.15g\n", pi);
return 1;
}
|
ast-dump-openmp-taskyield.c
|
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test() {
#pragma omp taskyield
}
// CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-taskyield.c:3:1, line:5:1> line:3:6 test 'void ()'
// CHECK-NEXT: `-CompoundStmt {{.*}} <col:13, line:5:1>
// CHECK-NEXT: `-OMPTaskyieldDirective {{.*}} <line:4:1, col:22> openmp_standalone_directive
|
textbook_msd.c
|
#include <math.h>
#include <stdio.h>
#include <stdbool.h>
void textbook_msd(unsigned int first, unsigned int second, unsigned short* in_data, double* mean, double* sd){
double sum = 0.0;
double temp_sd = 0.0;
for(unsigned int i = 0; i < first; i++){
sum = 0.0;
temp_sd = 0.0;
for(unsigned int j = 0; j < second; j++){
register unsigned short temp;
temp = in_data[i*second + j];
temp_sd += temp*temp;
sum += temp;
}
mean[i] = sum/second;
temp_sd = temp_sd - (sum*sum)/second;
sd[i] = sqrt(temp_sd/second);
}
// mean[0] = sum/N;
// sd[0] = temp_sd - (sum*sum)/N;
// sd[0] = sqrt(sd[0]/N);
}
void ttextbook_msd(unsigned int first, unsigned int second, unsigned short* in_data, double* mean, double* sd){
double sum = 0.0;
double temp_sd = 0.0;
int divchan=32;
int divtsamp = 10;
#pragma omp parallel for collapse(2)
for(unsigned int ii = 0; ii < first; ii+=divtsamp){
for(unsigned int jj = 0; jj < second; jj+=divchan){
for(unsigned int i = ii; i < ii + divtsamp; i++){
if (jj == 0){
sum = 0.0;
temp_sd = 0.0;
} else {
sum = mean[i];
temp_sd = sd[i];
}
for(unsigned int j = jj; j < jj+divchan; j++){
register unsigned short temp;
temp = in_data[i*second + j];
temp_sd += temp*temp;
sum += temp;
}
mean[i] = sum;
sd[i] = temp_sd;
} // i
} //jj
}
#pragma omp parallel for
for(unsigned int i = 0; i < first; i++){
sd[i] = sd[i] - mean[i]*mean[i]/second;
mean[i] = mean[i]/second;
sd[i] = sqrt(sd[i]/second);
}
// mean[0] = sum/N;
// sd[0] = temp_sd - (sum*sum)/N;
// sd[0] = sqrt(sd[0]/N);
}
void textbook_msd_parallel(unsigned int first, unsigned int second, unsigned short* in_data, double* mean, double* sd, bool outlier_rejection, double old_mean, double old_stdev, double sigma){
double sum = 0;
double temp_sd = 0;
unsigned int nElements = 0;
#pragma omp parallel for reduction (+: temp_sd, sum, nElements)
for(unsigned int i = 0; i < first; i++){
sum = 0.0;
temp_sd = 0.0;
nElements = 0;
for(unsigned int j = 0; j < second; j++){
temp_sd += in_data[i*second + j]*in_data[i*second + j];
sum += in_data[i*second + j];
nElements +=1;
}
mean[i] = sum/second;
temp_sd = temp_sd - (sum*sum)/second;
sd[i] = sqrt(temp_sd/second);
}
}
void textbook_divide_msd_parallel(unsigned int N, unsigned short* in_data, double* mean, double* sd){
int num_block = 8;
double sum[num_block];
double temp_sd[num_block];
int block_length = N/num_block;
int block_remainder = N - num_block*block_length;
double rest_sum = 0.0;
double rest_sd = 0.0;
for(int i = 0; i < num_block; i++){
sum[i] = 0.0;
temp_sd[i] = 0.0;
}
for(int i = 0; i < num_block; i++){
int shift = i*block_length;
#pragma omp parallel for reduction (+: temp_sd, sum)
for(int j = 0; j < block_length; j++){
temp_sd[i] += in_data[j + shift]*in_data[j + shift];
sum[i] += in_data[j + shift];
}
temp_sd[i] = temp_sd[i] - sum[i]*sum[i]/block_length;
}
if (block_remainder != 0){
for(int i = 0; i < block_remainder; i++){
rest_sum += in_data[num_block*block_length + i];
rest_sd += in_data[num_block*block_length + i]*in_data[num_block*block_length + i];
}
}
double final_sum = 0;
#pragma omp parallel for reduction (+: final_sum)
for(int i = 0; i < num_block; i++){
final_sum += sum[i];
// printf("%d %lf\n", i*block_length,final_sum);
}
int step = num_block;
int inner_step = 1;
int stop = log2(num_block);
for (int i = 0; i < stop; i++){
step = step/2;
for (int j = 0; j < step; j++){
// temp_sd[j*2*inner_step] += temp_sd[2*j*inner_step + inner_step] + (1/(2*num_block))*(2*num_block*sum[j*2*inner_step] - sum[2*j*inner_step + inner_step])*(2*num_block*sum[j*2*inner_step] - sum[2*j*inner_step + inner_step]);
temp_sd[2*j*inner_step] += temp_sd[2*j*inner_step + inner_step] + (1.0/(2*block_length))*(sum[2*j*inner_step] - sum[2*j*inner_step + inner_step])*(sum[2*j*inner_step] - sum[2*j*inner_step + inner_step]);
}
inner_step = inner_step*2;
}
if (block_remainder != 0){
temp_sd[0] += rest_sd + ((block_length)/(block_remainder*(block_length + block_remainder)))*((block_remainder + block_length)/(block_length)*final_sum - rest_sum)*((block_remainder + block_length)/(block_length)*final_sum - rest_sum);
final_sum += rest_sum;
}
mean[0] = final_sum/N;
sd[0] = sqrt(temp_sd[0]/N);
}
|
bt.c
|
/*--------------------------------------------------------------------
NAS Parallel Benchmarks 3.0 structured OpenMP C versions - BT
This benchmark is an OpenMP C version of the NPB BT code.
The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions
in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ.
Permission to use, copy, distribute and modify this software for any
purpose with or without fee is hereby granted.
This software is provided "as is" without express or implied warranty.
Information on OpenMP activities at RWCP is available at:
http://pdplab.trc.rwcp.or.jp/pdperf/Omni/
Information on NAS Parallel Benchmarks 2.3 is available at:
http://www.nas.nasa.gov/NAS/NPB/
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
Authors: R. Van der Wijngaart
T. Harris
M. Yarrow
OpenMP C version: S. Satoh
3.0 structure translation: M. Popov
--------------------------------------------------------------------*/
#include "../common/npb-C.h"
/* global variables */
#include "header.h"
/* function declarations */
static void add(void);
static void adi(void);
static void error_norm(double rms[5]);
static void rhs_norm(double rms[5]);
static void exact_rhs(void);
static void exact_solution(double xi, double eta, double zeta,
double dtemp[5]);
static void initialize(void);
static void lhsinit(void);
static void lhsx(void);
static void lhsy(void);
static void lhsz(void);
static void compute_rhs(void);
static void set_constants(void);
static void verify(int no_time_steps, char *class, boolean *verified);
static void x_solve(void);
static void x_backsubstitute(void);
static void x_solve_cell(void);
static void matvec_sub(double ablock[5][5], double avec[5], double bvec[5]);
static void matmul_sub(double ablock[5][5], double bblock[5][5],
double cblock[5][5]);
static void binvcrhs(double lhs[5][5], double c[5][5], double r[5]);
static void binvrhs(double lhs[5][5], double r[5]);
static void y_solve(void);
static void y_backsubstitute(void);
static void y_solve_cell(void);
static void z_solve(void);
static void z_backsubstitute(void);
static void z_solve_cell(void);
/*--------------------------------------------------------------------
program BT
c-------------------------------------------------------------------*/
int main(int argc, char **argv) {
int niter, step, n3;
int nthreads = 1;
double navg, mflops;
double tmax;
boolean verified;
char class;
FILE *fp;
/*--------------------------------------------------------------------
c Root node reads input file (if it exists) else takes
c defaults from parameters
c-------------------------------------------------------------------*/
printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version"
" - BT Benchmark\n\n");
fp = fopen("inputbt.data", "r");
if (fp != NULL) {
printf(" Reading from input file inputbt.data");
fscanf(fp, "%d", &niter);
while (fgetc(fp) != '\n');
fscanf(fp, "%lg", &dt);
while (fgetc(fp) != '\n');
fscanf(fp, "%d%d%d",
&grid_points[0], &grid_points[1], &grid_points[2]);
fclose(fp);
} else {
printf(" No input file inputbt.data. Using compiled defaults\n");
niter = NITER_DEFAULT;
dt = DT_DEFAULT;
grid_points[0] = PROBLEM_SIZE;
grid_points[1] = PROBLEM_SIZE;
grid_points[2] = PROBLEM_SIZE;
}
printf(" Size: %3dx%3dx%3d\n",
grid_points[0], grid_points[1], grid_points[2]);
printf(" Iterations: %3d dt: %10.6f\n", niter, dt);
if (grid_points[0] > IMAX ||
grid_points[1] > JMAX ||
grid_points[2] > KMAX) {
printf(" %dx%dx%d\n", grid_points[0], grid_points[1], grid_points[2]);
printf(" Problem size too big for compiled array sizes\n");
exit(1);
}
set_constants();
initialize();
lhsinit();
exact_rhs();
/*--------------------------------------------------------------------
c do one time step to touch all code, and reinitialize
c-------------------------------------------------------------------*/
adi();
initialize();
timer_clear(1);
timer_start(1);
for (step = 1; step <= niter; step++) {
if (step%20 == 0 || step == 1) {
printf(" Time step %4d\n", step);
}
adi();
}
#pragma omp parallel
{
#if defined(_OPENMP)
#pragma omp master
nthreads = omp_get_num_threads();
#endif /* _OPENMP */
} /* end parallel */
timer_stop(1);
tmax = timer_read(1);
verify(niter, &class, &verified);
n3 = grid_points[0]*grid_points[1]*grid_points[2];
navg = (grid_points[0]+grid_points[1]+grid_points[2])/3.0;
if ( tmax != 0.0 ) {
mflops = 1.0e-6*(double)niter*
(3478.8*(double)n3-17655.7*pow2(navg)+28023.7*navg) / tmax;
} else {
mflops = 0.0;
}
c_print_results("BT", class, grid_points[0],
grid_points[1], grid_points[2], niter, nthreads,
tmax, mflops, " floating point",
verified, NPBVERSION,COMPILETIME, CS1, CS2, CS3, CS4, CS5,
CS6, "(none)");
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void add(void) {
/*--------------------------------------------------------------------
c addition of update to the vector u
c-------------------------------------------------------------------*/
int i, j, k, m;
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
u[i][j][k][m] = u[i][j][k][m] + rhs[i][j][k][m];
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void adi(void) {
#pragma omp parallel
compute_rhs();
#pragma omp parallel
x_solve();
#pragma omp parallel
y_solve();
#pragma omp parallel
z_solve();
#pragma omp parallel
add();
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void error_norm(double rms[5]) {
/*--------------------------------------------------------------------
c this function computes the norm of the difference between the
c computed solution and the exact solution
c-------------------------------------------------------------------*/
int i, j, k, m, d;
double xi, eta, zeta, u_exact[5], add;
for (m = 0; m < 5; m++) {
rms[m] = 0.0;
}
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, u_exact);
for (m = 0; m < 5; m++) {
add = u[i][j][k][m] - u_exact[m];
rms[m] = rms[m] + add*add;
}
}
}
}
for (m = 0; m < 5; m++) {
for (d = 0; d <= 2; d++) {
rms[m] = rms[m] / (double)(grid_points[d]-2);
}
rms[m] = sqrt(rms[m]);
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void rhs_norm(double rms[5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
int i, j, k, d, m;
double add;
for (m = 0; m < 5; m++) {
rms[m] = 0.0;
}
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
add = rhs[i][j][k][m];
rms[m] = rms[m] + add*add;
}
}
}
}
for (m = 0; m < 5; m++) {
for (d = 0; d <= 2; d++) {
rms[m] = rms[m] / (double)(grid_points[d]-2);
}
rms[m] = sqrt(rms[m]);
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void exact_rhs(void) {
#pragma omp parallel
{
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c compute the right hand side based on exact solution
c-------------------------------------------------------------------*/
double dtemp[5], xi, eta, zeta, dtpp;
int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1;
/*--------------------------------------------------------------------
c initialize
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 0; k < grid_points[2]; k++) {
for (m = 0; m < 5; m++) {
forcing[i][j][k][m] = 0.0;
}
}
}
}
/*--------------------------------------------------------------------
c xi-direction flux differences
c-------------------------------------------------------------------*/
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
eta = (double)j * dnym1;
for (k = 1; k < grid_points[2]-1; k++) {
zeta = (double)k * dnzm1;
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
exact_solution(xi, eta, zeta, dtemp);
for (m = 0; m < 5; m++) {
ue[i][m] = dtemp[m];
}
dtpp = 1.0 / dtemp[0];
for (m = 1; m <= 4; m++) {
buf[i][m] = dtpp * dtemp[m];
}
cuf[i] = buf[i][1] * buf[i][1];
buf[i][0] = cuf[i] + buf[i][2] * buf[i][2] +
buf[i][3] * buf[i][3];
q[i] = 0.5*(buf[i][1]*ue[i][1] + buf[i][2]*ue[i][2] +
buf[i][3]*ue[i][3]);
}
for (i = 1; i < grid_points[0]-1; i++) {
im1 = i-1;
ip1 = i+1;
forcing[i][j][k][0] = forcing[i][j][k][0] -
tx2*(ue[ip1][1]-ue[im1][1])+
dx1tx1*(ue[ip1][0]-2.0*ue[i][0]+ue[im1][0]);
forcing[i][j][k][1] = forcing[i][j][k][1] -
tx2 * ((ue[ip1][1]*buf[ip1][1]+c2*(ue[ip1][4]-q[ip1]))-
(ue[im1][1]*buf[im1][1]+c2*(ue[im1][4]-q[im1])))+
xxcon1*(buf[ip1][1]-2.0*buf[i][1]+buf[im1][1])+
dx2tx1*( ue[ip1][1]-2.0* ue[i][1]+ ue[im1][1]);
forcing[i][j][k][2] = forcing[i][j][k][2] -
tx2 * (ue[ip1][2]*buf[ip1][1]-ue[im1][2]*buf[im1][1])+
xxcon2*(buf[ip1][2]-2.0*buf[i][2]+buf[im1][2])+
dx3tx1*( ue[ip1][2]-2.0* ue[i][2]+ ue[im1][2]);
forcing[i][j][k][3] = forcing[i][j][k][3] -
tx2*(ue[ip1][3]*buf[ip1][1]-ue[im1][3]*buf[im1][1])+
xxcon2*(buf[ip1][3]-2.0*buf[i][3]+buf[im1][3])+
dx4tx1*( ue[ip1][3]-2.0* ue[i][3]+ ue[im1][3]);
forcing[i][j][k][4] = forcing[i][j][k][4] -
tx2*(buf[ip1][1]*(c1*ue[ip1][4]-c2*q[ip1])-
buf[im1][1]*(c1*ue[im1][4]-c2*q[im1]))+
0.5*xxcon3*(buf[ip1][0]-2.0*buf[i][0]+buf[im1][0])+
xxcon4*(cuf[ip1]-2.0*cuf[i]+cuf[im1])+
xxcon5*(buf[ip1][4]-2.0*buf[i][4]+buf[im1][4])+
dx5tx1*( ue[ip1][4]-2.0* ue[i][4]+ ue[im1][4]);
}
/*--------------------------------------------------------------------
c Fourth-order dissipation
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
i = 1;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(5.0*ue[i][m] - 4.0*ue[i+1][m] +ue[i+2][m]);
i = 2;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(-4.0*ue[i-1][m] + 6.0*ue[i][m] -
4.0*ue[i+1][m] + ue[i+2][m]);
}
for (m = 0; m < 5; m++) {
for (i = 1*3; i <= grid_points[0]-3*1-1; i++) {
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp*
(ue[i-2][m] - 4.0*ue[i-1][m] +
6.0*ue[i][m] - 4.0*ue[i+1][m] + ue[i+2][m]);
}
}
for (m = 0; m < 5; m++) {
i = grid_points[0]-3;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(ue[i-2][m] - 4.0*ue[i-1][m] +
6.0*ue[i][m] - 4.0*ue[i+1][m]);
i = grid_points[0]-2;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(ue[i-2][m] - 4.0*ue[i-1][m] + 5.0*ue[i][m]);
}
}
}
/*--------------------------------------------------------------------
c eta-direction flux differences
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
xi = (double)i * dnxm1;
for (k = 1; k < grid_points[2]-1; k++) {
zeta = (double)k * dnzm1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
exact_solution(xi, eta, zeta, dtemp);
for (m = 0; m < 5; m++) {
ue[j][m] = dtemp[m];
}
dtpp = 1.0/dtemp[0];
for (m = 1; m <= 4; m++) {
buf[j][m] = dtpp * dtemp[m];
}
cuf[j] = buf[j][2] * buf[j][2];
buf[j][0] = cuf[j] + buf[j][1] * buf[j][1] +
buf[j][3] * buf[j][3];
q[j] = 0.5*(buf[j][1]*ue[j][1] + buf[j][2]*ue[j][2] +
buf[j][3]*ue[j][3]);
}
for (j = 1; j < grid_points[1]-1; j++) {
jm1 = j-1;
jp1 = j+1;
forcing[i][j][k][0] = forcing[i][j][k][0] -
ty2*( ue[jp1][2]-ue[jm1][2] )+
dy1ty1*(ue[jp1][0]-2.0*ue[j][0]+ue[jm1][0]);
forcing[i][j][k][1] = forcing[i][j][k][1] -
ty2*(ue[jp1][1]*buf[jp1][2]-ue[jm1][1]*buf[jm1][2])+
yycon2*(buf[jp1][1]-2.0*buf[j][1]+buf[jm1][1])+
dy2ty1*( ue[jp1][1]-2.0* ue[j][1]+ ue[jm1][1]);
forcing[i][j][k][2] = forcing[i][j][k][2] -
ty2*((ue[jp1][2]*buf[jp1][2]+c2*(ue[jp1][4]-q[jp1]))-
(ue[jm1][2]*buf[jm1][2]+c2*(ue[jm1][4]-q[jm1])))+
yycon1*(buf[jp1][2]-2.0*buf[j][2]+buf[jm1][2])+
dy3ty1*( ue[jp1][2]-2.0*ue[j][2] +ue[jm1][2]);
forcing[i][j][k][3] = forcing[i][j][k][3] -
ty2*(ue[jp1][3]*buf[jp1][2]-ue[jm1][3]*buf[jm1][2])+
yycon2*(buf[jp1][3]-2.0*buf[j][3]+buf[jm1][3])+
dy4ty1*( ue[jp1][3]-2.0*ue[j][3]+ ue[jm1][3]);
forcing[i][j][k][4] = forcing[i][j][k][4] -
ty2*(buf[jp1][2]*(c1*ue[jp1][4]-c2*q[jp1])-
buf[jm1][2]*(c1*ue[jm1][4]-c2*q[jm1]))+
0.5*yycon3*(buf[jp1][0]-2.0*buf[j][0]+
buf[jm1][0])+
yycon4*(cuf[jp1]-2.0*cuf[j]+cuf[jm1])+
yycon5*(buf[jp1][4]-2.0*buf[j][4]+buf[jm1][4])+
dy5ty1*(ue[jp1][4]-2.0*ue[j][4]+ue[jm1][4]);
}
/*--------------------------------------------------------------------
c Fourth-order dissipation
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
j = 1;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(5.0*ue[j][m] - 4.0*ue[j+1][m] +ue[j+2][m]);
j = 2;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(-4.0*ue[j-1][m] + 6.0*ue[j][m] -
4.0*ue[j+1][m] + ue[j+2][m]);
}
for (m = 0; m < 5; m++) {
for (j = 1*3; j <= grid_points[1]-3*1-1; j++) {
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp*
(ue[j-2][m] - 4.0*ue[j-1][m] +
6.0*ue[j][m] - 4.0*ue[j+1][m] + ue[j+2][m]);
}
}
for (m = 0; m < 5; m++) {
j = grid_points[1]-3;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(ue[j-2][m] - 4.0*ue[j-1][m] +
6.0*ue[j][m] - 4.0*ue[j+1][m]);
j = grid_points[1]-2;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(ue[j-2][m] - 4.0*ue[j-1][m] + 5.0*ue[j][m]);
}
}
}
/*--------------------------------------------------------------------
c zeta-direction flux differences
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
xi = (double)i * dnxm1;
for (j = 1; j < grid_points[1]-1; j++) {
eta = (double)j * dnym1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, dtemp);
for (m = 0; m < 5; m++) {
ue[k][m] = dtemp[m];
}
dtpp = 1.0/dtemp[0];
for (m = 1; m <= 4; m++) {
buf[k][m] = dtpp * dtemp[m];
}
cuf[k] = buf[k][3] * buf[k][3];
buf[k][0] = cuf[k] + buf[k][1] * buf[k][1] +
buf[k][2] * buf[k][2];
q[k] = 0.5*(buf[k][1]*ue[k][1] + buf[k][2]*ue[k][2] +
buf[k][3]*ue[k][3]);
}
for (k = 1; k < grid_points[2]-1; k++) {
km1 = k-1;
kp1 = k+1;
forcing[i][j][k][0] = forcing[i][j][k][0] -
tz2*( ue[kp1][3]-ue[km1][3] )+
dz1tz1*(ue[kp1][0]-2.0*ue[k][0]+ue[km1][0]);
forcing[i][j][k][1] = forcing[i][j][k][1] -
tz2 * (ue[kp1][1]*buf[kp1][3]-ue[km1][1]*buf[km1][3])+
zzcon2*(buf[kp1][1]-2.0*buf[k][1]+buf[km1][1])+
dz2tz1*( ue[kp1][1]-2.0* ue[k][1]+ ue[km1][1]);
forcing[i][j][k][2] = forcing[i][j][k][2] -
tz2 * (ue[kp1][2]*buf[kp1][3]-ue[km1][2]*buf[km1][3])+
zzcon2*(buf[kp1][2]-2.0*buf[k][2]+buf[km1][2])+
dz3tz1*(ue[kp1][2]-2.0*ue[k][2]+ue[km1][2]);
forcing[i][j][k][3] = forcing[i][j][k][3] -
tz2 * ((ue[kp1][3]*buf[kp1][3]+c2*(ue[kp1][4]-q[kp1]))-
(ue[km1][3]*buf[km1][3]+c2*(ue[km1][4]-q[km1])))+
zzcon1*(buf[kp1][3]-2.0*buf[k][3]+buf[km1][3])+
dz4tz1*( ue[kp1][3]-2.0*ue[k][3] +ue[km1][3]);
forcing[i][j][k][4] = forcing[i][j][k][4] -
tz2 * (buf[kp1][3]*(c1*ue[kp1][4]-c2*q[kp1])-
buf[km1][3]*(c1*ue[km1][4]-c2*q[km1]))+
0.5*zzcon3*(buf[kp1][0]-2.0*buf[k][0]
+buf[km1][0])+
zzcon4*(cuf[kp1]-2.0*cuf[k]+cuf[km1])+
zzcon5*(buf[kp1][4]-2.0*buf[k][4]+buf[km1][4])+
dz5tz1*( ue[kp1][4]-2.0*ue[k][4]+ ue[km1][4]);
}
/*--------------------------------------------------------------------
c Fourth-order dissipation
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
k = 1;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(5.0*ue[k][m] - 4.0*ue[k+1][m] +ue[k+2][m]);
k = 2;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(-4.0*ue[k-1][m] + 6.0*ue[k][m] -
4.0*ue[k+1][m] + ue[k+2][m]);
}
for (m = 0; m < 5; m++) {
for (k = 1*3; k <= grid_points[2]-3*1-1; k++) {
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp*
(ue[k-2][m] - 4.0*ue[k-1][m] +
6.0*ue[k][m] - 4.0*ue[k+1][m] + ue[k+2][m]);
}
}
for (m = 0; m < 5; m++) {
k = grid_points[2]-3;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(ue[k-2][m] - 4.0*ue[k-1][m] +
6.0*ue[k][m] - 4.0*ue[k+1][m]);
k = grid_points[2]-2;
forcing[i][j][k][m] = forcing[i][j][k][m] - dssp *
(ue[k-2][m] - 4.0*ue[k-1][m] + 5.0*ue[k][m]);
}
}
}
/*--------------------------------------------------------------------
c now change the sign of the forcing function,
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
forcing[i][j][k][m] = -1.0 * forcing[i][j][k][m];
}
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void exact_solution(double xi, double eta, double zeta,
double dtemp[5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c this function returns the exact solution at point xi, eta, zeta
c-------------------------------------------------------------------*/
int m;
for (m = 0; m < 5; m++) {
dtemp[m] = ce[m][0] +
xi*(ce[m][1] + xi*(ce[m][4] + xi*(ce[m][7]
+ xi*ce[m][10]))) +
eta*(ce[m][2] + eta*(ce[m][5] + eta*(ce[m][8]
+ eta*ce[m][11])))+
zeta*(ce[m][3] + zeta*(ce[m][6] + zeta*(ce[m][9] +
zeta*ce[m][12])));
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void initialize(void) {
#pragma omp parallel
{
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This subroutine initializes the field variable u using
c tri-linear transfinite interpolation of the boundary values
c-------------------------------------------------------------------*/
int i, j, k, m, ix, iy, iz;
double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5];
/*--------------------------------------------------------------------
c Later (in compute_rhs) we compute 1/u for every element. A few of
c the corner elements are not used, but it convenient (and faster)
c to compute the whole thing with a simple loop. Make sure those
c values are nonzero by initializing the whole thing here.
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 0; i < IMAX; i++) {
for (j = 0; j < IMAX; j++) {
for (k = 0; k < IMAX; k++) {
for (m = 0; m < 5; m++) {
u[i][j][k][m] = 1.0;
}
}
}
}
/*--------------------------------------------------------------------
c first store the "interpolated" values everywhere on the grid
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
for (ix = 0; ix < 2; ix++) {
exact_solution((double)ix, eta, zeta,
&(Pface[ix][0][0]));
}
for (iy = 0; iy < 2; iy++) {
exact_solution(xi, (double)iy , zeta,
&Pface[iy][1][0]);
}
for (iz = 0; iz < 2; iz++) {
exact_solution(xi, eta, (double)iz,
&Pface[iz][2][0]);
}
for (m = 0; m < 5; m++) {
Pxi = xi * Pface[1][0][m] +
(1.0-xi) * Pface[0][0][m];
Peta = eta * Pface[1][1][m] +
(1.0-eta) * Pface[0][1][m];
Pzeta = zeta * Pface[1][2][m] +
(1.0-zeta) * Pface[0][2][m];
u[i][j][k][m] = Pxi + Peta + Pzeta -
Pxi*Peta - Pxi*Pzeta - Peta*Pzeta +
Pxi*Peta*Pzeta;
}
}
}
}
/*--------------------------------------------------------------------
c now store the exact values on the boundaries
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c west face
c-------------------------------------------------------------------*/
i = 0;
xi = 0.0;
#pragma omp for nowait
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[i][j][k][m] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c east face
c-------------------------------------------------------------------*/
i = grid_points[0]-1;
xi = 1.0;
#pragma omp for
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[i][j][k][m] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c south face
c-------------------------------------------------------------------*/
j = 0;
eta = 0.0;
#pragma omp for nowait
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[i][j][k][m] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c north face
c-------------------------------------------------------------------*/
j = grid_points[1]-1;
eta = 1.0;
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[i][j][k][m] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c bottom face
c-------------------------------------------------------------------*/
k = 0;
zeta = 0.0;
#pragma omp for nowait
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i *dnxm1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[i][j][k][m] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c top face
c-------------------------------------------------------------------*/
k = grid_points[2]-1;
zeta = 1.0;
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[i][j][k][m] = temp[m];
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsinit(void) {
#pragma omp parallel
{
int i, j, k, m, n;
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c zero the whole left hand side for starters
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 0; k < grid_points[2]; k++) {
for (m = 0; m < 5; m++) {
for (n = 0; n < 5; n++) {
lhs[i][j][k][0][m][n] = 0.0;
lhs[i][j][k][1][m][n] = 0.0;
lhs[i][j][k][2][m][n] = 0.0;
}
}
}
}
}
/*--------------------------------------------------------------------
c next, set all diagonal values to 1. This is overkill, but convenient
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 0; k < grid_points[2]; k++) {
for (m = 0; m < 5; m++) {
lhs[i][j][k][1][m][m] = 1.0;
}
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsx(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This function computes the left hand side in the xi-direction
c-------------------------------------------------------------------*/
int i, j, k;
/*--------------------------------------------------------------------
c determine a (labeled f) and n jacobians
c-------------------------------------------------------------------*/
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (i = 0; i < grid_points[0]; i++) {
tmp1 = 1.0 / u[i][j][k][0];
tmp2 = tmp1 * tmp1;
tmp3 = tmp1 * tmp2;
/*--------------------------------------------------------------------
c
c-------------------------------------------------------------------*/
fjac[ i][ j][ k][0][0] = 0.0;
fjac[ i][ j][ k][0][1] = 1.0;
fjac[ i][ j][ k][0][2] = 0.0;
fjac[ i][ j][ k][0][3] = 0.0;
fjac[ i][ j][ k][0][4] = 0.0;
fjac[ i][ j][ k][1][0] = -(u[i][j][k][1] * tmp2 *
u[i][j][k][1])
+ c2 * 0.50 * (u[i][j][k][1] * u[i][j][k][1]
+ u[i][j][k][2] * u[i][j][k][2]
+ u[i][j][k][3] * u[i][j][k][3] ) * tmp2;
fjac[i][j][k][1][1] = ( 2.0 - c2 )
* ( u[i][j][k][1] / u[i][j][k][0] );
fjac[i][j][k][1][2] = - c2 * ( u[i][j][k][2] * tmp1 );
fjac[i][j][k][1][3] = - c2 * ( u[i][j][k][3] * tmp1 );
fjac[i][j][k][1][4] = c2;
fjac[i][j][k][2][0] = - ( u[i][j][k][1]*u[i][j][k][2] ) * tmp2;
fjac[i][j][k][2][1] = u[i][j][k][2] * tmp1;
fjac[i][j][k][2][2] = u[i][j][k][1] * tmp1;
fjac[i][j][k][2][3] = 0.0;
fjac[i][j][k][2][4] = 0.0;
fjac[i][j][k][3][0] = - ( u[i][j][k][1]*u[i][j][k][3] ) * tmp2;
fjac[i][j][k][3][1] = u[i][j][k][3] * tmp1;
fjac[i][j][k][3][2] = 0.0;
fjac[i][j][k][3][3] = u[i][j][k][1] * tmp1;
fjac[i][j][k][3][4] = 0.0;
fjac[i][j][k][4][0] = ( c2 * ( u[i][j][k][1] * u[i][j][k][1]
+ u[i][j][k][2] * u[i][j][k][2]
+ u[i][j][k][3] * u[i][j][k][3] ) * tmp2
- c1 * ( u[i][j][k][4] * tmp1 ) )
* ( u[i][j][k][1] * tmp1 );
fjac[i][j][k][4][1] = c1 * u[i][j][k][4] * tmp1
- 0.50 * c2
* ( 3.0*u[i][j][k][1]*u[i][j][k][1]
+ u[i][j][k][2]*u[i][j][k][2]
+ u[i][j][k][3]*u[i][j][k][3] ) * tmp2;
fjac[i][j][k][4][2] = - c2 * ( u[i][j][k][2]*u[i][j][k][1] )
* tmp2;
fjac[i][j][k][4][3] = - c2 * ( u[i][j][k][3]*u[i][j][k][1] )
* tmp2;
fjac[i][j][k][4][4] = c1 * ( u[i][j][k][1] * tmp1 );
njac[i][j][k][0][0] = 0.0;
njac[i][j][k][0][1] = 0.0;
njac[i][j][k][0][2] = 0.0;
njac[i][j][k][0][3] = 0.0;
njac[i][j][k][0][4] = 0.0;
njac[i][j][k][1][0] = - con43 * c3c4 * tmp2 * u[i][j][k][1];
njac[i][j][k][1][1] = con43 * c3c4 * tmp1;
njac[i][j][k][1][2] = 0.0;
njac[i][j][k][1][3] = 0.0;
njac[i][j][k][1][4] = 0.0;
njac[i][j][k][2][0] = - c3c4 * tmp2 * u[i][j][k][2];
njac[i][j][k][2][1] = 0.0;
njac[i][j][k][2][2] = c3c4 * tmp1;
njac[i][j][k][2][3] = 0.0;
njac[i][j][k][2][4] = 0.0;
njac[i][j][k][3][0] = - c3c4 * tmp2 * u[i][j][k][3];
njac[i][j][k][3][1] = 0.0;
njac[i][j][k][3][2] = 0.0;
njac[i][j][k][3][3] = c3c4 * tmp1;
njac[i][j][k][3][4] = 0.0;
njac[i][j][k][4][0] = - ( con43 * c3c4
- c1345 ) * tmp3 * (pow2(u[i][j][k][1]))
- ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][2]))
- ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][3]))
- c1345 * tmp2 * u[i][j][k][4];
njac[i][j][k][4][1] = ( con43 * c3c4
- c1345 ) * tmp2 * u[i][j][k][1];
njac[i][j][k][4][2] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][2];
njac[i][j][k][4][3] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][3];
njac[i][j][k][4][4] = ( c1345 ) * tmp1;
}
/*--------------------------------------------------------------------
c now jacobians set, so form left hand side in x direction
c-------------------------------------------------------------------*/
for (i = 1; i < grid_points[0]-1; i++) {
tmp1 = dt * tx1;
tmp2 = dt * tx2;
lhs[i][j][k][AA][0][0] = - tmp2 * fjac[i-1][j][k][0][0]
- tmp1 * njac[i-1][j][k][0][0]
- tmp1 * dx1;
lhs[i][j][k][AA][0][1] = - tmp2 * fjac[i-1][j][k][0][1]
- tmp1 * njac[i-1][j][k][0][1];
lhs[i][j][k][AA][0][2] = - tmp2 * fjac[i-1][j][k][0][2]
- tmp1 * njac[i-1][j][k][0][2];
lhs[i][j][k][AA][0][3] = - tmp2 * fjac[i-1][j][k][0][3]
- tmp1 * njac[i-1][j][k][0][3];
lhs[i][j][k][AA][0][4] = - tmp2 * fjac[i-1][j][k][0][4]
- tmp1 * njac[i-1][j][k][0][4];
lhs[i][j][k][AA][1][0] = - tmp2 * fjac[i-1][j][k][1][0]
- tmp1 * njac[i-1][j][k][1][0];
lhs[i][j][k][AA][1][1] = - tmp2 * fjac[i-1][j][k][1][1]
- tmp1 * njac[i-1][j][k][1][1]
- tmp1 * dx2;
lhs[i][j][k][AA][1][2] = - tmp2 * fjac[i-1][j][k][1][2]
- tmp1 * njac[i-1][j][k][1][2];
lhs[i][j][k][AA][1][3] = - tmp2 * fjac[i-1][j][k][1][3]
- tmp1 * njac[i-1][j][k][1][3];
lhs[i][j][k][AA][1][4] = - tmp2 * fjac[i-1][j][k][1][4]
- tmp1 * njac[i-1][j][k][1][4];
lhs[i][j][k][AA][2][0] = - tmp2 * fjac[i-1][j][k][2][0]
- tmp1 * njac[i-1][j][k][2][0];
lhs[i][j][k][AA][2][1] = - tmp2 * fjac[i-1][j][k][2][1]
- tmp1 * njac[i-1][j][k][2][1];
lhs[i][j][k][AA][2][2] = - tmp2 * fjac[i-1][j][k][2][2]
- tmp1 * njac[i-1][j][k][2][2]
- tmp1 * dx3;
lhs[i][j][k][AA][2][3] = - tmp2 * fjac[i-1][j][k][2][3]
- tmp1 * njac[i-1][j][k][2][3];
lhs[i][j][k][AA][2][4] = - tmp2 * fjac[i-1][j][k][2][4]
- tmp1 * njac[i-1][j][k][2][4];
lhs[i][j][k][AA][3][0] = - tmp2 * fjac[i-1][j][k][3][0]
- tmp1 * njac[i-1][j][k][3][0];
lhs[i][j][k][AA][3][1] = - tmp2 * fjac[i-1][j][k][3][1]
- tmp1 * njac[i-1][j][k][3][1];
lhs[i][j][k][AA][3][2] = - tmp2 * fjac[i-1][j][k][3][2]
- tmp1 * njac[i-1][j][k][3][2];
lhs[i][j][k][AA][3][3] = - tmp2 * fjac[i-1][j][k][3][3]
- tmp1 * njac[i-1][j][k][3][3]
- tmp1 * dx4;
lhs[i][j][k][AA][3][4] = - tmp2 * fjac[i-1][j][k][3][4]
- tmp1 * njac[i-1][j][k][3][4];
lhs[i][j][k][AA][4][0] = - tmp2 * fjac[i-1][j][k][4][0]
- tmp1 * njac[i-1][j][k][4][0];
lhs[i][j][k][AA][4][1] = - tmp2 * fjac[i-1][j][k][4][1]
- tmp1 * njac[i-1][j][k][4][1];
lhs[i][j][k][AA][4][2] = - tmp2 * fjac[i-1][j][k][4][2]
- tmp1 * njac[i-1][j][k][4][2];
lhs[i][j][k][AA][4][3] = - tmp2 * fjac[i-1][j][k][4][3]
- tmp1 * njac[i-1][j][k][4][3];
lhs[i][j][k][AA][4][4] = - tmp2 * fjac[i-1][j][k][4][4]
- tmp1 * njac[i-1][j][k][4][4]
- tmp1 * dx5;
lhs[i][j][k][BB][0][0] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][0][0]
+ tmp1 * 2.0 * dx1;
lhs[i][j][k][BB][0][1] = tmp1 * 2.0 * njac[i][j][k][0][1];
lhs[i][j][k][BB][0][2] = tmp1 * 2.0 * njac[i][j][k][0][2];
lhs[i][j][k][BB][0][3] = tmp1 * 2.0 * njac[i][j][k][0][3];
lhs[i][j][k][BB][0][4] = tmp1 * 2.0 * njac[i][j][k][0][4];
lhs[i][j][k][BB][1][0] = tmp1 * 2.0 * njac[i][j][k][1][0];
lhs[i][j][k][BB][1][1] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][1][1]
+ tmp1 * 2.0 * dx2;
lhs[i][j][k][BB][1][2] = tmp1 * 2.0 * njac[i][j][k][1][2];
lhs[i][j][k][BB][1][3] = tmp1 * 2.0 * njac[i][j][k][1][3];
lhs[i][j][k][BB][1][4] = tmp1 * 2.0 * njac[i][j][k][1][4];
lhs[i][j][k][BB][2][0] = tmp1 * 2.0 * njac[i][j][k][2][0];
lhs[i][j][k][BB][2][1] = tmp1 * 2.0 * njac[i][j][k][2][1];
lhs[i][j][k][BB][2][2] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][2][2]
+ tmp1 * 2.0 * dx3;
lhs[i][j][k][BB][2][3] = tmp1 * 2.0 * njac[i][j][k][2][3];
lhs[i][j][k][BB][2][4] = tmp1 * 2.0 * njac[i][j][k][2][4];
lhs[i][j][k][BB][3][0] = tmp1 * 2.0 * njac[i][j][k][3][0];
lhs[i][j][k][BB][3][1] = tmp1 * 2.0 * njac[i][j][k][3][1];
lhs[i][j][k][BB][3][2] = tmp1 * 2.0 * njac[i][j][k][3][2];
lhs[i][j][k][BB][3][3] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][3][3]
+ tmp1 * 2.0 * dx4;
lhs[i][j][k][BB][3][4] = tmp1 * 2.0 * njac[i][j][k][3][4];
lhs[i][j][k][BB][4][0] = tmp1 * 2.0 * njac[i][j][k][4][0];
lhs[i][j][k][BB][4][1] = tmp1 * 2.0 * njac[i][j][k][4][1];
lhs[i][j][k][BB][4][2] = tmp1 * 2.0 * njac[i][j][k][4][2];
lhs[i][j][k][BB][4][3] = tmp1 * 2.0 * njac[i][j][k][4][3];
lhs[i][j][k][BB][4][4] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][4][4]
+ tmp1 * 2.0 * dx5;
lhs[i][j][k][CC][0][0] = tmp2 * fjac[i+1][j][k][0][0]
- tmp1 * njac[i+1][j][k][0][0]
- tmp1 * dx1;
lhs[i][j][k][CC][0][1] = tmp2 * fjac[i+1][j][k][0][1]
- tmp1 * njac[i+1][j][k][0][1];
lhs[i][j][k][CC][0][2] = tmp2 * fjac[i+1][j][k][0][2]
- tmp1 * njac[i+1][j][k][0][2];
lhs[i][j][k][CC][0][3] = tmp2 * fjac[i+1][j][k][0][3]
- tmp1 * njac[i+1][j][k][0][3];
lhs[i][j][k][CC][0][4] = tmp2 * fjac[i+1][j][k][0][4]
- tmp1 * njac[i+1][j][k][0][4];
lhs[i][j][k][CC][1][0] = tmp2 * fjac[i+1][j][k][1][0]
- tmp1 * njac[i+1][j][k][1][0];
lhs[i][j][k][CC][1][1] = tmp2 * fjac[i+1][j][k][1][1]
- tmp1 * njac[i+1][j][k][1][1]
- tmp1 * dx2;
lhs[i][j][k][CC][1][2] = tmp2 * fjac[i+1][j][k][1][2]
- tmp1 * njac[i+1][j][k][1][2];
lhs[i][j][k][CC][1][3] = tmp2 * fjac[i+1][j][k][1][3]
- tmp1 * njac[i+1][j][k][1][3];
lhs[i][j][k][CC][1][4] = tmp2 * fjac[i+1][j][k][1][4]
- tmp1 * njac[i+1][j][k][1][4];
lhs[i][j][k][CC][2][0] = tmp2 * fjac[i+1][j][k][2][0]
- tmp1 * njac[i+1][j][k][2][0];
lhs[i][j][k][CC][2][1] = tmp2 * fjac[i+1][j][k][2][1]
- tmp1 * njac[i+1][j][k][2][1];
lhs[i][j][k][CC][2][2] = tmp2 * fjac[i+1][j][k][2][2]
- tmp1 * njac[i+1][j][k][2][2]
- tmp1 * dx3;
lhs[i][j][k][CC][2][3] = tmp2 * fjac[i+1][j][k][2][3]
- tmp1 * njac[i+1][j][k][2][3];
lhs[i][j][k][CC][2][4] = tmp2 * fjac[i+1][j][k][2][4]
- tmp1 * njac[i+1][j][k][2][4];
lhs[i][j][k][CC][3][0] = tmp2 * fjac[i+1][j][k][3][0]
- tmp1 * njac[i+1][j][k][3][0];
lhs[i][j][k][CC][3][1] = tmp2 * fjac[i+1][j][k][3][1]
- tmp1 * njac[i+1][j][k][3][1];
lhs[i][j][k][CC][3][2] = tmp2 * fjac[i+1][j][k][3][2]
- tmp1 * njac[i+1][j][k][3][2];
lhs[i][j][k][CC][3][3] = tmp2 * fjac[i+1][j][k][3][3]
- tmp1 * njac[i+1][j][k][3][3]
- tmp1 * dx4;
lhs[i][j][k][CC][3][4] = tmp2 * fjac[i+1][j][k][3][4]
- tmp1 * njac[i+1][j][k][3][4];
lhs[i][j][k][CC][4][0] = tmp2 * fjac[i+1][j][k][4][0]
- tmp1 * njac[i+1][j][k][4][0];
lhs[i][j][k][CC][4][1] = tmp2 * fjac[i+1][j][k][4][1]
- tmp1 * njac[i+1][j][k][4][1];
lhs[i][j][k][CC][4][2] = tmp2 * fjac[i+1][j][k][4][2]
- tmp1 * njac[i+1][j][k][4][2];
lhs[i][j][k][CC][4][3] = tmp2 * fjac[i+1][j][k][4][3]
- tmp1 * njac[i+1][j][k][4][3];
lhs[i][j][k][CC][4][4] = tmp2 * fjac[i+1][j][k][4][4]
- tmp1 * njac[i+1][j][k][4][4]
- tmp1 * dx5;
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsy(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This function computes the left hand side for the three y-factors
c-------------------------------------------------------------------*/
int i, j, k;
/*--------------------------------------------------------------------
c Compute the indices for storing the tri-diagonal matrix;
c determine a (labeled f) and n jacobians for cell c
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
tmp1 = 1.0 / u[i][j][k][0];
tmp2 = tmp1 * tmp1;
tmp3 = tmp1 * tmp2;
fjac[ i][ j][ k][0][0] = 0.0;
fjac[ i][ j][ k][0][1] = 0.0;
fjac[ i][ j][ k][0][2] = 1.0;
fjac[ i][ j][ k][0][3] = 0.0;
fjac[ i][ j][ k][0][4] = 0.0;
fjac[i][j][k][1][0] = - ( u[i][j][k][1]*u[i][j][k][2] )
* tmp2;
fjac[i][j][k][1][1] = u[i][j][k][2] * tmp1;
fjac[i][j][k][1][2] = u[i][j][k][1] * tmp1;
fjac[i][j][k][1][3] = 0.0;
fjac[i][j][k][1][4] = 0.0;
fjac[i][j][k][2][0] = - ( u[i][j][k][2]*u[i][j][k][2]*tmp2)
+ 0.50 * c2 * ( ( u[i][j][k][1] * u[i][j][k][1]
+ u[i][j][k][2] * u[i][j][k][2]
+ u[i][j][k][3] * u[i][j][k][3] )
* tmp2 );
fjac[i][j][k][2][1] = - c2 * u[i][j][k][1] * tmp1;
fjac[i][j][k][2][2] = ( 2.0 - c2 )
* u[i][j][k][2] * tmp1;
fjac[i][j][k][2][3] = - c2 * u[i][j][k][3] * tmp1;
fjac[i][j][k][2][4] = c2;
fjac[i][j][k][3][0] = - ( u[i][j][k][2]*u[i][j][k][3] )
* tmp2;
fjac[i][j][k][3][1] = 0.0;
fjac[i][j][k][3][2] = u[i][j][k][3] * tmp1;
fjac[i][j][k][3][3] = u[i][j][k][2] * tmp1;
fjac[i][j][k][3][4] = 0.0;
fjac[i][j][k][4][0] = ( c2 * ( u[i][j][k][1] * u[i][j][k][1]
+ u[i][j][k][2] * u[i][j][k][2]
+ u[i][j][k][3] * u[i][j][k][3] )
* tmp2
- c1 * u[i][j][k][4] * tmp1 )
* u[i][j][k][2] * tmp1;
fjac[i][j][k][4][1] = - c2 * u[i][j][k][1]*u[i][j][k][2]
* tmp2;
fjac[i][j][k][4][2] = c1 * u[i][j][k][4] * tmp1
- 0.50 * c2
* ( ( u[i][j][k][1]*u[i][j][k][1]
+ 3.0 * u[i][j][k][2]*u[i][j][k][2]
+ u[i][j][k][3]*u[i][j][k][3] )
* tmp2 );
fjac[i][j][k][4][3] = - c2 * ( u[i][j][k][2]*u[i][j][k][3] )
* tmp2;
fjac[i][j][k][4][4] = c1 * u[i][j][k][2] * tmp1;
njac[i][j][k][0][0] = 0.0;
njac[i][j][k][0][1] = 0.0;
njac[i][j][k][0][2] = 0.0;
njac[i][j][k][0][3] = 0.0;
njac[i][j][k][0][4] = 0.0;
njac[i][j][k][1][0] = - c3c4 * tmp2 * u[i][j][k][1];
njac[i][j][k][1][1] = c3c4 * tmp1;
njac[i][j][k][1][2] = 0.0;
njac[i][j][k][1][3] = 0.0;
njac[i][j][k][1][4] = 0.0;
njac[i][j][k][2][0] = - con43 * c3c4 * tmp2 * u[i][j][k][2];
njac[i][j][k][2][1] = 0.0;
njac[i][j][k][2][2] = con43 * c3c4 * tmp1;
njac[i][j][k][2][3] = 0.0;
njac[i][j][k][2][4] = 0.0;
njac[i][j][k][3][0] = - c3c4 * tmp2 * u[i][j][k][3];
njac[i][j][k][3][1] = 0.0;
njac[i][j][k][3][2] = 0.0;
njac[i][j][k][3][3] = c3c4 * tmp1;
njac[i][j][k][3][4] = 0.0;
njac[i][j][k][4][0] = - ( c3c4
- c1345 ) * tmp3 * (pow2(u[i][j][k][1]))
- ( con43 * c3c4
- c1345 ) * tmp3 * (pow2(u[i][j][k][2]))
- ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][3]))
- c1345 * tmp2 * u[i][j][k][4];
njac[i][j][k][4][1] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][1];
njac[i][j][k][4][2] = ( con43 * c3c4
- c1345 ) * tmp2 * u[i][j][k][2];
njac[i][j][k][4][3] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][3];
njac[i][j][k][4][4] = ( c1345 ) * tmp1;
}
}
}
/*--------------------------------------------------------------------
c now joacobians set, so form left hand side in y direction
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
tmp1 = dt * ty1;
tmp2 = dt * ty2;
lhs[i][j][k][AA][0][0] = - tmp2 * fjac[i][j-1][k][0][0]
- tmp1 * njac[i][j-1][k][0][0]
- tmp1 * dy1;
lhs[i][j][k][AA][0][1] = - tmp2 * fjac[i][j-1][k][0][1]
- tmp1 * njac[i][j-1][k][0][1];
lhs[i][j][k][AA][0][2] = - tmp2 * fjac[i][j-1][k][0][2]
- tmp1 * njac[i][j-1][k][0][2];
lhs[i][j][k][AA][0][3] = - tmp2 * fjac[i][j-1][k][0][3]
- tmp1 * njac[i][j-1][k][0][3];
lhs[i][j][k][AA][0][4] = - tmp2 * fjac[i][j-1][k][0][4]
- tmp1 * njac[i][j-1][k][0][4];
lhs[i][j][k][AA][1][0] = - tmp2 * fjac[i][j-1][k][1][0]
- tmp1 * njac[i][j-1][k][1][0];
lhs[i][j][k][AA][1][1] = - tmp2 * fjac[i][j-1][k][1][1]
- tmp1 * njac[i][j-1][k][1][1]
- tmp1 * dy2;
lhs[i][j][k][AA][1][2] = - tmp2 * fjac[i][j-1][k][1][2]
- tmp1 * njac[i][j-1][k][1][2];
lhs[i][j][k][AA][1][3] = - tmp2 * fjac[i][j-1][k][1][3]
- tmp1 * njac[i][j-1][k][1][3];
lhs[i][j][k][AA][1][4] = - tmp2 * fjac[i][j-1][k][1][4]
- tmp1 * njac[i][j-1][k][1][4];
lhs[i][j][k][AA][2][0] = - tmp2 * fjac[i][j-1][k][2][0]
- tmp1 * njac[i][j-1][k][2][0];
lhs[i][j][k][AA][2][1] = - tmp2 * fjac[i][j-1][k][2][1]
- tmp1 * njac[i][j-1][k][2][1];
lhs[i][j][k][AA][2][2] = - tmp2 * fjac[i][j-1][k][2][2]
- tmp1 * njac[i][j-1][k][2][2]
- tmp1 * dy3;
lhs[i][j][k][AA][2][3] = - tmp2 * fjac[i][j-1][k][2][3]
- tmp1 * njac[i][j-1][k][2][3];
lhs[i][j][k][AA][2][4] = - tmp2 * fjac[i][j-1][k][2][4]
- tmp1 * njac[i][j-1][k][2][4];
lhs[i][j][k][AA][3][0] = - tmp2 * fjac[i][j-1][k][3][0]
- tmp1 * njac[i][j-1][k][3][0];
lhs[i][j][k][AA][3][1] = - tmp2 * fjac[i][j-1][k][3][1]
- tmp1 * njac[i][j-1][k][3][1];
lhs[i][j][k][AA][3][2] = - tmp2 * fjac[i][j-1][k][3][2]
- tmp1 * njac[i][j-1][k][3][2];
lhs[i][j][k][AA][3][3] = - tmp2 * fjac[i][j-1][k][3][3]
- tmp1 * njac[i][j-1][k][3][3]
- tmp1 * dy4;
lhs[i][j][k][AA][3][4] = - tmp2 * fjac[i][j-1][k][3][4]
- tmp1 * njac[i][j-1][k][3][4];
lhs[i][j][k][AA][4][0] = - tmp2 * fjac[i][j-1][k][4][0]
- tmp1 * njac[i][j-1][k][4][0];
lhs[i][j][k][AA][4][1] = - tmp2 * fjac[i][j-1][k][4][1]
- tmp1 * njac[i][j-1][k][4][1];
lhs[i][j][k][AA][4][2] = - tmp2 * fjac[i][j-1][k][4][2]
- tmp1 * njac[i][j-1][k][4][2];
lhs[i][j][k][AA][4][3] = - tmp2 * fjac[i][j-1][k][4][3]
- tmp1 * njac[i][j-1][k][4][3];
lhs[i][j][k][AA][4][4] = - tmp2 * fjac[i][j-1][k][4][4]
- tmp1 * njac[i][j-1][k][4][4]
- tmp1 * dy5;
lhs[i][j][k][BB][0][0] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][0][0]
+ tmp1 * 2.0 * dy1;
lhs[i][j][k][BB][0][1] = tmp1 * 2.0 * njac[i][j][k][0][1];
lhs[i][j][k][BB][0][2] = tmp1 * 2.0 * njac[i][j][k][0][2];
lhs[i][j][k][BB][0][3] = tmp1 * 2.0 * njac[i][j][k][0][3];
lhs[i][j][k][BB][0][4] = tmp1 * 2.0 * njac[i][j][k][0][4];
lhs[i][j][k][BB][1][0] = tmp1 * 2.0 * njac[i][j][k][1][0];
lhs[i][j][k][BB][1][1] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][1][1]
+ tmp1 * 2.0 * dy2;
lhs[i][j][k][BB][1][2] = tmp1 * 2.0 * njac[i][j][k][1][2];
lhs[i][j][k][BB][1][3] = tmp1 * 2.0 * njac[i][j][k][1][3];
lhs[i][j][k][BB][1][4] = tmp1 * 2.0 * njac[i][j][k][1][4];
lhs[i][j][k][BB][2][0] = tmp1 * 2.0 * njac[i][j][k][2][0];
lhs[i][j][k][BB][2][1] = tmp1 * 2.0 * njac[i][j][k][2][1];
lhs[i][j][k][BB][2][2] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][2][2]
+ tmp1 * 2.0 * dy3;
lhs[i][j][k][BB][2][3] = tmp1 * 2.0 * njac[i][j][k][2][3];
lhs[i][j][k][BB][2][4] = tmp1 * 2.0 * njac[i][j][k][2][4];
lhs[i][j][k][BB][3][0] = tmp1 * 2.0 * njac[i][j][k][3][0];
lhs[i][j][k][BB][3][1] = tmp1 * 2.0 * njac[i][j][k][3][1];
lhs[i][j][k][BB][3][2] = tmp1 * 2.0 * njac[i][j][k][3][2];
lhs[i][j][k][BB][3][3] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][3][3]
+ tmp1 * 2.0 * dy4;
lhs[i][j][k][BB][3][4] = tmp1 * 2.0 * njac[i][j][k][3][4];
lhs[i][j][k][BB][4][0] = tmp1 * 2.0 * njac[i][j][k][4][0];
lhs[i][j][k][BB][4][1] = tmp1 * 2.0 * njac[i][j][k][4][1];
lhs[i][j][k][BB][4][2] = tmp1 * 2.0 * njac[i][j][k][4][2];
lhs[i][j][k][BB][4][3] = tmp1 * 2.0 * njac[i][j][k][4][3];
lhs[i][j][k][BB][4][4] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][4][4]
+ tmp1 * 2.0 * dy5;
lhs[i][j][k][CC][0][0] = tmp2 * fjac[i][j+1][k][0][0]
- tmp1 * njac[i][j+1][k][0][0]
- tmp1 * dy1;
lhs[i][j][k][CC][0][1] = tmp2 * fjac[i][j+1][k][0][1]
- tmp1 * njac[i][j+1][k][0][1];
lhs[i][j][k][CC][0][2] = tmp2 * fjac[i][j+1][k][0][2]
- tmp1 * njac[i][j+1][k][0][2];
lhs[i][j][k][CC][0][3] = tmp2 * fjac[i][j+1][k][0][3]
- tmp1 * njac[i][j+1][k][0][3];
lhs[i][j][k][CC][0][4] = tmp2 * fjac[i][j+1][k][0][4]
- tmp1 * njac[i][j+1][k][0][4];
lhs[i][j][k][CC][1][0] = tmp2 * fjac[i][j+1][k][1][0]
- tmp1 * njac[i][j+1][k][1][0];
lhs[i][j][k][CC][1][1] = tmp2 * fjac[i][j+1][k][1][1]
- tmp1 * njac[i][j+1][k][1][1]
- tmp1 * dy2;
lhs[i][j][k][CC][1][2] = tmp2 * fjac[i][j+1][k][1][2]
- tmp1 * njac[i][j+1][k][1][2];
lhs[i][j][k][CC][1][3] = tmp2 * fjac[i][j+1][k][1][3]
- tmp1 * njac[i][j+1][k][1][3];
lhs[i][j][k][CC][1][4] = tmp2 * fjac[i][j+1][k][1][4]
- tmp1 * njac[i][j+1][k][1][4];
lhs[i][j][k][CC][2][0] = tmp2 * fjac[i][j+1][k][2][0]
- tmp1 * njac[i][j+1][k][2][0];
lhs[i][j][k][CC][2][1] = tmp2 * fjac[i][j+1][k][2][1]
- tmp1 * njac[i][j+1][k][2][1];
lhs[i][j][k][CC][2][2] = tmp2 * fjac[i][j+1][k][2][2]
- tmp1 * njac[i][j+1][k][2][2]
- tmp1 * dy3;
lhs[i][j][k][CC][2][3] = tmp2 * fjac[i][j+1][k][2][3]
- tmp1 * njac[i][j+1][k][2][3];
lhs[i][j][k][CC][2][4] = tmp2 * fjac[i][j+1][k][2][4]
- tmp1 * njac[i][j+1][k][2][4];
lhs[i][j][k][CC][3][0] = tmp2 * fjac[i][j+1][k][3][0]
- tmp1 * njac[i][j+1][k][3][0];
lhs[i][j][k][CC][3][1] = tmp2 * fjac[i][j+1][k][3][1]
- tmp1 * njac[i][j+1][k][3][1];
lhs[i][j][k][CC][3][2] = tmp2 * fjac[i][j+1][k][3][2]
- tmp1 * njac[i][j+1][k][3][2];
lhs[i][j][k][CC][3][3] = tmp2 * fjac[i][j+1][k][3][3]
- tmp1 * njac[i][j+1][k][3][3]
- tmp1 * dy4;
lhs[i][j][k][CC][3][4] = tmp2 * fjac[i][j+1][k][3][4]
- tmp1 * njac[i][j+1][k][3][4];
lhs[i][j][k][CC][4][0] = tmp2 * fjac[i][j+1][k][4][0]
- tmp1 * njac[i][j+1][k][4][0];
lhs[i][j][k][CC][4][1] = tmp2 * fjac[i][j+1][k][4][1]
- tmp1 * njac[i][j+1][k][4][1];
lhs[i][j][k][CC][4][2] = tmp2 * fjac[i][j+1][k][4][2]
- tmp1 * njac[i][j+1][k][4][2];
lhs[i][j][k][CC][4][3] = tmp2 * fjac[i][j+1][k][4][3]
- tmp1 * njac[i][j+1][k][4][3];
lhs[i][j][k][CC][4][4] = tmp2 * fjac[i][j+1][k][4][4]
- tmp1 * njac[i][j+1][k][4][4]
- tmp1 * dy5;
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsz(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This function computes the left hand side for the three z-factors
c-------------------------------------------------------------------*/
int i, j, k;
/*--------------------------------------------------------------------
c Compute the indices for storing the block-diagonal matrix;
c determine c (labeled f) and s jacobians
c---------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 0; k < grid_points[2]; k++) {
tmp1 = 1.0 / u[i][j][k][0];
tmp2 = tmp1 * tmp1;
tmp3 = tmp1 * tmp2;
fjac[i][j][k][0][0] = 0.0;
fjac[i][j][k][0][1] = 0.0;
fjac[i][j][k][0][2] = 0.0;
fjac[i][j][k][0][3] = 1.0;
fjac[i][j][k][0][4] = 0.0;
fjac[i][j][k][1][0] = - ( u[i][j][k][1]*u[i][j][k][3] )
* tmp2;
fjac[i][j][k][1][1] = u[i][j][k][3] * tmp1;
fjac[i][j][k][1][2] = 0.0;
fjac[i][j][k][1][3] = u[i][j][k][1] * tmp1;
fjac[i][j][k][1][4] = 0.0;
fjac[i][j][k][2][0] = - ( u[i][j][k][2]*u[i][j][k][3] )
* tmp2;
fjac[i][j][k][2][1] = 0.0;
fjac[i][j][k][2][2] = u[i][j][k][3] * tmp1;
fjac[i][j][k][2][3] = u[i][j][k][2] * tmp1;
fjac[i][j][k][2][4] = 0.0;
fjac[i][j][k][3][0] = - (u[i][j][k][3]*u[i][j][k][3] * tmp2 )
+ 0.50 * c2 * ( ( u[i][j][k][1] * u[i][j][k][1]
+ u[i][j][k][2] * u[i][j][k][2]
+ u[i][j][k][3] * u[i][j][k][3] ) * tmp2 );
fjac[i][j][k][3][1] = - c2 * u[i][j][k][1] * tmp1;
fjac[i][j][k][3][2] = - c2 * u[i][j][k][2] * tmp1;
fjac[i][j][k][3][3] = ( 2.0 - c2 )
* u[i][j][k][3] * tmp1;
fjac[i][j][k][3][4] = c2;
fjac[i][j][k][4][0] = ( c2 * ( u[i][j][k][1] * u[i][j][k][1]
+ u[i][j][k][2] * u[i][j][k][2]
+ u[i][j][k][3] * u[i][j][k][3] )
* tmp2
- c1 * ( u[i][j][k][4] * tmp1 ) )
* ( u[i][j][k][3] * tmp1 );
fjac[i][j][k][4][1] = - c2 * ( u[i][j][k][1]*u[i][j][k][3] )
* tmp2;
fjac[i][j][k][4][2] = - c2 * ( u[i][j][k][2]*u[i][j][k][3] )
* tmp2;
fjac[i][j][k][4][3] = c1 * ( u[i][j][k][4] * tmp1 )
- 0.50 * c2
* ( ( u[i][j][k][1]*u[i][j][k][1]
+ u[i][j][k][2]*u[i][j][k][2]
+ 3.0*u[i][j][k][3]*u[i][j][k][3] )
* tmp2 );
fjac[i][j][k][4][4] = c1 * u[i][j][k][3] * tmp1;
njac[i][j][k][0][0] = 0.0;
njac[i][j][k][0][1] = 0.0;
njac[i][j][k][0][2] = 0.0;
njac[i][j][k][0][3] = 0.0;
njac[i][j][k][0][4] = 0.0;
njac[i][j][k][1][0] = - c3c4 * tmp2 * u[i][j][k][1];
njac[i][j][k][1][1] = c3c4 * tmp1;
njac[i][j][k][1][2] = 0.0;
njac[i][j][k][1][3] = 0.0;
njac[i][j][k][1][4] = 0.0;
njac[i][j][k][2][0] = - c3c4 * tmp2 * u[i][j][k][2];
njac[i][j][k][2][1] = 0.0;
njac[i][j][k][2][2] = c3c4 * tmp1;
njac[i][j][k][2][3] = 0.0;
njac[i][j][k][2][4] = 0.0;
njac[i][j][k][3][0] = - con43 * c3c4 * tmp2 * u[i][j][k][3];
njac[i][j][k][3][1] = 0.0;
njac[i][j][k][3][2] = 0.0;
njac[i][j][k][3][3] = con43 * c3 * c4 * tmp1;
njac[i][j][k][3][4] = 0.0;
njac[i][j][k][4][0] = - ( c3c4
- c1345 ) * tmp3 * (pow2(u[i][j][k][1]))
- ( c3c4 - c1345 ) * tmp3 * (pow2(u[i][j][k][2]))
- ( con43 * c3c4
- c1345 ) * tmp3 * (pow2(u[i][j][k][3]))
- c1345 * tmp2 * u[i][j][k][4];
njac[i][j][k][4][1] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][1];
njac[i][j][k][4][2] = ( c3c4 - c1345 ) * tmp2 * u[i][j][k][2];
njac[i][j][k][4][3] = ( con43 * c3c4
- c1345 ) * tmp2 * u[i][j][k][3];
njac[i][j][k][4][4] = ( c1345 )* tmp1;
}
}
}
/*--------------------------------------------------------------------
c now jacobians set, so form left hand side in z direction
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
tmp1 = dt * tz1;
tmp2 = dt * tz2;
lhs[i][j][k][AA][0][0] = - tmp2 * fjac[i][j][k-1][0][0]
- tmp1 * njac[i][j][k-1][0][0]
- tmp1 * dz1;
lhs[i][j][k][AA][0][1] = - tmp2 * fjac[i][j][k-1][0][1]
- tmp1 * njac[i][j][k-1][0][1];
lhs[i][j][k][AA][0][2] = - tmp2 * fjac[i][j][k-1][0][2]
- tmp1 * njac[i][j][k-1][0][2];
lhs[i][j][k][AA][0][3] = - tmp2 * fjac[i][j][k-1][0][3]
- tmp1 * njac[i][j][k-1][0][3];
lhs[i][j][k][AA][0][4] = - tmp2 * fjac[i][j][k-1][0][4]
- tmp1 * njac[i][j][k-1][0][4];
lhs[i][j][k][AA][1][0] = - tmp2 * fjac[i][j][k-1][1][0]
- tmp1 * njac[i][j][k-1][1][0];
lhs[i][j][k][AA][1][1] = - tmp2 * fjac[i][j][k-1][1][1]
- tmp1 * njac[i][j][k-1][1][1]
- tmp1 * dz2;
lhs[i][j][k][AA][1][2] = - tmp2 * fjac[i][j][k-1][1][2]
- tmp1 * njac[i][j][k-1][1][2];
lhs[i][j][k][AA][1][3] = - tmp2 * fjac[i][j][k-1][1][3]
- tmp1 * njac[i][j][k-1][1][3];
lhs[i][j][k][AA][1][4] = - tmp2 * fjac[i][j][k-1][1][4]
- tmp1 * njac[i][j][k-1][1][4];
lhs[i][j][k][AA][2][0] = - tmp2 * fjac[i][j][k-1][2][0]
- tmp1 * njac[i][j][k-1][2][0];
lhs[i][j][k][AA][2][1] = - tmp2 * fjac[i][j][k-1][2][1]
- tmp1 * njac[i][j][k-1][2][1];
lhs[i][j][k][AA][2][2] = - tmp2 * fjac[i][j][k-1][2][2]
- tmp1 * njac[i][j][k-1][2][2]
- tmp1 * dz3;
lhs[i][j][k][AA][2][3] = - tmp2 * fjac[i][j][k-1][2][3]
- tmp1 * njac[i][j][k-1][2][3];
lhs[i][j][k][AA][2][4] = - tmp2 * fjac[i][j][k-1][2][4]
- tmp1 * njac[i][j][k-1][2][4];
lhs[i][j][k][AA][3][0] = - tmp2 * fjac[i][j][k-1][3][0]
- tmp1 * njac[i][j][k-1][3][0];
lhs[i][j][k][AA][3][1] = - tmp2 * fjac[i][j][k-1][3][1]
- tmp1 * njac[i][j][k-1][3][1];
lhs[i][j][k][AA][3][2] = - tmp2 * fjac[i][j][k-1][3][2]
- tmp1 * njac[i][j][k-1][3][2];
lhs[i][j][k][AA][3][3] = - tmp2 * fjac[i][j][k-1][3][3]
- tmp1 * njac[i][j][k-1][3][3]
- tmp1 * dz4;
lhs[i][j][k][AA][3][4] = - tmp2 * fjac[i][j][k-1][3][4]
- tmp1 * njac[i][j][k-1][3][4];
lhs[i][j][k][AA][4][0] = - tmp2 * fjac[i][j][k-1][4][0]
- tmp1 * njac[i][j][k-1][4][0];
lhs[i][j][k][AA][4][1] = - tmp2 * fjac[i][j][k-1][4][1]
- tmp1 * njac[i][j][k-1][4][1];
lhs[i][j][k][AA][4][2] = - tmp2 * fjac[i][j][k-1][4][2]
- tmp1 * njac[i][j][k-1][4][2];
lhs[i][j][k][AA][4][3] = - tmp2 * fjac[i][j][k-1][4][3]
- tmp1 * njac[i][j][k-1][4][3];
lhs[i][j][k][AA][4][4] = - tmp2 * fjac[i][j][k-1][4][4]
- tmp1 * njac[i][j][k-1][4][4]
- tmp1 * dz5;
lhs[i][j][k][BB][0][0] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][0][0]
+ tmp1 * 2.0 * dz1;
lhs[i][j][k][BB][0][1] = tmp1 * 2.0 * njac[i][j][k][0][1];
lhs[i][j][k][BB][0][2] = tmp1 * 2.0 * njac[i][j][k][0][2];
lhs[i][j][k][BB][0][3] = tmp1 * 2.0 * njac[i][j][k][0][3];
lhs[i][j][k][BB][0][4] = tmp1 * 2.0 * njac[i][j][k][0][4];
lhs[i][j][k][BB][1][0] = tmp1 * 2.0 * njac[i][j][k][1][0];
lhs[i][j][k][BB][1][1] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][1][1]
+ tmp1 * 2.0 * dz2;
lhs[i][j][k][BB][1][2] = tmp1 * 2.0 * njac[i][j][k][1][2];
lhs[i][j][k][BB][1][3] = tmp1 * 2.0 * njac[i][j][k][1][3];
lhs[i][j][k][BB][1][4] = tmp1 * 2.0 * njac[i][j][k][1][4];
lhs[i][j][k][BB][2][0] = tmp1 * 2.0 * njac[i][j][k][2][0];
lhs[i][j][k][BB][2][1] = tmp1 * 2.0 * njac[i][j][k][2][1];
lhs[i][j][k][BB][2][2] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][2][2]
+ tmp1 * 2.0 * dz3;
lhs[i][j][k][BB][2][3] = tmp1 * 2.0 * njac[i][j][k][2][3];
lhs[i][j][k][BB][2][4] = tmp1 * 2.0 * njac[i][j][k][2][4];
lhs[i][j][k][BB][3][0] = tmp1 * 2.0 * njac[i][j][k][3][0];
lhs[i][j][k][BB][3][1] = tmp1 * 2.0 * njac[i][j][k][3][1];
lhs[i][j][k][BB][3][2] = tmp1 * 2.0 * njac[i][j][k][3][2];
lhs[i][j][k][BB][3][3] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][3][3]
+ tmp1 * 2.0 * dz4;
lhs[i][j][k][BB][3][4] = tmp1 * 2.0 * njac[i][j][k][3][4];
lhs[i][j][k][BB][4][0] = tmp1 * 2.0 * njac[i][j][k][4][0];
lhs[i][j][k][BB][4][1] = tmp1 * 2.0 * njac[i][j][k][4][1];
lhs[i][j][k][BB][4][2] = tmp1 * 2.0 * njac[i][j][k][4][2];
lhs[i][j][k][BB][4][3] = tmp1 * 2.0 * njac[i][j][k][4][3];
lhs[i][j][k][BB][4][4] = 1.0
+ tmp1 * 2.0 * njac[i][j][k][4][4]
+ tmp1 * 2.0 * dz5;
lhs[i][j][k][CC][0][0] = tmp2 * fjac[i][j][k+1][0][0]
- tmp1 * njac[i][j][k+1][0][0]
- tmp1 * dz1;
lhs[i][j][k][CC][0][1] = tmp2 * fjac[i][j][k+1][0][1]
- tmp1 * njac[i][j][k+1][0][1];
lhs[i][j][k][CC][0][2] = tmp2 * fjac[i][j][k+1][0][2]
- tmp1 * njac[i][j][k+1][0][2];
lhs[i][j][k][CC][0][3] = tmp2 * fjac[i][j][k+1][0][3]
- tmp1 * njac[i][j][k+1][0][3];
lhs[i][j][k][CC][0][4] = tmp2 * fjac[i][j][k+1][0][4]
- tmp1 * njac[i][j][k+1][0][4];
lhs[i][j][k][CC][1][0] = tmp2 * fjac[i][j][k+1][1][0]
- tmp1 * njac[i][j][k+1][1][0];
lhs[i][j][k][CC][1][1] = tmp2 * fjac[i][j][k+1][1][1]
- tmp1 * njac[i][j][k+1][1][1]
- tmp1 * dz2;
lhs[i][j][k][CC][1][2] = tmp2 * fjac[i][j][k+1][1][2]
- tmp1 * njac[i][j][k+1][1][2];
lhs[i][j][k][CC][1][3] = tmp2 * fjac[i][j][k+1][1][3]
- tmp1 * njac[i][j][k+1][1][3];
lhs[i][j][k][CC][1][4] = tmp2 * fjac[i][j][k+1][1][4]
- tmp1 * njac[i][j][k+1][1][4];
lhs[i][j][k][CC][2][0] = tmp2 * fjac[i][j][k+1][2][0]
- tmp1 * njac[i][j][k+1][2][0];
lhs[i][j][k][CC][2][1] = tmp2 * fjac[i][j][k+1][2][1]
- tmp1 * njac[i][j][k+1][2][1];
lhs[i][j][k][CC][2][2] = tmp2 * fjac[i][j][k+1][2][2]
- tmp1 * njac[i][j][k+1][2][2]
- tmp1 * dz3;
lhs[i][j][k][CC][2][3] = tmp2 * fjac[i][j][k+1][2][3]
- tmp1 * njac[i][j][k+1][2][3];
lhs[i][j][k][CC][2][4] = tmp2 * fjac[i][j][k+1][2][4]
- tmp1 * njac[i][j][k+1][2][4];
lhs[i][j][k][CC][3][0] = tmp2 * fjac[i][j][k+1][3][0]
- tmp1 * njac[i][j][k+1][3][0];
lhs[i][j][k][CC][3][1] = tmp2 * fjac[i][j][k+1][3][1]
- tmp1 * njac[i][j][k+1][3][1];
lhs[i][j][k][CC][3][2] = tmp2 * fjac[i][j][k+1][3][2]
- tmp1 * njac[i][j][k+1][3][2];
lhs[i][j][k][CC][3][3] = tmp2 * fjac[i][j][k+1][3][3]
- tmp1 * njac[i][j][k+1][3][3]
- tmp1 * dz4;
lhs[i][j][k][CC][3][4] = tmp2 * fjac[i][j][k+1][3][4]
- tmp1 * njac[i][j][k+1][3][4];
lhs[i][j][k][CC][4][0] = tmp2 * fjac[i][j][k+1][4][0]
- tmp1 * njac[i][j][k+1][4][0];
lhs[i][j][k][CC][4][1] = tmp2 * fjac[i][j][k+1][4][1]
- tmp1 * njac[i][j][k+1][4][1];
lhs[i][j][k][CC][4][2] = tmp2 * fjac[i][j][k+1][4][2]
- tmp1 * njac[i][j][k+1][4][2];
lhs[i][j][k][CC][4][3] = tmp2 * fjac[i][j][k+1][4][3]
- tmp1 * njac[i][j][k+1][4][3];
lhs[i][j][k][CC][4][4] = tmp2 * fjac[i][j][k+1][4][4]
- tmp1 * njac[i][j][k+1][4][4]
- tmp1 * dz5;
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void compute_rhs(void) {
int i, j, k, m;
double rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1;
/*--------------------------------------------------------------------
c compute the reciprocal of density, and the kinetic energy,
c and the speed of sound.
c-------------------------------------------------------------------*/
#pragma omp for nowait
for (i = 0; i < grid_points[0]; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 0; k < grid_points[2]; k++) {
rho_inv = 1.0/u[i][j][k][0];
rho_i[i][j][k] = rho_inv;
us[i][j][k] = u[i][j][k][1] * rho_inv;
vs[i][j][k] = u[i][j][k][2] * rho_inv;
ws[i][j][k] = u[i][j][k][3] * rho_inv;
square[i][j][k] = 0.5 * (u[i][j][k][1]*u[i][j][k][1] +
u[i][j][k][2]*u[i][j][k][2] +
u[i][j][k][3]*u[i][j][k][3] ) * rho_inv;
qs[i][j][k] = square[i][j][k] * rho_inv;
}
}
}
/*--------------------------------------------------------------------
c copy the exact forcing term to the right hand side; because
c this forcing term is known, we can store it on the whole grid
c including the boundary
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 0; k < grid_points[2]; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = forcing[i][j][k][m];
}
}
}
}
/*--------------------------------------------------------------------
c compute xi-direction fluxes
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
uijk = us[i][j][k];
up1 = us[i+1][j][k];
um1 = us[i-1][j][k];
rhs[i][j][k][0] = rhs[i][j][k][0] + dx1tx1 *
(u[i+1][j][k][0] - 2.0*u[i][j][k][0] +
u[i-1][j][k][0]) -
tx2 * (u[i+1][j][k][1] - u[i-1][j][k][1]);
rhs[i][j][k][1] = rhs[i][j][k][1] + dx2tx1 *
(u[i+1][j][k][1] - 2.0*u[i][j][k][1] +
u[i-1][j][k][1]) +
xxcon2*con43 * (up1 - 2.0*uijk + um1) -
tx2 * (u[i+1][j][k][1]*up1 -
u[i-1][j][k][1]*um1 +
(u[i+1][j][k][4]- square[i+1][j][k]-
u[i-1][j][k][4]+ square[i-1][j][k])*
c2);
rhs[i][j][k][2] = rhs[i][j][k][2] + dx3tx1 *
(u[i+1][j][k][2] - 2.0*u[i][j][k][2] +
u[i-1][j][k][2]) +
xxcon2 * (vs[i+1][j][k] - 2.0*vs[i][j][k] +
vs[i-1][j][k]) -
tx2 * (u[i+1][j][k][2]*up1 -
u[i-1][j][k][2]*um1);
rhs[i][j][k][3] = rhs[i][j][k][3] + dx4tx1 *
(u[i+1][j][k][3] - 2.0*u[i][j][k][3] +
u[i-1][j][k][3]) +
xxcon2 * (ws[i+1][j][k] - 2.0*ws[i][j][k] +
ws[i-1][j][k]) -
tx2 * (u[i+1][j][k][3]*up1 -
u[i-1][j][k][3]*um1);
rhs[i][j][k][4] = rhs[i][j][k][4] + dx5tx1 *
(u[i+1][j][k][4] - 2.0*u[i][j][k][4] +
u[i-1][j][k][4]) +
xxcon3 * (qs[i+1][j][k] - 2.0*qs[i][j][k] +
qs[i-1][j][k]) +
xxcon4 * (up1*up1 - 2.0*uijk*uijk +
um1*um1) +
xxcon5 * (u[i+1][j][k][4]*rho_i[i+1][j][k] -
2.0*u[i][j][k][4]*rho_i[i][j][k] +
u[i-1][j][k][4]*rho_i[i-1][j][k]) -
tx2 * ( (c1*u[i+1][j][k][4] -
c2*square[i+1][j][k])*up1 -
(c1*u[i-1][j][k][4] -
c2*square[i-1][j][k])*um1 );
}
}
}
/*--------------------------------------------------------------------
c add fourth order xi-direction dissipation
c-------------------------------------------------------------------*/
i = 1;
#pragma omp for nowait
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m]- dssp *
( 5.0*u[i][j][k][m] - 4.0*u[i+1][j][k][m] +
u[i+2][j][k][m]);
}
}
}
i = 2;
#pragma omp for nowait
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
(-4.0*u[i-1][j][k][m] + 6.0*u[i][j][k][m] -
4.0*u[i+1][j][k][m] + u[i+2][j][k][m]);
}
}
}
#pragma omp for nowait
for (i = 3; i < grid_points[0]-3; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i-2][j][k][m] - 4.0*u[i-1][j][k][m] +
6.0*u[i][j][k][m] - 4.0*u[i+1][j][k][m] +
u[i+2][j][k][m] );
}
}
}
}
i = grid_points[0]-3;
#pragma omp for nowait
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i-2][j][k][m] - 4.0*u[i-1][j][k][m] +
6.0*u[i][j][k][m] - 4.0*u[i+1][j][k][m] );
}
}
}
i = grid_points[0]-2;
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i-2][j][k][m] - 4.*u[i-1][j][k][m] +
5.0*u[i][j][k][m] );
}
}
}
/*--------------------------------------------------------------------
c compute eta-direction fluxes
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
vijk = vs[i][j][k];
vp1 = vs[i][j+1][k];
vm1 = vs[i][j-1][k];
rhs[i][j][k][0] = rhs[i][j][k][0] + dy1ty1 *
(u[i][j+1][k][0] - 2.0*u[i][j][k][0] +
u[i][j-1][k][0]) -
ty2 * (u[i][j+1][k][2] - u[i][j-1][k][2]);
rhs[i][j][k][1] = rhs[i][j][k][1] + dy2ty1 *
(u[i][j+1][k][1] - 2.0*u[i][j][k][1] +
u[i][j-1][k][1]) +
yycon2 * (us[i][j+1][k] - 2.0*us[i][j][k] +
us[i][j-1][k]) -
ty2 * (u[i][j+1][k][1]*vp1 -
u[i][j-1][k][1]*vm1);
rhs[i][j][k][2] = rhs[i][j][k][2] + dy3ty1 *
(u[i][j+1][k][2] - 2.0*u[i][j][k][2] +
u[i][j-1][k][2]) +
yycon2*con43 * (vp1 - 2.0*vijk + vm1) -
ty2 * (u[i][j+1][k][2]*vp1 -
u[i][j-1][k][2]*vm1 +
(u[i][j+1][k][4] - square[i][j+1][k] -
u[i][j-1][k][4] + square[i][j-1][k])
*c2);
rhs[i][j][k][3] = rhs[i][j][k][3] + dy4ty1 *
(u[i][j+1][k][3] - 2.0*u[i][j][k][3] +
u[i][j-1][k][3]) +
yycon2 * (ws[i][j+1][k] - 2.0*ws[i][j][k] +
ws[i][j-1][k]) -
ty2 * (u[i][j+1][k][3]*vp1 -
u[i][j-1][k][3]*vm1);
rhs[i][j][k][4] = rhs[i][j][k][4] + dy5ty1 *
(u[i][j+1][k][4] - 2.0*u[i][j][k][4] +
u[i][j-1][k][4]) +
yycon3 * (qs[i][j+1][k] - 2.0*qs[i][j][k] +
qs[i][j-1][k]) +
yycon4 * (vp1*vp1 - 2.0*vijk*vijk +
vm1*vm1) +
yycon5 * (u[i][j+1][k][4]*rho_i[i][j+1][k] -
2.0*u[i][j][k][4]*rho_i[i][j][k] +
u[i][j-1][k][4]*rho_i[i][j-1][k]) -
ty2 * ((c1*u[i][j+1][k][4] -
c2*square[i][j+1][k]) * vp1 -
(c1*u[i][j-1][k][4] -
c2*square[i][j-1][k]) * vm1);
}
}
}
/*--------------------------------------------------------------------
c add fourth order eta-direction dissipation
c-------------------------------------------------------------------*/
j = 1;
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m]- dssp *
( 5.0*u[i][j][k][m] - 4.0*u[i][j+1][k][m] +
u[i][j+2][k][m]);
}
}
}
j = 2;
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
(-4.0*u[i][j-1][k][m] + 6.0*u[i][j][k][m] -
4.0*u[i][j+1][k][m] + u[i][j+2][k][m]);
}
}
}
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 3; j < grid_points[1]-3; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i][j-2][k][m] - 4.0*u[i][j-1][k][m] +
6.0*u[i][j][k][m] - 4.0*u[i][j+1][k][m] +
u[i][j+2][k][m] );
}
}
}
}
j = grid_points[1]-3;
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i][j-2][k][m] - 4.0*u[i][j-1][k][m] +
6.0*u[i][j][k][m] - 4.0*u[i][j+1][k][m] );
}
}
}
j = grid_points[1]-2;
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i][j-2][k][m] - 4.*u[i][j-1][k][m] +
5.*u[i][j][k][m] );
}
}
}
/*--------------------------------------------------------------------
c compute zeta-direction fluxes
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
wijk = ws[i][j][k];
wp1 = ws[i][j][k+1];
wm1 = ws[i][j][k-1];
rhs[i][j][k][0] = rhs[i][j][k][0] + dz1tz1 *
(u[i][j][k+1][0] - 2.0*u[i][j][k][0] +
u[i][j][k-1][0]) -
tz2 * (u[i][j][k+1][3] - u[i][j][k-1][3]);
rhs[i][j][k][1] = rhs[i][j][k][1] + dz2tz1 *
(u[i][j][k+1][1] - 2.0*u[i][j][k][1] +
u[i][j][k-1][1]) +
zzcon2 * (us[i][j][k+1] - 2.0*us[i][j][k] +
us[i][j][k-1]) -
tz2 * (u[i][j][k+1][1]*wp1 -
u[i][j][k-1][1]*wm1);
rhs[i][j][k][2] = rhs[i][j][k][2] + dz3tz1 *
(u[i][j][k+1][2] - 2.0*u[i][j][k][2] +
u[i][j][k-1][2]) +
zzcon2 * (vs[i][j][k+1] - 2.0*vs[i][j][k] +
vs[i][j][k-1]) -
tz2 * (u[i][j][k+1][2]*wp1 -
u[i][j][k-1][2]*wm1);
rhs[i][j][k][3] = rhs[i][j][k][3] + dz4tz1 *
(u[i][j][k+1][3] - 2.0*u[i][j][k][3] +
u[i][j][k-1][3]) +
zzcon2*con43 * (wp1 - 2.0*wijk + wm1) -
tz2 * (u[i][j][k+1][3]*wp1 -
u[i][j][k-1][3]*wm1 +
(u[i][j][k+1][4] - square[i][j][k+1] -
u[i][j][k-1][4] + square[i][j][k-1])
*c2);
rhs[i][j][k][4] = rhs[i][j][k][4] + dz5tz1 *
(u[i][j][k+1][4] - 2.0*u[i][j][k][4] +
u[i][j][k-1][4]) +
zzcon3 * (qs[i][j][k+1] - 2.0*qs[i][j][k] +
qs[i][j][k-1]) +
zzcon4 * (wp1*wp1 - 2.0*wijk*wijk +
wm1*wm1) +
zzcon5 * (u[i][j][k+1][4]*rho_i[i][j][k+1] -
2.0*u[i][j][k][4]*rho_i[i][j][k] +
u[i][j][k-1][4]*rho_i[i][j][k-1]) -
tz2 * ( (c1*u[i][j][k+1][4] -
c2*square[i][j][k+1])*wp1 -
(c1*u[i][j][k-1][4] -
c2*square[i][j][k-1])*wm1);
}
}
}
/*--------------------------------------------------------------------
c add fourth order zeta-direction dissipation
c-------------------------------------------------------------------*/
k = 1;
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m]- dssp *
( 5.0*u[i][j][k][m] - 4.0*u[i][j][k+1][m] +
u[i][j][k+2][m]);
}
}
}
k = 2;
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
(-4.0*u[i][j][k-1][m] + 6.0*u[i][j][k][m] -
4.0*u[i][j][k+1][m] + u[i][j][k+2][m]);
}
}
}
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 3; k < grid_points[2]-3; k++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i][j][k-2][m] - 4.0*u[i][j][k-1][m] +
6.0*u[i][j][k][m] - 4.0*u[i][j][k+1][m] +
u[i][j][k+2][m] );
}
}
}
}
k = grid_points[2]-3;
#pragma omp for nowait
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i][j][k-2][m] - 4.0*u[i][j][k-1][m] +
6.0*u[i][j][k][m] - 4.0*u[i][j][k+1][m] );
}
}
}
k = grid_points[2]-2;
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (m = 0; m < 5; m++) {
rhs[i][j][k][m] = rhs[i][j][k][m] - dssp *
( u[i][j][k-2][m] - 4.0*u[i][j][k-1][m] +
5.0*u[i][j][k][m] );
}
}
}
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < 5; m++) {
for (i = 1; i < grid_points[0]-1; i++) {
rhs[i][j][k][m] = rhs[i][j][k][m] * dt;
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void set_constants(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
ce[0][0] = 2.0;
ce[0][1] = 0.0;
ce[0][2] = 0.0;
ce[0][3] = 4.0;
ce[0][4] = 5.0;
ce[0][5] = 3.0;
ce[0][6] = 0.5;
ce[0][7] = 0.02;
ce[0][8] = 0.01;
ce[0][9] = 0.03;
ce[0][10] = 0.5;
ce[0][11] = 0.4;
ce[0][12] = 0.3;
ce[1][0] = 1.0;
ce[1][1] = 0.0;
ce[1][2] = 0.0;
ce[1][3] = 0.0;
ce[1][4] = 1.0;
ce[1][5] = 2.0;
ce[1][6] = 3.0;
ce[1][7] = 0.01;
ce[1][8] = 0.03;
ce[1][9] = 0.02;
ce[1][10] = 0.4;
ce[1][11] = 0.3;
ce[1][12] = 0.5;
ce[2][0] = 2.0;
ce[2][1] = 2.0;
ce[2][2] = 0.0;
ce[2][3] = 0.0;
ce[2][4] = 0.0;
ce[2][5] = 2.0;
ce[2][6] = 3.0;
ce[2][7] = 0.04;
ce[2][8] = 0.03;
ce[2][9] = 0.05;
ce[2][10] = 0.3;
ce[2][11] = 0.5;
ce[2][12] = 0.4;
ce[3][0] = 2.0;
ce[3][1] = 2.0;
ce[3][2] = 0.0;
ce[3][3] = 0.0;
ce[3][4] = 0.0;
ce[3][5] = 2.0;
ce[3][6] = 3.0;
ce[3][7] = 0.03;
ce[3][8] = 0.05;
ce[3][9] = 0.04;
ce[3][10] = 0.2;
ce[3][11] = 0.1;
ce[3][12] = 0.3;
ce[4][0] = 5.0;
ce[4][1] = 4.0;
ce[4][2] = 3.0;
ce[4][3] = 2.0;
ce[4][4] = 0.1;
ce[4][5] = 0.4;
ce[4][6] = 0.3;
ce[4][7] = 0.05;
ce[4][8] = 0.04;
ce[4][9] = 0.03;
ce[4][10] = 0.1;
ce[4][11] = 0.3;
ce[4][12] = 0.2;
c1 = 1.4;
c2 = 0.4;
c3 = 0.1;
c4 = 1.0;
c5 = 1.4;
dnxm1 = 1.0 / (double)(grid_points[0]-1);
dnym1 = 1.0 / (double)(grid_points[1]-1);
dnzm1 = 1.0 / (double)(grid_points[2]-1);
c1c2 = c1 * c2;
c1c5 = c1 * c5;
c3c4 = c3 * c4;
c1345 = c1c5 * c3c4;
conz1 = (1.0-c1c5);
tx1 = 1.0 / (dnxm1 * dnxm1);
tx2 = 1.0 / (2.0 * dnxm1);
tx3 = 1.0 / dnxm1;
ty1 = 1.0 / (dnym1 * dnym1);
ty2 = 1.0 / (2.0 * dnym1);
ty3 = 1.0 / dnym1;
tz1 = 1.0 / (dnzm1 * dnzm1);
tz2 = 1.0 / (2.0 * dnzm1);
tz3 = 1.0 / dnzm1;
dx1 = 0.75;
dx2 = 0.75;
dx3 = 0.75;
dx4 = 0.75;
dx5 = 0.75;
dy1 = 0.75;
dy2 = 0.75;
dy3 = 0.75;
dy4 = 0.75;
dy5 = 0.75;
dz1 = 1.0;
dz2 = 1.0;
dz3 = 1.0;
dz4 = 1.0;
dz5 = 1.0;
dxmax = max(dx3, dx4);
dymax = max(dy2, dy4);
dzmax = max(dz2, dz3);
dssp = 0.25 * max(dx1, max(dy1, dz1) );
c4dssp = 4.0 * dssp;
c5dssp = 5.0 * dssp;
dttx1 = dt*tx1;
dttx2 = dt*tx2;
dtty1 = dt*ty1;
dtty2 = dt*ty2;
dttz1 = dt*tz1;
dttz2 = dt*tz2;
c2dttx1 = 2.0*dttx1;
c2dtty1 = 2.0*dtty1;
c2dttz1 = 2.0*dttz1;
dtdssp = dt*dssp;
comz1 = dtdssp;
comz4 = 4.0*dtdssp;
comz5 = 5.0*dtdssp;
comz6 = 6.0*dtdssp;
c3c4tx3 = c3c4*tx3;
c3c4ty3 = c3c4*ty3;
c3c4tz3 = c3c4*tz3;
dx1tx1 = dx1*tx1;
dx2tx1 = dx2*tx1;
dx3tx1 = dx3*tx1;
dx4tx1 = dx4*tx1;
dx5tx1 = dx5*tx1;
dy1ty1 = dy1*ty1;
dy2ty1 = dy2*ty1;
dy3ty1 = dy3*ty1;
dy4ty1 = dy4*ty1;
dy5ty1 = dy5*ty1;
dz1tz1 = dz1*tz1;
dz2tz1 = dz2*tz1;
dz3tz1 = dz3*tz1;
dz4tz1 = dz4*tz1;
dz5tz1 = dz5*tz1;
c2iv = 2.5;
con43 = 4.0/3.0;
con16 = 1.0/6.0;
xxcon1 = c3c4tx3*con43*tx3;
xxcon2 = c3c4tx3*tx3;
xxcon3 = c3c4tx3*conz1*tx3;
xxcon4 = c3c4tx3*con16*tx3;
xxcon5 = c3c4tx3*c1c5*tx3;
yycon1 = c3c4ty3*con43*ty3;
yycon2 = c3c4ty3*ty3;
yycon3 = c3c4ty3*conz1*ty3;
yycon4 = c3c4ty3*con16*ty3;
yycon5 = c3c4ty3*c1c5*ty3;
zzcon1 = c3c4tz3*con43*tz3;
zzcon2 = c3c4tz3*tz3;
zzcon3 = c3c4tz3*conz1*tz3;
zzcon4 = c3c4tz3*con16*tz3;
zzcon5 = c3c4tz3*c1c5*tz3;
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void verify(int no_time_steps, char *class, boolean *verified) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c verification routine
c-------------------------------------------------------------------*/
double xcrref[5],xceref[5],xcrdif[5],xcedif[5],
epsilon, xce[5], xcr[5], dtref;
int m;
/*--------------------------------------------------------------------
c tolerance level
c-------------------------------------------------------------------*/
epsilon = 1.0e-08;
/*--------------------------------------------------------------------
c compute the error norm and the residual norm, and exit if not printing
c-------------------------------------------------------------------*/
error_norm(xce);
compute_rhs();
rhs_norm(xcr);
for (m = 0; m < 5; m++) {
xcr[m] = xcr[m] / dt;
}
*class = 'U';
*verified = TRUE;
for (m = 0; m < 5; m++) {
xcrref[m] = 1.0;
xceref[m] = 1.0;
}
/*--------------------------------------------------------------------
c reference data for 12X12X12 grids after 100 time steps, with DT = 1.0d-02
c-------------------------------------------------------------------*/
if (grid_points[0] == 12 &&
grid_points[1] == 12 &&
grid_points[2] == 12 &&
no_time_steps == 60) {
*class = 'S';
dtref = 1.0e-2;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
c-------------------------------------------------------------------*/
xcrref[0] = 1.7034283709541311e-01;
xcrref[1] = 1.2975252070034097e-02;
xcrref[2] = 3.2527926989486055e-02;
xcrref[3] = 2.6436421275166801e-02;
xcrref[4] = 1.9211784131744430e-01;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
c-------------------------------------------------------------------*/
xceref[0] = 4.9976913345811579e-04;
xceref[1] = 4.5195666782961927e-05;
xceref[2] = 7.3973765172921357e-05;
xceref[3] = 7.3821238632439731e-05;
xceref[4] = 8.9269630987491446e-04;
/*--------------------------------------------------------------------
c reference data for 24X24X24 grids after 200 time steps, with DT = 0.8d-3
c-------------------------------------------------------------------*/
} else if (grid_points[0] == 24 &&
grid_points[1] == 24 &&
grid_points[2] == 24 &&
no_time_steps == 200) {
*class = 'W';
dtref = 0.8e-3;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
c-------------------------------------------------------------------*/
xcrref[0] = 0.1125590409344e+03;
xcrref[1] = 0.1180007595731e+02;
xcrref[2] = 0.2710329767846e+02;
xcrref[3] = 0.2469174937669e+02;
xcrref[4] = 0.2638427874317e+03;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
c-------------------------------------------------------------------*/
xceref[0] = 0.4419655736008e+01;
xceref[1] = 0.4638531260002e+00;
xceref[2] = 0.1011551749967e+01;
xceref[3] = 0.9235878729944e+00;
xceref[4] = 0.1018045837718e+02;
/*--------------------------------------------------------------------
c reference data for 64X64X64 grids after 200 time steps, with DT = 0.8d-3
c-------------------------------------------------------------------*/
} else if (grid_points[0] == 64 &&
grid_points[1] == 64 &&
grid_points[2] == 64 &&
no_time_steps == 200) {
*class = 'A';
dtref = 0.8e-3;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
c-------------------------------------------------------------------*/
xcrref[0] = 1.0806346714637264e+02;
xcrref[1] = 1.1319730901220813e+01;
xcrref[2] = 2.5974354511582465e+01;
xcrref[3] = 2.3665622544678910e+01;
xcrref[4] = 2.5278963211748344e+02;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
c-------------------------------------------------------------------*/
xceref[0] = 4.2348416040525025e+00;
xceref[1] = 4.4390282496995698e-01;
xceref[2] = 9.6692480136345650e-01;
xceref[3] = 8.8302063039765474e-01;
xceref[4] = 9.7379901770829278e+00;
/*--------------------------------------------------------------------
c reference data for 102X102X102 grids after 200 time steps,
c with DT = 3.0d-04
c-------------------------------------------------------------------*/
} else if (grid_points[0] == 102 &&
grid_points[1] == 102 &&
grid_points[2] == 102 &&
no_time_steps == 200) {
*class = 'B';
dtref = 3.0e-4;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
c-------------------------------------------------------------------*/
xcrref[0] = 1.4233597229287254e+03;
xcrref[1] = 9.9330522590150238e+01;
xcrref[2] = 3.5646025644535285e+02;
xcrref[3] = 3.2485447959084092e+02;
xcrref[4] = 3.2707541254659363e+03;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
c-------------------------------------------------------------------*/
xceref[0] = 5.2969847140936856e+01;
xceref[1] = 4.4632896115670668e+00;
xceref[2] = 1.3122573342210174e+01;
xceref[3] = 1.2006925323559144e+01;
xceref[4] = 1.2459576151035986e+02;
/*--------------------------------------------------------------------
c reference data for 162X162X162 grids after 200 time steps,
c with DT = 1.0d-04
c-------------------------------------------------------------------*/
} else if (grid_points[0] == 162 &&
grid_points[1] == 162 &&
grid_points[2] == 162 &&
no_time_steps == 200) {
*class = 'C';
dtref = 1.0e-4;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
c-------------------------------------------------------------------*/
xcrref[0] = 0.62398116551764615e+04;
xcrref[1] = 0.50793239190423964e+03;
xcrref[2] = 0.15423530093013596e+04;
xcrref[3] = 0.13302387929291190e+04;
xcrref[4] = 0.11604087428436455e+05;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
c-------------------------------------------------------------------*/
xceref[0] = 0.16462008369091265e+03;
xceref[1] = 0.11497107903824313e+02;
xceref[2] = 0.41207446207461508e+02;
xceref[3] = 0.37087651059694167e+02;
xceref[4] = 0.36211053051841265e+03;
} else {
*verified = FALSE;
}
/*--------------------------------------------------------------------
c verification test for residuals if gridsize is either 12X12X12 or
c 64X64X64 or 102X102X102 or 162X162X162
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Compute the difference of solution values and the known reference values.
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
xcrdif[m] = fabs((xcr[m]-xcrref[m])/xcrref[m]);
xcedif[m] = fabs((xce[m]-xceref[m])/xceref[m]);
}
/*--------------------------------------------------------------------
c Output the comparison of computed results to known cases.
c-------------------------------------------------------------------*/
if (*class != 'U') {
printf(" Verification being performed for class %1c\n", *class);
printf(" accuracy setting for epsilon = %20.13e\n", epsilon);
if (fabs(dt-dtref) > epsilon) {
*verified = FALSE;
*class = 'U';
printf(" DT does not match the reference value of %15.8e\n", dtref);
}
} else {
printf(" Unknown class\n");
}
if (*class != 'U') {
printf(" Comparison of RMS-norms of residual\n");
} else {
printf(" RMS-norms of residual\n");
}
for (m = 0; m < 5; m++) {
if (*class == 'U') {
printf(" %2d%20.13e\n", m, xcr[m]);
} else if (xcrdif[m] > epsilon) {
*verified = FALSE;
printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n",
m, xcr[m], xcrref[m], xcrdif[m]);
} else {
printf(" %2d%20.13e%20.13e%20.13e\n",
m, xcr[m], xcrref[m], xcrdif[m]);
}
}
if (*class != 'U') {
printf(" Comparison of RMS-norms of solution error\n");
} else {
printf(" RMS-norms of solution error\n");
}
for (m = 0; m < 5; m++) {
if (*class == 'U') {
printf(" %2d%20.13e\n", m, xce[m]);
} else if (xcedif[m] > epsilon) {
*verified = FALSE;
printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n",
m, xce[m], xceref[m], xcedif[m]);
} else {
printf(" %2d%20.13e%20.13e%20.13e\n",
m, xce[m], xceref[m], xcedif[m]);
}
}
if (*class == 'U') {
printf(" No reference values provided\n");
printf(" No verification performed\n");
} else if (*verified == TRUE) {
printf(" Verification Successful\n");
} else {
printf(" Verification failed\n");
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void x_solve(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c
c Performs line solves in X direction by first factoring
c the block-tridiagonal matrix into an upper triangular matrix,
c and then performing back substitution to solve for the unknow
c vectors of each line.
c
c Make sure we treat elements zero to cell_size in the direction
c of the sweep.
c
c-------------------------------------------------------------------*/
lhsx();
x_solve_cell();
x_backsubstitute();
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void x_backsubstitute(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c back solve: if last cell, then generate U(isize)=rhs[isize)
c else assume U(isize) is loaded in un pack backsub_info
c so just use it
c after call u(istart) will be sent to next cell
c-------------------------------------------------------------------*/
int i, j, k, m, n;
for (i = grid_points[0]-2; i >= 0; i--) {
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < BLOCK_SIZE; m++) {
for (n = 0; n < BLOCK_SIZE; n++) {
rhs[i][j][k][m] = rhs[i][j][k][m]
- lhs[i][j][k][CC][m][n]*rhs[i+1][j][k][n];
}
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void x_solve_cell(void) {
/*--------------------------------------------------------------------
c performs guaussian elimination on this cell.
c
c assumes that unpacking routines for non-first cells
c preload C' and rhs' from previous cell.
c
c assumed send happens outside this routine, but that
c c'(IMAX) and rhs'(IMAX) will be sent to next cell
c-------------------------------------------------------------------*/
int i,j,k,isize;
isize = grid_points[0]-1;
/*--------------------------------------------------------------------
c outer most do loops - sweeping in i direction
c-------------------------------------------------------------------*/
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
/*--------------------------------------------------------------------
c multiply c(0,j,k) by b_inverse and copy back to c
c multiply rhs(0) by b_inverse(0) and copy to rhs
c-------------------------------------------------------------------*/
binvcrhs( lhs[0][j][k][BB],
lhs[0][j][k][CC],
rhs[0][j][k] );
}
}
/*--------------------------------------------------------------------
c begin inner most do loop
c do all the elements of the cell unless last
c-------------------------------------------------------------------*/
for (i = 1; i < isize; i++) {
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
/*--------------------------------------------------------------------
c rhs(i) = rhs(i) - A*rhs(i-1)
c-------------------------------------------------------------------*/
matvec_sub(lhs[i][j][k][AA],
rhs[i-1][j][k], rhs[i][j][k]);
/*--------------------------------------------------------------------
c B(i) = B(i) - C(i-1)*A(i)
c-------------------------------------------------------------------*/
matmul_sub(lhs[i][j][k][AA],
lhs[i-1][j][k][CC],
lhs[i][j][k][BB]);
/*--------------------------------------------------------------------
c multiply c(i,j,k) by b_inverse and copy back to c
c multiply rhs(1,j,k) by b_inverse(1,j,k) and copy to rhs
c-------------------------------------------------------------------*/
binvcrhs( lhs[i][j][k][BB],
lhs[i][j][k][CC],
rhs[i][j][k] );
}
}
}
#pragma omp for
for (j = 1; j < grid_points[1]-1; j++) {
for (k = 1; k < grid_points[2]-1; k++) {
/*--------------------------------------------------------------------
c rhs(isize) = rhs(isize) - A*rhs(isize-1)
c-------------------------------------------------------------------*/
matvec_sub(lhs[isize][j][k][AA],
rhs[isize-1][j][k], rhs[isize][j][k]);
/*--------------------------------------------------------------------
c B(isize) = B(isize) - C(isize-1)*A(isize)
c-------------------------------------------------------------------*/
matmul_sub(lhs[isize][j][k][AA],
lhs[isize-1][j][k][CC],
lhs[isize][j][k][BB]);
/*--------------------------------------------------------------------
c multiply rhs() by b_inverse() and copy to rhs
c-------------------------------------------------------------------*/
binvrhs( lhs[i][j][k][BB],
rhs[i][j][k] );
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void matvec_sub(double ablock[5][5], double avec[5], double bvec[5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c subtracts bvec=bvec - ablock*avec
c-------------------------------------------------------------------*/
int i;
for (i = 0; i < 5; i++) {
/*--------------------------------------------------------------------
c rhs(i,ic,jc,kc,ccell) = rhs(i,ic,jc,kc,ccell)
c $ - lhs[i,1,ablock,ia,ja,ka,acell)*
c-------------------------------------------------------------------*/
bvec[i] = bvec[i] - ablock[i][0]*avec[0]
- ablock[i][1]*avec[1]
- ablock[i][2]*avec[2]
- ablock[i][3]*avec[3]
- ablock[i][4]*avec[4];
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void matmul_sub(double ablock[5][5], double bblock[5][5],
double cblock[5][5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c subtracts a(i,j,k) X b(i,j,k) from c(i,j,k)
c-------------------------------------------------------------------*/
int j;
for (j = 0; j < 5; j++) {
cblock[0][j] = cblock[0][j] - ablock[0][0]*bblock[0][j]
- ablock[0][1]*bblock[1][j]
- ablock[0][2]*bblock[2][j]
- ablock[0][3]*bblock[3][j]
- ablock[0][4]*bblock[4][j];
cblock[1][j] = cblock[1][j] - ablock[1][0]*bblock[0][j]
- ablock[1][1]*bblock[1][j]
- ablock[1][2]*bblock[2][j]
- ablock[1][3]*bblock[3][j]
- ablock[1][4]*bblock[4][j];
cblock[2][j] = cblock[2][j] - ablock[2][0]*bblock[0][j]
- ablock[2][1]*bblock[1][j]
- ablock[2][2]*bblock[2][j]
- ablock[2][3]*bblock[3][j]
- ablock[2][4]*bblock[4][j];
cblock[3][j] = cblock[3][j] - ablock[3][0]*bblock[0][j]
- ablock[3][1]*bblock[1][j]
- ablock[3][2]*bblock[2][j]
- ablock[3][3]*bblock[3][j]
- ablock[3][4]*bblock[4][j];
cblock[4][j] = cblock[4][j] - ablock[4][0]*bblock[0][j]
- ablock[4][1]*bblock[1][j]
- ablock[4][2]*bblock[2][j]
- ablock[4][3]*bblock[3][j]
- ablock[4][4]*bblock[4][j];
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void binvcrhs(double lhs[5][5], double c[5][5], double r[5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
double pivot, coeff;
/*--------------------------------------------------------------------
c
c-------------------------------------------------------------------*/
pivot = 1.00/lhs[0][0];
lhs[0][1] = lhs[0][1]*pivot;
lhs[0][2] = lhs[0][2]*pivot;
lhs[0][3] = lhs[0][3]*pivot;
lhs[0][4] = lhs[0][4]*pivot;
c[0][0] = c[0][0]*pivot;
c[0][1] = c[0][1]*pivot;
c[0][2] = c[0][2]*pivot;
c[0][3] = c[0][3]*pivot;
c[0][4] = c[0][4]*pivot;
r[0] = r[0] *pivot;
coeff = lhs[1][0];
lhs[1][1]= lhs[1][1] - coeff*lhs[0][1];
lhs[1][2]= lhs[1][2] - coeff*lhs[0][2];
lhs[1][3]= lhs[1][3] - coeff*lhs[0][3];
lhs[1][4]= lhs[1][4] - coeff*lhs[0][4];
c[1][0] = c[1][0] - coeff*c[0][0];
c[1][1] = c[1][1] - coeff*c[0][1];
c[1][2] = c[1][2] - coeff*c[0][2];
c[1][3] = c[1][3] - coeff*c[0][3];
c[1][4] = c[1][4] - coeff*c[0][4];
r[1] = r[1] - coeff*r[0];
coeff = lhs[2][0];
lhs[2][1]= lhs[2][1] - coeff*lhs[0][1];
lhs[2][2]= lhs[2][2] - coeff*lhs[0][2];
lhs[2][3]= lhs[2][3] - coeff*lhs[0][3];
lhs[2][4]= lhs[2][4] - coeff*lhs[0][4];
c[2][0] = c[2][0] - coeff*c[0][0];
c[2][1] = c[2][1] - coeff*c[0][1];
c[2][2] = c[2][2] - coeff*c[0][2];
c[2][3] = c[2][3] - coeff*c[0][3];
c[2][4] = c[2][4] - coeff*c[0][4];
r[2] = r[2] - coeff*r[0];
coeff = lhs[3][0];
lhs[3][1]= lhs[3][1] - coeff*lhs[0][1];
lhs[3][2]= lhs[3][2] - coeff*lhs[0][2];
lhs[3][3]= lhs[3][3] - coeff*lhs[0][3];
lhs[3][4]= lhs[3][4] - coeff*lhs[0][4];
c[3][0] = c[3][0] - coeff*c[0][0];
c[3][1] = c[3][1] - coeff*c[0][1];
c[3][2] = c[3][2] - coeff*c[0][2];
c[3][3] = c[3][3] - coeff*c[0][3];
c[3][4] = c[3][4] - coeff*c[0][4];
r[3] = r[3] - coeff*r[0];
coeff = lhs[4][0];
lhs[4][1]= lhs[4][1] - coeff*lhs[0][1];
lhs[4][2]= lhs[4][2] - coeff*lhs[0][2];
lhs[4][3]= lhs[4][3] - coeff*lhs[0][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[0][4];
c[4][0] = c[4][0] - coeff*c[0][0];
c[4][1] = c[4][1] - coeff*c[0][1];
c[4][2] = c[4][2] - coeff*c[0][2];
c[4][3] = c[4][3] - coeff*c[0][3];
c[4][4] = c[4][4] - coeff*c[0][4];
r[4] = r[4] - coeff*r[0];
pivot = 1.00/lhs[1][1];
lhs[1][2] = lhs[1][2]*pivot;
lhs[1][3] = lhs[1][3]*pivot;
lhs[1][4] = lhs[1][4]*pivot;
c[1][0] = c[1][0]*pivot;
c[1][1] = c[1][1]*pivot;
c[1][2] = c[1][2]*pivot;
c[1][3] = c[1][3]*pivot;
c[1][4] = c[1][4]*pivot;
r[1] = r[1] *pivot;
coeff = lhs[0][1];
lhs[0][2]= lhs[0][2] - coeff*lhs[1][2];
lhs[0][3]= lhs[0][3] - coeff*lhs[1][3];
lhs[0][4]= lhs[0][4] - coeff*lhs[1][4];
c[0][0] = c[0][0] - coeff*c[1][0];
c[0][1] = c[0][1] - coeff*c[1][1];
c[0][2] = c[0][2] - coeff*c[1][2];
c[0][3] = c[0][3] - coeff*c[1][3];
c[0][4] = c[0][4] - coeff*c[1][4];
r[0] = r[0] - coeff*r[1];
coeff = lhs[2][1];
lhs[2][2]= lhs[2][2] - coeff*lhs[1][2];
lhs[2][3]= lhs[2][3] - coeff*lhs[1][3];
lhs[2][4]= lhs[2][4] - coeff*lhs[1][4];
c[2][0] = c[2][0] - coeff*c[1][0];
c[2][1] = c[2][1] - coeff*c[1][1];
c[2][2] = c[2][2] - coeff*c[1][2];
c[2][3] = c[2][3] - coeff*c[1][3];
c[2][4] = c[2][4] - coeff*c[1][4];
r[2] = r[2] - coeff*r[1];
coeff = lhs[3][1];
lhs[3][2]= lhs[3][2] - coeff*lhs[1][2];
lhs[3][3]= lhs[3][3] - coeff*lhs[1][3];
lhs[3][4]= lhs[3][4] - coeff*lhs[1][4];
c[3][0] = c[3][0] - coeff*c[1][0];
c[3][1] = c[3][1] - coeff*c[1][1];
c[3][2] = c[3][2] - coeff*c[1][2];
c[3][3] = c[3][3] - coeff*c[1][3];
c[3][4] = c[3][4] - coeff*c[1][4];
r[3] = r[3] - coeff*r[1];
coeff = lhs[4][1];
lhs[4][2]= lhs[4][2] - coeff*lhs[1][2];
lhs[4][3]= lhs[4][3] - coeff*lhs[1][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[1][4];
c[4][0] = c[4][0] - coeff*c[1][0];
c[4][1] = c[4][1] - coeff*c[1][1];
c[4][2] = c[4][2] - coeff*c[1][2];
c[4][3] = c[4][3] - coeff*c[1][3];
c[4][4] = c[4][4] - coeff*c[1][4];
r[4] = r[4] - coeff*r[1];
pivot = 1.00/lhs[2][2];
lhs[2][3] = lhs[2][3]*pivot;
lhs[2][4] = lhs[2][4]*pivot;
c[2][0] = c[2][0]*pivot;
c[2][1] = c[2][1]*pivot;
c[2][2] = c[2][2]*pivot;
c[2][3] = c[2][3]*pivot;
c[2][4] = c[2][4]*pivot;
r[2] = r[2] *pivot;
coeff = lhs[0][2];
lhs[0][3]= lhs[0][3] - coeff*lhs[2][3];
lhs[0][4]= lhs[0][4] - coeff*lhs[2][4];
c[0][0] = c[0][0] - coeff*c[2][0];
c[0][1] = c[0][1] - coeff*c[2][1];
c[0][2] = c[0][2] - coeff*c[2][2];
c[0][3] = c[0][3] - coeff*c[2][3];
c[0][4] = c[0][4] - coeff*c[2][4];
r[0] = r[0] - coeff*r[2];
coeff = lhs[1][2];
lhs[1][3]= lhs[1][3] - coeff*lhs[2][3];
lhs[1][4]= lhs[1][4] - coeff*lhs[2][4];
c[1][0] = c[1][0] - coeff*c[2][0];
c[1][1] = c[1][1] - coeff*c[2][1];
c[1][2] = c[1][2] - coeff*c[2][2];
c[1][3] = c[1][3] - coeff*c[2][3];
c[1][4] = c[1][4] - coeff*c[2][4];
r[1] = r[1] - coeff*r[2];
coeff = lhs[3][2];
lhs[3][3]= lhs[3][3] - coeff*lhs[2][3];
lhs[3][4]= lhs[3][4] - coeff*lhs[2][4];
c[3][0] = c[3][0] - coeff*c[2][0];
c[3][1] = c[3][1] - coeff*c[2][1];
c[3][2] = c[3][2] - coeff*c[2][2];
c[3][3] = c[3][3] - coeff*c[2][3];
c[3][4] = c[3][4] - coeff*c[2][4];
r[3] = r[3] - coeff*r[2];
coeff = lhs[4][2];
lhs[4][3]= lhs[4][3] - coeff*lhs[2][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[2][4];
c[4][0] = c[4][0] - coeff*c[2][0];
c[4][1] = c[4][1] - coeff*c[2][1];
c[4][2] = c[4][2] - coeff*c[2][2];
c[4][3] = c[4][3] - coeff*c[2][3];
c[4][4] = c[4][4] - coeff*c[2][4];
r[4] = r[4] - coeff*r[2];
pivot = 1.00/lhs[3][3];
lhs[3][4] = lhs[3][4]*pivot;
c[3][0] = c[3][0]*pivot;
c[3][1] = c[3][1]*pivot;
c[3][2] = c[3][2]*pivot;
c[3][3] = c[3][3]*pivot;
c[3][4] = c[3][4]*pivot;
r[3] = r[3] *pivot;
coeff = lhs[0][3];
lhs[0][4]= lhs[0][4] - coeff*lhs[3][4];
c[0][0] = c[0][0] - coeff*c[3][0];
c[0][1] = c[0][1] - coeff*c[3][1];
c[0][2] = c[0][2] - coeff*c[3][2];
c[0][3] = c[0][3] - coeff*c[3][3];
c[0][4] = c[0][4] - coeff*c[3][4];
r[0] = r[0] - coeff*r[3];
coeff = lhs[1][3];
lhs[1][4]= lhs[1][4] - coeff*lhs[3][4];
c[1][0] = c[1][0] - coeff*c[3][0];
c[1][1] = c[1][1] - coeff*c[3][1];
c[1][2] = c[1][2] - coeff*c[3][2];
c[1][3] = c[1][3] - coeff*c[3][3];
c[1][4] = c[1][4] - coeff*c[3][4];
r[1] = r[1] - coeff*r[3];
coeff = lhs[2][3];
lhs[2][4]= lhs[2][4] - coeff*lhs[3][4];
c[2][0] = c[2][0] - coeff*c[3][0];
c[2][1] = c[2][1] - coeff*c[3][1];
c[2][2] = c[2][2] - coeff*c[3][2];
c[2][3] = c[2][3] - coeff*c[3][3];
c[2][4] = c[2][4] - coeff*c[3][4];
r[2] = r[2] - coeff*r[3];
coeff = lhs[4][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[3][4];
c[4][0] = c[4][0] - coeff*c[3][0];
c[4][1] = c[4][1] - coeff*c[3][1];
c[4][2] = c[4][2] - coeff*c[3][2];
c[4][3] = c[4][3] - coeff*c[3][3];
c[4][4] = c[4][4] - coeff*c[3][4];
r[4] = r[4] - coeff*r[3];
pivot = 1.00/lhs[4][4];
c[4][0] = c[4][0]*pivot;
c[4][1] = c[4][1]*pivot;
c[4][2] = c[4][2]*pivot;
c[4][3] = c[4][3]*pivot;
c[4][4] = c[4][4]*pivot;
r[4] = r[4] *pivot;
coeff = lhs[0][4];
c[0][0] = c[0][0] - coeff*c[4][0];
c[0][1] = c[0][1] - coeff*c[4][1];
c[0][2] = c[0][2] - coeff*c[4][2];
c[0][3] = c[0][3] - coeff*c[4][3];
c[0][4] = c[0][4] - coeff*c[4][4];
r[0] = r[0] - coeff*r[4];
coeff = lhs[1][4];
c[1][0] = c[1][0] - coeff*c[4][0];
c[1][1] = c[1][1] - coeff*c[4][1];
c[1][2] = c[1][2] - coeff*c[4][2];
c[1][3] = c[1][3] - coeff*c[4][3];
c[1][4] = c[1][4] - coeff*c[4][4];
r[1] = r[1] - coeff*r[4];
coeff = lhs[2][4];
c[2][0] = c[2][0] - coeff*c[4][0];
c[2][1] = c[2][1] - coeff*c[4][1];
c[2][2] = c[2][2] - coeff*c[4][2];
c[2][3] = c[2][3] - coeff*c[4][3];
c[2][4] = c[2][4] - coeff*c[4][4];
r[2] = r[2] - coeff*r[4];
coeff = lhs[3][4];
c[3][0] = c[3][0] - coeff*c[4][0];
c[3][1] = c[3][1] - coeff*c[4][1];
c[3][2] = c[3][2] - coeff*c[4][2];
c[3][3] = c[3][3] - coeff*c[4][3];
c[3][4] = c[3][4] - coeff*c[4][4];
r[3] = r[3] - coeff*r[4];
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void binvrhs( double lhs[5][5], double r[5] ) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
double pivot, coeff;
/*--------------------------------------------------------------------
c
c-------------------------------------------------------------------*/
pivot = 1.00/lhs[0][0];
lhs[0][1] = lhs[0][1]*pivot;
lhs[0][2] = lhs[0][2]*pivot;
lhs[0][3] = lhs[0][3]*pivot;
lhs[0][4] = lhs[0][4]*pivot;
r[0] = r[0] *pivot;
coeff = lhs[1][0];
lhs[1][1]= lhs[1][1] - coeff*lhs[0][1];
lhs[1][2]= lhs[1][2] - coeff*lhs[0][2];
lhs[1][3]= lhs[1][3] - coeff*lhs[0][3];
lhs[1][4]= lhs[1][4] - coeff*lhs[0][4];
r[1] = r[1] - coeff*r[0];
coeff = lhs[2][0];
lhs[2][1]= lhs[2][1] - coeff*lhs[0][1];
lhs[2][2]= lhs[2][2] - coeff*lhs[0][2];
lhs[2][3]= lhs[2][3] - coeff*lhs[0][3];
lhs[2][4]= lhs[2][4] - coeff*lhs[0][4];
r[2] = r[2] - coeff*r[0];
coeff = lhs[3][0];
lhs[3][1]= lhs[3][1] - coeff*lhs[0][1];
lhs[3][2]= lhs[3][2] - coeff*lhs[0][2];
lhs[3][3]= lhs[3][3] - coeff*lhs[0][3];
lhs[3][4]= lhs[3][4] - coeff*lhs[0][4];
r[3] = r[3] - coeff*r[0];
coeff = lhs[4][0];
lhs[4][1]= lhs[4][1] - coeff*lhs[0][1];
lhs[4][2]= lhs[4][2] - coeff*lhs[0][2];
lhs[4][3]= lhs[4][3] - coeff*lhs[0][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[0][4];
r[4] = r[4] - coeff*r[0];
pivot = 1.00/lhs[1][1];
lhs[1][2] = lhs[1][2]*pivot;
lhs[1][3] = lhs[1][3]*pivot;
lhs[1][4] = lhs[1][4]*pivot;
r[1] = r[1] *pivot;
coeff = lhs[0][1];
lhs[0][2]= lhs[0][2] - coeff*lhs[1][2];
lhs[0][3]= lhs[0][3] - coeff*lhs[1][3];
lhs[0][4]= lhs[0][4] - coeff*lhs[1][4];
r[0] = r[0] - coeff*r[1];
coeff = lhs[2][1];
lhs[2][2]= lhs[2][2] - coeff*lhs[1][2];
lhs[2][3]= lhs[2][3] - coeff*lhs[1][3];
lhs[2][4]= lhs[2][4] - coeff*lhs[1][4];
r[2] = r[2] - coeff*r[1];
coeff = lhs[3][1];
lhs[3][2]= lhs[3][2] - coeff*lhs[1][2];
lhs[3][3]= lhs[3][3] - coeff*lhs[1][3];
lhs[3][4]= lhs[3][4] - coeff*lhs[1][4];
r[3] = r[3] - coeff*r[1];
coeff = lhs[4][1];
lhs[4][2]= lhs[4][2] - coeff*lhs[1][2];
lhs[4][3]= lhs[4][3] - coeff*lhs[1][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[1][4];
r[4] = r[4] - coeff*r[1];
pivot = 1.00/lhs[2][2];
lhs[2][3] = lhs[2][3]*pivot;
lhs[2][4] = lhs[2][4]*pivot;
r[2] = r[2] *pivot;
coeff = lhs[0][2];
lhs[0][3]= lhs[0][3] - coeff*lhs[2][3];
lhs[0][4]= lhs[0][4] - coeff*lhs[2][4];
r[0] = r[0] - coeff*r[2];
coeff = lhs[1][2];
lhs[1][3]= lhs[1][3] - coeff*lhs[2][3];
lhs[1][4]= lhs[1][4] - coeff*lhs[2][4];
r[1] = r[1] - coeff*r[2];
coeff = lhs[3][2];
lhs[3][3]= lhs[3][3] - coeff*lhs[2][3];
lhs[3][4]= lhs[3][4] - coeff*lhs[2][4];
r[3] = r[3] - coeff*r[2];
coeff = lhs[4][2];
lhs[4][3]= lhs[4][3] - coeff*lhs[2][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[2][4];
r[4] = r[4] - coeff*r[2];
pivot = 1.00/lhs[3][3];
lhs[3][4] = lhs[3][4]*pivot;
r[3] = r[3] *pivot;
coeff = lhs[0][3];
lhs[0][4]= lhs[0][4] - coeff*lhs[3][4];
r[0] = r[0] - coeff*r[3];
coeff = lhs[1][3];
lhs[1][4]= lhs[1][4] - coeff*lhs[3][4];
r[1] = r[1] - coeff*r[3];
coeff = lhs[2][3];
lhs[2][4]= lhs[2][4] - coeff*lhs[3][4];
r[2] = r[2] - coeff*r[3];
coeff = lhs[4][3];
lhs[4][4]= lhs[4][4] - coeff*lhs[3][4];
r[4] = r[4] - coeff*r[3];
pivot = 1.00/lhs[4][4];
r[4] = r[4] *pivot;
coeff = lhs[0][4];
r[0] = r[0] - coeff*r[4];
coeff = lhs[1][4];
r[1] = r[1] - coeff*r[4];
coeff = lhs[2][4];
r[2] = r[2] - coeff*r[4];
coeff = lhs[3][4];
r[3] = r[3] - coeff*r[4];
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void y_solve(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Performs line solves in Y direction by first factoring
c the block-tridiagonal matrix into an upper triangular matrix][
c and then performing back substitution to solve for the unknow
c vectors of each line.
c
c Make sure we treat elements zero to cell_size in the direction
c of the sweep.
c-------------------------------------------------------------------*/
lhsy();
y_solve_cell();
y_backsubstitute();
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void y_backsubstitute(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c back solve: if last cell][ then generate U(jsize)=rhs(jsize)
c else assume U(jsize) is loaded in un pack backsub_info
c so just use it
c after call u(jstart) will be sent to next cell
c-------------------------------------------------------------------*/
int i, j, k, m, n;
for (j = grid_points[1]-2; j >= 0; j--) {
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
for (m = 0; m < BLOCK_SIZE; m++) {
for (n = 0; n < BLOCK_SIZE; n++) {
rhs[i][j][k][m] = rhs[i][j][k][m]
- lhs[i][j][k][CC][m][n]*rhs[i][j+1][k][n];
}
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void y_solve_cell(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c performs guaussian elimination on this cell.
c
c assumes that unpacking routines for non-first cells
c preload C' and rhs' from previous cell.
c
c assumed send happens outside this routine, but that
c c'(JMAX) and rhs'(JMAX) will be sent to next cell
c-------------------------------------------------------------------*/
int i, j, k, jsize;
jsize = grid_points[1]-1;
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
/*--------------------------------------------------------------------
c multiply c(i,0,k) by b_inverse and copy back to c
c multiply rhs(0) by b_inverse(0) and copy to rhs
c-------------------------------------------------------------------*/
binvcrhs( lhs[i][0][k][BB],
lhs[i][0][k][CC],
rhs[i][0][k] );
}
}
/*--------------------------------------------------------------------
c begin inner most do loop
c do all the elements of the cell unless last
c-------------------------------------------------------------------*/
for (j = 1; j < jsize; j++) {
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
/*--------------------------------------------------------------------
c subtract A*lhs_vector(j-1) from lhs_vector(j)
c
c rhs(j) = rhs(j) - A*rhs(j-1)
c-------------------------------------------------------------------*/
matvec_sub(lhs[i][j][k][AA],
rhs[i][j-1][k], rhs[i][j][k]);
/*--------------------------------------------------------------------
c B(j) = B(j) - C(j-1)*A(j)
c-------------------------------------------------------------------*/
matmul_sub(lhs[i][j][k][AA],
lhs[i][j-1][k][CC],
lhs[i][j][k][BB]);
/*--------------------------------------------------------------------
c multiply c(i,j,k) by b_inverse and copy back to c
c multiply rhs(i,1,k) by b_inverse(i,1,k) and copy to rhs
c-------------------------------------------------------------------*/
binvcrhs( lhs[i][j][k][BB],
lhs[i][j][k][CC],
rhs[i][j][k] );
}
}
}
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (k = 1; k < grid_points[2]-1; k++) {
/*--------------------------------------------------------------------
c rhs(jsize) = rhs(jsize) - A*rhs(jsize-1)
c-------------------------------------------------------------------*/
matvec_sub(lhs[i][jsize][k][AA],
rhs[i][jsize-1][k], rhs[i][jsize][k]);
/*--------------------------------------------------------------------
c B(jsize) = B(jsize) - C(jsize-1)*A(jsize)
c call matmul_sub(aa,i,jsize,k,c,
c $ cc,i,jsize-1,k,c,BB,i,jsize,k)
c-------------------------------------------------------------------*/
matmul_sub(lhs[i][jsize][k][AA],
lhs[i][jsize-1][k][CC],
lhs[i][jsize][k][BB]);
/*--------------------------------------------------------------------
c multiply rhs(jsize) by b_inverse(jsize) and copy to rhs
c-------------------------------------------------------------------*/
binvrhs( lhs[i][jsize][k][BB],
rhs[i][jsize][k] );
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void z_solve(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Performs line solves in Z direction by first factoring
c the block-tridiagonal matrix into an upper triangular matrix,
c and then performing back substitution to solve for the unknow
c vectors of each line.
c
c Make sure we treat elements zero to cell_size in the direction
c of the sweep.
c-------------------------------------------------------------------*/
lhsz();
z_solve_cell();
z_backsubstitute();
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void z_backsubstitute(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c back solve: if last cell, then generate U(ksize)=rhs(ksize)
c else assume U(ksize) is loaded in un pack backsub_info
c so just use it
c after call u(kstart) will be sent to next cell
c-------------------------------------------------------------------*/
int i, j, k, m, n;
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
for (k = grid_points[2]-2; k >= 0; k--) {
for (m = 0; m < BLOCK_SIZE; m++) {
for (n = 0; n < BLOCK_SIZE; n++) {
rhs[i][j][k][m] = rhs[i][j][k][m]
- lhs[i][j][k][CC][m][n]*rhs[i][j][k+1][n];
}
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void z_solve_cell(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c performs guaussian elimination on this cell.
c
c assumes that unpacking routines for non-first cells
c preload C' and rhs' from previous cell.
c
c assumed send happens outside this routine, but that
c c'(KMAX) and rhs'(KMAX) will be sent to next cell.
c-------------------------------------------------------------------*/
int i,j,k,ksize;
ksize = grid_points[2]-1;
/*--------------------------------------------------------------------
c outer most do loops - sweeping in i direction
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
/*--------------------------------------------------------------------
c multiply c(i,j,0) by b_inverse and copy back to c
c multiply rhs(0) by b_inverse(0) and copy to rhs
c-------------------------------------------------------------------*/
binvcrhs( lhs[i][j][0][BB],
lhs[i][j][0][CC],
rhs[i][j][0] );
}
}
/*--------------------------------------------------------------------
c begin inner most do loop
c do all the elements of the cell unless last
c-------------------------------------------------------------------*/
for (k = 1; k < ksize; k++) {
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
/*--------------------------------------------------------------------
c subtract A*lhs_vector(k-1) from lhs_vector(k)
c
c rhs(k) = rhs(k) - A*rhs(k-1)
c-------------------------------------------------------------------*/
matvec_sub(lhs[i][j][k][AA],
rhs[i][j][k-1], rhs[i][j][k]);
/*--------------------------------------------------------------------
c B(k) = B(k) - C(k-1)*A(k)
c call matmul_sub(aa,i,j,k,c,cc,i,j,k-1,c,BB,i,j,k)
c-------------------------------------------------------------------*/
matmul_sub(lhs[i][j][k][AA],
lhs[i][j][k-1][CC],
lhs[i][j][k][BB]);
/*--------------------------------------------------------------------
c multiply c(i,j,k) by b_inverse and copy back to c
c multiply rhs(i,j,1) by b_inverse(i,j,1) and copy to rhs
c-------------------------------------------------------------------*/
binvcrhs( lhs[i][j][k][BB],
lhs[i][j][k][CC],
rhs[i][j][k] );
}
}
}
/*--------------------------------------------------------------------
c Now finish up special cases for last cell
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i < grid_points[0]-1; i++) {
for (j = 1; j < grid_points[1]-1; j++) {
/*--------------------------------------------------------------------
c rhs(ksize) = rhs(ksize) - A*rhs(ksize-1)
c-------------------------------------------------------------------*/
matvec_sub(lhs[i][j][ksize][AA],
rhs[i][j][ksize-1], rhs[i][j][ksize]);
/*--------------------------------------------------------------------
c B(ksize) = B(ksize) - C(ksize-1)*A(ksize)
c call matmul_sub(aa,i,j,ksize,c,
c $ cc,i,j,ksize-1,c,BB,i,j,ksize)
c-------------------------------------------------------------------*/
matmul_sub(lhs[i][j][ksize][AA],
lhs[i][j][ksize-1][CC],
lhs[i][j][ksize][BB]);
/*--------------------------------------------------------------------
c multiply rhs(ksize) by b_inverse(ksize) and copy to rhs
c-------------------------------------------------------------------*/
binvrhs( lhs[i][j][ksize][BB],
rhs[i][j][ksize] );
}
}
}
|
Quicksort.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <time.h>
// array init modes -> "random", "crescent", "decrescent"
#define ARRAY_INIT_MODE "random"
#define ARRAY_SIZE 500000
// quicksort modes -> "sequential", "tasks", "tasks_and_for", "sections"
#define QUICKSORT_MODE "tasks_and_for"
#define parallelStop partitionSize <= 2500
/*
* 5000
* 2500 **
* 1200
* 300
*/
void swap(int index1, int index2, int *array)
{
int copy1 = array[index1];
array[index1] = array[index2];
array[index2] = copy1;
}
// ------------------- QUICKSORT PARALELO COM TAREFAS
void parallelDivideTasks(int initialLeft, int initialRight, int *array)
{
int left = initialLeft;
int right = initialRight;
int pivot = array[ (left + right) / 2 ];
int leftElement;
int rightElement;
const int partitionSize = initialRight - initialLeft + 1;
while (left <= right)
{
leftElement = array[left];
rightElement = array[right];
// cria uma tarefa para alguma thread executar e
// compartilha com essa tarefa as variaveis left e
// leftElement da thread atual
//#pragma omp task shared(left, leftElement)
while (left < initialRight && leftElement < pivot)
{
leftElement = array[++left];
}
//#pragma omp task shared(right, rightElement)
while (right > initialLeft && rightElement > pivot)
{
rightElement = array[--right];
}
// espera as tarefas que essa thread criou terminar
//#pragma omp taskwait
if (left <= right)
{
swap(left++, right--, array);
}
}
if (parallelStop)
{
if (right > initialLeft)
{
parallelDivideTasks(initialLeft, right, array);
}
if (left < initialRight)
{
parallelDivideTasks(left, initialRight, array);
}
}
else
{
if (right > initialLeft)
{
#pragma omp task
parallelDivideTasks(initialLeft, right, array);
}
if (left < initialRight)
{
#pragma omp task
parallelDivideTasks(left, initialRight, array);
}
}
}
void parallelQuicksortTasks(int *array, int arrayLength)
{
#pragma omp parallel // omp parallel -> cria uma regiao paralela
// omp single -> apenas uma thread executa a proxima linha,
// alem disso, as outras threads so' iniciam suas atividades
// depois que essa linha for executada
#pragma omp single
parallelDivideTasks(0, arrayLength - 1, array);
}
// ------------------- FIM DO QUICKSORT PARALELO COM TAREFAS
// ------------------- QUICKSORT PARALELO COM FOR E TAREFAS
void parallelDivideFor(int initialLeft, int initialRight, int *array)
{
const int partitionSize = initialRight - initialLeft + 1;
int pivot = array[ (initialLeft + initialRight) / 2 ];
int lessThanPivot[partitionSize];
int greaterThanPivot[partitionSize];
int ltPivotCounter = 0;
int gtPivotCounter = 0;
int currentElement;
int i;
if (parallelStop)
{
// percorre o arranjo separando os elementos que
// sao menores que o pivo e maiores ou iguais a ele
for (i = 0; i < partitionSize; i++)
{
currentElement = array[initialLeft + i];
if (currentElement < pivot)
{
lessThanPivot[ltPivotCounter++] = currentElement;
}
else
{
greaterThanPivot[gtPivotCounter++] = currentElement;
}
}
// percorre o arranjo dos menores que o pivo e os
// coloca na parte esquerda do arranjo original
for (i = 0; i < ltPivotCounter; i++)
{
array[initialLeft + i] = lessThanPivot[i];
}
// percorre o arranjo dos maiores ou iguais ao pivo
// e os coloca na parte direita do arranjo original
for (i = 0; i < gtPivotCounter; i++)
{
array[initialLeft + ltPivotCounter + i] = greaterThanPivot[i];
}
if (ltPivotCounter > 1)
{
parallelDivideFor(initialLeft, initialLeft + ltPivotCounter - 1, array);
}
if (gtPivotCounter > 1)
{
parallelDivideFor(initialLeft + ltPivotCounter, initialLeft + ltPivotCounter + gtPivotCounter - 1, array);
}
}
else
{
#pragma omp parallel for private(currentElement)
for (i = 0; i < partitionSize; i++)
{
currentElement = array[initialLeft + i];
if (currentElement < pivot)
{
lessThanPivot[ltPivotCounter++] = currentElement;
}
else
{
greaterThanPivot[gtPivotCounter++] = currentElement;
}
}
// cria uma tarefa para alguma thread executar e,
// ao mesmo tempo, uma copia local de i para a thread
// que for executar a tarefa
#pragma omp task private(i)
for (i = 0; i < ltPivotCounter; i++)
{
array[initialLeft + i] = lessThanPivot[i];
}
#pragma omp task private(i)
for (i = 0; i < gtPivotCounter; i++)
{
array[initialLeft + ltPivotCounter + i] = greaterThanPivot[i];
}
// espera as tarefas que essa thread criou terminar
#pragma omp taskwait
if (ltPivotCounter > 1)
{
#pragma omp task
parallelDivideFor(initialLeft, initialLeft + ltPivotCounter - 1, array);
}
if (gtPivotCounter > 1)
{
#pragma omp task
parallelDivideFor(initialLeft + ltPivotCounter, initialLeft + ltPivotCounter + gtPivotCounter - 1, array);
}
}
}
void parallelQuicksortFor(int *array, int arrayLength)
{
#pragma omp parallel // omp parallel -> cria uma regiao paralela
// omp single -> apenas uma thread executa a proxima linha,
// alem disso, as outras threads so' iniciam suas atividades
// depois que essa linha for executada
#pragma omp single
parallelDivideFor(0, arrayLength - 1, array);
}
// ------------------- FIM DO QUICKSORT PARALELO COM FOR E TAREFAS
// ------------------- QUICKSORT PARALELO COM SECOES
void parallelDivideSections(int initialLeft, int initialRight, int *array)
{
int left = initialLeft;
int right = initialRight;
int pivot = array[ (left + right) / 2 ];
int leftElement;
int rightElement;
const int partitionSize = initialRight - initialLeft + 1;
while (left <= right)
{
leftElement = array[left];
rightElement = array[right];
while (left < initialRight && leftElement < pivot)
{
leftElement = array[++left];
}
while (right > initialLeft && rightElement > pivot)
{
rightElement = array[--right];
}
if (left <= right)
{
swap(left++, right--, array);
}
}
if (parallelStop)
{
if (right > initialLeft)
{
parallelDivideSections(initialLeft, right, array);
}
if (left < initialRight)
{
parallelDivideSections(left, initialRight, array);
}
}
else
{
#pragma omp parallel sections
{
#pragma omp section // cada secao e' enviada para uma thread
right > initialLeft ? parallelDivideSections(initialLeft, right, array) : 0;
#pragma omp section
left < initialRight ? parallelDivideSections(left, initialRight, array) : 0;
}
}
}
void parallelQuicksortSections(int *array, int arrayLength)
{
parallelDivideSections(0, arrayLength - 1, array);
}
// ------------------- FIM DO QUICKSORT PARALELO COM SECOES
// ------------------- QUICKSORT SEQUENCIAL
void sequentialDivide(int initialLeft, int initialRight, int *array)
{
int left = initialLeft;
int right = initialRight;
int pivot = array[ (left + right) / 2 ];
int leftElement;
int rightElement;
while (left <= right)
{
leftElement = array[left];
rightElement = array[right];
while (left < initialRight && leftElement < pivot)
{
leftElement = array[++left];
}
while (right > initialLeft && rightElement > pivot)
{
rightElement = array[--right];
}
if (left <= right)
{
swap(left++, right--, array);
}
}
if (right > initialLeft)
{
sequentialDivide(initialLeft, right, array);
}
if (left < initialRight)
{
sequentialDivide(left, initialRight, array);
}
}
void sequentialQuicksort(int *array, int arrayLength)
{
sequentialDivide(0, arrayLength - 1, array);
}
// ------------------- FIM DO QUICKSORT SEQUENCIAL
// ------------------- FIM DOS QUICKSORTS
// ------------------- FUNCOES DE UTILIDADE
// preenchimento do array -> { 1, 2, 3, ..., arrayLength }
void initCrescentArray(int *array, int arrayLength)
{
int i;
#pragma omp parallel for
for (i = 0; i < arrayLength; i++)
{
array[i] = i + 1;
}
}
// preenchimento do array -> { arrayLength, arrayLength - 1, ..., 2, 1 }
void initDecrescentArray(int *array, int arrayLength)
{
int i;
#pragma omp parallel for
for (i = 0; i < arrayLength; i++)
{
array[i] = arrayLength - i;
}
}
void initRandomArray(int *array, int arrayLength)
{
int i;
srand( time(NULL) );
// a paralelizacao desse looping gera problemas
// na geracao dos numeros aleatorios
for (i = 0; i < arrayLength; i++)
{
array[i] = rand() % arrayLength + 1;
}
}
void initArray(int *array, const char *mode, int arrayLength)
{
if (strcmp(mode, "random") == 0)
initRandomArray(array, arrayLength);
else if (strcmp(mode, "crescent") == 0)
initCrescentArray(array, arrayLength);
else if (strcmp(mode, "decrescent") == 0)
initDecrescentArray(array, arrayLength);
}
// checa se a ordenacao do arranjo esta' incorreta
int ordenationIsWrong(int *array, int arrayLength)
{
int wrong = 0;
int i;
#pragma omp parallel for reduction(+:wrong)
for (i = 0; i < arrayLength - 1; i++)
{
wrong = ( wrong ? 1 : array[i] > array[i + 1] );
}
return wrong > 0;
}
void quicksort(int *array, const char *mode, int arrayLength)
{
if (strcmp(mode, "sequential") == 0)
sequentialQuicksort(array, arrayLength);
else if (strcmp(mode, "tasks") == 0)
parallelQuicksortTasks(array, arrayLength);
else if (strcmp(mode, "tasks_and_for") == 0)
parallelQuicksortFor(array, arrayLength);
else if (strcmp(mode, "sections") == 0)
parallelQuicksortSections(array, arrayLength);
}
int main()
{
int array[ARRAY_SIZE];
initArray(array, ARRAY_INIT_MODE, ARRAY_SIZE);
quicksort(array, QUICKSORT_MODE, ARRAY_SIZE);
if (ordenationIsWrong(array, ARRAY_SIZE)) printf("Ordenacao errada\n");
return EXIT_SUCCESS;
}
|
6708.c
|
/* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <[email protected]>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "3mm.h"
/* Array initialization. */
static
void init_array(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nk; j++)
A[i][j] = ((DATA_TYPE) i*j) / ni;
for (i = 0; i < nk; i++)
for (j = 0; j < nj; j++)
B[i][j] = ((DATA_TYPE) i*(j+1)) / nj;
for (i = 0; i < nj; i++)
for (j = 0; j < nm; j++)
C[i][j] = ((DATA_TYPE) i*(j+3)) / nl;
for (i = 0; i < nm; i++)
for (j = 0; j < nl; j++)
D[i][j] = ((DATA_TYPE) i*(j+2)) / nk;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int ni, int nl,
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nl; j++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]);
if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_3mm(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj),
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl),
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j, k;
#pragma scop
#pragma omp parallel private (i, j, k) num_threads(#P11)
{
/* E := A*B */
#pragma omp target teams distribute
for (i = 0; i < _PB_NI; i++)
{
for (j = 0; j < _PB_NJ; j++)
{
E[i][j] = 0;
for (k = 0; k < _PB_NK; ++k)
E[i][j] += A[i][k] * B[k][j];
}
}
/* F := C*D */
#pragma omp target teams distribute
for (i = 0; i < _PB_NJ; i++)
{
for (j = 0; j < _PB_NL; j++)
{
F[i][j] = 0;
for (k = 0; k < _PB_NM; ++k)
F[i][j] += C[i][k] * D[k][j];
}
}
/* G := E*F */
#pragma omp target teams distribute
for (i = 0; i < _PB_NI; i++)
{
for (j = 0; j < _PB_NL; j++)
{
G[i][j] = 0;
for (k = 0; k < _PB_NJ; ++k)
G[i][j] += E[i][k] * F[k][j];
}
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int ni = NI;
int nj = NJ;
int nk = NK;
int nl = NL;
int nm = NM;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj);
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk);
POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj);
POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl);
POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm);
POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl);
POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl);
/* Initialize array(s). */
init_array (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_3mm (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(E),
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(F),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D),
POLYBENCH_ARRAY(G));
/* 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(ni, nl, POLYBENCH_ARRAY(G)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(E);
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
POLYBENCH_FREE_ARRAY(F);
POLYBENCH_FREE_ARRAY(C);
POLYBENCH_FREE_ARRAY(D);
POLYBENCH_FREE_ARRAY(G);
return 0;
}
|
GB_binop__isle_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__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_unaryop__identity_uint8_uint32.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__identity_uint8_uint32
// op(A') function: GB_tran__identity_uint8_uint32
// C type: uint8_t
// A type: uint32_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, aij) \
uint8_t z = (uint8_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_uint8_uint32
(
uint8_t *Cx, // Cx and Ax may be aliased
uint32_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__identity_uint8_uint32
(
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
|
GB_unop__identity_int16_uint32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_int16_uint32)
// op(A') function: GB (_unop_tran__identity_int16_uint32)
// C type: int16_t
// A type: uint32_t
// cast: int16_t cij = (int16_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int16_t z = (int16_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int16_t z = (int16_t) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int16_uint32)
(
int16_t *Cx, // Cx and Ax may be aliased
const uint32_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++)
{
uint32_t aij = Ax [p] ;
int16_t z = (int16_t) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint32_t aij = Ax [p] ;
int16_t z = (int16_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_int16_uint32)
(
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
|
pst_search.c
|
#include <omp.h>
#include <string.h>
#include "tldevel.h"
#include "tlrng.h"
#include "tlseqio.h"
#include "tlmisc.h"
#include "tlalphabet.h"
#include "pst.h"
#include "pst_structs.h"
#include "pst_hash.h"
#include "search_db.h"
#define PST_SEARCH_IMPORT
#include "pst_search.h"
static int copy_sequences(struct tl_seq_buffer* sb, struct tl_seq* a);
int search_db(struct pst* p, char* filename, double thres,struct tl_seq_buffer** hits, uint64_t* db_size)
{
#ifdef HAVE_OPENMP
omp_lock_t writelock;
omp_set_num_threads(8);
omp_init_lock(&writelock);
#endif
struct file_handler* f = NULL;
struct tl_seq_buffer* sb = NULL;
struct rng_state* rng = NULL;
struct alphabet* alphabet = NULL;
struct tl_seq_buffer* h = NULL;
int chunk,i;
int n_hits = 0;
uint64_t total_nseq =0;
if(*hits){
h = *hits;
}else{
RUN(alloc_tl_seq_buffer(&h, 10000));
}
//LOG_MSG("%s",infile);
if(!my_file_exists(filename)){
ERROR_MSG("File %s not found");
}
RUNP(rng = init_rng(42));
RUN(open_fasta_fastq_file(&f, filename, TLSEQIO_READ));
chunk =1;
total_nseq = 0;
while(1){
RUN(read_fasta_fastq_file(f, &sb, 1000000));
int alloc = 0;
for(i = 0; i < sb->num_seq;i++){
alloc+= sb->sequences[i]->malloc_len;
}
LOG_MSG("CHUNK:%d %d",chunk, alloc);
if(chunk == 1){
if(sb->L == TL_SEQ_BUFFER_DNA){
RUN(create_alphabet(&alphabet, rng, TLALPHABET_NOAMBIGUOUS_DNA));
}else if(sb->L == TL_SEQ_BUFFER_PROTEIN){
RUN(create_alphabet(&alphabet, rng, TLALPHABET_NOAMBIGIOUS_PROTEIN ));
}
}
total_nseq+= sb->num_seq;
if(sb->num_seq == 0){
break;
}
for(i = 0; i < sb->num_seq;i++){
struct tl_seq* seq = sb->sequences[i];
int len = seq->len;
convert_to_internal(alphabet, (uint8_t*)seq->seq,len);
}
#ifdef HAVE_OPENMP
#pragma omp parallel default(shared)
#pragma omp for schedule(dynamic) nowait
#endif
for(i = 0; i < sb->num_seq;i++){
double z_score;
float score;
//len = MACRO_MIN(len, 100);
score_pst(p, sb->sequences[i]->seq, sb->sequences[i]->len, &score);
z_score_pst(p, sb->sequences[i]->len, score, &z_score);
if(z_score >= thres){
omp_set_lock(&writelock);
//int thread_id = omp_get_thread_num();
//LOG_MSG("Thread %d locking ", thread_id);
copy_sequences(h, sb->sequences[i]);
n_hits++;
if(sb->sequences[i]->len > h->max_len){
h->max_len = sb->sequences[i]->len;
}
omp_unset_lock(&writelock);
//fprintf(stdout,"Hit: %f\t%s\n",z_score,seq->name);
}
}
//#ifdef HAVE_OPENMP
// }
//#endif
//free_tl_seq_buffer(sb);
//sb = NULL;
//break;
chunk++;
}
RUN(close_seq_file(&f));
free_rng(rng);
free_tl_seq_buffer(sb);
free_alphabet(alphabet);
LOG_MSG("Scanned %0.2f M sequences.", (double)total_nseq / 1000000.0);
//LOG_MSG("Found %d hits", n_hits);
*hits = h;
*db_size = total_nseq;
#ifdef HAVE_OPENMP
omp_destroy_lock(&writelock);
#endif
return OK;
ERROR:
return FAIL;
}
int copy_sequences(struct tl_seq_buffer* sb, struct tl_seq* a)
{
int printed;
struct tl_seq* target = NULL;
if(sb->num_seq == sb->malloc_num){
RUN(resize_tl_seq_buffer(sb));
}
target = sb->sequences[sb->num_seq];
printed = snprintf(target->name, TL_SEQ_MAX_NAME_LEN, "%s", a->name);
ASSERT(printed < TL_SEQ_MAX_NAME_LEN ,"characters printed entirely fills buffer");
while(target->malloc_len <= a->len){
RUN(resize_tl_seq(target));
}
memcpy(target->seq, a->seq, a->len);
target->len = a->len;
sb->num_seq++;
return OK;
ERROR:
return FAIL;
}
int search_db_hdf5(struct pst* p, char* filename, double thres)
{
int chunk,i;
#ifdef HAVE_OPENMP
omp_lock_t writelock;
omp_set_num_threads(8);
omp_init_lock(&writelock);
#endif
//LOG_MSG("%s",infile);
if(!my_file_exists(filename)){
ERROR_MSG("File %s not found");
}
struct hdf_seq_store*h = NULL;
int numseq;
int hits = 0;
while(1){
RUN(read_hdf_seq_store_chunk(&h, filename));
if(!h->num_seq){
break;
}
#ifdef HAVE_OPENMP
#pragma omp parallel shared(h) private(i)
{
#pragma omp for schedule(dynamic) nowait
#endif
for(i = 0; i < h->num_seq;i++){
uint8_t* seq = h->seq + h->len[i];
int len = h->len[i+1] - h->len[i];
double z_score;
float score;
score_pst(p, seq, len, &score);
z_score_pst(p, len, score, &z_score);
if(z_score >= thres){
omp_set_lock(&writelock);
hits++;
omp_unset_lock(&writelock);
//fprintf(stdout,"Hit: %f\t%s\n",z_score,seq->name);
}
}
#ifdef HAVE_OPENMP
}
#endif
numseq+= h->num_seq;
LOG_MSG("Scanned %d seqs",numseq);
}
free_hdf_seq_store(h);
LOG_MSG("Found %d hits", hits);
#ifdef HAVE_OPENMP
omp_destroy_lock(&writelock);
#endif
return OK;
ERROR:
return FAIL;
}
|
Trapezium.c
|
/** Trapezoidal rule for Numerical Integration
https://rosettacode.org/wiki/Numerical_integration
@file Trapezium.c */
#include "Trapezium.h"
//TRAP-Serial
double trapezium(double from, double to, double n, double (*func)())
{
double h = (to-from)/n;
double sum = func(from)+func(to);
int i;
for(i=1; i<n; i++)
sum += 2.0*func(from+i*h);
return h*sum/2.0;
}
//TRAP-OMP FOR CRITICAL
double trapezium_omp_for_critical(double from, double to, double n, double (*func)())
{
double h = (to - from) / n;
double sum = func(from) + func(to);
int i;
#pragma omp parallel for shared(h,i)
for(i=1; i<(int)n; i++)
#pragma omp critical
sum += 2.0*func(from+i*h);
return h * sum / 2.0;
}
//TRAP-OMP FOR REDUCTION
double trapezium_omp_for_reduction(double from, double to, double n, double (*func)())
{
double h = (to - from) / n;
double sum = func(from) + func(to);
int i;
#pragma omp parallel for reduction(+:sum) shared(h,i)
for(i=1; i<(int)n; i++)
sum += 2.0*func(from+i*h);
return h*sum / 2.0;
}
//TRAP-OMP SHARED
double trapezium_omp_shared(double from, double to, double n, double (*func)())
{
int tid, tstart, tend, nthreads, i;
double h, sum, psum;
h = (to-from)/n;
sum = func(from)+func(to);
#pragma omp parallel private(i,tid,psum,tstart,tend) shared(nthreads,sum,h,n,to,from)
{
psum = 0.0;
nthreads = omp_get_num_threads();
tid = omp_get_thread_num();
tstart = tid*ceil(n/nthreads);
tend = (tid+1)*ceil(n/nthreads);
if (nthreads == 1 || (tend > n && tstart < 1))
for(i=1; i<n; i++)
psum += 2.0*func(from+i*h);
else if (tend > n)
for(i=tstart; i<n; i++)
psum += 2.0*func(from+i*h);
else if (tstart < 1)
for (i=1; i<tend; i++)
psum += 2.0*func(from+i*h);
else
for (i=tstart; i<tend; i++)
psum += 2.0*func(from+i*h);
#pragma omp critical
sum += psum;
}
return h*sum/2.0;
}
|
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] = 32;
tile_size[1] = 32;
tile_size[2] = 32;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
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,16);t1++) {
lbp=max(ceild(t1,2),ceild(32*t1-Nt+3,32));
ubp=min(floord(Nt+Nz-4,32),floord(16*t1+Nz+13,32));
#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-1,2)),ceild(32*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(16*t1+Ny+29,32)),floord(32*t2+Ny+28,32)),floord(32*t1-32*t2+Nz+Ny+27,32));t3++) {
for (t4=max(max(max(0,ceild(t1-31,32)),ceild(32*t2-Nz-508,512)),ceild(32*t3-Ny-508,512));t4<=min(min(min(min(floord(Nt+Nx-4,512),floord(16*t1+Nx+29,512)),floord(32*t2+Nx+28,512)),floord(32*t3+Nx+28,512)),floord(32*t1-32*t2+Nz+Nx+27,512));t4++) {
for (t5=max(max(max(max(max(0,16*t1),32*t1-32*t2+1),32*t2-Nz+2),32*t3-Ny+2),512*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,16*t1+31),32*t2+30),32*t3+30),512*t4+510),32*t1-32*t2+Nz+29);t5++) {
for (t6=max(max(32*t2,t5+1),-32*t1+32*t2+2*t5-31);t6<=min(min(32*t2+31,-32*t1+32*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(512*t4,t5+1);
ubv=min(512*t4+511,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((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__div_fp64.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__div_fp64
// A.*B function (eWiseMult): GB_AemultB__div_fp64
// A*D function (colscale): GB_AxD__div_fp64
// D*A function (rowscale): GB_DxB__div_fp64
// C+=B function (dense accum): GB_Cdense_accumB__div_fp64
// C+=b function (dense accum): GB_Cdense_accumb__div_fp64
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__div_fp64
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__div_fp64
// C=scalar+B GB_bind1st__div_fp64
// C=scalar+B' GB_bind1st_tran__div_fp64
// C=A+scalar GB_bind2nd__div_fp64
// C=A'+scalar GB_bind2nd_tran__div_fp64
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = (aij / bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
double bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
double t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = (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_DIV || GxB_NO_FP64 || GxB_NO_DIV_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB_Cdense_ewise3_accum__div_fp64
(
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__div_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__div_fp64
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__div_fp64
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__div_fp64
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *GB_RESTRICT Cx = (double *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__div_fp64
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *GB_RESTRICT Cx = (double *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// 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__div_fp64
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_add_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__div_fp64
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_emult_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__div_fp64
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *GB_RESTRICT Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
double bij = Bx [p] ;
Cx [p] = (x / bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__div_fp64
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *GB_RESTRICT Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double aij = Ax [p] ;
Cx [p] = (aij / y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (x / aij) ; \
}
GrB_Info GB_bind1st_tran__div_fp64
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (aij / y) ; \
}
GrB_Info GB_bind2nd_tran__div_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
decode_from_pgm.c
|
#include "PGM.h"
void extract_img(int height, int width, int *p1, int *q1, int *p1_star, int *p2_star, int *q1_star, int *q2_star)
{
// Creating the original image.
int *original_img = (int *)malloc(height * width * sizeof(int));
if (!original_img)
{
printf("ERROR: Memory Allocation of Image Extraction Failed\n");
exit(1);
}
#pragma omp parallel for shared(p1_star, q1_star, p2_star, q2_star, original_img, p1, q1) schedule(static, 4)
for (int i = 0; i < height * width; i++)
{
p1[i] = (p1_star[i] + q1_star[i]) / 2;
q1[i] = (p2_star[i] + q2_star[i]) / 2;
original_img[i] = (p1[i] + q1[i]) / 2;
}
write_to_pgm(original_img, "original.pgm", height, width);
free(original_img);
}
void adjust_l1(int height, int width, int *p1_star, int *p2_star, int *q1_star, int *q2_star)
{
#pragma omp parallel for shared(p1_star, q1_star, p2_star, q2_star) schedule(static, 4)
for (int i = 0; i < height * width; i++)
{
if (p1_star[i] + 2 == q1_star[i])
{
p1_star[i] += 2;
}
if (p2_star[i] + 2 == q2_star[i])
{
p2_star[i] += 2;
}
}
}
void extract_secret(int *pixel, int height, int width, int *p1, int *q1, int *p1_star, int *p2_star, int *q1_star, int *q2_star)
{
#pragma omp parallel for shared(pixel, p1_star, q1_star, p2_star, q2_star, p1, q1) schedule(static, 4)
for (int i = 0; i < height * width; i++)
{
int b1, b2, b3, b4, b5, b6;
b1 = get_lsb(p1[i]);
b2 = get_lsb((p1[i] / 2) + q1[i]);
b3 = get_lsb(p1_star[i]);
b4 = get_lsb((p1_star[i] / 2) + p2_star[i]);
b5 = get_lsb(q1_star[i]);
b6 = get_lsb((q1_star[i] / 2) + q2_star[i]);
set_bit(&pixel[i], 1, b1);
set_bit(&pixel[i], 2, b2);
set_bit(&pixel[i], 3, b3);
set_bit(&pixel[i], 4, b4);
set_bit(&pixel[i], 5, b5);
set_bit(&pixel[i], 6, b6);
}
}
void decode(int height, int width, char *p1_star_img, char *p2_star_img, char *q1_star_img, char *q2_star_img)
{
int *p1_star, *p2_star, *q1_star, *q2_star;
p1_star = allocate_space(height, width);
p2_star = allocate_space(height, width);
q1_star = allocate_space(height, width);
q2_star = allocate_space(height, width);
p1_star = read_from_pgm(p1_star_img, &height, &width);
p2_star = read_from_pgm(p2_star_img, &height, &width);
q1_star = read_from_pgm(q1_star_img, &height, &width);
q2_star = read_from_pgm(q2_star_img, &height, &width);
int *p1, *q1;
p1 = allocate_space(height, width);
q1 = allocate_space(height, width);
extract_img(height, width, p1, q1, p1_star, p2_star, q1_star, q2_star);
adjust_l1(height, width, p1_star, p2_star, q1_star, q2_star);
int *image = (int *)calloc(height * width, sizeof(int));
extract_secret(image, height, width, p1, q1, p1_star, p2_star, q1_star, q2_star);
FILE *secret = fopen("secretE.txt", "w");
for (int i = 0; i < height * width; i++)
{
int temp;
temp = image[i];
fprintf(secret, "%d ", temp);
if (i % 100 == 0)
{
fprintf(secret, "\n");
}
}
fclose(secret);
free(p1);
free(q1);
free(p1_star);
free(p2_star);
free(q1_star);
free(q2_star);
free(image);
}
|
fill_ints.c
|
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
* Author: Qiming Sun <[email protected]>
*/
#include <stdlib.h>
#include <string.h>
#include <complex.h>
#include <assert.h>
#include "config.h"
#include "cint.h"
#include "vhf/fblas.h"
#include "pbc/optimizer.h"
#define INTBUFMAX 1000
#define INTBUFMAX10 8000
#define IMGBLK 80
#define OF_CMPLX 2
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
int GTOmax_shell_dim(int *ao_loc, int *shls_slice, int ncenter);
int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter,
int *atm, int natm, int *bas, int nbas, double *env);
static int shloc_partition(int *kshloc, int *ao_loc, int ksh0, int ksh1, int dkmax)
{
int ksh;
int nloc = 0;
int loclast = ao_loc[ksh0];
kshloc[0] = ksh0;
for (ksh = ksh0+1; ksh < ksh1; ksh++) {
assert(ao_loc[ksh+1] - ao_loc[ksh] < dkmax);
if (ao_loc[ksh+1] - loclast > dkmax) {
nloc += 1;
kshloc[nloc] = ksh;
loclast = ao_loc[ksh];
}
}
nloc += 1;
kshloc[nloc] = ksh1;
return nloc;
}
static void shift_bas(double *env_loc, double *env, double *Ls, int ptr, int iL)
{
env_loc[ptr+0] = env[ptr+0] + Ls[iL*3+0];
env_loc[ptr+1] = env[ptr+1] + Ls[iL*3+1];
env_loc[ptr+2] = env[ptr+2] + Ls[iL*3+2];
}
static void sort3c_kks1(double complex *out, double *bufr, double *bufi,
int *kptij_idx, int *shls_slice, int *ao_loc,
int nkpts, int nkpts_ij, int comp, int ish, int jsh,
int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naoi = ao_loc[ish1] - ao_loc[ish0];
const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
const size_t njk = naoj * naok;
const size_t nijk = njk * naoi;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int ip = ao_loc[ish] - ao_loc[ish0];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
const int dij = di * dj;
const int dkmax = ao_loc[msh1] - ao_loc[msh0];
const size_t dijmc = dij * dkmax * comp;
out += (ip * naoj + jp) * naok;
int i, j, k, kk, ik, jk, ksh, ic, dk, dijk;
size_t off;
double *pbr, *pbi;
double complex *pout;
for (kk = 0; kk < nkpts_ij; kk++) {
ik = kptij_idx[kk] / nkpts;
jk = kptij_idx[kk] % nkpts;
off = (ik*nkpts+jk) * dijmc;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0];
pbr = bufr + off + dijk*ic;
pbi = bufi + off + dijk*ic;
for (j = 0; j < dj; j++) {
for (k = 0; k < dk; k++) {
for (i = 0; i < di; i++) {
pout[i*njk+k] = pbr[k*dij+i] + pbi[k*dij+i]*_Complex_I;
} }
pout += naok;
pbr += di;
pbi += di;
}
}
off += dijk * comp;
}
out += nijk * comp;
}
}
static void _nr3c_fill_kk(int (*intor)(), void (*fsort)(),
double complex *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int jsh0 = shls_slice[2];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const char TRANS_N = 'N';
const double D0 = 0;
const double D1 = 1;
const double ND1 = -1;
jsh += jsh0;
ish += ish0;
int iptrxyz = atm[PTR_COORD+bas[ATOM_OF+ish*BAS_SLOTS]*ATM_SLOTS];
int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS];
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
int dkmax = INTBUFMAX / dij;
int kshloc[ksh1-ksh0+1];
int nkshloc = shloc_partition(kshloc, ao_loc, ksh0, ksh1, dkmax);
int i, m, msh0, msh1, dijm, dijmc, dijmk, empty;
int ksh, dk, iL0, iL, jL, iLcount;
int shls[3];
double *bufkk_r, *bufkk_i, *bufkL_r, *bufkL_i, *bufL, *pbuf, *cache;
int (*fprescreen)();
if (pbcopt != NULL) {
fprescreen = pbcopt->fprescreen;
} else {
fprescreen = PBCnoscreen;
}
shls[0] = ish;
shls[1] = jsh;
for (m = 0; m < nkshloc; m++) {
msh0 = kshloc[m];
msh1 = kshloc[m+1];
dkmax = ao_loc[msh1] - ao_loc[msh0];
dijm = dij * dkmax;
dijmc = dijm * comp;
dijmk = dijmc * nkpts;
bufkk_r = buf;
bufkk_i = bufkk_r + (size_t)nkpts * dijmk;
bufkL_r = bufkk_i + (size_t)nkpts * dijmk;
bufkL_i = bufkL_r + (size_t)MIN(nimgs,IMGBLK) * dijmk;
bufL = bufkL_i + (size_t)MIN(nimgs,IMGBLK) * dijmk;
cache = bufL + (size_t)nimgs * dijmc;
for (i = 0; i < nkpts*dijmk*OF_CMPLX; i++) {
bufkk_r[i] = 0;
}
for (iL0 = 0; iL0 < nimgs; iL0+=IMGBLK) {
iLcount = MIN(IMGBLK, nimgs - iL0);
for (iL = iL0; iL < iL0+iLcount; iL++) {
shift_bas(env_loc, env, Ls, iptrxyz, iL);
pbuf = bufL;
for (jL = 0; jL < nimgs; jL++) {
shift_bas(env_loc, env, Ls, jptrxyz, jL);
if ((*fprescreen)(shls, pbcopt, atm, bas, env_loc)) {
for (ksh = msh0; ksh < msh1; ksh++) {
shls[2] = ksh;
if ((*intor)(pbuf, NULL, shls, atm, natm, bas, nbas,
env_loc, cintopt, cache)) {
empty = 0;
}
dk = ao_loc[ksh+1] - ao_loc[ksh];
pbuf += dij*dk * comp;
}
} else {
for (i = 0; i < dijmc; i++) {
pbuf[i] = 0;
}
pbuf += dijmc;
}
}
dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &nimgs,
&D1, bufL, &dijmc, expkL_r, &nimgs,
&D0, bufkL_r+(iL-iL0)*(size_t)dijmk, &dijmc);
dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &nimgs,
&D1, bufL, &dijmc, expkL_i, &nimgs,
&D0, bufkL_i+(iL-iL0)*(size_t)dijmk, &dijmc);
} // iL in range(0, nimgs)
// conj(exp(1j*dot(h,k)))
dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount,
&D1, bufkL_r, &dijmk, expkL_r+iL0, &nimgs,
&D1, bufkk_r, &dijmk);
dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount,
&D1, bufkL_i, &dijmk, expkL_i+iL0, &nimgs,
&D1, bufkk_r, &dijmk);
dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount,
&D1, bufkL_i, &dijmk, expkL_r+iL0, &nimgs,
&D1, bufkk_i, &dijmk);
dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount,
&ND1, bufkL_r, &dijmk, expkL_i+iL0, &nimgs,
&D1, bufkk_i, &dijmk);
}
(*fsort)(out, bufkk_r, bufkk_i, kptij_idx, shls_slice,
ao_loc, nkpts, nkpts_ij, comp, ish, jsh,
msh0, msh1);
}
}
/* ('...LM,kL,lM->...kl', int3c, exp_kL, exp_kL) */
void PBCnr3c_fill_kks1(int (*intor)(), double complex *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
_nr3c_fill_kk(intor, &sort3c_kks1, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
static void sort3c_kks2_igtj(double complex *out, double *bufr, double *bufi,
int *kptij_idx, int *shls_slice, int *ao_loc,
int nkpts, int nkpts_ij, int comp, int ish, int jsh,
int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naoi = ao_loc[ish1] - ao_loc[ish0];
const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
assert(naoi == naoj);
const size_t njk = naoj * naok;
const size_t nijk = njk * naoi;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int ip = ao_loc[ish] - ao_loc[ish0];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
const int dij = di * dj;
const int dkmax = ao_loc[msh1] - ao_loc[msh0];
const size_t dijmc = dij * dkmax * comp;
double complex *outij = out + (ip * naoj + jp) * naok;
double complex *outji = out + (jp * naoj + ip) * naok;
int i, j, k, kk, ik, jk, ksh, ic, dk, dijk;
size_t offij, offji;
double *pbij_r, *pbij_i, *pbji_r, *pbji_i;
double complex *poutij, *poutji;
for (kk = 0; kk < nkpts_ij; kk++) {
ik = kptij_idx[kk] / nkpts;
jk = kptij_idx[kk] % nkpts;
offij = (ik*nkpts+jk) * dijmc;
offji = (jk*nkpts+ik) * dijmc;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
poutij = outij + nijk*ic + ao_loc[ksh]-ao_loc[ksh0];
poutji = outji + nijk*ic + ao_loc[ksh]-ao_loc[ksh0];
pbij_r = bufr + offij + dijk*ic;
pbij_i = bufi + offij + dijk*ic;
pbji_r = bufr + offji + dijk*ic;
pbji_i = bufi + offji + dijk*ic;
for (j = 0; j < dj; j++) {
for (k = 0; k < dk; k++) {
for (i = 0; i < di; i++) {
poutij[i*njk +k] = pbij_r[k*dij+i] + pbij_i[k*dij+i]*_Complex_I;
poutji[i*naok+k] = pbji_r[k*dij+i] - pbji_i[k*dij+i]*_Complex_I;
} }
poutij += naok;
poutji += njk;
pbij_r += di;
pbij_i += di;
pbji_r += di;
pbji_i += di;
}
}
offij += dijk * comp;
offji += dijk * comp;
}
outij += nijk * comp;
outji += nijk * comp;
}
}
/* ('...LM,kL,lM->...kl', int3c, exp_kL, exp_kL) */
void PBCnr3c_fill_kks2(int (*intor)(), double complex *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
int ip = ish + shls_slice[0];
int jp = jsh + shls_slice[2] - nbas;
if (ip > jp) {
_nr3c_fill_kk(intor, &sort3c_kks2_igtj, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
} else if (ip == jp) {
_nr3c_fill_kk(intor, &sort3c_kks1, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
}
static void sort3c_ks1(double complex *out, double *bufr, double *bufi,
int *shls_slice, int *ao_loc, int nkpts, int comp,
int ish, int jsh, int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naoi = ao_loc[ish1] - ao_loc[ish0];
const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
const size_t njk = naoj * naok;
const size_t nijk = njk * naoi;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int ip = ao_loc[ish] - ao_loc[ish0];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
const int dij = di * dj;
const int dkmax = ao_loc[msh1] - ao_loc[msh0];
const size_t dijmc = dij * dkmax * comp;
out += (ip * naoj + jp) * naok;
int i, j, k, kk, ksh, ic, dk, dijk;
size_t off;
double *pbr, *pbi;
double complex *pout;
for (kk = 0; kk < nkpts; kk++) {
off = kk * dijmc;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0];
pbr = bufr + off + dijk*ic;
pbi = bufi + off + dijk*ic;
for (j = 0; j < dj; j++) {
for (k = 0; k < dk; k++) {
for (i = 0; i < di; i++) {
pout[i*njk+k] = pbr[k*dij+i] + pbi[k*dij+i]*_Complex_I;
} }
pout += naok;
pbr += di;
pbi += di;
}
}
off += dijk * comp;
}
out += nijk * comp;
}
}
/* ('...LM,kL,kM->...k', int3c, exp_kL, exp_kL) */
static void _nr3c_fill_k(int (*intor)(), void (*fsort)(),
double complex *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int jsh0 = shls_slice[2];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const char TRANS_N = 'N';
const double D1 = 1;
jsh += jsh0;
ish += ish0;
int iptrxyz = atm[PTR_COORD+bas[ATOM_OF+ish*BAS_SLOTS]*ATM_SLOTS];
int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS];
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
int dkmax = INTBUFMAX10 / dij;
int kshloc[ksh1-ksh0+1];
int nkshloc = shloc_partition(kshloc, ao_loc, ksh0, ksh1, dkmax);
int i, m, msh0, msh1, dijmc, empty;
size_t dijmk;
int ksh, dk, iL, jL, jLcount;
int shls[3];
double *bufexp_r = buf;
double *bufexp_i = bufexp_r + nimgs * nkpts;
double *bufk_r = bufexp_i + nimgs * nkpts;
double *bufk_i, *bufL, *pbuf, *cache;
int (*fprescreen)();
if (pbcopt != NULL) {
fprescreen = pbcopt->fprescreen;
} else {
fprescreen = PBCnoscreen;
}
shls[0] = ish;
shls[1] = jsh;
for (m = 0; m < nkshloc; m++) {
msh0 = kshloc[m];
msh1 = kshloc[m+1];
dkmax = ao_loc[msh1] - ao_loc[msh0];
dijmc = dij * dkmax * comp;
dijmk = dijmc * nkpts;
bufk_i = bufk_r + dijmk;
bufL = bufk_i + dijmk;
cache = bufL + nimgs * dijmc;
for (i = 0; i < dijmk*OF_CMPLX; i++) {
bufk_r[i] = 0;
}
for (iL = 0; iL < nimgs; iL++) {
shift_bas(env_loc, env, Ls, iptrxyz, iL);
pbuf = bufL;
jLcount = 0;
for (jL = 0; jL < nimgs; jL++) {
shift_bas(env_loc, env, Ls, jptrxyz, jL);
if ((*fprescreen)(shls, pbcopt, atm, bas, env_loc)) {
for (ksh = msh0; ksh < msh1; ksh++) {
shls[2] = ksh;
if ((*intor)(pbuf, NULL, shls, atm, natm, bas, nbas,
env_loc, cintopt, cache)) {
empty = 0;
}
dk = ao_loc[ksh+1] - ao_loc[ksh];
pbuf += dij*dk * comp;
}
// ('k,kL->kL', conj(expkL[iL]), expkL)
for (i = 0; i < nkpts; i++) {
bufexp_r[i*nimgs+jLcount] = expkL_r[i*nimgs+jL] * expkL_r[i*nimgs+iL];
bufexp_r[i*nimgs+jLcount]+= expkL_i[i*nimgs+jL] * expkL_i[i*nimgs+iL];
bufexp_i[i*nimgs+jLcount] = expkL_i[i*nimgs+jL] * expkL_r[i*nimgs+iL];
bufexp_i[i*nimgs+jLcount]-= expkL_r[i*nimgs+jL] * expkL_i[i*nimgs+iL];
}
jLcount++;
}
}
dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &jLcount,
&D1, bufL, &dijmc, bufexp_r, &nimgs, &D1, bufk_r, &dijmc);
dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &jLcount,
&D1, bufL, &dijmc, bufexp_i, &nimgs, &D1, bufk_i, &dijmc);
} // iL in range(0, nimgs)
(*fsort)(out, bufk_r, bufk_i, shls_slice, ao_loc,
nkpts, comp, ish, jsh, msh0, msh1);
}
}
/* ('...LM,kL,kM->...k', int3c, exp_kL, exp_kL) */
void PBCnr3c_fill_ks1(int (*intor)(), double complex *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
_nr3c_fill_k(intor, sort3c_ks1, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
static void sort3c_ks2_igtj(double complex *out, double *bufr, double *bufi,
int *shls_slice, int *ao_loc, int nkpts, int comp,
int ish, int jsh, int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
const size_t off0 = ao_loc[ish0] * (ao_loc[ish0] + 1) / 2;
const size_t nij = ao_loc[ish1] * (ao_loc[ish1] + 1) / 2 - off0;
const size_t nijk = nij * naok;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
const int dkmax = ao_loc[msh1] - ao_loc[msh0];
const size_t dijmc = dij * dkmax * comp;
const int jp = ao_loc[jsh] - ao_loc[jsh0];
out += (ao_loc[ish]*(ao_loc[ish]+1)/2-off0 + jp) * naok;
int i, j, k, ij, kk, ksh, ic, dk, dijk;
size_t off;
double *pbr, *pbi;
double complex *pout;
for (kk = 0; kk < nkpts; kk++) {
off = kk * dijmc;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0];
pbr = bufr + off + dijk*ic;
pbi = bufi + off + dijk*ic;
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
ij = j * di + i;
for (k = 0; k < dk; k++) {
pout[j*naok+k] = pbr[k*dij+ij] + pbi[k*dij+ij]*_Complex_I;
}
}
pout += (i+ao_loc[ish]+1) * naok;
}
}
off += dijk * comp;
}
out += nijk * comp;
}
}
static void sort3c_ks2_ieqj(double complex *out, double *bufr, double *bufi,
int *shls_slice, int *ao_loc, int nkpts, int comp,
int ish, int jsh, int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
const size_t off0 = ao_loc[ish0] * (ao_loc[ish0] + 1) / 2;
const size_t nij = ao_loc[ish1] * (ao_loc[ish1] + 1) / 2 - off0;
const size_t nijk = nij * naok;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
const int dkmax = ao_loc[msh1] - ao_loc[msh0];
const size_t dijmc = dij * dkmax * comp;
const int jp = ao_loc[jsh] - ao_loc[jsh0];
out += (ao_loc[ish]*(ao_loc[ish]+1)/2-off0 + jp) * naok;
int i, j, k, ij, kk, ksh, ic, dk, dijk;
size_t off;
double *pbr, *pbi;
double complex *pout;
for (kk = 0; kk < nkpts; kk++) {
off = kk * dijmc;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0];
pbr = bufr + off + dijk*ic;
pbi = bufi + off + dijk*ic;
for (i = 0; i < di; i++) {
for (j = 0; j <= i; j++) {
ij = j * di + i;
for (k = 0; k < dk; k++) {
pout[j*naok+k] = pbr[k*dij+ij] + pbi[k*dij+ij]*_Complex_I;
}
}
pout += (i+ao_loc[ish]+1) * naok;
}
}
off += dijk * comp;
}
out += nijk * comp;
}
}
/* ('...LM,kL,kM->...k', int3c, exp_kL, exp_kL) */
void PBCnr3c_fill_ks2(int (*intor)(), double complex *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
int ip = ish + shls_slice[0];
int jp = jsh + shls_slice[2] - nbas;
if (ip > jp) {
_nr3c_fill_k(intor, &sort3c_ks2_igtj, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
} else if (ip == jp) {
_nr3c_fill_k(intor, &sort3c_ks2_ieqj, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
}
static void sort3c_gs1(double *out, double *in, int *shls_slice, int *ao_loc,
int comp, int ish, int jsh, int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naoi = ao_loc[ish1] - ao_loc[ish0];
const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
const size_t njk = naoj * naok;
const size_t nijk = njk * naoi;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int ip = ao_loc[ish] - ao_loc[ish0];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
const int dij = di * dj;
const int dkmax = ao_loc[msh1] - ao_loc[msh0];
out += (ip * naoj + jp) * naok;
int i, j, k, ksh, ic, dk, dijk;
double *pin, *pout;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
pout = out + nijk * ic + ao_loc[ksh]-ao_loc[ksh0];
pin = in + dijk * ic;
for (j = 0; j < dj; j++) {
for (i = 0; i < di; i++) {
for (k = 0; k < dk; k++) {
pout[i*njk+k] = pin[k*dij+i];
} }
pout += naok;
pin += di;
}
}
in += dijk * comp;
}
}
static void _nr3c_fill_g(int (*intor)(), void (*fsort)(), double *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int jsh0 = shls_slice[2];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
jsh += jsh0;
ish += ish0;
int iptrxyz = atm[PTR_COORD+bas[ATOM_OF+ish*BAS_SLOTS]*ATM_SLOTS];
int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS];
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
int dkmax = INTBUFMAX10 / dij / 2 * MIN(IMGBLK,nimgs);
int kshloc[ksh1-ksh0+1];
int nkshloc = shloc_partition(kshloc, ao_loc, ksh0, ksh1, dkmax);
int i, m, msh0, msh1, dijm;
int ksh, dk, iL, jL, dijkc;
int shls[3];
int dijmc = dij * dkmax * comp;
double *bufL = buf + dijmc;
double *cache = bufL + dijmc;
double *pbuf;
int (*fprescreen)();
if (pbcopt != NULL) {
fprescreen = pbcopt->fprescreen;
} else {
fprescreen = PBCnoscreen;
}
shls[0] = ish;
shls[1] = jsh;
for (m = 0; m < nkshloc; m++) {
msh0 = kshloc[m];
msh1 = kshloc[m+1];
dkmax = ao_loc[msh1] - ao_loc[msh0];
dijm = dij * dkmax;
dijmc = dijm * comp;
for (i = 0; i < dijmc; i++) {
bufL[i] = 0;
}
for (iL = 0; iL < nimgs; iL++) {
shift_bas(env_loc, env, Ls, iptrxyz, iL);
for (jL = 0; jL < nimgs; jL++) {
shift_bas(env_loc, env, Ls, jptrxyz, jL);
if ((*fprescreen)(shls, pbcopt, atm, bas, env_loc)) {
pbuf = bufL;
for (ksh = msh0; ksh < msh1; ksh++) {
shls[2] = ksh;
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijkc = dij*dk * comp;
if ((*intor)(buf, NULL, shls, atm, natm, bas, nbas,
env_loc, cintopt, cache)) {
for (i = 0; i < dijkc; i++) {
pbuf[i] += buf[i];
}
}
pbuf += dijkc;
}
}
}
} // iL in range(0, nimgs)
(*fsort)(out, bufL, shls_slice, ao_loc, comp, ish, jsh, msh0, msh1);
}
}
/* ('...LM->...', int3c) */
void PBCnr3c_fill_gs1(int (*intor)(), double *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
_nr3c_fill_g(intor, &sort3c_gs1, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
static void sort3c_gs2_igtj(double *out, double *in, int *shls_slice, int *ao_loc,
int comp, int ish, int jsh, int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
const size_t off0 = ao_loc[ish0] * (ao_loc[ish0] + 1) / 2;
const size_t nij = ao_loc[ish1] * (ao_loc[ish1] + 1) / 2 - off0;
const size_t nijk = nij * naok;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int dij = di * dj;
const int jp = ao_loc[jsh] - ao_loc[jsh0];
out += (ao_loc[ish]*(ao_loc[ish]+1)/2-off0 + jp) * naok;
int i, j, k, ij, ksh, ic, dk, dijk;
double *pin, *pout;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
pout = out + nijk * ic + ao_loc[ksh]-ao_loc[ksh0];
pin = in + dijk * ic;
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
ij = j * di + i;
for (k = 0; k < dk; k++) {
pout[j*naok+k] = pin[k*dij+ij];
}
}
pout += (i+ao_loc[ish]+1) * naok;
}
}
in += dijk * comp;
}
}
static void sort3c_gs2_ieqj(double *out, double *in, int *shls_slice, int *ao_loc,
int comp, int ish, int jsh, int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int ksh0 = shls_slice[4];
const int ksh1 = shls_slice[5];
const size_t naok = ao_loc[ksh1] - ao_loc[ksh0];
const size_t off0 = ao_loc[ish0] * (ao_loc[ish0] + 1) / 2;
const size_t nij = ao_loc[ish1] * (ao_loc[ish1] + 1) / 2 - off0;
const size_t nijk = nij * naok;
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dij = di * di;
const int jp = ao_loc[jsh] - ao_loc[jsh0];
out += (ao_loc[ish]*(ao_loc[ish]+1)/2-off0 + jp) * naok;
int i, j, k, ij, ksh, ic, dk, dijk;
double *pin, *pout;
for (ksh = msh0; ksh < msh1; ksh++) {
dk = ao_loc[ksh+1] - ao_loc[ksh];
dijk = dij * dk;
for (ic = 0; ic < comp; ic++) {
pout = out + nijk * ic + ao_loc[ksh]-ao_loc[ksh0];
pin = in + dijk * ic;
for (i = 0; i < di; i++) {
for (j = 0; j <= i; j++) {
ij = j * di + i;
for (k = 0; k < dk; k++) {
pout[j*naok+k] = pin[k*dij+ij];
}
}
pout += (i+ao_loc[ish]+1) * naok;
}
}
in += dijk * comp;
}
}
/* ('...LM->...', int3c) */
void PBCnr3c_fill_gs2(int (*intor)(), double *out, int nkpts_ij,
int nkpts, int comp, int nimgs, int ish, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
int ip = ish + shls_slice[0];
int jp = jsh + shls_slice[2] - nbas;
if (ip > jp) {
_nr3c_fill_g(intor, &sort3c_gs2_igtj, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
} else if (ip == jp) {
_nr3c_fill_g(intor, &sort3c_gs2_ieqj, out,
nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
}
int PBCsizeof_env(int *shls_slice,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
int ish, ia, np, nc;
int nenv = 0;
for (ish = ish0; ish < ish1; ish++) {
ia = bas[ATOM_OF +ish*BAS_SLOTS];
nenv = MAX(atm[PTR_COORD+ia*ATM_SLOTS]+3, nenv);
np = bas[NPRIM_OF+ish*BAS_SLOTS];
nc = bas[NCTR_OF +ish*BAS_SLOTS];
nenv = MAX(bas[PTR_EXP +ish*BAS_SLOTS]+np, nenv);
nenv = MAX(bas[PTR_COEFF+ish*BAS_SLOTS]+np*nc, nenv);
}
return nenv;
}
void PBCnr3c_drv(int (*intor)(), void (*fill)(), double complex *eri,
int nkpts_ij, int nkpts, int comp, int nimgs,
double *Ls, double complex *expkL, int *kptij_idx,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int nish = ish1 - ish0;
const int njsh = jsh1 - jsh0;
double *expkL_r = malloc(sizeof(double) * nimgs*nkpts * OF_CMPLX);
double *expkL_i = expkL_r + nimgs*nkpts;
int i;
for (i = 0; i < nimgs*nkpts; i++) {
expkL_r[i] = creal(expkL[i]);
expkL_i[i] = cimag(expkL[i]);
}
size_t count;
if (fill == &PBCnr3c_fill_kks1 || fill == &PBCnr3c_fill_kks2) {
int dijk =(GTOmax_shell_dim(ao_loc, shls_slice+0, 1) *
GTOmax_shell_dim(ao_loc, shls_slice+2, 1) *
GTOmax_shell_dim(ao_loc, shls_slice+4, 1));
count = nkpts*nkpts * OF_CMPLX +
nkpts*MIN(nimgs,IMGBLK) * OF_CMPLX + nimgs;
// MAX(INTBUFMAX, dijk) to ensure buffer is enough for at least one (i,j,k) shell
count*= MAX(INTBUFMAX, dijk) * comp;
} else {
count = (nkpts * OF_CMPLX + nimgs) * INTBUFMAX10 * comp;
count+= nimgs * nkpts * OF_CMPLX;
}
const int cache_size = GTOmax_cache_size(intor, shls_slice, 3,
atm, natm, bas, nbas, env);
#pragma omp parallel default(none) \
shared(intor, fill, eri, nkpts_ij, nkpts, comp, nimgs, \
Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, \
atm, natm, bas, nbas, env, count)
{
int ish, jsh, ij;
int nenv = PBCsizeof_env(shls_slice, atm, natm, bas, nbas, env);
nenv = MAX(nenv, PBCsizeof_env(shls_slice+2, atm, natm, bas, nbas, env));
nenv = MAX(nenv, PBCsizeof_env(shls_slice+4, atm, natm, bas, nbas, env));
double *env_loc = malloc(sizeof(double)*nenv);
memcpy(env_loc, env, sizeof(double)*nenv);
double *buf = malloc(sizeof(double)*(count+cache_size));
#pragma omp for schedule(dynamic)
for (ij = 0; ij < nish*njsh; ij++) {
ish = ij / njsh;
jsh = ij % njsh;
(*fill)(intor, eri, nkpts_ij, nkpts, comp, nimgs, ish, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
free(buf);
free(env_loc);
}
free(expkL_r);
}
static void sort2c_ks1(double complex *out, double *bufr, double *bufi,
int *shls_slice, int *ao_loc, int nkpts, int comp,
int jsh, int msh0, int msh1)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const size_t naoi = ao_loc[ish1] - ao_loc[ish0];
const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
const size_t nij = naoi * naoj;
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
const int dimax = ao_loc[msh1] - ao_loc[msh0];
const size_t dmjc = dimax * dj * comp;
out += jp;
int i, j, kk, ish, ic, di, dij;
size_t off;
double *pbr, *pbi;
double complex *pout;
for (kk = 0; kk < nkpts; kk++) {
off = kk * dmjc;
for (ish = msh0; ish < msh1; ish++) {
di = ao_loc[ish+1] - ao_loc[ish];
dij = di * dj;
for (ic = 0; ic < comp; ic++) {
pout = out + nij*ic + naoj*(ao_loc[ish]-ao_loc[ish0]);
pbr = bufr + off + dij*ic;
pbi = bufi + off + dij*ic;
for (j = 0; j < dj; j++) {
for (i = 0; i < di; i++) {
pout[i*naoj+j] = pbr[j*di+i] + pbi[j*di+i]*_Complex_I;
}
}
}
off += dij * comp;
}
out += nij * comp;
}
}
static void _nr2c_fill(int (*intor)(), double complex *out,
int nkpts, int comp, int nimgs, int jsh, int ish0,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const char TRANS_N = 'N';
const double D1 = 1;
const double D0 = 0;
ish0 += shls_slice[0];
jsh += jsh0;
int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
int dimax = INTBUFMAX10 / dj;
int ishloc[ish1-ish0+1];
int nishloc = shloc_partition(ishloc, ao_loc, ish0, ish1, dimax);
int m, msh0, msh1, dmjc, ish, di, empty;
int jL;
int shls[2];
double *bufk_r = buf;
double *bufk_i, *bufL, *pbuf, *cache;
shls[1] = jsh;
for (m = 0; m < nishloc; m++) {
msh0 = ishloc[m];
msh1 = ishloc[m+1];
dimax = ao_loc[msh1] - ao_loc[msh0];
dmjc = dj * dimax * comp;
bufk_i = bufk_r + dmjc * nkpts;
bufL = bufk_i + dmjc * nkpts;
cache = bufL + dmjc * nimgs;
pbuf = bufL;
for (jL = 0; jL < nimgs; jL++) {
shift_bas(env_loc, env, Ls, jptrxyz, jL);
for (ish = msh0; ish < msh1; ish++) {
shls[0] = ish;
di = ao_loc[ish+1] - ao_loc[ish];
if ((*intor)(pbuf, NULL, shls, atm, natm, bas, nbas,
env_loc, cintopt, cache)) {
empty = 0;
}
pbuf += di * dj * comp;
}
}
dgemm_(&TRANS_N, &TRANS_N, &dmjc, &nkpts, &nimgs,
&D1, bufL, &dmjc, expkL_r, &nimgs, &D0, bufk_r, &dmjc);
dgemm_(&TRANS_N, &TRANS_N, &dmjc, &nkpts, &nimgs,
&D1, bufL, &dmjc, expkL_i, &nimgs, &D0, bufk_i, &dmjc);
sort2c_ks1(out, bufk_r, bufk_i, shls_slice, ao_loc,
nkpts, comp, jsh, msh0, msh1);
}
}
/* ('...M,kL->...k', int3c, exp_kL, exp_kL) */
void PBCnr2c_fill_ks1(int (*intor)(), double complex *out,
int nkpts, int comp, int nimgs, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
_nr2c_fill(intor, out, nkpts, comp, nimgs, jsh, 0,
buf, env_loc, Ls, expkL_r, expkL_i, shls_slice, ao_loc,
cintopt, pbcopt, atm, natm, bas, nbas, env);
}
void PBCnr2c_fill_ks2(int (*intor)(), double complex *out,
int nkpts, int comp, int nimgs, int jsh,
double *buf, double *env_loc, double *Ls,
double *expkL_r, double *expkL_i,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
_nr2c_fill(intor, out, nkpts, comp, nimgs, jsh, jsh,
buf, env_loc, Ls, expkL_r, expkL_i, shls_slice, ao_loc,
cintopt, pbcopt, atm, natm, bas, nbas, env);
}
void PBCnr2c_drv(int (*intor)(), void (*fill)(), double complex *out,
int nkpts, int comp, int nimgs,
double *Ls, double complex *expkL,
int *shls_slice, int *ao_loc,
CINTOpt *cintopt, PBCOpt *pbcopt,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int njsh = jsh1 - jsh0;
double *expkL_r = malloc(sizeof(double) * nimgs*nkpts * OF_CMPLX);
double *expkL_i = expkL_r + nimgs*nkpts;
int i;
for (i = 0; i < nimgs*nkpts; i++) {
expkL_r[i] = creal(expkL[i]);
expkL_i[i] = cimag(expkL[i]);
}
const int cache_size = GTOmax_cache_size(intor, shls_slice, 2,
atm, natm, bas, nbas, env);
#pragma omp parallel default(none) \
shared(intor, fill, out, nkpts, comp, nimgs, \
Ls, expkL_r, expkL_i, shls_slice, ao_loc, cintopt, pbcopt, \
atm, natm, bas, nbas, env)
{
int jsh;
int nenv = PBCsizeof_env(shls_slice, atm, natm, bas, nbas, env);
nenv = MAX(nenv, PBCsizeof_env(shls_slice+2, atm, natm, bas, nbas, env));
double *env_loc = malloc(sizeof(double)*nenv);
memcpy(env_loc, env, sizeof(double)*nenv);
size_t count = nkpts * OF_CMPLX + nimgs;
double *buf = malloc(sizeof(double)*(count*INTBUFMAX10*comp+cache_size));
#pragma omp for schedule(dynamic)
for (jsh = 0; jsh < njsh; jsh++) {
(*fill)(intor, out, nkpts, comp, nimgs, jsh,
buf, env_loc, Ls, expkL_r, expkL_i,
shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env);
}
free(buf);
free(env_loc);
}
free(expkL_r);
}
|
kernel.h
|
/*
* This file contains the implementation of a kernel for the
* point-in-polygon problem using the crossing number algorithm
*
* The kernel pnpoly_base is used for correctness checking.
*
* The algorithm used here is adapted from:
* 'Inclusion of a Point in a Polygon', Dan Sunday, 2001
* (http://geomalgorithms.com/a03-_inclusion.html)
*
* Author: Ben van Werkhoven <[email protected]>
*/
/*
* The is_between method returns a boolean that is True when the a is between c and b.
*/
#pragma omp declare target
inline int is_between(float a, float b, float c) {
return (b > a) != (c > a);
}
#pragma omp end declare target
/*
* The Point-in-Polygon kernel
*/
template <int tile_size>
void pnpoly_opt(
int*__restrict bitmap,
const float2*__restrict point,
const float2*__restrict vertex,
int n)
{
#pragma omp target teams distribute parallel for thread_limit(256)
for (int i = 0; i < n; i++) {
int c[tile_size];
float2 lpoint[tile_size];
#pragma unroll
for (int ti=0; ti<tile_size; ti++) {
c[ti] = 0;
if (i+BLOCK_SIZE_X*ti < n) {
lpoint[ti] = point[i+BLOCK_SIZE_X*ti];
}
}
int k = VERTICES-1;
for (int j=0; j<VERTICES; k = j++) { // edge from vj to vk
float2 vj = vertex[j];
float2 vk = vertex[k];
float slope = (vk.x-vj.x) / (vk.y-vj.y);
#pragma unroll
for (int ti=0; ti<tile_size; ti++) {
float2 p = lpoint[ti];
if (is_between(p.y, vj.y, vk.y) && //if p is between vj and vk vertically
(p.x < slope * (p.y-vj.y) + vj.x)
) { //if p.x crosses the line vj-vk when moved in positive x-direction
c[ti] = !c[ti];
}
}
}
#pragma unroll
for (int ti=0; ti<tile_size; ti++) {
//could do an if statement here if 1s are expected to be rare
if (i+BLOCK_SIZE_X*ti < n)
bitmap[i+BLOCK_SIZE_X*ti] = c[ti];
}
}
}
/*
* The naive implementation is used for verifying correctness of the optimized implementation
*/
void pnpoly_base(
int*__restrict bitmap,
const float2*__restrict point,
const float2*__restrict vertex,
int n)
{
#pragma omp target teams distribute parallel for thread_limit(256)
for (int i = 0; i < n; i++) {
int c = 0;
float2 p = point[i];
int k = VERTICES-1;
for (int j=0; j<VERTICES; k = j++) { // edge from v to vp
float2 vj = vertex[j];
float2 vk = vertex[k];
float slope = (vk.x-vj.x) / (vk.y-vj.y);
if (((vj.y>p.y) != (vk.y>p.y)) && //if p is between vj and vk vertically
(p.x < slope * (p.y-vj.y) + vj.x)) { //if p.x crosses the line vj-vk when moved in positive x-direction
c = !c;
}
}
bitmap[i] = c; // 0 if even (out), and 1 if odd (in)
}
}
|
compiler_cgen.c
|
/* Generated by Nim Compiler v0.15.0 */
/* (c) 2016 Andreas Rumpf */
/* The generated code is subject to the original license. */
#define NIM_INTBITS 32
#include "nimbase.h"
#include <string.h>
typedef struct Tcgen527027 Tcgen527027;
typedef struct TNimType TNimType;
typedef struct TNimNode TNimNode;
typedef struct Ropeobj177006 Ropeobj177006;
typedef struct NimStringDesc NimStringDesc;
typedef struct TGenericSeq TGenericSeq;
typedef struct Cell46904 Cell46904;
typedef struct Cellseq46920 Cellseq46920;
typedef struct Gcheap49418 Gcheap49418;
typedef struct Gcstack49416 Gcstack49416;
typedef struct Memregion29085 Memregion29085;
typedef struct Smallchunk29039 Smallchunk29039;
typedef struct Llchunk29079 Llchunk29079;
typedef struct Bigchunk29041 Bigchunk29041;
typedef struct Intset29014 Intset29014;
typedef struct Trunk29010 Trunk29010;
typedef struct Avlnode29083 Avlnode29083;
typedef struct Gcstat49414 Gcstat49414;
typedef struct Cellset46916 Cellset46916;
typedef struct Pagedesc46912 Pagedesc46912;
typedef struct Ttypeseq290836 Ttypeseq290836;
typedef struct Ttype290840 Ttype290840;
typedef struct Intset266030 Intset266030;
typedef struct Trunk266026 Trunk266026;
typedef struct Trunkseq266028 Trunkseq266028;
typedef struct Tpasscontext339002 Tpasscontext339002;
typedef struct Tsym290834 Tsym290834;
typedef struct Tidobj197004 Tidobj197004;
typedef struct TNimObject TNimObject;
typedef struct TY290929 TY290929;
typedef struct Tstrtable290806 Tstrtable290806;
typedef struct Tsymseq290804 Tsymseq290804;
typedef struct Tident197010 Tident197010;
typedef struct Tlineinfo189336 Tlineinfo189336;
typedef struct Tnode290802 Tnode290802;
typedef struct Tloc290816 Tloc290816;
typedef struct Tlib290820 Tlib290820;
typedef struct TY527153 TY527153;
typedef struct TY201018 TY201018;
typedef struct Tidtable290850 Tidtable290850;
typedef struct Tidpairseq290848 Tidpairseq290848;
typedef struct Tlinkedlist147013 Tlinkedlist147013;
typedef struct Tlistentry147007 Tlistentry147007;
typedef struct Tcproc527021 Tcproc527021;
typedef struct Tnodetable290862 Tnodetable290862;
typedef struct Tnodepairseq290860 Tnodepairseq290860;
typedef struct Debuginfo201009 Debuginfo201009;
typedef struct TY201021 TY201021;
typedef struct TY201023 TY201023;
typedef struct Tnodeseq290796 Tnodeseq290796;
typedef struct TY189350 TY189350;
typedef struct TY527095 TY527095;
typedef struct Trodreader330021 Trodreader330021;
typedef struct TY290960 TY290960;
typedef struct TY201017 TY201017;
typedef struct Enumdesc201007 Enumdesc201007;
typedef struct Tinfocc271008 Tinfocc271008;
typedef struct Tblock527019 Tblock527019;
typedef struct Ttraversalclosure535019 Ttraversalclosure535019;
typedef struct TY134602 TY134602;
typedef struct Tbitset337004 Tbitset337004;
typedef struct TY189612 TY189612;
typedef struct Tfileinfo189334 Tfileinfo189334;
typedef struct Tinfoos175035 Tinfoos175035;
typedef struct Tinfocpu175476 Tinfocpu175476;
typedef struct Tstrentry147009 Tstrentry147009;
typedef struct TY124315 TY124315;
typedef struct Basechunk29037 Basechunk29037;
typedef struct Freecell29029 Freecell29029;
typedef struct Tinstantiation290824 Tinstantiation290824;
typedef struct Tidpair290846 Tidpair290846;
typedef struct Tnodepair290858 Tnodepair290858;
typedef struct Filenamemapping201005 Filenamemapping201005;
typedef struct TY330033 TY330033;
typedef struct Tindex330019 Tindex330019;
typedef struct Tiitable297142 Tiitable297142;
typedef struct Tiipairseq297140 Tiipairseq297140;
typedef struct Table330054 Table330054;
typedef struct Keyvaluepairseq330057 Keyvaluepairseq330057;
typedef struct Memfile328202 Memfile328202;
typedef struct TY290961 TY290961;
typedef struct Tiipair297138 Tiipair297138;
typedef struct Keyvaluepair330060 Keyvaluepair330060;
typedef NU8 Tnimkind3403;
typedef NU8 Tnimtypeflag3409Set;
typedef N_NIMCALL_PTR(void, TY3489) (void* p0, NI op0);
typedef N_NIMCALL_PTR(void*, TY3494) (void* p0);
struct TNimType {
NI size;
Tnimkind3403 kind;
Tnimtypeflag3409Set flags;
TNimType* base;
TNimNode* node;
void* finalizer;
TY3489 marker;
TY3494 deepcopy;
};
typedef NU8 Tnimnodekind3405;
struct TNimNode {
Tnimnodekind3405 kind;
NI offset;
TNimType* typ;
NCSTRING name;
NI len;
TNimNode** sons;
};
typedef N_NIMCALL_PTR(void, Globalmarkerproc55402) (void);
struct TGenericSeq {
NI len;
NI reserved;
};
struct NimStringDesc {
TGenericSeq Sup;
NIM_CHAR data[SEQ_DECL_SIZE];
};
struct Cell46904 {
NI refcount;
TNimType* typ;
};
struct Cellseq46920 {
NI len;
NI cap;
Cell46904** d;
};
typedef Smallchunk29039* TY29100[512];
typedef Trunk29010* Trunkbuckets29012[256];
struct Intset29014 {
Trunkbuckets29012 data;
};
struct Memregion29085 {
NI minlargeobj;
NI maxlargeobj;
TY29100 freesmallchunks;
Llchunk29079* llmem;
NI currmem;
NI maxmem;
NI freemem;
NI lastsize;
Bigchunk29041* freechunkslist;
Intset29014 chunkstarts;
Avlnode29083* root;
Avlnode29083* deleted;
Avlnode29083* last;
Avlnode29083* freeavlnodes;
NIM_BOOL locked;
};
struct Gcstat49414 {
NI stackscans;
NI cyclecollections;
NI maxthreshold;
NI maxstacksize;
NI maxstackcells;
NI cycletablesize;
NI64 maxpause;
};
struct Cellset46916 {
NI counter;
NI max;
Pagedesc46912* head;
Pagedesc46912** data;
};
struct Gcheap49418 {
Gcstack49416* stack;
void* stackbottom;
NI cyclethreshold;
Cellseq46920 zct;
Cellseq46920 decstack;
Cellseq46920 tempstack;
NI recgclock;
Memregion29085 region;
Gcstat49414 stat;
Cellset46916 marked;
Cellseq46920 additionalroots;
};
struct Intset266030 {
NI counter;
NI max;
Trunk266026* head;
Trunkseq266028* data;
};
struct TNimObject {
TNimType* m_type;
};
struct Tidobj197004 {
TNimObject Sup;
NI id;
};
typedef NU8 Tsymkind290435;
struct Tstrtable290806 {
NI counter;
Tsymseq290804* data;
};
typedef NU16 Tmagic290524;
struct Tlineinfo189336 {
NI16 line;
NI16 col;
NI32 fileindex;
};
typedef NU32 Tsymflag290184Set;
typedef NU32 Toption168009Set;
typedef NU8 Tlockind290808;
typedef NU8 Tstorageloc290812;
typedef NU16 Tlocflag290810Set;
struct Tloc290816 {
Tlockind290808 k;
Tstorageloc290812 s;
Tlocflag290810Set flags;
Ttype290840* t;
Ropeobj177006* r;
};
struct Tsym290834 {
Tidobj197004 Sup;
Tsymkind290435 kind;
union{
struct {Ttypeseq290836* typeinstcache;
} S1;
struct {TY290929* procinstcache;
Tsym290834* gcunsafetyreason;
} S2;
struct {TY290929* usedgenerics;
Tstrtable290806 tab;
} S3;
struct {Tsym290834* guard;
NI bitsize;
} S4;
} kindU;
Tmagic290524 magic;
Ttype290840* typ;
Tident197010* name;
Tlineinfo189336 info;
Tsym290834* owner;
Tsymflag290184Set flags;
Tnode290802* ast;
Toption168009Set options;
NI position;
NI offset;
Tloc290816 loc;
Tlib290820* annex;
Tnode290802* constraint;
};
struct TY201018 {
NimStringDesc* Field0;
NI Field1;
};
struct Tpasscontext339002 {
TNimObject Sup;
NIM_BOOL fromcache;
};
typedef Ropeobj177006* Tcfilesections527009[18];
typedef NU8 Codegenflag527025Set;
struct Tidtable290850 {
NI counter;
Tidpairseq290848* data;
};
struct Tlinkedlist147013 {
Tlistentry147007* head;
Tlistentry147007* tail;
NI counter;
};
struct Tnodetable290862 {
NI counter;
Tnodepairseq290860* data;
};
typedef Ropeobj177006* TY527136[10];
struct Tcgen527027 {
Tpasscontext339002 Sup;
Tcfilesections527009 s;
Codegenflag527025Set flags;
Tsym290834* module;
NimStringDesc* filename;
NimStringDesc* cfilename;
Ropeobj177006* tmpbase;
Tidtable290850 typecache;
Tidtable290850 forwtypecache;
Intset266030 declaredthings;
Intset266030 declaredprotos;
Tlinkedlist147013 headerfiles;
Intset266030 typeinfomarker;
Tcproc527021* initproc;
Tcproc527021* postinitproc;
Tcproc527021* preinitproc;
Ttypeseq290836* typestack;
Tnodetable290862 datacache;
Tsymseq290804* forwardedprocs;
NI typenodes;
NI nimtypes;
Ropeobj177006* typenodesname;
Ropeobj177006* nimtypesname;
NI labels;
TY527136 extensionloaders;
Ropeobj177006* injectstmt;
};
struct Debuginfo201009 {
NI version;
TY201021* files;
TY201023* enums;
NIM_BOOL conflicts;
};
struct Tident197010 {
Tidobj197004 Sup;
NimStringDesc* s;
Tident197010* next;
NI h;
};
struct Tcproc527021 {
Tsym290834* prc;
NIM_BOOL beforeretneeded;
NIM_BOOL threadvaraccessed;
Tlineinfo189336 lastlineinfo;
Tnodeseq290796* nestedtrystmts;
NI inexceptblock;
TY189350* finallysafepoints;
NI labels;
TY527095* blocks;
NI breakidx;
Toption168009Set options;
NI maxframelen;
Tcgen527027* module;
NI withinloop;
NI splitdecls;
NI gcframeid;
Ropeobj177006* gcframetype;
};
typedef NU8 Tsymflag290184;
typedef NU8 Codegenflag527025;
typedef NU8 Toption168009;
typedef NU64 Tglobaloption168013Set;
typedef NU8 Tglobaloption168013;
typedef NU8 Tcommands168076;
typedef NU16 Tnodeflag290427Set;
typedef NU8 Tnodekind290020;
struct Tnode290802 {
Ttype290840* typ;
Tlineinfo189336 info;
Tnodeflag290427Set flags;
Tnodekind290020 kind;
union{
struct {NI64 intval;
} S1;
struct {NF floatval;
} S2;
struct {NimStringDesc* strval;
} S3;
struct {Tsym290834* sym;
} S4;
struct {Tident197010* ident;
} S5;
struct {Tnodeseq290796* sons;
} S6;
} kindU;
NimStringDesc* comment;
};
typedef Ropeobj177006* TY531289[1];
typedef NU8 Tlocflag290810;
struct Tlistentry147007 {
TNimObject Sup;
Tlistentry147007* prev;
Tlistentry147007* next;
};
typedef NU8 Tlibkind290818;
struct Tlib290820 {
Tlistentry147007 Sup;
Tlibkind290818 kind;
NIM_BOOL generated;
NIM_BOOL isoverriden;
Ropeobj177006* name;
Tnode290802* path;
};
typedef NU8 Tcfilesection527005;
typedef NU8 Ttypekind290244;
typedef NU8 Tcallingconvention290002;
typedef NU32 Ttypeflag290431Set;
struct Ttype290840 {
Tidobj197004 Sup;
Ttypekind290244 kind;
Tcallingconvention290002 callconv;
Ttypeflag290431Set flags;
Ttypeseq290836* sons;
Tnode290802* n;
Tsym290834* owner;
Tsym290834* sym;
Tsym290834* destructor;
Tsym290834* deepcopy;
Tsym290834* assignment;
TY290960* methods;
NI64 size;
NI16 align;
NI16 locklevel;
Tloc290816 loc;
};
typedef Ropeobj177006* TY530811[2];
typedef NU8 Tctypekind527007;
typedef NU64 Ttypekind290244Set;
typedef NU8 Ttypeflag290431;
typedef NimStringDesc* TY531943[14];
typedef NU8 Tprefereddesc318011;
typedef Ropeobj177006* TY177507[1];
struct Enumdesc201007 {
NI size;
NU32 owner;
NI id;
NimStringDesc* name;
TY201017* values;
};
typedef Ropeobj177006* TY533235[4];
typedef NimStringDesc* TY290016[10];
typedef Ropeobj177006* TY533238[3];
struct Ropeobj177006 {
TNimObject Sup;
Ropeobj177006* left;
Ropeobj177006* right;
NI length;
NimStringDesc* data;
};
typedef NU8 Tinfoccprop271004Set;
struct Tinfocc271008 {
NimStringDesc* Field0;
NimStringDesc* Field1;
NimStringDesc* Field2;
NimStringDesc* Field3;
NimStringDesc* Field4;
NimStringDesc* Field5;
NimStringDesc* Field6;
NimStringDesc* Field7;
NimStringDesc* Field8;
NimStringDesc* Field9;
NimStringDesc* Field10;
NimStringDesc* Field11;
NimStringDesc* Field12;
NimStringDesc* Field13;
NimStringDesc* Field14;
NimStringDesc* Field15;
NimStringDesc* Field16;
NimStringDesc* Field17;
NimStringDesc* Field18;
NimStringDesc* Field19;
Tinfoccprop271004Set Field20;
};
typedef Tinfocc271008 TY271427[13];
typedef NU8 Tsystemcc271002;
typedef NU8 Tnodeflag290427;
typedef NU8 Tcprocsection527011;
typedef Ropeobj177006* Tcprocsections527013[3];
struct Tblock527019 {
NI id;
Ropeobj177006* label;
Tcprocsections527013 sections;
NIM_BOOL isloop;
NI16 nestedtrystmts;
NI16 nestedexceptstmts;
NI16 framelen;
};
typedef NU8 Tgcmode168080;
typedef NU8 Ttypeinforeason535016;
struct Ttraversalclosure535019 {
Tcproc527021* p;
NimStringDesc* visitorfrmt;
};
typedef NU8 Ttypefieldresult318145;
typedef NU8 Tinfoccprop271004;
typedef Ropeobj177006* TY534847[6];
typedef Ropeobj177006* TY534401[7];
typedef Ropeobj177006* TY534475[5];
typedef NU16 Tmsgkind189002;
typedef NU8 Tassignmentflag536302Set;
typedef NU8 Tassignmentflag536302;
typedef NimStringDesc* TY550655[19];
typedef NimStringDesc* TY549642[3];
typedef NimStringDesc* TY554764[4];
typedef NimStringDesc* TY549828[42];
typedef NimStringDesc* TY549281[7];
typedef NU8 Trenderflag309004Set;
typedef NimStringDesc* TY555052[2];
typedef NU8 Tclosuretypekind533679;
typedef NimStringDesc* TY554428[6];
typedef NU8 Tanalysisresult471003;
typedef NU8 char136Set[32];
typedef NU8 Tdistinctcompare322427;
typedef NU8 Ttypecmpflag322429Set;
typedef NU16 Tspecialword273003;
typedef NU8 Tsystemos175004;
struct Tfileinfo189334 {
NimStringDesc* fullpath;
NimStringDesc* projpath;
NimStringDesc* shortname;
Ropeobj177006* quotedname;
Ropeobj177006* quotedfullname;
TY189350* lines;
NimStringDesc* dirtyfile;
};
typedef NU8 Tinfoosprop175031Set;
struct Tinfoos175035 {
NimStringDesc* Field0;
NimStringDesc* Field1;
NimStringDesc* Field2;
NimStringDesc* Field3;
NimStringDesc* Field4;
NimStringDesc* Field5;
NimStringDesc* Field6;
NimStringDesc* Field7;
NimStringDesc* Field8;
NimStringDesc* Field9;
NimStringDesc* Field10;
NimStringDesc* Field11;
Tinfoosprop175031Set Field12;
};
typedef Tinfoos175035 TY175082[24];
typedef NU8 Tendian175474;
struct Tinfocpu175476 {
NimStringDesc* Field0;
NI Field1;
Tendian175474 Field2;
NI Field3;
NI Field4;
};
typedef Tinfocpu175476 TY175510[19];
typedef NU8 Tsystemcpu175452;
struct Tstrentry147009 {
Tlistentry147007 Sup;
NimStringDesc* data;
};
struct TY124315 {
NimStringDesc* Field0;
NimStringDesc* Field1;
NimStringDesc* Field2;
};
struct Gcstack49416 {
Gcstack49416* prev;
Gcstack49416* next;
void* starts;
void* pos;
NI maxstacksize;
};
struct Basechunk29037 {
NI prevsize;
NI size;
NIM_BOOL used;
};
struct Smallchunk29039 {
Basechunk29037 Sup;
Smallchunk29039* next;
Smallchunk29039* prev;
Freecell29029* freelist;
NI free;
NI acc;
NF data;
};
struct Llchunk29079 {
NI size;
NI acc;
Llchunk29079* next;
};
struct Bigchunk29041 {
Basechunk29037 Sup;
Bigchunk29041* next;
Bigchunk29041* prev;
NI align;
NF data;
};
typedef NI TY29018[16];
struct Trunk29010 {
Trunk29010* next;
NI key;
TY29018 bits;
};
typedef Avlnode29083* TY29090[2];
struct Avlnode29083 {
TY29090 link;
NI key;
NI upperbound;
NI level;
};
struct Pagedesc46912 {
Pagedesc46912* next;
NI key;
TY29018 bits;
};
struct Trunk266026 {
Trunk266026* next;
NI key;
TY29018 bits;
};
struct Tidpair290846 {
Tidobj197004* key;
TNimObject* val;
};
struct Tnodepair290858 {
NI h;
Tnode290802* key;
NI val;
};
struct Filenamemapping201005 {
NimStringDesc* package;
NimStringDesc* file;
NU32 mangled;
};
typedef NU8 Treasonforrecompile330002;
struct Tiitable297142 {
NI counter;
Tiipairseq297140* data;
};
struct Tindex330019 {
NI lastidxkey;
NI lastidxval;
Tiitable297142 tab;
NimStringDesc* r;
NI offset;
};
struct Table330054 {
Keyvaluepairseq330057* data;
NI counter;
};
struct Memfile328202 {
void* mem;
NI size;
NI fhandle;
NI maphandle;
NIM_BOOL wasopened;
};
struct Trodreader330021 {
TNimObject Sup;
NI pos;
NCSTRING s;
Toption168009Set options;
Treasonforrecompile330002 reason;
TY330033* moddeps;
TY330033* files;
NI dataidx;
NI convertersidx;
NI initidx;
NI interfidx;
NI compilerprocsidx;
NI methodsidx;
NimStringDesc* filename;
Tindex330019 index;
Tindex330019 imports;
NI readerindex;
NI line;
NI moduleid;
Table330054 syms;
Memfile328202 memfile;
Tsymseq290804* methods;
NimStringDesc* origfile;
NIM_BOOL inviewmode;
};
struct TY290961 {
NI Field0;
Tsym290834* Field1;
};
struct Freecell29029 {
Freecell29029* next;
NI zerofield;
};
struct Tinstantiation290824 {
Tsym290834* sym;
Ttypeseq290836* concretetypes;
NI compilesid;
};
struct Tiipair297138 {
NI key;
NI val;
};
struct Keyvaluepair330060 {
NI Field0;
NI Field1;
Tsym290834* Field2;
};
struct Ttypeseq290836 {
TGenericSeq Sup;
Ttype290840* data[SEQ_DECL_SIZE];
};
struct TY527153 {
TGenericSeq Sup;
Tcgen527027* data[SEQ_DECL_SIZE];
};
struct Tsymseq290804 {
TGenericSeq Sup;
Tsym290834* data[SEQ_DECL_SIZE];
};
struct TY201017 {
TGenericSeq Sup;
TY201018 data[SEQ_DECL_SIZE];
};
struct TY134602 {
TGenericSeq Sup;
NimStringDesc* data[SEQ_DECL_SIZE];
};
struct Tbitset337004 {
TGenericSeq Sup;
NI8 data[SEQ_DECL_SIZE];
};
struct TY527095 {
TGenericSeq Sup;
Tblock527019 data[SEQ_DECL_SIZE];
};
struct TY189350 {
TGenericSeq Sup;
Ropeobj177006* data[SEQ_DECL_SIZE];
};
struct Tnodeseq290796 {
TGenericSeq Sup;
Tnode290802* data[SEQ_DECL_SIZE];
};
struct TY189612 {
TGenericSeq Sup;
Tfileinfo189334 data[SEQ_DECL_SIZE];
};
struct Trunkseq266028 {
TGenericSeq Sup;
Trunk266026* data[SEQ_DECL_SIZE];
};
struct TY290929 {
TGenericSeq Sup;
Tinstantiation290824* data[SEQ_DECL_SIZE];
};
struct Tidpairseq290848 {
TGenericSeq Sup;
Tidpair290846 data[SEQ_DECL_SIZE];
};
struct Tnodepairseq290860 {
TGenericSeq Sup;
Tnodepair290858 data[SEQ_DECL_SIZE];
};
struct TY201021 {
TGenericSeq Sup;
Filenamemapping201005 data[SEQ_DECL_SIZE];
};
struct TY201023 {
TGenericSeq Sup;
Enumdesc201007 data[SEQ_DECL_SIZE];
};
struct TY290960 {
TGenericSeq Sup;
TY290961 data[SEQ_DECL_SIZE];
};
struct TY330033 {
TGenericSeq Sup;
NI32 data[SEQ_DECL_SIZE];
};
struct Tiipairseq297140 {
TGenericSeq Sup;
Tiipair297138 data[SEQ_DECL_SIZE];
};
struct Keyvaluepairseq330057 {
TGenericSeq Sup;
Keyvaluepair330060 data[SEQ_DECL_SIZE];
};
N_NIMCALL(void, nimGCvisit)(void* d0, NI op0);
N_NIMCALL(void, T839829468_2)(void);
N_NIMCALL(void, nimRegisterGlobalMarker)(Globalmarkerproc55402 markerproc0);
N_NIMCALL(void, T839829468_3)(void);
N_NIMCALL(Ropeobj177006*, rope_177277_2381377266)(NimStringDesc* s0);
static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0);
static N_INLINE(Cell46904*, usrtocell_51040_1689653243)(void* usr0);
static N_INLINE(void, rtladdzct_52201_1689653243)(Cell46904* c0);
N_NOINLINE(void, addzct_51017_1689653243)(Cellseq46920* s0, Cell46904* c0);
N_NIMCALL(void, T839829468_5)(void);
N_NIMCALL(void, T839829468_6)(void);
static N_INLINE(void, nimGCunrefNoCycle)(void* p0);
N_NIMCALL(void*, newSeqRC1)(TNimType* typ0, NI len0);
N_NIMCALL(void, T839829468_7)(void);
N_NIMCALL(void, initintset_266885_2627731572)(Intset266030* Result);
N_NOINLINE(void, chckNil)(void* p0);
N_NIMCALL(void, genericReset)(void* dest0, TNimType* mt0);
N_NIMCALL(void, T839829468_8)(void);
N_NIMCALL(Tcgen527027*, newmodule_561045_839829468)(Tsym290834* module0);
N_NIMCALL(Tcgen527027*, getcgenmodule_530226_839829468)(Tsym290834* s0);
N_NIMCALL(void, internalerror_194113_155036129)(NimStringDesc* errmsg0);
N_NIMCALL(NimStringDesc*, HEX24_194185_1689653243)(TY201018 x0);
N_NIMCALL(Tcgen527027*, rawnewmodule_561038_839829468)(Tsym290834* module0);
N_NIMCALL(Tcgen527027*, rawnewmodule_560663_839829468)(Tsym290834* module0, NimStringDesc* filename0);
N_NIMCALL(void*, newObj)(TNimType* typ0, NI size0);
static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0);
static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0);
N_NIMCALL(NimStringDesc*, HEX24_8401_1689653243)(NU64 x0);
N_NIMCALL(NU32, hashowner_530977_839829468)(Tsym290834* s0);
N_NIMCALL(NU32, register_201121_1926258066)(Debuginfo201009* self0, NimStringDesc* package0, NimStringDesc* file0);
N_NIMCALL(NimStringDesc*, rawNewString)(NI space0);
N_NIMCALL(void, initlinkedlist_147031_3771138726)(Tlinkedlist147013* list0);
N_NIMCALL(NimStringDesc*, copyStringRC1)(NimStringDesc* src0);
N_NIMCALL(void, initidtable_294019_850551059)(Tidtable290850* x0);
N_NIMCALL(Tcproc527021*, newproc_527206_3723162438)(Tsym290834* prc0, Tcgen527027* module0);
static N_INLINE(void, asgnRef)(void** dest0, void* src0);
static N_INLINE(void, incref_53019_1689653243)(Cell46904* c0);
static N_INLINE(void, decref_52601_1689653243)(Cell46904* c0);
N_NIMCALL(Toption168009Set, initprocoptions_560635_839829468)(Tcgen527027* m0);
N_NIMCALL(Tcproc527021*, newpreinitproc_560625_839829468)(Tcgen527027* m0);
N_NIMCALL(Tcproc527021*, newpostinitproc_560630_839829468)(Tcgen527027* m0);
N_NIMCALL(void, initnodetable_294085_850551059)(Tnodetable290862* x0);
N_NIMCALL(Ropeobj177006*, gettempname_531596_839829468)(Tcgen527027* m0);
N_NIMCALL(Ropeobj177006*, HEX26_177418_2381377266)(Ropeobj177006* a0, Ropeobj177006* b0);
N_NIMCALL(Ropeobj177006*, rope_177401_2381377266)(NI64 i0);
N_NIMCALL(NimStringDesc*, tofullpath_190264_155036129)(NI32 fileidx0);
N_NIMCALL(TGenericSeq*, setLengthSeq)(TGenericSeq* seq0, NI elemsize0, NI newlen0);
N_NIMCALL(NimStringDesc*, tofilename_190260_155036129)(NI32 fileidx0);
N_NIMCALL(NimStringDesc*, noschangeFileExt)(NimStringDesc* filename0, NimStringDesc* ext0);
N_NIMCALL(NimStringDesc*, completecfilepath_271854_2528170400)(NimStringDesc* cfile0, NIM_BOOL createsubdir0);
N_NIMCALL(void, readmergeinfo_528613_2760143328)(NimStringDesc* cfilename0, Tcgen527027* m0);
N_NIMCALL(NimStringDesc*, getcfile_561204_839829468)(Tcgen527027* m0);
N_NIMCALL(NimStringDesc*, copyString)(NimStringDesc* src0);
N_NIMCALL(NimStringDesc*, withpackagename_169065_2607990831)(NimStringDesc* path0);
static N_INLINE(NIM_BOOL, skipcodegen_339085_2355241294)(Tnode290802* n0);
N_NIMCALL(void, genstmts_537244_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(void, expr_537248_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, fillprocloc_537201_839829468)(Tsym290834* sym0);
N_NIMCALL(void, fillloc_530282_839829468)(Tloc290816* a0, Tlockind290808 k0, Ttype290840* typ0, Ropeobj177006* r0, Tstorageloc290812 s0);
N_NIMCALL(void, unsureAsgnRef)(void** dest0, void* src0);
N_NIMCALL(Ropeobj177006*, manglename_531205_839829468)(Tsym290834* s0);
N_NIMCALL(NIM_BOOL, iskeyword_530960_839829468)(Tident197010* w0);
N_NIMCALL(NimStringDesc*, mangle_526847_2036603609)(NimStringDesc* name0);
N_NIMCALL(void, add_177487_2381377266)(Ropeobj177006** a0, NimStringDesc* b0);
N_NIMCALL(void, add_177482_2381377266)(Ropeobj177006** a0, Ropeobj177006* b0);
N_NIMCALL(Ropeobj177006*, HEX25_177905_2381377266)(NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(void, genprocprototype_537254_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(void, useheader_530369_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(NIM_BOOL, includestr_147249_3771138726)(Tlinkedlist147013* list0, NimStringDesc* data0);
N_NIMCALL(NimStringDesc*, getstr_295230_850551059)(Tnode290802* a0);
N_NIMCALL(Tsym290834*, getmodule_297123_2984716966)(Tsym290834* s0);
N_NIMCALL(NIM_BOOL, containsorincl_266862_2627731572)(Intset266030* s0, NI key0);
N_NIMCALL(Ropeobj177006*, ropecg_530407_839829468)(Tcgen527027* m0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(NimStringDesc*, nimIntToStr)(NI x0);
static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0);
N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI start_78810_1689653243, NI last0);
N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI first0, NI last0);
N_NIMCALL(Ropeobj177006*, cgsym_530403_839829468)(Tcgen527027* m0, NimStringDesc* name0);
N_NIMCALL(Tsym290834*, getcompilerproc_336746_3937434831)(NimStringDesc* name0);
N_NIMCALL(void, genproc_530951_839829468)(Tcgen527027* m0, Tsym290834* prc0);
N_NIMCALL(NIM_BOOL, isactivated_559431_839829468)(Tsym290834* prc0);
N_NIMCALL(void, addforwardedproc_530203_839829468)(Tcgen527027* m0, Tsym290834* prc0);
N_NIMCALL(TGenericSeq*, incrSeqV2)(TGenericSeq* seq0, NI elemsize0);
N_NIMCALL(void, genprocnoforward_558906_839829468)(Tcgen527027* m0, Tsym290834* prc0);
N_NIMCALL(void, genprocaux_558284_839829468)(Tcgen527027* m0, Tsym290834* prc0);
N_NIMCALL(Ropeobj177006*, genprocheader_533867_839829468)(Tcgen527027* m0, Tsym290834* prc0);
N_NIMCALL(void, genclinedir_530813_839829468)(Ropeobj177006** r0, Tlineinfo189336 info0);
N_NIMCALL(void, genclinedir_530725_839829468)(Ropeobj177006** r0, NimStringDesc* filename0, NI line0);
N_NIMCALL(void, addf_178205_2381377266)(Ropeobj177006** c0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(NimStringDesc*, makesinglelinecstring_526835_2036603609)(NimStringDesc* s0);
N_NIMCALL(NI, safelinenm_530721_839829468)(Tlineinfo189336 info0);
static N_INLINE(NI, tolinenumber_190415_155036129)(Tlineinfo189336 info0);
N_NIMCALL(void, genprocparams_532115_839829468)(Tcgen527027* m0, Ttype290840* t0, Ropeobj177006** rettype0, Ropeobj177006** params0, Intset266030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0);
N_NIMCALL(NIM_BOOL, isinvalidreturntype_531548_839829468)(Ttype290840* rettype0);
N_NIMCALL(Tctypekind527007, maptype_531393_839829468)(Ttype290840* typ0);
N_NIMCALL(Tctypekind527007, mapsettype_531389_839829468)(Ttype290840* typ0);
N_NIMCALL(NI64, getsize_318135_3876443242)(Ttype290840* typ0);
N_NIMCALL(Ttype290840*, lastson_293377_850551059)(Ttype290840* n0);
N_NIMCALL(NI64, firstord_318001_3876443242)(Ttype290840* t0);
N_NIMCALL(Ttype290840*, skiptypes_294099_850551059)(Ttype290840* t0, Ttypekind290244Set kinds0);
N_NIMCALL(NIM_BOOL, isimportedcpptype_531476_839829468)(Ttype290840* t0);
N_NIMCALL(NIM_BOOL, needscomplexassignment_531509_839829468)(Ttype290840* typ0);
N_NIMCALL(NIM_BOOL, containsgarbagecollectedref_318117_3876443242)(Ttype290840* typ0);
static N_INLINE(NIM_BOOL, isobjlackingtypefield_531513_839829468)(Ttype290840* typ0);
N_NIMCALL(NIM_BOOL, ispureobject_318138_3876443242)(Ttype290840* typ0);
N_NIMCALL(Ropeobj177006*, gettypedescaux_531503_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0);
N_NIMCALL(Ttype290840*, getuniquetype_526640_2036603609)(Ttype290840* key0);
N_NIMCALL(Ropeobj177006*, gettypepre_531972_839829468)(Tcgen527027* m0, Ttype290840* typ0);
N_NIMCALL(Ropeobj177006*, getsimpletypedesc_531936_839829468)(Tcgen527027* m0, Ttype290840* typ0);
N_NIMCALL(Ropeobj177006*, typenameorliteral_531898_839829468)(Ttype290840* t0, NimStringDesc* literal0);
N_NIMCALL(Ropeobj177006*, gettypename_531313_839829468)(Ttype290840* typ0);
N_NIMCALL(Ropeobj177006*, typename_531292_839829468)(Ttype290840* typ0);
N_NIMCALL(NimStringDesc*, reprEnum)(NI e0, TNimType* typ0);
N_NIMCALL(Ropeobj177006*, cachegettype_531591_839829468)(Tidtable290850 tab0, Ttype290840* key0);
N_NIMCALL(TNimObject*, idtableget_297086_2984716966)(Tidtable290850 t0, Tidobj197004* key0);
N_NIMCALL(NimStringDesc*, typetostring_318017_3876443242)(Ttype290840* typ0, Tprefereddesc318011 prefer0);
N_NIMCALL(Ttype290840*, elemtype_318394_3876443242)(Ttype290840* t0);
N_NIMCALL(Ropeobj177006*, HEX26_177447_2381377266)(Ropeobj177006* a0, NimStringDesc* b0);
N_NIMCALL(Ropeobj177006*, gettypeforward_532039_839829468)(Tcgen527027* m0, Ttype290840* typ0);
N_NIMCALL(NIM_BOOL, isimportedtype_531449_839829468)(Ttype290840* t0);
N_NIMCALL(NimStringDesc*, getforwardstructformat_532015_839829468)(Tcgen527027* m0);
N_NIMCALL(Ropeobj177006*, structorunion_532001_839829468)(Ttype290840* t0);
N_NIMCALL(void, idtableput_297094_2984716966)(Tidtable290850* t0, Tidobj197004* key0, TNimObject* val0);
N_NIMCALL(void, pushtype_531958_839829468)(Tcgen527027* m0, Ttype290840* typ0);
N_NIMCALL(Ropeobj177006*, gettypedescweak_532079_839829468)(Tcgen527027* m0, Ttype290840* t0, Intset266030* check0);
N_NIMCALL(void, internalerror_194100_155036129)(Tlineinfo189336 info0, NimStringDesc* errmsg0);
N_NIMCALL(NIM_BOOL, hasenum_201230_1926258066)(Debuginfo201009 self0, NimStringDesc* ename0, NI id0, NU32 owner0);
N_NIMCALL(void*, newSeq)(TNimType* typ0, NI len0);
static N_INLINE(NI, len_291081_850551059)(Tnode290802* n0);
N_NIMCALL(void, registerenum_201419_1926258066)(Debuginfo201009* self0, Enumdesc201007* ed0);
N_NIMCALL(void, genericSeqAssign)(void* dest0, void* src_86004_1689653243, TNimType* mt0);
N_NIMCALL(void, appcg_530632_839829468)(Tcgen527027* m0, Ropeobj177006** c0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(NI64, lengthord_318007_3876443242)(Ttype290840* t0);
N_NIMCALL(NIM_BOOL, scancppgenericslot_532827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0);
N_NIMCALL(Ttype290840*, resolvestarsincpptype_532891_839829468)(Ttype290840* typ0, NI idx0, NI stars0);
N_NIMCALL(NI, len_293339_850551059)(Ttype290840* n0);
N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI start0);
N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI first0);
N_NIMCALL(Ropeobj177006*, getrecorddesc_532643_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0);
N_NIMCALL(Ropeobj177006*, getrecordfields_532636_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0);
N_NIMCALL(Ropeobj177006*, genrecordfieldsaux_532421_839829468)(Tcgen527027* m0, Tnode290802* n0, Ropeobj177006* accessexpr0, Ttype290840* rectype0, Intset266030* check0);
N_NIMCALL(NI, sonslen_293351_850551059)(Tnode290802* n0);
N_NIMCALL(Tnode290802*, lastson_293364_850551059)(Tnode290802* n0);
N_NIMCALL(Ropeobj177006*, HEX26_177452_2381377266)(NimStringDesc* a0, Ropeobj177006* b0);
N_NIMCALL(Ropeobj177006*, manglerecfieldname_532361_839829468)(Tsym290834* field0, Ttype290840* rectype0);
N_NIMCALL(NimStringDesc*, manglefield_530973_839829468)(Tident197010* name0);
N_NIMCALL(NIM_CHAR, nsuToUpperAsciiChar)(NIM_CHAR c0);
N_NIMCALL(Ropeobj177006*, gettupledesc_532777_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0);
N_NIMCALL(NI, sonslen_293327_850551059)(Ttype290840* n0);
N_NIMCALL(void, excl_266841_2627731572)(Intset266030* s0, NI key0);
static N_INLINE(NIM_BOOL, iscompiletimeonly_326706_3876443242)(Ttype290840* t0);
N_NIMCALL(Tstorageloc290812, paramstorageloc_532098_839829468)(Tsym290834* param0);
N_NIMCALL(NIM_BOOL, ccgintroducedptr_531609_839829468)(Tsym290834* s0);
N_NIMCALL(Tctypekind527007, mapreturntype_531445_839829468)(Ttype290840* typ0);
N_NIMCALL(Tnode290802*, easyresultasgn_558191_839829468)(Tnode290802* n0);
static N_INLINE(Tnode290802*, HEX5BHEX5D_291238_850551059)(Tnode290802* n0, NI i0);
N_NIMCALL(Tnode290802*, getbody_333227_1724185294)(Tsym290834* s0);
N_NIMCALL(Ropeobj177006*, localvardecl_536532_839829468)(Tcproc527021* p0, Tsym290834* s0);
N_NIMCALL(Ropeobj177006*, gettypedesc_533671_839829468)(Tcgen527027* m0, Ttype290840* typ0);
N_NIMCALL(void, initlocexprsingleuse_537289_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0);
N_NIMCALL(void, initloc_530273_839829468)(Tloc290816* result0, Tlockind290808 k0, Ttype290840* typ0, Tstorageloc290812 s0);
N_NIMCALL(void, linefmt_530714_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
static N_INLINE(Ropeobj177006**, s_527179_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0);
N_NIMCALL(Ropeobj177006*, indentline_530656_839829468)(Tcproc527021* p0, Ropeobj177006* r0);
N_NIMCALL(void, prepend_177893_2381377266)(Ropeobj177006** a0, Ropeobj177006* b0);
N_NIMCALL(Ropeobj177006*, rdloc_536188_839829468)(Tloc290816 a0);
N_NIMCALL(void, assignlocalvar_536614_839829468)(Tcproc527021* p0, Tsym290834* s0);
N_NIMCALL(void, line_530690_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, Ropeobj177006* r0);
N_NIMCALL(void, localdebuginfo_536449_839829468)(Tcproc527021* p0, Tsym290834* s0);
N_NIMCALL(void, linef_530700_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(Ropeobj177006*, makecstring_189638_155036129)(NimStringDesc* s0);
N_NIMCALL(NimStringDesc*, nsuNormalize)(NimStringDesc* s0);
N_NIMCALL(Ropeobj177006*, gentypeinfo_533941_839829468)(Tcgen527027* m0, Ttype290840* t_533944_839829468);
N_NIMCALL(Tcgen527027*, bmod_527201_3723162438)(Tsym290834* module0);
N_NIMCALL(void, gentypeinfoauxbase_533960_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0, Ropeobj177006* base0);
N_NIMCALL(NIM_BOOL, canformacycle_318123_3876443242)(Ttype290840* typ0);
N_NIMCALL(void, gentupleinfo_534549_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0);
N_NIMCALL(Ropeobj177006*, getnimnode_533945_839829468)(Tcgen527027* m0);
N_NIMCALL(Ttype290840*, fakeclosuretype_535010_839829468)(Tsym290834* owner0);
N_NIMCALL(Ttype290840*, newtype_293107_850551059)(Ttypekind290244 kind0, Tsym290834* owner0);
N_NIMCALL(void, rawaddson_294394_850551059)(Ttype290840* father0, Ttype290840* son0);
N_NIMCALL(void, gentypeinfoaux_534027_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0);
N_NIMCALL(Ropeobj177006*, gentraverseproc_535632_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttypeinforeason535016 reason0);
N_NIMCALL(void, gentraverseprocseq_535399_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ0);
N_NIMCALL(void, gettemp_535032_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816* result0, NIM_BOOL needsinit0);
N_NIMCALL(void, constructloc_536388_839829468)(Tcproc527021* p0, Tloc290816 loc0, NIM_BOOL istemp0);
static N_INLINE(NIM_BOOL, iscomplexvaluetype_536317_839829468)(Ttype290840* t0);
N_NIMCALL(void, usestringh_530345_839829468)(Tcgen527027* m0);
N_NIMCALL(Ropeobj177006*, addrloc_536204_839829468)(Tloc290816 a0);
N_NIMCALL(void, genobjectinit_536242_839829468)(Tcproc527021* p0, Tcprocsection527011 section0, Ttype290840* t0, Tloc290816 a0, NIM_BOOL takeaddr0);
N_NIMCALL(Ttypefieldresult318145, analyseobjectwithtypefield_318149_3876443242)(Ttype290840* t0);
N_NIMCALL(Ttype290840*, getsystype_336150_3937434831)(Ttypekind290244 kind0);
N_NIMCALL(void, gentraverseproc_535022_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ_535027_839829468);
static N_INLINE(Ropeobj177006*, parentobj_535257_839829468)(Ropeobj177006* accessor0, Tcgen527027* m0);
N_NIMCALL(void, gentraverseproc_535039_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Tnode290802* n0);
N_NIMCALL(void, gencaserange_535028_839829468)(Tcproc527021* p0, Tnode290802* branch0);
N_NIMCALL(Ropeobj177006*, genliteral_537273_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(Ropeobj177006*, genliteral_547476_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* ty0);
N_NIMCALL(Ropeobj177006*, intliteral_537270_839829468)(NI64 i0);
N_NIMCALL(Ropeobj177006*, int64literal_547430_839829468)(NI64 i0);
N_NIMCALL(Ropeobj177006*, uint64literal_547442_839829468)(NU64 i0);
N_NIMCALL(NI, nodetabletestorset_340682_1142335848)(Tnodetable290862* t0, Tnode290802* key0, NI val0);
N_NIMCALL(Ropeobj177006*, getstrlit_547468_839829468)(Tcgen527027* m0, NimStringDesc* s0);
N_NIMCALL(NimStringDesc*, tostrmaxprecision_296007_3471544153)(NF f0);
N_NIMCALL(Tnode290802*, copynode_294528_850551059)(Tnode290802* src0);
N_NIMCALL(void, linecg_530707_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(void, genarrayinfo_535005_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0);
N_NIMCALL(void, gensetinfo_534867_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0);
N_NIMCALL(void, genenuminfo_534597_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0);
N_NIMCALL(void, genobjectinfo_534506_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0);
N_NIMCALL(void, genobjectfields_534104_839829468)(Tcgen527027* m0, Ttype290840* typ0, Tnode290802* n0, Ropeobj177006* expr0);
N_NIMCALL(Ropeobj177006*, discriminatortablename_534057_839829468)(Tcgen527027* m0, Ttype290840* objtype_534060_839829468, Tsym290834* d0);
N_NIMCALL(Tsym290834*, lookupinrecord_297119_2984716966)(Tnode290802* n0, Tident197010* field0);
N_NIMCALL(NI64, getordvalue_318129_3876443242)(Tnode290802* n0);
N_NIMCALL(void, gendeepcopyproc_536066_839829468)(Tcgen527027* m0, Tsym290834* s0, Ropeobj177006* result0);
N_NIMCALL(void, initlocalvar_536398_839829468)(Tcproc527021* p0, Tsym290834* v0, NIM_BOOL immediateasgn0);
N_NIMCALL(void, fillresult_531865_839829468)(Tsym290834* param0);
N_NIMCALL(void, assignparam_536994_839829468)(Tcproc527021* p0, Tsym290834* s0);
N_NIMCALL(void, closuresetup_558158_839829468)(Tcproc527021* p0, Tsym290834* prc0);
N_NIMCALL(Ropeobj177006*, initgcframe_536435_839829468)(Tcproc527021* p0);
N_NIMCALL(Ropeobj177006*, initframe_558140_839829468)(Tcproc527021* p0, Ropeobj177006* procname0, Ropeobj177006* filename0);
N_NIMCALL(Ropeobj177006*, quotedfilename_194818_155036129)(Tlineinfo189336 i0);
N_NIMCALL(void, appcg_530648_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(Ropeobj177006*, deinitgcframe_536441_839829468)(Tcproc527021* p0);
N_NIMCALL(Ropeobj177006*, deinitframe_558150_839829468)(Tcproc527021* p0);
N_NIMCALL(Tcgen527027*, findpendingmodule_530241_839829468)(Tcgen527027* m0, Tsym290834* s0);
N_NIMCALL(void, symindynamiclib_557929_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(NIM_BOOL, isgetprocaddr_557442_839829468)(Tlib290820* lib0);
N_NIMCALL(void, loaddynamiclib_557480_839829468)(Tcgen527027* m0, Tlib290820* lib0);
N_NIMCALL(void, libcandidates_169605_2607990831)(NimStringDesc* s0, TY134602** dest0);
N_NIMCALL(void, rawmessage_192612_155036129)(Tmsgkind189002 msg0, NimStringDesc* arg0);
N_NIMCALL(void, initlocexpr_537283_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0);
N_NIMCALL(Ropeobj177006*, mangledynlibproc_536816_839829468)(Tsym290834* sym0);
N_NIMCALL(NimStringDesc*, HEX24_177856_2381377266)(Ropeobj177006* r0);
N_NIMCALL(void, symindynamiclibpartial_558071_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(void, genvarprototype_537236_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(void, genvarprototypeaux_542254_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(void, declarethreadvar_536676_839829468)(Tcgen527027* m0, Tsym290834* s0, NIM_BOOL isextern0);
static N_INLINE(NIM_BOOL, emulatedthreadvars_530949_839829468)(void);
static N_INLINE(NIM_BOOL, crossescppboundary_558754_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(void, putlocintodest_537258_839829468)(Tcproc527021* p0, Tloc290816* d0, Tloc290816 s0);
N_NIMCALL(void, genassignment_537264_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0);
N_NIMCALL(void, genrefassign_536311_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0);
static N_INLINE(NIM_BOOL, usesnativegc_168177_2607990831)(void);
N_NIMCALL(void, optasgnloc_547788_839829468)(Tloc290816 a0, Ttype290840* t0, Ropeobj177006* field0, Tloc290816* Result);
N_NIMCALL(void, genoptasgntuple_548001_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0);
N_NIMCALL(void, gengenericasgn_548167_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0);
N_NIMCALL(NI, asgncomplexity_547750_839829468)(Tnode290802* n0);
N_NIMCALL(void, genoptasgnobject_548084_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0, Tnode290802* t0);
N_NIMCALL(void, genericAssign)(void* dest0, void* src0, TNimType* mt0);
N_NIMCALL(void, localerror_194085_155036129)(Tlineinfo189336 info0, NimStringDesc* arg0);
N_NIMCALL(NIM_BOOL, issimpleconst_530311_839829468)(Ttype290840* typ0);
N_NIMCALL(void, putintodest_548468_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0, Tstorageloc290812 s0);
N_NIMCALL(void, gencomplexconst_556249_839829468)(Tcproc527021* p0, Tsym290834* sym0, Tloc290816* d0);
N_NIMCALL(void, requestconstimpl_537240_839829468)(Tcproc527021* p0, Tsym290834* sym0);
N_NIMCALL(Ropeobj177006*, genconstexpr_552849_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, tobitset_338001_452470228)(Tnode290802* s0, Tbitset337004** b0);
N_NIMCALL(Ropeobj177006*, genrawsetdata_547629_839829468)(Tbitset337004* cs0, NI size0);
N_NIMCALL(NimStringDesc*, nsuToHex)(NI64 x0, NI len0);
N_NIMCALL(NI64, bitsettoword_547578_839829468)(Tbitset337004* s0, NI size0);
N_NIMCALL(Ropeobj177006*, genconstseq_557371_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* t0);
N_NIMCALL(void, appcg_530640_839829468)(Tcgen527027* m0, Tcfilesection527005 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(Ropeobj177006*, genconstsimplelist_557299_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(Ropeobj177006*, gennamedconstexpr_557284_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, accessthreadlocalvar_530945_839829468)(Tcproc527021* p0, Tsym290834* s0);
static N_INLINE(Ropeobj177006**, procsec_527194_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0);
static N_INLINE(NIM_BOOL, isemptytype_295440_850551059)(Ttype290840* t0);
N_NIMCALL(void, putdataintodest_548436_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0);
N_NIMCALL(void, genlinedir_530823_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(Ropeobj177006*, sourceline_190068_155036129)(Tlineinfo189336 i0);
N_NIMCALL(NIM_BOOL, freshlineinfo_530818_839829468)(Tcproc527021* p0, Tlineinfo189336 info0);
N_NIMCALL(void, genmagicexpr_555033_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0);
N_NIMCALL(void, genandor_552311_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0);
N_NIMCALL(Ropeobj177006*, getlabel_537217_839829468)(Tcproc527021* p0);
N_NIMCALL(void, fixlabel_537230_839829468)(Tcproc527021* p0, Ropeobj177006* labl0);
N_NIMCALL(void, unaryarith_550646_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0);
N_NIMCALL(void, unaryarithoverflow_549633_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0);
N_NIMCALL(void, binaryfloatarith_554728_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0);
N_NIMCALL(void, binaryarith_549819_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0);
N_NIMCALL(void, geneqproc_550214_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, binaryarithoverflow_549262_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0);
N_NIMCALL(Ropeobj177006*, binaryarithoverflowraw_549235_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816 a0, Tloc290816 b0, NimStringDesc* frmt0);
N_NIMCALL(Ropeobj177006*, rdcharloc_536227_839829468)(Tloc290816 a0);
N_NIMCALL(NI64, lastord_318004_3876443242)(Ttype290840* t0);
N_NIMCALL(void, genrepr_553339_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(Ropeobj177006*, lenfield_537305_839829468)(Tcproc527021* p0);
N_NIMCALL(void, gcusage_552439_839829468)(Tnode290802* n0);
N_NIMCALL(void, message_194095_155036129)(Tlineinfo189336 info0, Tmsgkind189002 msg0, NimStringDesc* arg0);
N_NIMCALL(NimStringDesc*, rendertree_309044_382274130)(Tnode290802* n0, Trenderflag309004Set renderflags0);
N_NIMCALL(void, gengettypeinfo_553383_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genswap_553638_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, unaryexpr_549209_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, binarystmt_548501_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, genstrconcat_552452_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genstrappend_552554_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genseqelemappend_552683_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genstrequals_554666_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, binaryexpr_548549_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, genisnil_550620_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, gendollar_553391_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, genof_553331_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, genof_553201_839829468)(Tcproc527021* p0, Tnode290802* x0, Ttype290840* typ0, Tloc290816* d0);
N_NIMCALL(void, globalerror_194071_155036129)(Tlineinfo189336 info0, Tmsgkind189002 msg0, NimStringDesc* arg0);
N_NIMCALL(Ropeobj177006*, genofhelper_553139_839829468)(Tcproc527021* p0, Ttype290840* dest0, Ropeobj177006* a0);
N_NIMCALL(void, gennew_552782_839829468)(Tcproc527021* p0, Tnode290802* e0);
N_NIMCALL(void, rawgennew_552741_839829468)(Tcproc527021* p0, Tloc290816 a0, Ropeobj177006* sizeexpr_552745_839829468);
N_NIMCALL(void, gennewfinalize_553110_839829468)(Tcproc527021* p0, Tnode290802* e0);
N_NIMCALL(void, gennewseq_552824_839829468)(Tcproc527021* p0, Tnode290802* e0);
N_NIMCALL(void, gennewseqaux_552795_839829468)(Tcproc527021* p0, Tloc290816 dest0, Ropeobj177006* length0);
N_NIMCALL(void, gennewseqofcap_552836_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, gensomecast_554480_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(Ropeobj177006*, getclosuretype_533683_839829468)(Tcgen527027* m0, Ttype290840* t0, Tclosuretypekind533679 kind0);
N_NIMCALL(void, genord_554474_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, unaryexprchar_549222_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, genarraylen_553415_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0);
N_NIMCALL(void, unarystmt_548527_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, gensetlengthstr_553632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, gensetlengthseq_553500_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, gensetop_554419_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0);
N_NIMCALL(void, binarystmtinexcl_553857_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(Ropeobj177006*, rdsetelemloc_553662_839829468)(Tloc290816 a0, Ttype290840* settype0);
N_NIMCALL(void, binaryexprchar_548809_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, geninop_554009_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(NIM_BOOL, fewcmps_553803_839829468)(Tnode290802* s0);
N_NIMCALL(void, geninexpraux_551496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0);
N_NIMCALL(void, binaryexprin_553837_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0, NimStringDesc* frmt0);
N_NIMCALL(void, gencall_541632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genclosurecall_538452_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0);
N_NIMCALL(Ropeobj177006*, genarg_537787_839829468)(Tcproc527021* p0, Tnode290802* n_537790_839829468, Tsym290834* param0, Tnode290802* call0);
static N_INLINE(Ropeobj177006*, genargstringtocstring_537776_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(Ropeobj177006*, openarrayloc_537665_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(Tnode290802*, skipconv_326882_3876443242)(Tnode290802* n0);
N_NIMCALL(Tmagic290524, getmagic_316502_2616423590)(Tnode290802* op0);
N_NIMCALL(Ropeobj177006*, genargnoparam_537938_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(Ropeobj177006*, getrawproctype_538459_839829468)(Tcproc527021* p0, Ttype290840* t0);
N_NIMCALL(NIM_BOOL, leftappearsonrightside_537329_839829468)(Tnode290802* le0, Tnode290802* ri0);
N_NIMCALL(Tanalysisresult471003, ispartof_471340_788060399)(Tnode290802* a0, Tnode290802* b0);
static N_INLINE(NIM_BOOL, hasnoinit_537383_839829468)(Tnode290802* call0);
N_NIMCALL(void, resetloc_536350_839829468)(Tcproc527021* p0, Tloc290816* loc0);
N_NIMCALL(Ropeobj177006*, addcomma_538464_839829468)(Ropeobj177006* r0);
N_NIMCALL(void, geninfixcall_539929_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0);
N_NIMCALL(NIM_BOOL, contains_109056_4286263276)(NimStringDesc* s0, char136Set chars0);
N_NIMCALL(Ropeobj177006*, genpatterncall_539699_839829468)(Tcproc527021* p0, Tnode290802* ri_539702_839829468, NimStringDesc* pat0, Ttype290840* typ_539704_839829468);
N_NIMCALL(Ropeobj177006*, genotherarg_537277_839829468)(Tcproc527021* p0, Tnode290802* ri0, NI i0, Ttype290840* typ0);
N_NIMCALL(Ropeobj177006*, genthisarg_539475_839829468)(Tcproc527021* p0, Tnode290802* ri_539478_839829468, NI i0, Ttype290840* typ0);
N_NIMCALL(Tnode290802*, skipaddrderef_539433_839829468)(Tnode290802* node0);
N_NIMCALL(void, fixupcall_537410_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0, Ropeobj177006* callee0, Ropeobj177006* params0);
N_NIMCALL(void, gennamedparamcall_540616_839829468)(Tcproc527021* p0, Tnode290802* ri0, Tloc290816* d0);
N_NIMCALL(NIM_BOOL, contains_109046_4286263276)(NimStringDesc* s0, NIM_CHAR c0);
N_NIMCALL(void, genprefixcall_537960_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0);
static N_INLINE(void, poststmtactions_530942_839829468)(Tcproc527021* p0);
N_NIMCALL(void, genreset_552731_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, genecho_552369_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(NimStringDesc*, nsuRepeatStr)(NimStringDesc* s0, NI n0);
N_NIMCALL(void, genarrtoseq_553046_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0);
N_NIMCALL(void, genseqconstr_553004_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0);
N_NIMCALL(void, localerror_194080_155036129)(Tlineinfo189336 info0, Tmsgkind189002 msg0, NimStringDesc* arg0);
N_NIMCALL(Tnode290802*, wrapprocforspawn_433501_2218250499)(Tsym290834* owner0, Tnode290802* spawnexpr0, Ttype290840* rettype0, Tnode290802* barrier0, Tnode290802* dest0);
N_NIMCALL(Tnode290802*, liftparallel_476822_1773027539)(Tsym290834* owner0, Tnode290802* n0);
N_NIMCALL(void, gendeepcopy_548374_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0);
N_NIMCALL(NIM_BOOL, isdeepconstexpr_316566_2616423590)(Tnode290802* n0);
N_NIMCALL(Ropeobj177006*, gensetnode_547664_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, gensetconstr_555496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(NimStringDesc*, nimInt64ToStr)(NI64 x0);
N_NIMCALL(void, exprcomplexconst_556684_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, genarrayconstr_556207_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(NIM_BOOL, handleconstexpr_552853_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, gentupleconstr_555618_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, genobjconstr_552903_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(Tsym290834*, lookupfieldagain_551153_839829468)(Tcproc527021* p0, Ttype290840* ty_551156_839829468, Tsym290834* field0, Ropeobj177006** r0);
N_NIMCALL(void, genfieldcheck_551504_839829468)(Tcproc527021* p0, Tnode290802* e0, Ropeobj177006* obj0, Tsym290834* field0, Ttype290840* origty0);
N_NIMCALL(Tnode290802*, newstrnode_291678_850551059)(Tnodekind290020 kind0, NimStringDesc* strval0);
N_NIMCALL(void, gencast_554537_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genconv_554632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(NIM_BOOL, comparetypes_324214_3876443242)(Ttype290840* x0, Ttype290840* y0, Tdistinctcompare322427 cmp0, Ttypecmpflag322429Set flags0);
N_NIMCALL(void, genaddr_551051_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
static N_INLINE(NIM_BOOL, iscppref_550807_839829468)(Tcproc527021* p0, Ttype290840* typ0);
N_NIMCALL(void, genbracketexpr_552277_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, genarrayelem_552093_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0);
N_NIMCALL(NIM_BOOL, isconstexpr_316510_2616423590)(Tnode290802* n0);
N_NIMCALL(void, genopenarrayelem_552169_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0);
N_NIMCALL(void, genseqelem_552205_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0);
N_NIMCALL(void, gencstringelem_552144_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0);
N_NIMCALL(void, gentupleelem_551124_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genderef_541921_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NIM_BOOL enforcederef0);
N_NIMCALL(void, genrecordfield_551448_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(Ttype290840*, genrecordfieldaux_551096_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tloc290816* a0);
N_NIMCALL(void, gencheckedrecordfield_552046_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0);
N_NIMCALL(void, genblock_544083_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(NI, startblock_541978_839829468)(Tcproc527021* p0, NimStringDesc* start0, Ropeobj177006** args0, NI args0Len0);
N_NIMCALL(void, endblock_542060_839829468)(Tcproc527021* p0);
N_NIMCALL(void, endblock_542035_839829468)(Tcproc527021* p0, Ropeobj177006* blockend0);
N_NIMCALL(Ropeobj177006*, blockbody_542025_839829468)(Tblock527019* b0);
N_NIMCALL(void, genstmtlistexpr_556402_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, genif_542982_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, downconv_556581_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(NI, inheritancediff_324252_3876443242)(Ttype290840* a0, Ttype290840* b0);
N_NIMCALL(void, upconv_556431_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, genrangechck_554590_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* magic0);
N_NIMCALL(void, convstrtocstr_554642_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, convcstrtostr_554654_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, genclosure_555836_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
static N_INLINE(NIM_BOOL, isconstclosure_555810_839829468)(Tnode290802* n0);
static N_INLINE(NIM_BOOL, isroutine_295323_850551059)(Tsym290834* s0);
N_NIMCALL(void, genwhilestmt_543984_839829468)(Tcproc527021* p0, Tnode290802* t0);
static N_INLINE(Ropeobj177006*, assignlabel_542020_839829468)(Tblock527019* b0);
N_NIMCALL(NIM_BOOL, stmtscontainpragma_526083_2036603609)(Tnode290802* n0, Tspecialword273003 w0);
N_NIMCALL(void, gencomputedgoto_543744_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, genvarstmt_542854_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, gensinglevar_542276_839829468)(Tcproc527021* p0, Tnode290802* a0);
N_NIMCALL(void, gengotovar_542258_839829468)(Tcproc527021* p0, Tnode290802* value0);
N_NIMCALL(void, assignglobalvar_536819_839829468)(Tcproc527021* p0, Tsym290834* s0);
N_NIMCALL(void, varindynamiclib_536812_839829468)(Tcgen527027* m0, Tsym290834* sym0);
N_NIMCALL(void, registergcroot_541762_839829468)(Tcproc527021* p0, Tsym290834* v0);
N_NIMCALL(Ropeobj177006*, gentraverseprocforglobal_536032_839829468)(Tcgen527027* m0, Tsym290834* s0);
static N_INLINE(NIM_BOOL, isassignedimmediately_541781_839829468)(Tnode290802* n0);
N_NIMCALL(NIM_BOOL, containshiddenpointer_318120_3876443242)(Ttype290840* typ0);
static N_INLINE(void, loadinto_541928_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* a0);
N_NIMCALL(void, genasgncall_541695_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0);
N_NIMCALL(void, genclosurevar_542832_839829468)(Tcproc527021* p0, Tnode290802* a0);
N_NIMCALL(void, genvartuple_541794_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(Tnode290802*, lowertupleunpacking_431037_2218250499)(Tnode290802* n0, Tsym290834* owner0);
N_NIMCALL(void, genconststmt_542909_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(NIM_BOOL, containscompiletimeonly_326721_3876443242)(Ttype290840* t0);
static N_INLINE(NIM_BOOL, emitlazily_530248_839829468)(Tsym290834* s0);
N_NIMCALL(void, gencase_545826_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0);
N_NIMCALL(void, genstringcase_545416_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0);
N_NIMCALL(NI, nextpoweroftwo_100629_1009420244)(NI x0);
N_NIMCALL(void, gencasestringbranch_545100_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816 e0, Ropeobj177006* labl0, Ropeobj177006** branches0, NI branches0Len0);
N_NIMCALL(NI64, hashstring_526100_2036603609)(NimStringDesc* s0);
N_NIMCALL(Ropeobj177006*, gencasesecondpass_544965_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NI labid0, NI until0);
N_NIMCALL(void, exprblock_542103_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(void, gencasegeneric_545087_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0);
N_NIMCALL(Ropeobj177006*, genifforcaseuntil_545021_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc290816 a0);
N_NIMCALL(void, gencasegenericbranch_544910_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816 e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj177006* labl0);
N_NIMCALL(void, gengotoforcase_543673_839829468)(Tcproc527021* p0, Tnode290802* casestmt0);
N_NIMCALL(void, genordinalcase_545724_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0);
N_NIMCALL(NI, ifswitchsplitpoint_545615_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(NIM_BOOL, branchhastoobigrange_545575_839829468)(Tnode290802* b0);
N_NIMCALL(void, genreturnstmt_543617_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(void, blockleaveactions_543442_839829468)(Tcproc527021* p0, NI howmanytrys0, NI howmanyexcepts0);
static N_INLINE(Tnode290802*, pop_316246_1689653243)(Tnodeseq290796** s0);
N_NIMCALL(void, genbreakstmt_544444_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(void, genasgn_547239_839829468)(Tcproc527021* p0, Tnode290802* e0, NIM_BOOL fastasgn0);
N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_547080_839829468)(Tcproc527021* p0, Tnode290802* asgn0);
N_NIMCALL(void, asgnfielddiscriminant_547209_839829468)(Tcproc527021* p0, Tnode290802* e0);
N_NIMCALL(void, gendiscriminantcheck_547144_839829468)(Tcproc527021* p0, Tloc290816 a0, Tloc290816 tmp0, Ttype290840* objtype0, Tsym290834* field0);
N_NIMCALL(Ropeobj177006*, discriminatortabledecl_534094_839829468)(Tcgen527027* m0, Ttype290840* objtype0, Tsym290834* d0);
N_NIMCALL(void, genasmstmt_546659_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(Ropeobj177006*, genasmoremitstmt_546529_839829468)(Tcproc527021* p0, Tnode290802* t0, NIM_BOOL isasmstmt0);
N_NIMCALL(NimStringDesc*, resizeString)(NimStringDesc* dest0, NI addlen0);
N_NIMCALL(void, gentrycpp_545865_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0);
static N_INLINE(void, gensimpleblock_542095_839829468)(Tcproc527021* p0, Tnode290802* stmts0);
N_NIMCALL(void, gentry_546114_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0);
N_NIMCALL(NIM_BOOL, isdefined_198011_1967573533)(NimStringDesc* symbol0);
N_NIMCALL(void, line_530695_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* r0);
static N_INLINE(Ropeobj177006*, pop_177530_1689653243)(TY189350** s0);
N_NIMCALL(void, genraisestmt_544828_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(NimStringDesc*, getraisefrmt_544824_839829468)(Tcproc527021* p0);
N_NIMCALL(void, gentypesection_536184_839829468)(Tcgen527027* m0, Tnode290802* n0);
N_NIMCALL(void, genpragma_547039_839829468)(Tcproc527021* p_547041_839829468, Tnode290802* n0);
N_NIMCALL(Tspecialword273003, whichpragma_316911_2616423590)(Tnode290802* n0);
N_NIMCALL(void, genemit_546839_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(Tcfilesection527005, determinesection_546819_839829468)(Tnode290802* n0);
N_NIMCALL(NIM_BOOL, nsuStartsWith)(NimStringDesc* s0, NimStringDesc* prefix0);
N_NIMCALL(void, genbreakpoint_546862_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(void, genwatchpoint_547016_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(Tsym290834*, skipgenericowner_295279_850551059)(Tsym290834* s0);
N_NIMCALL(void, genparforstmt_544208_839829468)(Tcproc527021* p0, Tnode290802* t0);
N_NIMCALL(void, genstate_542117_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, gengotostate_542144_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, genbreakstate_542229_839829468)(Tcproc527021* p0, Tnode290802* n0);
N_NIMCALL(void, registermoduletomain_560243_839829468)(Tsym290834* m0);
N_NIMCALL(Ropeobj177006*, getinitname_560235_839829468)(Tsym290834* m0);
N_NIMCALL(Ropeobj177006*, getsomeinitname_559904_839829468)(Tsym290834* m0, NimStringDesc* suffix0);
N_NIMCALL(Ropeobj177006*, getdatinitname_560239_839829468)(Tsym290834* m0);
N_NIMCALL(Tnode290802*, generatemethoddispatchers_430151_3853300031)(void);
N_NIMCALL(void, genmainproc_559729_839829468)(Tcgen527027* m0);
N_NIMCALL(Ropeobj177006*, genfilenames_559688_839829468)(Tcgen527027* m0);
N_NIMCALL(void, finishmodule_561420_839829468)(Tcgen527027* m0);
N_NIMCALL(void, updatecachedmodule_561813_839829468)(Tcgen527027* m0);
N_NIMCALL(NIM_BOOL, mergerequired_528832_2760143328)(Tcgen527027* m0);
N_NIMCALL(void, mergefiles_529241_2760143328)(NimStringDesc* cfilename0, Tcgen527027* m0);
N_NIMCALL(void, geninitcode_560286_839829468)(Tcgen527027* m0);
N_NIMCALL(Ropeobj177006*, gensectionstart_528081_2760143328)(Tcprocsection527011 ps0);
N_NIMCALL(Ropeobj177006*, gensectionend_528116_2760143328)(Tcprocsection527011 ps0);
N_NIMCALL(Ropeobj177006*, gensectionstart_528015_2760143328)(Tcfilesection527005 fs0);
N_NIMCALL(Ropeobj177006*, gensectionend_528050_2760143328)(Tcfilesection527005 fs0);
N_NIMCALL(void, finishtypedescriptions_533842_839829468)(Tcgen527027* m0);
N_NIMCALL(Ropeobj177006*, genmodule_560491_839829468)(Tcgen527027* m0, NimStringDesc* cfile0);
N_NIMCALL(Ropeobj177006*, getfileheader_559683_839829468)(NimStringDesc* cfile0);
N_NIMCALL(Ropeobj177006*, getcopyright_559665_839829468)(NimStringDesc* cfile0);
N_NIMCALL(NimStringDesc*, getcompilecfilecmd_272284_2528170400)(NimStringDesc* cfilename0, NIM_BOOL isexternal0);
static N_INLINE(void, addinttypes_559659_839829468)(Ropeobj177006** result0);
N_NIMCALL(Ropeobj177006*, genmergeinfo_528203_2760143328)(Tcgen527027* m0);
N_NIMCALL(void, generatethreadlocalstorage_536717_839829468)(Tcgen527027* m0);
N_NIMCALL(void, generateheaders_558104_839829468)(Tcgen527027* m0);
N_NIMCALL(NimStringDesc*, nsuReplaceChar)(NimStringDesc* s0, NIM_CHAR sub0, NIM_CHAR by0);
N_NIMCALL(void, writerope_177836_2381377266)(Ropeobj177006* head0, NimStringDesc* filename0, NIM_BOOL usewarning0);
N_NIMCALL(void, addfiletocompile_271863_2528170400)(NimStringDesc* filename0);
N_NIMCALL(void, addfiletolink_271872_2528170400)(NimStringDesc* filename0);
N_NIMCALL(void, writemodule_561637_839829468)(Tcgen527027* m0, NIM_BOOL pending0);
N_NIMCALL(void, generatethreadvarssize_536771_839829468)(Tcgen527027* m0);
N_NIMCALL(NIM_BOOL, shouldrecompile_561621_839829468)(Ropeobj177006* code0, NimStringDesc* cfile0);
N_NIMCALL(NimStringDesc*, toobjfile_271859_2528170400)(NimStringDesc* filename0);
N_NIMCALL(NIM_BOOL, writeropeifnotequal_178511_2381377266)(Ropeobj177006* r0, NimStringDesc* filename0);
N_NIMCALL(NIM_BOOL, nosexistsFile)(NimStringDesc* filename0);
N_NIMCALL(NIM_BOOL, nosfileNewer)(NimStringDesc* a0, NimStringDesc* b0);
N_NIMCALL(void, writemapping_272789_2528170400)(Ropeobj177006* gsymbolmapping0);
N_NIMCALL(void, writeheader_561152_839829468)(Tcgen527027* m0);
N_NIMCALL(void, nossplitFile)(NimStringDesc* path0, TY124315* Result);
N_NIMCALL(void, resetmodule_560763_839829468)(Tcgen527027* m0);
N_NIMCALL(void, nullify_560833_839829468)(Ropeobj177006** arr0);
N_NIMCALL(void, nullify_560858_839829468)(Ropeobj177006** arr0);
STRING_LITERAL(T839829468_4, "\011", 1);
STRING_LITERAL(T839829468_10, "compiler/cgen.nim", 17);
NIM_CONST TY201018 T839829468_9 = {((NimStringDesc*) &T839829468_10),
((NI) 1158)}
;
STRING_LITERAL(T839829468_11, "T", 1);
STRING_LITERAL(T839829468_12, "_", 1);
STRING_LITERAL(T839829468_13, "added pending module twice: ", 28);
STRING_LITERAL(T839829468_14, ".h", 2);
STRING_LITERAL(T839829468_15, ".cpp", 4);
STRING_LITERAL(T839829468_16, ".m", 2);
STRING_LITERAL(T839829468_17, ".c", 2);
STRING_LITERAL(T839829468_18, "0", 1);
STRING_LITERAL(T839829468_19, "$", 1);
STRING_LITERAL(T839829468_20, "ropes: invalid format string $", 30);
STRING_LITERAL(T839829468_21, "$N#line $2 $1$N", 15);
STRING_LITERAL(T839829468_22, "N_LIB_IMPORT ", 13);
STRING_LITERAL(T839829468_23, "N_LIB_EXPORT ", 13);
STRING_LITERAL(T839829468_24, "static ", 7);
STRING_LITERAL(T839829468_25, "mapType", 7);
STRING_LITERAL(T839829468_26, "void", 4);
STRING_LITERAL(T839829468_27, "getTypeDescAux: t == nil", 24);
STRING_LITERAL(T839829468_28, "TY", 2);
STRING_LITERAL(T839829468_29, "getTypeName: ", 13);
STRING_LITERAL(T839829468_30, "void*", 5);
STRING_LITERAL(T839829468_31, "NimStringDesc", 13);
STRING_LITERAL(T839829468_32, "NimStringDesc*", 14);
STRING_LITERAL(T839829468_33, "NCSTRING", 8);
STRING_LITERAL(T839829468_34, "NIM_BOOL", 8);
STRING_LITERAL(T839829468_35, "NIM_CHAR", 8);
STRING_LITERAL(T839829468_36, "NI", 2);
STRING_LITERAL(T839829468_37, "NI8", 3);
STRING_LITERAL(T839829468_38, "NI16", 4);
STRING_LITERAL(T839829468_39, "NI32", 4);
STRING_LITERAL(T839829468_40, "NI64", 4);
STRING_LITERAL(T839829468_41, "NF", 2);
STRING_LITERAL(T839829468_42, "NF32", 4);
STRING_LITERAL(T839829468_43, "NF64", 4);
STRING_LITERAL(T839829468_44, "NF128", 5);
STRING_LITERAL(T839829468_45, "NU", 2);
STRING_LITERAL(T839829468_46, "NU8", 3);
STRING_LITERAL(T839829468_47, "NU16", 4);
STRING_LITERAL(T839829468_48, "NU32", 4);
STRING_LITERAL(T839829468_49, "NU64", 4);
NIM_CONST TY531943 Numericaltypetostr_531941_839829468 = {((NimStringDesc*) &T839829468_36),
((NimStringDesc*) &T839829468_37),
((NimStringDesc*) &T839829468_38),
((NimStringDesc*) &T839829468_39),
((NimStringDesc*) &T839829468_40),
((NimStringDesc*) &T839829468_41),
((NimStringDesc*) &T839829468_42),
((NimStringDesc*) &T839829468_43),
((NimStringDesc*) &T839829468_44),
((NimStringDesc*) &T839829468_45),
((NimStringDesc*) &T839829468_46),
((NimStringDesc*) &T839829468_47),
((NimStringDesc*) &T839829468_48),
((NimStringDesc*) &T839829468_49)}
;
STRING_LITERAL(T839829468_50, "tyStatic for getSimpleTypeDesc", 30);
STRING_LITERAL(T839829468_51, "cannot generate C type for: ", 28);
STRING_LITERAL(T839829468_52, "&", 1);
STRING_LITERAL(T839829468_53, "*", 1);
STRING_LITERAL(T839829468_54, "$1 $2;$n", 8);
STRING_LITERAL(T839829468_55, "typedef $1 $2 $2;$n", 19);
STRING_LITERAL(T839829468_56, "union", 5);
STRING_LITERAL(T839829468_57, "struct", 6);
STRING_LITERAL(T839829468_58, "getTypeForward(", 15);
STRING_LITERAL(T839829468_59, "typedef NI32 $1;$n", 18);
STRING_LITERAL(T839829468_60, "typedef NU8 $1;$n", 17);
STRING_LITERAL(T839829468_61, "typedef NU16 $1;$n", 18);
STRING_LITERAL(T839829468_62, "typedef NI64 $1;$n", 18);
STRING_LITERAL(T839829468_63, "getTypeDescAux: enum", 20);
STRING_LITERAL(T839829468_64, "typedef $1_PTR($2, $3) $4;$n", 28);
STRING_LITERAL(T839829468_65, "N_NIMCALL", 9);
STRING_LITERAL(T839829468_66, "N_STDCALL", 9);
STRING_LITERAL(T839829468_67, "N_CDECL", 7);
STRING_LITERAL(T839829468_68, "N_SAFECALL", 10);
STRING_LITERAL(T839829468_69, "N_SYSCALL", 9);
STRING_LITERAL(T839829468_70, "N_INLINE", 8);
STRING_LITERAL(T839829468_71, "N_NOINLINE", 10);
STRING_LITERAL(T839829468_72, "N_FASTCALL", 10);
STRING_LITERAL(T839829468_73, "N_CLOSURE", 9);
STRING_LITERAL(T839829468_74, "N_NOCONV", 8);
NIM_CONST TY290016 Callingconvtostr_531585_839829468 = {((NimStringDesc*) &T839829468_65),
((NimStringDesc*) &T839829468_66),
((NimStringDesc*) &T839829468_67),
((NimStringDesc*) &T839829468_68),
((NimStringDesc*) &T839829468_69),
((NimStringDesc*) &T839829468_70),
((NimStringDesc*) &T839829468_71),
((NimStringDesc*) &T839829468_72),
((NimStringDesc*) &T839829468_73),
((NimStringDesc*) &T839829468_74)}
;
STRING_LITERAL(T839829468_75, "typedef struct {$nN_NIMCALL_PTR($2, ClPrc) $3;$nvoid* ClEnv;$n}"
" $1;$n", 69);
STRING_LITERAL(T839829468_76, "struct $2 : #TGenericSeq {$n", 28);
STRING_LITERAL(T839829468_77, "struct $2 {$n #TGenericSeq Sup;$n", 34);
STRING_LITERAL(T839829468_78, " $1 data[SEQ_DECL_SIZE];$n};$n", 31);
STRING_LITERAL(T839829468_79, "TGenericSeq", 11);
STRING_LITERAL(T839829468_80, "typedef $1 $2[$3];$n", 20);
STRING_LITERAL(T839829468_81, "invalid apostrophe type parameter index", 39);
STRING_LITERAL(T839829468_82, "<", 1);
STRING_LITERAL(T839829468_83, " COMMA ", 7);
STRING_LITERAL(T839829468_84, "> ", 2);
extern NIM_CONST TY271427 Cc_271413_2528170400;
STRING_LITERAL(T839829468_85, " {$n", 4);
STRING_LITERAL(T839829468_86, " {$n#TNimType* m_type;$n", 24);
STRING_LITERAL(T839829468_87, " : public $1 {$n", 16);
STRING_LITERAL(T839829468_88, " {$n $1 Sup;$n", 15);
STRING_LITERAL(T839829468_89, "genRecordFieldsAux", 18);
STRING_LITERAL(T839829468_90, "$1.$2", 5);
STRING_LITERAL(T839829468_91, "S", 1);
STRING_LITERAL(T839829468_92, "struct {", 8);
STRING_LITERAL(T839829468_93, "} $1;$n", 7);
STRING_LITERAL(T839829468_94, "genRecordFieldsAux(record case branch)", 38);
STRING_LITERAL(T839829468_95, "union{$n$1} $2;$n", 17);
STRING_LITERAL(T839829468_96, "mangleRecFieldName", 18);
STRING_LITERAL(T839829468_97, "$1 $2[SEQ_DECL_SIZE];$n", 23);
STRING_LITERAL(T839829468_98, "$1 $2:$3;$n", 11);
STRING_LITERAL(T839829468_99, "genRecordFieldsAux()", 20);
STRING_LITERAL(T839829468_100, "char dummy;$n", 13);
STRING_LITERAL(T839829468_101, "};", 2);
STRING_LITERAL(T839829468_102, "$1 $2 {$n", 9);
STRING_LITERAL(T839829468_103, "$1 Field$2;$n", 13);
STRING_LITERAL(T839829468_104, "char dummy;", 11);
STRING_LITERAL(T839829468_105, "Set", 3);
STRING_LITERAL(T839829468_106, "typedef NU$2 $1;$n", 18);
STRING_LITERAL(T839829468_107, "typedef NU8 $1[$2];$n", 21);
STRING_LITERAL(T839829468_108, "getTypeDescAux(", 15);
STRING_LITERAL(T839829468_109, "genProcParams", 13);
STRING_LITERAL(T839829468_110, ", ", 2);
STRING_LITERAL(T839829468_111, " ", 1);
STRING_LITERAL(T839829468_112, ", NI $1Len$2", 12);
STRING_LITERAL(T839829468_113, " Result", 7);
STRING_LITERAL(T839829468_114, "void* ClEnv", 11);
STRING_LITERAL(T839829468_115, "...", 3);
STRING_LITERAL(T839829468_116, "void)", 5);
STRING_LITERAL(T839829468_117, ")", 1);
STRING_LITERAL(T839829468_118, "(", 1);
STRING_LITERAL(T839829468_119, "$1($2, $3)$4", 12);
STRING_LITERAL(T839829468_120, "proc has no result symbol", 25);
STRING_LITERAL(T839829468_121, " register", 9);
STRING_LITERAL(T839829468_122, " volatile", 9);
STRING_LITERAL(T839829468_123, "$1 = $2;$n", 10);
STRING_LITERAL(T839829468_124, "(*$1)", 5);
STRING_LITERAL(T839829468_125, ";", 1);
STRING_LITERAL(T839829468_126, "FR.s[$1].address = (void*)$3; FR.s[$1].typ = $4; FR.s[$1].name "
"= $2;$n", 70);
STRING_LITERAL(T839829468_127, "NTI$1", 5);
STRING_LITERAL(T839829468_128, "(&", 2);
STRING_LITERAL(T839829468_129, "TNimType", 8);
STRING_LITERAL(T839829468_130, "TNimNode", 8);
STRING_LITERAL(T839829468_131, "extern TNimType $1; /* $2 */$n", 30);
STRING_LITERAL(T839829468_132, "0", 1);
STRING_LITERAL(T839829468_133, "void*", 5);
STRING_LITERAL(T839829468_134, "$1.size = sizeof($2);$n$1.kind = $3;$n$1.base = $4;$n", 53);
STRING_LITERAL(T839829468_135, "$1.flags = $2;$n", 16);
STRING_LITERAL(T839829468_136, "TNimType $1; /* $2 */$n", 23);
STRING_LITERAL(T839829468_137, "genTypeInfo(", 12);
STRING_LITERAL(T839829468_138, "$1[$2]", 6);
STRING_LITERAL(T839829468_139, "static TNimNode* $1[$2];$n", 26);
STRING_LITERAL(T839829468_140, "$1[$2] = &$3;$n", 15);
STRING_LITERAL(T839829468_141, "$1.kind = 1;$n$1.offset = offsetof($2, Field$3);$n$1.typ = $4;$"
"n$1.name = \"Field$3\";$n", 86);
STRING_LITERAL(T839829468_142, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n", 45);
STRING_LITERAL(T839829468_143, "$1.len = $2; $1.kind = 2;$n", 27);
STRING_LITERAL(T839829468_144, "$1.node = &$2;$n", 16);
STRING_LITERAL(T839829468_145, "#nimGCvisit((void*)$1, op);$n", 29);
STRING_LITERAL(T839829468_146, "N_NIMCALL(void, $1)(void* p, NI op)", 35);
STRING_LITERAL(T839829468_147, "$1 a;$n", 7);
STRING_LITERAL(T839829468_148, "a = ($1)p;$n", 12);
STRING_LITERAL(T839829468_149, "LOC", 3);
STRING_LITERAL(T839829468_150, "$1 = ($2)0;$n", 13);
STRING_LITERAL(T839829468_151, "<string.h>", 10);
STRING_LITERAL(T839829468_152, "memset((void*)$1, 0, sizeof($2));$n", 35);
STRING_LITERAL(T839829468_153, ".Sup", 4);
STRING_LITERAL(T839829468_154, "$1.m_type = $2;$n", 17);
STRING_LITERAL(T839829468_155, "#objectInit($1, $2);$n", 22);
STRING_LITERAL(T839829468_156, "for ($1 = 0; $1 < $2->$3; $1++) {$n", 35);
STRING_LITERAL(T839829468_157, "len", 3);
STRING_LITERAL(T839829468_158, "Sup.len", 7);
STRING_LITERAL(T839829468_159, "for ($1 = 0; $1 < $2; $1++) {$n", 31);
STRING_LITERAL(T839829468_160, "}$n", 3);
STRING_LITERAL(T839829468_161, "$1.Sup", 6);
STRING_LITERAL(T839829468_162, "genTraverseProc", 15);
STRING_LITERAL(T839829468_163, "switch ($1.$2) {$n", 18);
STRING_LITERAL(T839829468_164, "case $1 ... $2:$n", 17);
STRING_LITERAL(T839829468_165, "genLiteral: ty is nil", 21);
STRING_LITERAL(T839829468_166, "(-2147483647 -1)", 16);
STRING_LITERAL(T839829468_167, "IL64($1)", 8);
STRING_LITERAL(T839829468_168, "(IL64(-9223372036854775807) - IL64(1))", 38);
STRING_LITERAL(T839829468_169, "NIM_TRUE", 8);
STRING_LITERAL(T839829468_170, "NIM_FALSE", 9);
STRING_LITERAL(T839829468_171, "ULL", 3);
STRING_LITERAL(T839829468_172, "(($1) $2)", 9);
STRING_LITERAL(T839829468_173, "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n", 45);
STRING_LITERAL(T839829468_174, "NIM_NIL", 7);
STRING_LITERAL(T839829468_175, "((#NimStringDesc*) NIM_NIL)", 27);
STRING_LITERAL(T839829468_176, "((#NimStringDesc*) &$1)", 23);
STRING_LITERAL(T839829468_177, "STRING_LITERAL($1, $2, $3);$n", 29);
STRING_LITERAL(T839829468_178, "((#NimStringDesc*) &$1$2)", 25);
STRING_LITERAL(T839829468_179, "genLiteral(", 11);
STRING_LITERAL(T839829468_180, "case $1:$n", 10);
STRING_LITERAL(T839829468_181, "default:$n", 10);
STRING_LITERAL(T839829468_182, "break;$n", 8);
STRING_LITERAL(T839829468_183, "} $n", 4);
STRING_LITERAL(T839829468_184, "genTraverseProc()", 17);
STRING_LITERAL(T839829468_185, "$1.Field$2", 10);
STRING_LITERAL(T839829468_186, "$1.ClEnv", 8);
STRING_LITERAL(T839829468_187, "$1->data[$2]", 12);
STRING_LITERAL(T839829468_188, "a", 1);
STRING_LITERAL(T839829468_189, "(*a)", 4);
STRING_LITERAL(T839829468_190, "$1 {$n$2$3$4}$n", 15);
STRING_LITERAL(T839829468_191, "$1;$n", 5);
STRING_LITERAL(T839829468_192, "$1.marker = $2;$n", 17);
STRING_LITERAL(T839829468_193, "$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n", 43);
STRING_LITERAL(T839829468_194, "$1.offset = $2;$n", 17);
STRING_LITERAL(T839829468_195, "NI $1;$n", 8);
STRING_LITERAL(T839829468_196, "static char* NIM_CONST $1[$2] = {$n$3};$n", 41);
STRING_LITERAL(T839829468_197, "for ($1 = 0; $1 < $2; $1++) {$n$3[$1+$4].kind = 1;$n$3[$1+$4].o"
"ffset = $1;$n$3[$1+$4].name = $5[$1];$n$6[$1] = &$3[$1+$4];$n}$n", 127);
STRING_LITERAL(T839829468_198, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n", 61);
STRING_LITERAL(T839829468_199, "$1.flags = 1<<2;$n", 18);
STRING_LITERAL(T839829468_200, "anonymous obj with discriminator", 32);
STRING_LITERAL(T839829468_201, "NimDT_$1_$2", 11);
STRING_LITERAL(T839829468_202, "$1.kind = 3;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n"
"ame = $5;$n$1.sons = &$6[0];$n$1.len = $7;$n", 107);
STRING_LITERAL(T839829468_203, "TNimNode* $1[$2];$n", 19);
STRING_LITERAL(T839829468_204, "genObjectFields; nkOfBranch broken", 34);
STRING_LITERAL(T839829468_205, "genObjectFields(nkRecCase)", 26);
STRING_LITERAL(T839829468_206, "$1.kind = 1;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n"
"ame = $5;$n", 74);
STRING_LITERAL(T839829468_207, "genObjectFields", 15);
STRING_LITERAL(T839829468_208, "$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n", 49);
STRING_LITERAL(T839829468_209, "\011return $1;$n", 13);
STRING_LITERAL(T839829468_210, "Result", 6);
STRING_LITERAL(T839829468_211, "closure generation failed", 25);
STRING_LITERAL(T839829468_212, "$1 = ($2) ClEnv;$n", 18);
STRING_LITERAL(T839829468_213, "__declspec(noreturn) ", 21);
STRING_LITERAL(T839829468_214, "__declspec(naked) ", 18);
STRING_LITERAL(T839829468_215, "$N$1 {$n$2$3$4}$N$N", 19);
STRING_LITERAL(T839829468_216, "$N$1 {$N", 8);
STRING_LITERAL(T839829468_217, "struct {$1} GCFRAME;$n", 22);
STRING_LITERAL(T839829468_218, "nimFrame", 8);
STRING_LITERAL(T839829468_219, "VarSlot", 7);
STRING_LITERAL(T839829468_220, "\011nimfrs($1, $2, $3, $4)$N", 25);
STRING_LITERAL(T839829468_221, "\011nimfr($1, $2)$N", 16);
STRING_LITERAL(T839829468_222, "\011#nimProfile();$n", 17);
STRING_LITERAL(T839829468_223, "{", 1);
STRING_LITERAL(T839829468_224, "\011}BeforeRet: ;$n", 16);
STRING_LITERAL(T839829468_225, "if (((NU)&GCFRAME) < 4096) #nimGCFrame(&GCFRAME);$n", 51);
STRING_LITERAL(T839829468_226, "\011#popFrame();$n", 15);
STRING_LITERAL(T839829468_227, "}$N", 3);
STRING_LITERAL(T839829468_228, "static void* $1;$n", 18);
STRING_LITERAL(T839829468_229, "||", 2);
STRING_LITERAL(T839829468_230, "($1 = #nimLoadLibrary((#NimStringDesc*) &$2))$n", 47);
STRING_LITERAL(T839829468_231, "if (!($1)) #nimLoadLibraryError((#NimStringDesc*) &$2);$n", 57);
STRING_LITERAL(T839829468_232, "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n", 60);
STRING_LITERAL(T839829468_233, "loadDynamicLib", 14);
STRING_LITERAL(T839829468_234, "Dl_$1", 5);
STRING_LITERAL(T839829468_235, "\011$1 = ($2) ($3$4));$n", 21);
NIM_CONST TY201018 T839829468_236 = {((NimStringDesc*) &T839829468_10),
((NI) 535)}
;
STRING_LITERAL(T839829468_237, "wrong index: ", 13);
STRING_LITERAL(T839829468_238, "\011$1 = ($2) #nimGetProcAddr($3, $4);$n", 37);
STRING_LITERAL(T839829468_239, "$2 $1;$n", 8);
STRING_LITERAL(T839829468_240, "extern ", 7);
STRING_LITERAL(T839829468_241, "NIM_THREADVAR ", 14);
STRING_LITERAL(T839829468_242, " $1;$n", 6);
STRING_LITERAL(T839829468_243, "cgsym: ", 7);
STRING_LITERAL(T839829468_244, ": ", 2);
STRING_LITERAL(T839829468_245, "extern $1 $2;$n", 15);
STRING_LITERAL(T839829468_246, "extern \"C\" ", 11);
STRING_LITERAL(T839829468_247, " __attribute__((naked))", 23);
STRING_LITERAL(T839829468_248, " __attribute__((noreturn))", 26);
STRING_LITERAL(T839829468_249, "#asgnRef((void**) $1, $2);$n", 28);
STRING_LITERAL(T839829468_250, "#asgnRefNoCycle((void**) $1, $2);$n", 35);
STRING_LITERAL(T839829468_251, "#unsureAsgnRef((void**) $1, $2);$n", 34);
STRING_LITERAL(T839829468_252, "#genericSeqAssign($1, $2, $3);$n", 32);
STRING_LITERAL(T839829468_253, "$1 = #copyString($2);$n", 23);
STRING_LITERAL(T839829468_254, "$3 = $1; $1 = #copyStringRC1($2);$n", 35);
STRING_LITERAL(T839829468_255, "if ($1) #nimGCunrefNoCycle($1);$n", 33);
STRING_LITERAL(T839829468_256, "#unsureAsgnRef((void**) $1, #copyString($2));$n", 47);
STRING_LITERAL(T839829468_257, ".", 1);
STRING_LITERAL(T839829468_258, "ClEnv", 5);
STRING_LITERAL(T839829468_259, "$1.ClPrc = $2.ClPrc;$n", 22);
STRING_LITERAL(T839829468_260, "Field$1", 7);
STRING_LITERAL(T839829468_261, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n", 53);
STRING_LITERAL(T839829468_262, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n", 50);
STRING_LITERAL(T839829468_263, "#genericAssign((void*)$1, (void*)$2, $3);$n", 43);
STRING_LITERAL(T839829468_265, "compiler/ccgexprs.nim", 21);
NIM_CONST TY201018 T839829468_264 = {((NimStringDesc*) &T839829468_265),
((NI) 320)}
;
STRING_LITERAL(T839829468_266, "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 60);
STRING_LITERAL(T839829468_267, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len0);$n", 63);
STRING_LITERAL(T839829468_268, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n", 45);
STRING_LITERAL(T839829468_269, "genAssignment: ", 15);
STRING_LITERAL(T839829468_270, "request to generate code for .compileTime proc: ", 48);
STRING_LITERAL(T839829468_271, "expr: proc not init ", 20);
STRING_LITERAL(T839829468_272, "NIM_CONST $1 $2 = $3;$n", 23);
STRING_LITERAL(T839829468_273, "{$n", 3);
STRING_LITERAL(T839829468_274, "0x$1,$n", 7);
STRING_LITERAL(T839829468_275, "0x$1, ", 6);
STRING_LITERAL(T839829468_276, "0x$1}$n", 7);
STRING_LITERAL(T839829468_277, "{{$1, $1}", 9);
STRING_LITERAL(T839829468_278, ", {", 3);
STRING_LITERAL(T839829468_279, ",$n", 3);
STRING_LITERAL(T839829468_280, "}", 1);
STRING_LITERAL(T839829468_281, "NIM_CONST struct {$n #TGenericSeq Sup;$n $1 data[$2];$n} $3 ="
" $4;$n", 69);
STRING_LITERAL(T839829468_282, "(($1)&$2)", 9);
STRING_LITERAL(T839829468_283, "$1,$n", 5);
STRING_LITERAL(T839829468_284, "extern NIM_CONST $1 $2;$n", 25);
STRING_LITERAL(T839829468_285, "expr: var not init ", 19);
STRING_LITERAL(T839829468_286, "\011NimThreadVars* NimTV;$n", 24);
STRING_LITERAL(T839829468_287, "\011NimTV = (NimThreadVars*) #GetThreadLocalVars();$n", 50);
STRING_LITERAL(T839829468_288, "NimTV->", 7);
STRING_LITERAL(T839829468_289, "expr: temp not init ", 20);
STRING_LITERAL(T839829468_290, "expr: param not init ", 21);
STRING_LITERAL(T839829468_291, "expr(", 5);
STRING_LITERAL(T839829468_292, "); unknown symbol", 17);
STRING_LITERAL(T839829468_293, "//", 2);
STRING_LITERAL(T839829468_294, "#endb($1, $2);$n", 16);
STRING_LITERAL(T839829468_295, "nimln($1, $2);$n", 16);
STRING_LITERAL(T839829468_296, "LA", 2);
STRING_LITERAL(T839829468_297, "if ($1) goto $2;$n", 18);
STRING_LITERAL(T839829468_298, "if (!($1)) goto $2;$n", 21);
STRING_LITERAL(T839829468_299, "$1: ;$n", 7);
STRING_LITERAL(T839829468_300, "!($1)", 5);
STRING_LITERAL(T839829468_301, "$1", 2);
STRING_LITERAL(T839829468_302, "($3)((NU$2) ~($1))", 18);
STRING_LITERAL(T839829468_303, "-($1)", 5);
STRING_LITERAL(T839829468_304, "($1 > 0? ($1) : -($1))", 22);
STRING_LITERAL(T839829468_305, "(($3)(NU)(NU8)($1))", 19);
STRING_LITERAL(T839829468_306, "(($3)(NU64)(NU8)($1))", 21);
STRING_LITERAL(T839829468_307, "(($3)(NU)(NU16)($1))", 20);
STRING_LITERAL(T839829468_308, "(($3)(NU64)(NU16)($1))", 22);
STRING_LITERAL(T839829468_309, "(($3)(NU64)(NU32)($1))", 22);
STRING_LITERAL(T839829468_310, "(($3)(NU64)(NU)($1))", 20);
STRING_LITERAL(T839829468_311, "(($3)(NU8)(NU)($1))", 19);
STRING_LITERAL(T839829468_312, "(($3)(NU16)(NU)($1))", 20);
STRING_LITERAL(T839829468_313, "(($3)(NU32)(NU64)($1))", 22);
STRING_LITERAL(T839829468_314, "((double) ($1))", 15);
STRING_LITERAL(T839829468_315, "float64ToInt32($1)", 18);
STRING_LITERAL(T839829468_316, "float64ToInt64($1)", 18);
NIM_CONST TY550655 unarithtab_550653_839829468 = {((NimStringDesc*) &T839829468_300),
((NimStringDesc*) &T839829468_301),
((NimStringDesc*) &T839829468_302),
((NimStringDesc*) &T839829468_301),
((NimStringDesc*) &T839829468_303),
((NimStringDesc*) &T839829468_304),
((NimStringDesc*) &T839829468_305),
((NimStringDesc*) &T839829468_306),
((NimStringDesc*) &T839829468_307),
((NimStringDesc*) &T839829468_308),
((NimStringDesc*) &T839829468_309),
((NimStringDesc*) &T839829468_310),
((NimStringDesc*) &T839829468_311),
((NimStringDesc*) &T839829468_312),
((NimStringDesc*) &T839829468_313),
((NimStringDesc*) &T839829468_314),
((NimStringDesc*) &T839829468_314),
((NimStringDesc*) &T839829468_315),
((NimStringDesc*) &T839829468_316)}
;
STRING_LITERAL(T839829468_317, "if ($1 == $2) #raiseOverflow();$n", 33);
STRING_LITERAL(T839829468_318, "((NI$2)-($1))", 13);
NIM_CONST TY549642 opr_549640_839829468 = {((NimStringDesc*) &T839829468_318),
((NimStringDesc*) &T839829468_303),
((NimStringDesc*) &T839829468_304)}
;
STRING_LITERAL(T839829468_319, "(($4)($2) $1 ($4)($3))", 22);
STRING_LITERAL(T839829468_320, "+", 1);
STRING_LITERAL(T839829468_321, "-", 1);
STRING_LITERAL(T839829468_322, "/", 1);
NIM_CONST TY554764 opr_554762_839829468 = {((NimStringDesc*) &T839829468_320),
((NimStringDesc*) &T839829468_321),
((NimStringDesc*) &T839829468_53),
((NimStringDesc*) &T839829468_322)}
;
STRING_LITERAL(T839829468_323, "#nanCheck($1);$n", 16);
STRING_LITERAL(T839829468_324, "#infCheck($1);$n", 16);
STRING_LITERAL(T839829468_325, "(($4)($1) + ($4)($2))", 21);
STRING_LITERAL(T839829468_326, "(($4)($1) - ($4)($2))", 21);
STRING_LITERAL(T839829468_327, "(($4)($1) * ($4)($2))", 21);
STRING_LITERAL(T839829468_328, "(($4)($1) / ($4)($2))", 21);
STRING_LITERAL(T839829468_329, "($4)((NU$3)($1) >> (NU$3)($2))", 30);
STRING_LITERAL(T839829468_330, "($4)((NU$3)($1) << (NU$3)($2))", 30);
STRING_LITERAL(T839829468_331, "($4)($1 & $2)", 13);
STRING_LITERAL(T839829468_332, "($4)($1 | $2)", 13);
STRING_LITERAL(T839829468_333, "($4)($1 ^ $2)", 13);
STRING_LITERAL(T839829468_334, "(($1 <= $2) ? $1 : $2)", 22);
STRING_LITERAL(T839829468_335, "(($1 >= $2) ? $1 : $2)", 22);
STRING_LITERAL(T839829468_336, "($4)((NU$3)($1) + (NU$3)($2))", 29);
STRING_LITERAL(T839829468_337, "($4)((NU$3)($1) - (NU$3)($2))", 29);
STRING_LITERAL(T839829468_338, "($4)((NU$3)($1) * (NU$3)($2))", 29);
STRING_LITERAL(T839829468_339, "($4)((NU$3)($1) / (NU$3)($2))", 29);
STRING_LITERAL(T839829468_340, "($4)((NU$3)($1) % (NU$3)($2))", 29);
STRING_LITERAL(T839829468_341, "($1 == $2)", 10);
STRING_LITERAL(T839829468_342, "($1 <= $2)", 10);
STRING_LITERAL(T839829468_343, "($1 < $2)", 9);
STRING_LITERAL(T839829468_344, "((NU$3)($1) <= (NU$3)($2))", 26);
STRING_LITERAL(T839829468_345, "((NU$3)($1) < (NU$3)($2))", 25);
STRING_LITERAL(T839829468_346, "((NU64)($1) <= (NU64)($2))", 26);
STRING_LITERAL(T839829468_347, "((NU64)($1) < (NU64)($2))", 25);
STRING_LITERAL(T839829468_348, "((NU8)($1) == (NU8)($2))", 24);
STRING_LITERAL(T839829468_349, "((NU8)($1) <= (NU8)($2))", 24);
STRING_LITERAL(T839829468_350, "((NU8)($1) < (NU8)($2))", 23);
STRING_LITERAL(T839829468_351, "($1 != $2)", 10);
NIM_CONST TY549828 binarithtab_549826_839829468 = {((NimStringDesc*) &T839829468_325),
((NimStringDesc*) &T839829468_326),
((NimStringDesc*) &T839829468_327),
((NimStringDesc*) &T839829468_328),
((NimStringDesc*) &T839829468_329),
((NimStringDesc*) &T839829468_330),
((NimStringDesc*) &T839829468_331),
((NimStringDesc*) &T839829468_332),
((NimStringDesc*) &T839829468_333),
((NimStringDesc*) &T839829468_334),
((NimStringDesc*) &T839829468_335),
((NimStringDesc*) &T839829468_334),
((NimStringDesc*) &T839829468_335),
((NimStringDesc*) &T839829468_336),
((NimStringDesc*) &T839829468_337),
((NimStringDesc*) &T839829468_338),
((NimStringDesc*) &T839829468_339),
((NimStringDesc*) &T839829468_340),
((NimStringDesc*) &T839829468_341),
((NimStringDesc*) &T839829468_342),
((NimStringDesc*) &T839829468_343),
((NimStringDesc*) &T839829468_341),
((NimStringDesc*) &T839829468_342),
((NimStringDesc*) &T839829468_343),
((NimStringDesc*) &T839829468_344),
((NimStringDesc*) &T839829468_345),
((NimStringDesc*) &T839829468_346),
((NimStringDesc*) &T839829468_347),
((NimStringDesc*) &T839829468_341),
((NimStringDesc*) &T839829468_342),
((NimStringDesc*) &T839829468_343),
((NimStringDesc*) &T839829468_348),
((NimStringDesc*) &T839829468_349),
((NimStringDesc*) &T839829468_350),
((NimStringDesc*) &T839829468_341),
((NimStringDesc*) &T839829468_342),
((NimStringDesc*) &T839829468_343),
((NimStringDesc*) &T839829468_341),
((NimStringDesc*) &T839829468_341),
((NimStringDesc*) &T839829468_342),
((NimStringDesc*) &T839829468_343),
((NimStringDesc*) &T839829468_351)}
;
STRING_LITERAL(T839829468_352, "($1.ClPrc == $2.ClPrc && $1.ClEnv == $2.ClEnv)", 46);
STRING_LITERAL(T839829468_353, "($#)($# + $#)", 13);
STRING_LITERAL(T839829468_354, "($#)($# - $#)", 13);
STRING_LITERAL(T839829468_355, "($#)($# * $#)", 13);
STRING_LITERAL(T839829468_356, "($#)($# / $#)", 13);
STRING_LITERAL(T839829468_357, "($#)($# % $#)", 13);
NIM_CONST TY549281 opr_549279_839829468 = {((NimStringDesc*) &T839829468_353),
((NimStringDesc*) &T839829468_354),
((NimStringDesc*) &T839829468_355),
((NimStringDesc*) &T839829468_356),
((NimStringDesc*) &T839829468_357),
((NimStringDesc*) &T839829468_353),
((NimStringDesc*) &T839829468_354)}
;
STRING_LITERAL(T839829468_358, "((NU8)($1))", 11);
STRING_LITERAL(T839829468_359, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n", 43);
STRING_LITERAL(T839829468_360, "$# = #addInt64($#, $#);$n", 25);
STRING_LITERAL(T839829468_361, "$# = #subInt64($#, $#);$n", 25);
STRING_LITERAL(T839829468_362, "$# = #mulInt64($#, $#);$n", 25);
STRING_LITERAL(T839829468_363, "$# = #divInt64($#, $#);$n", 25);
STRING_LITERAL(T839829468_364, "$# = #modInt64($#, $#);$n", 25);
NIM_CONST TY549281 prc64_549274_839829468 = {((NimStringDesc*) &T839829468_360),
((NimStringDesc*) &T839829468_361),
((NimStringDesc*) &T839829468_362),
((NimStringDesc*) &T839829468_363),
((NimStringDesc*) &T839829468_364),
((NimStringDesc*) &T839829468_360),
((NimStringDesc*) &T839829468_361)}
;
STRING_LITERAL(T839829468_365, "$# = #addInt($#, $#);$n", 23);
STRING_LITERAL(T839829468_366, "$# = #subInt($#, $#);$n", 23);
STRING_LITERAL(T839829468_367, "$# = #mulInt($#, $#);$n", 23);
STRING_LITERAL(T839829468_368, "$# = #divInt($#, $#);$n", 23);
STRING_LITERAL(T839829468_369, "$# = #modInt($#, $#);$n", 23);
NIM_CONST TY549281 prc_549269_839829468 = {((NimStringDesc*) &T839829468_365),
((NimStringDesc*) &T839829468_366),
((NimStringDesc*) &T839829468_367),
((NimStringDesc*) &T839829468_368),
((NimStringDesc*) &T839829468_369),
((NimStringDesc*) &T839829468_365),
((NimStringDesc*) &T839829468_366)}
;
STRING_LITERAL(T839829468_370, "($#)($#)", 8);
STRING_LITERAL(T839829468_371, "#reprInt((NI64)$1)", 18);
STRING_LITERAL(T839829468_372, "#reprFloat($1)", 14);
STRING_LITERAL(T839829468_373, "#reprBool($1)", 13);
STRING_LITERAL(T839829468_374, "#reprChar($1)", 13);
STRING_LITERAL(T839829468_375, "#reprEnum((NI)$1, $2)", 21);
STRING_LITERAL(T839829468_376, "#reprStr($1)", 12);
STRING_LITERAL(T839829468_377, "#reprSet($1, $2)", 16);
STRING_LITERAL(T839829468_378, "$1, $1Len0", 10);
STRING_LITERAL(T839829468_379, "$1->data, $1->$2", 16);
STRING_LITERAL(T839829468_380, "$1, $2", 6);
STRING_LITERAL(T839829468_381, "genRepr()", 9);
STRING_LITERAL(T839829468_382, "#reprOpenArray($1, $2)", 22);
STRING_LITERAL(T839829468_383, "#reprAny($1, $2)", 16);
STRING_LITERAL(T839829468_384, "\'repr\' doesn\'t support \'void\' type", 34);
STRING_LITERAL(T839829468_385, "($1 - 1)", 8);
STRING_LITERAL(T839829468_386, "#subInt($1, 1)", 14);
STRING_LITERAL(T839829468_387, "binaryStmt", 10);
STRING_LITERAL(T839829468_388, "$1 += $2;$n", 11);
STRING_LITERAL(T839829468_389, "$1 -= $2;$n", 11);
NIM_CONST TY555052 opr_555050_839829468 = {((NimStringDesc*) &T839829468_388),
((NimStringDesc*) &T839829468_389)}
;
NIM_CONST TY555052 fun64_555055_839829468 = {((NimStringDesc*) &T839829468_360),
((NimStringDesc*) &T839829468_361)}
;
NIM_CONST TY555052 fun_555060_839829468 = {((NimStringDesc*) &T839829468_365),
((NimStringDesc*) &T839829468_366)}
;
STRING_LITERAL(T839829468_390, "#appendChar($1, $2);$n", 22);
STRING_LITERAL(T839829468_391, "$1->$2 + ", 9);
STRING_LITERAL(T839829468_392, "#appendString($1, $2);$n", 24);
STRING_LITERAL(T839829468_393, "$1 = #rawNewString($2$3);$n", 27);
STRING_LITERAL(T839829468_394, "$1 = #addChar($1, $2);$n", 24);
STRING_LITERAL(T839829468_395, "$1 = #resizeString($1, $2$3);$n", 31);
STRING_LITERAL(T839829468_396, "$1 = ($2) #incrSeqV2(&($1)->Sup, sizeof($3));$n", 47);
STRING_LITERAL(T839829468_397, "$1 = ($2) #incrSeqV2($1, sizeof($3));$n", 39);
STRING_LITERAL(T839829468_398, "$1->data[$1->$2]", 16);
STRING_LITERAL(T839829468_399, "++$1->$2;$n", 11);
STRING_LITERAL(T839829468_400, "(($1) && ($1)->$2 == 0)", 23);
STRING_LITERAL(T839829468_401, "#eqStrings($1, $2)", 18);
STRING_LITERAL(T839829468_402, "(#cmpStrings($1, $2) <= 0)", 26);
STRING_LITERAL(T839829468_403, "(#cmpStrings($1, $2) < 0)", 25);
STRING_LITERAL(T839829468_404, "$1.ClPrc == 0", 13);
STRING_LITERAL(T839829468_405, "$1 == 0", 7);
STRING_LITERAL(T839829468_406, "#nimIntToStr($1)", 16);
STRING_LITERAL(T839829468_407, "#nimInt64ToStr($1)", 18);
STRING_LITERAL(T839829468_408, "#nimBoolToStr($1)", 17);
STRING_LITERAL(T839829468_409, "#nimCharToStr($1)", 17);
STRING_LITERAL(T839829468_410, "#nimFloatToStr($1)", 18);
STRING_LITERAL(T839829468_411, "#cstrToNimstr($1)", 17);
STRING_LITERAL(T839829468_412, "no \'of\' operator available for pure objects", 43);
STRING_LITERAL(T839829468_413, "(($1) && ($2))", 14);
STRING_LITERAL(T839829468_414, "$1.m_type == $2", 15);
STRING_LITERAL(T839829468_415, "Nim_OfCheck_CACHE", 17);
STRING_LITERAL(T839829468_416, "static TNimType* $#[2];$n", 25);
STRING_LITERAL(T839829468_417, "#isObjWithCache($#.m_type, $#, $#)", 34);
STRING_LITERAL(T839829468_418, "($1)", 4);
STRING_LITERAL(T839829468_419, "sizeof($1)", 10);
STRING_LITERAL(T839829468_420, "if ($1) #nimGCunref($1);$n", 26);
STRING_LITERAL(T839829468_421, "($1) #newObjRC1($2, $3)", 23);
STRING_LITERAL(T839829468_422, "($1) #newObj($2, $3)", 20);
STRING_LITERAL(T839829468_423, "$1->finalizer = (void*)$2;$n", 28);
STRING_LITERAL(T839829468_424, "($1) #newObj($2, sizeof($3))", 28);
STRING_LITERAL(T839829468_425, "($1) #newSeqRC1($2, $3)", 23);
STRING_LITERAL(T839829468_426, "($1) #newSeq($2, $3)", 20);
STRING_LITERAL(T839829468_427, "($1)#nimNewSeqOfCap($2, $3)", 27);
STRING_LITERAL(T839829468_428, "((NI)sizeof($1))", 16);
STRING_LITERAL(T839829468_429, "(*($1*) ($2))", 13);
STRING_LITERAL(T839829468_430, "(($1) ($2))", 11);
STRING_LITERAL(T839829468_431, "($1Len0-1)", 10);
STRING_LITERAL(T839829468_432, "$1Len0", 6);
STRING_LITERAL(T839829468_433, "($1 ? (strlen($1)-1) : -1)", 26);
STRING_LITERAL(T839829468_434, "($1 ? strlen($1) : 0)", 21);
STRING_LITERAL(T839829468_435, "($1 ? ($1->Sup.len-1) : -1)", 27);
STRING_LITERAL(T839829468_436, "($1 ? $1->Sup.len : 0)", 22);
STRING_LITERAL(T839829468_437, "($1 ? ($1->len-1) : -1)", 23);
STRING_LITERAL(T839829468_438, "($1 ? $1->len : 0)", 18);
STRING_LITERAL(T839829468_439, "genArrayLen()", 13);
STRING_LITERAL(T839829468_440, "($1->Sup.len)", 13);
STRING_LITERAL(T839829468_441, "$1->len", 7);
STRING_LITERAL(T839829468_442, "unaryStmt", 9);
STRING_LITERAL(T839829468_443, "#nimGCref($1);$n", 16);
STRING_LITERAL(T839829468_444, "#nimGCunref($1);$n", 18);
STRING_LITERAL(T839829468_445, "$1 = #setLengthStr($1, $2);$n", 29);
STRING_LITERAL(T839829468_446, "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n", 54);
STRING_LITERAL(T839829468_447, "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n", 46);
STRING_LITERAL(T839829468_448, "($1- $2)", 8);
STRING_LITERAL(T839829468_449, "$1 |= ((", 8);
STRING_LITERAL(T839829468_450, ")1)<<(($2)%(sizeof(", 19);
STRING_LITERAL(T839829468_451, ")*8));$n", 8);
STRING_LITERAL(T839829468_452, "$1 &= ~(((", 10);
STRING_LITERAL(T839829468_453, ")1) << (($2) % (sizeof(", 23);
STRING_LITERAL(T839829468_454, ")*8)));$n", 9);
STRING_LITERAL(T839829468_455, "#countBits32($1)", 16);
STRING_LITERAL(T839829468_456, "#countBits64($1)", 16);
STRING_LITERAL(T839829468_457, "(($1 & ~ $2 ==0)&&($1 != $2))", 29);
STRING_LITERAL(T839829468_458, "(($1 & ~ $2)==0)", 16);
STRING_LITERAL(T839829468_459, "($1 & $2)", 9);
STRING_LITERAL(T839829468_460, "($1 | $2)", 9);
STRING_LITERAL(T839829468_461, "($1 & ~ $2)", 11);
STRING_LITERAL(T839829468_462, "($1 ^ $2)", 9);
STRING_LITERAL(T839829468_463, "fewCmps", 7);
STRING_LITERAL(T839829468_464, "$1 >= $2 && $1 <= $3", 20);
STRING_LITERAL(T839829468_465, "$1 == $2", 8);
STRING_LITERAL(T839829468_466, " || ", 4);
STRING_LITERAL(T839829468_467, "(($1 &(1U<<((NU)($2)&7U)))!=0)", 30);
STRING_LITERAL(T839829468_468, "(($1 &(1U<<((NU)($2)&15U)))!=0)", 31);
STRING_LITERAL(T839829468_469, "(($1 &(1U<<((NU)($2)&31U)))!=0)", 31);
STRING_LITERAL(T839829468_470, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)", 36);
STRING_LITERAL(T839829468_471, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)", 43);
STRING_LITERAL(T839829468_472, "genSetOp()", 10);
STRING_LITERAL(T839829468_473, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n", 34);
STRING_LITERAL(T839829468_474, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n", 36);
STRING_LITERAL(T839829468_475, "#cardSet($1, ", 13);
STRING_LITERAL(T839829468_476, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == "
"0);$n if (!$3) break;}$n", 88);
STRING_LITERAL(T839829468_477, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == "
"0);$n if (!$3) break;}$nif ($3) $3 = (memcmp($4, $5, $2) != 0);"
"$n", 129);
STRING_LITERAL(T839829468_478, "|", 1);
STRING_LITERAL(T839829468_479, "& ~", 3);
STRING_LITERAL(T839829468_480, "^", 1);
NIM_CONST TY554428 lookupopr_554426_839829468 = {((NimStringDesc*) &T839829468_476),
((NimStringDesc*) &T839829468_477),
((NimStringDesc*) &T839829468_52),
((NimStringDesc*) &T839829468_478),
((NimStringDesc*) &T839829468_479),
((NimStringDesc*) &T839829468_480)}
;
STRING_LITERAL(T839829468_481, "(memcmp($1, $2, ", 16);
STRING_LITERAL(T839829468_482, ")==0)", 5);
STRING_LITERAL(T839829468_483, "for ($1 = 0; $1 < $2; $1++) $n $3[$1] = $4[$1] $6 $5[$1];$n", 60);
STRING_LITERAL(T839829468_484, "genSetOp", 8);
STRING_LITERAL(T839829468_485, "$1->data", 8);
STRING_LITERAL(T839829468_486, "($1)+($2), ($3)-($2)+1", 22);
STRING_LITERAL(T839829468_487, "(*$1)->data+($2), ($3)-($2)+1", 29);
STRING_LITERAL(T839829468_488, "$1->data+($2), ($3)-($2)+1", 26);
STRING_LITERAL(T839829468_489, "openArrayLoc: ", 14);
STRING_LITERAL(T839829468_490, "", 0);
STRING_LITERAL(T839829468_491, "(*$1)->data, (*$1)->$2", 22);
STRING_LITERAL(T839829468_492, "$1.ClPrc($3$1.ClEnv)", 20);
STRING_LITERAL(T839829468_493, "$1.ClEnv? $1.ClPrc($3$1.ClEnv):(($4)($1.ClPrc))($2)", 51);
STRING_LITERAL(T839829468_494, "$1 = 0;$n", 9);
STRING_LITERAL(T839829468_495, "#chckNil((void*)$1);$n", 22);
STRING_LITERAL(T839829468_496, "#genericReset((void*)$1, $2);$n", 31);
STRING_LITERAL(T839829468_497, ";$n", 3);
STRING_LITERAL(T839829468_499, "compiler/ccgcalls.nim", 21);
NIM_CONST TY201018 T839829468_498 = {((NimStringDesc*) &T839829468_499),
((NI) 423)}
;
static NIM_CONST char136Set T839829468_500 = {
0x00, 0x00, 0x00, 0x00, 0x88, 0x01, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
;
STRING_LITERAL(T839829468_501, "wrong argument count", 20);
STRING_LITERAL(T839829468_502, "call expression expected for C++ pattern", 40);
NIM_CONST TY201018 T839829468_503 = {((NimStringDesc*) &T839829468_499),
((NI) 328)}
;
STRING_LITERAL(T839829468_504, "->", 2);
STRING_LITERAL(T839829468_505, ");$n", 4);
STRING_LITERAL(T839829468_506, "[", 1);
NIM_CONST TY201018 T839829468_507 = {((NimStringDesc*) &T839829468_499),
((NI) 472)}
;
STRING_LITERAL(T839829468_508, "varargs for objective C method?", 31);
STRING_LITERAL(T839829468_509, "Result: ", 8);
STRING_LITERAL(T839829468_510, "];$n", 4);
STRING_LITERAL(T839829468_511, "]", 1);
NIM_CONST TY201018 T839829468_512 = {((NimStringDesc*) &T839829468_265),
((NI) 925)}
;
STRING_LITERAL(T839829468_513, "<stdio.h>", 9);
STRING_LITERAL(T839829468_514, ", \"nil\"", 7);
STRING_LITERAL(T839829468_515, ", $1? ($1)->data:\"nil\"", 22);
STRING_LITERAL(T839829468_516, "printf($1$2);$n", 15);
STRING_LITERAL(T839829468_517, "%s", 2);
STRING_LITERAL(T839829468_518, "fflush(stdout);$n", 17);
STRING_LITERAL(T839829468_519, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n", 45);
STRING_LITERAL(T839829468_520, "#genericSeqDeepCopy($1, $2, $3);$n", 34);
STRING_LITERAL(T839829468_521, "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 62);
STRING_LITERAL(T839829468_522, "genDeepCopy: ", 13);
STRING_LITERAL(T839829468_523, "genMagicExpr: ", 14);
STRING_LITERAL(T839829468_524, "static NIM_CONST $1 $2 = $3;$n", 30);
STRING_LITERAL(T839829468_525, "memset($1, 0, sizeof($1));$n", 28);
STRING_LITERAL(T839829468_526, "for ($1 = $3; $1 <= $4; $1++) $n$2[(NU)($1)>>3] |=(1U<<((NU)($1"
")&7U));$n", 72);
STRING_LITERAL(T839829468_527, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n", 40);
STRING_LITERAL(T839829468_528, "for ($1 = $3; $1 <= $4; $1++) $n$2 |=((", 39);
STRING_LITERAL(T839829468_529, ")(1)<<(($1)%(sizeof(", 20);
STRING_LITERAL(T839829468_530, "$1 |=((", 7);
STRING_LITERAL(T839829468_531, ")(1)<<(($2)%(sizeof(", 20);
STRING_LITERAL(T839829468_532, "genCheckedRecordField", 21);
STRING_LITERAL(T839829468_533, "genObjConstr", 12);
STRING_LITERAL(T839829468_534, "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n", 52);
STRING_LITERAL(T839829468_535, "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n", 55);
STRING_LITERAL(T839829468_536, "LOC$1.source", 12);
STRING_LITERAL(T839829468_537, "union { $1 source; $2 dest; } LOC$3;$n", 38);
STRING_LITERAL(T839829468_538, "LOC$#.dest", 10);
STRING_LITERAL(T839829468_539, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n", 46);
STRING_LITERAL(T839829468_540, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n", 45);
STRING_LITERAL(T839829468_541, "$1[($2)- $3]", 12);
STRING_LITERAL(T839829468_542, "if ((NU)($1) >= (NU)($2Len0)) #raiseIndexError();$n", 51);
STRING_LITERAL(T839829468_543, "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n", 50);
STRING_LITERAL(T839829468_544, "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n", 51);
STRING_LITERAL(T839829468_545, "genTupleElem", 12);
STRING_LITERAL(T839829468_546, ".Field$1", 8);
STRING_LITERAL(T839829468_547, "expr(nkBracketExpr, ", 20);
STRING_LITERAL(T839829468_548, "genDeref ", 9);
STRING_LITERAL(T839829468_549, "genRecordFieldAux", 17);
STRING_LITERAL(T839829468_550, "genRecordField 3", 16);
STRING_LITERAL(T839829468_551, ".$1", 3);
STRING_LITERAL(T839829468_552, "} $1: ;$n", 9);
STRING_LITERAL(T839829468_553, "FR.len-=$1;$n", 13);
STRING_LITERAL(T839829468_554, "FR.len+=$1;$n", 13);
STRING_LITERAL(T839829468_555, "if (!$1) goto $2;$n", 19);
STRING_LITERAL(T839829468_556, "goto $1;$n", 10);
STRING_LITERAL(T839829468_557, "genIf()", 7);
STRING_LITERAL(T839829468_558, "->Sup", 5);
STRING_LITERAL(T839829468_559, "$1 = &$2;$n", 11);
STRING_LITERAL(T839829468_560, "if ($1) #chckObj($2.m_type, $3);$n", 34);
STRING_LITERAL(T839829468_561, "#chckObj($1.m_type, $2);$n", 26);
STRING_LITERAL(T839829468_562, "(($1)#$5($2, $3, $4))", 21);
STRING_LITERAL(T839829468_563, "chckRangeF", 10);
STRING_LITERAL(T839829468_564, "chckRange64", 11);
STRING_LITERAL(T839829468_565, "chckRange", 9);
STRING_LITERAL(T839829468_566, "CNSTCLOSURE", 11);
STRING_LITERAL(T839829468_567, "closure to closure created", 26);
STRING_LITERAL(T839829468_568, "$1.ClPrc = $2; $1.ClEnv = $3;$n", 31);
STRING_LITERAL(T839829468_569, "while (1) {$n", 13);
STRING_LITERAL(T839829468_570, "case statement must be exhaustive for computed goto", 51);
STRING_LITERAL(T839829468_571, "case statement has too many cases for computed goto", 51);
STRING_LITERAL(T839829468_572, "case statement has to start at 0 for computed goto", 50);
STRING_LITERAL(T839829468_573, "no case statement found for computed goto", 41);
STRING_LITERAL(T839829468_574, "TMP$1", 5);
STRING_LITERAL(T839829468_575, "static void* $#[$#] = {", 23);
STRING_LITERAL(T839829468_576, "&&TMP$#, ", 9);
STRING_LITERAL(T839829468_577, "&&TMP$#};$n", 11);
STRING_LITERAL(T839829468_578, "goto *$#[$#];$n", 15);
STRING_LITERAL(T839829468_579, "range notation not available for computed goto", 46);
STRING_LITERAL(T839829468_580, "TMP$#:$n", 8);
STRING_LITERAL(T839829468_581, "#nimProfile();$n", 16);
STRING_LITERAL(T839829468_582, "\'goto\' target must be a literal value", 37);
STRING_LITERAL(T839829468_583, "goto NIMSTATE_$#;$n", 19);
STRING_LITERAL(T839829468_584, "$1 = ($2*) #nimGetProcAddr($3, $4);$n", 37);
STRING_LITERAL(T839829468_585, "$2* $1;$n", 9);
STRING_LITERAL(T839829468_586, "#dbgRegisterGlobal($1, &$2, $3);$n", 34);
STRING_LITERAL(T839829468_587, "#nimGCvisit((void*)$1, 0);$n", 28);
STRING_LITERAL(T839829468_588, "N_NIMCALL(void, $1)(void)", 25);
STRING_LITERAL(T839829468_589, "#nimRegisterGlobalMarker($1);$n", 31);
STRING_LITERAL(T839829468_590, "$#($#);$n", 9);
STRING_LITERAL(T839829468_591, "$# = $#;$n", 10);
STRING_LITERAL(T839829468_592, "genVarTuple", 11);
STRING_LITERAL(T839829468_593, "genConstStmt", 12);
STRING_LITERAL(T839829468_594, "for statement not eliminated", 28);
STRING_LITERAL(T839829468_595, "if (#eqStrings($1, $2)) goto $3;$n", 34);
STRING_LITERAL(T839829468_596, "switch (#hashString($1) & $2) {$n", 33);
STRING_LITERAL(T839829468_597, "case $1: $n$2break;$n", 21);
STRING_LITERAL(T839829468_598, "goto LA$1;$n", 12);
STRING_LITERAL(T839829468_599, "LA$1: ;$n", 9);
STRING_LITERAL(T839829468_600, "if ($1 >= $2 && $1 <= $3) goto $4;$n", 36);
STRING_LITERAL(T839829468_601, "if ($1 == $2) goto $3;$n", 24);
STRING_LITERAL(T839829468_602, "NIMSTATE_$#:$n", 14);
STRING_LITERAL(T839829468_603, "switch ($1) {$n", 15);
STRING_LITERAL(T839829468_604, "default: __assume(0);$n", 23);
STRING_LITERAL(T839829468_605, "#popSafePoint();$n", 18);
STRING_LITERAL(T839829468_606, "#popCurrentException();$n", 25);
STRING_LITERAL(T839829468_607, "if ($1.status != 0) #popCurrentException();$n", 45);
STRING_LITERAL(T839829468_608, "goto BeforeRet;$n", 17);
STRING_LITERAL(T839829468_609, "no loop to break", 16);
STRING_LITERAL(T839829468_610, "extern $1", 9);
STRING_LITERAL(T839829468_611, "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n", 62);
STRING_LITERAL(T839829468_612, "genAsmOrEmitStmt()", 18);
STRING_LITERAL(T839829468_613, "\"", 1);
STRING_LITERAL(T839829468_614, "\\n\"\015\012", 5);
STRING_LITERAL(T839829468_615, "Exception", 9);
STRING_LITERAL(T839829468_616, "E_Base", 6);
STRING_LITERAL(T839829468_617, "try {$n", 7);
STRING_LITERAL(T839829468_618, "} catch (NimException& $1) {$n", 30);
STRING_LITERAL(T839829468_619, "#setFrame((TFrame*)&FR);$n", 26);
STRING_LITERAL(T839829468_620, "else ", 5);
STRING_LITERAL(T839829468_621, "#isObj($1.exp->m_type, $2)", 26);
STRING_LITERAL(T839829468_622, "if ($1) ", 8);
STRING_LITERAL(T839829468_623, "throw;$n", 8);
STRING_LITERAL(T839829468_624, "<setjmp.h>", 10);
STRING_LITERAL(T839829468_625, "#TSafePoint $1;$n", 17);
STRING_LITERAL(T839829468_626, "#pushSafePoint(&$1);$n", 22);
STRING_LITERAL(T839829468_627, "nimStdSetjmp", 12);
STRING_LITERAL(T839829468_628, "$1.status = setjmp($1.context);$n", 33);
STRING_LITERAL(T839829468_629, "nimSigSetjmp", 12);
STRING_LITERAL(T839829468_630, "$1.status = sigsetjmp($1.context, 0);$n", 39);
STRING_LITERAL(T839829468_631, "nimRawSetjmp", 12);
STRING_LITERAL(T839829468_632, "$1.status = _setjmp($1.context);$n", 34);
STRING_LITERAL(T839829468_633, "if ($1.status == 0) {$n", 23);
STRING_LITERAL(T839829468_634, "else {$n", 8);
STRING_LITERAL(T839829468_635, "else", 4);
STRING_LITERAL(T839829468_636, "$1.status = 0;$n", 16);
STRING_LITERAL(T839829468_637, "#isObj(#getCurrentException()->Sup.m_type, $1)", 46);
STRING_LITERAL(T839829468_638, "#isObj(#getCurrentException()->m_type, $1)", 42);
STRING_LITERAL(T839829468_639, "if ($1) {$n", 11);
STRING_LITERAL(T839829468_640, "if ($1.status != 0) #reraiseException();$n", 42);
STRING_LITERAL(T839829468_641, "#raiseException((#Exception*)$1, $2);$n", 39);
STRING_LITERAL(T839829468_642, "#reraiseException();$n", 22);
STRING_LITERAL(T839829468_643, "/*TYPESECTION*/", 15);
STRING_LITERAL(T839829468_644, "/*VARSECTION*/", 14);
STRING_LITERAL(T839829468_645, "/*INCLUDESECTION*/", 18);
STRING_LITERAL(T839829468_646, "bp", 2);
STRING_LITERAL(T839829468_647, "#dbgRegisterBreakpoint($1, (NCSTRING)$2, (NCSTRING)$3);$n", 57);
STRING_LITERAL(T839829468_648, "#dbgRegisterWatchpoint($1, (NCSTRING)$2, $3);$n", 47);
STRING_LITERAL(T839829468_649, "#pragma omp parallel for $4$nfor ($1 = $2; $1 <= $3; ++$1)", 58);
STRING_LITERAL(T839829468_651, "compiler/ccgstmts.nim", 21);
NIM_CONST TY201018 T839829468_650 = {((NimStringDesc*) &T839829468_651),
((NI) 145)}
;
STRING_LITERAL(T839829468_652, "STATE$1: ;$n", 12);
STRING_LITERAL(T839829468_653, "case -1: goto BeforeRet;$n", 26);
STRING_LITERAL(T839829468_654, "case $1: goto STATE$1;$n", 24);
STRING_LITERAL(T839829468_655, "if (((NI*) $1)[0] < 0) break;$n", 31);
STRING_LITERAL(T839829468_656, "if ((((NI*) $1.ClEnv)[0]) < 0) break;$n", 39);
STRING_LITERAL(T839829468_657, "); unknown node kind", 20);
NIM_CONST TY201018 T839829468_658 = {((NimStringDesc*) &T839829468_651),
((NI) 1122)}
;
STRING_LITERAL(T839829468_659, "Init000", 7);
STRING_LITERAL(T839829468_660, "DatInit000", 10);
STRING_LITERAL(T839829468_661, "NIM_EXTERNC N_NOINLINE(void, $1)(void);$N", 41);
STRING_LITERAL(T839829468_662, "\011$1();$N", 8);
STRING_LITERAL(T839829468_663, "N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDECL(void, NimMa"
"in)(void) {$N\011void (*volatile inner)();$N\011PreMain();$N\011inner = N"
"imMainInner;$N$2\011(*inner)();$N}$N$N", 162);
STRING_LITERAL(T839829468_664, "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N "
" HINSTANCE hPrevInstance, $N LP"
"STR lpCmdLine, int nCmdShow) {$N\011NimMain();$N\011return nim_program"
"_result;$N}$N$N", 206);
STRING_LITERAL(T839829468_665, "N_LIB_EXPORT N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDEC"
"L(void, NimMain)(void) {$N\011void (*volatile inner)();$N\011PreMain()"
";$N\011inner = NimMainInner;$N$2\011(*inner)();$N}$N$N", 175);
STRING_LITERAL(T839829468_666, "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N "
" LPVOID lpvReserved) {$N\011if(fwdreason == DLL_PROC"
"ESS_ATTACH) {$N\011NimMain();$N}$N\011return 1;$N}$N$N", 175);
STRING_LITERAL(T839829468_667, "<windows.h>", 11);
STRING_LITERAL(T839829468_668, "void NIM_POSIX_INIT NimMainInit(void) {$N\011NimMain();$N}$N$N", 59);
STRING_LITERAL(T839829468_669, "int cmdCount;$Nchar** cmdLine;$Nchar** gEnv;$NN_CDECL(void, Nim"
"MainInner)(void) {$N$1}$N$NN_CDECL(void, NimMain)(void) {$N\011void"
" (*volatile inner)();$N\011PreMain();$N\011inner = NimMainInner;$N$2\011("
"*inner)();$N}$N$N", 208);
STRING_LITERAL(T839829468_670, "int main(void) {$N\011NimMain();$N\011return 0;$N}$N$N", 48);
STRING_LITERAL(T839829468_671, "int main(int argc, char** args, char** env) {$N\011cmdLine = args;"
"$N\011cmdCount = argc;$N\011gEnv = env;$N\011NimMain();$N\011return nim_prog"
"ram_result;$N}$N$N", 145);
STRING_LITERAL(T839829468_672, "dbgRegisterBreakpoint", 21);
STRING_LITERAL(T839829468_673, "dbgRegisterFilename", 19);
STRING_LITERAL(T839829468_674, "dbgRegisterFilename($1);$N", 26);
STRING_LITERAL(T839829468_675, "\011#initStackBottomWith((void *)&inner);$N", 40);
STRING_LITERAL(T839829468_676, "void PreMainInner() {$N\011systemInit000();$N$1$2$3}$N$Nvoid PreMa"
"in() {$N\011void (*volatile inner)();$N\011systemDatInit000();$N\011inner"
" = PreMainInner;$N$4$5\011(*inner)();$N}$N$N", 168);
STRING_LITERAL(T839829468_677, "\011#initThreadVarsEmulation();$N", 30);
STRING_LITERAL(T839829468_678, "still forwarded: ", 17);
STRING_LITERAL(T839829468_679, "NIM_EXTERNC N_NOINLINE(void, $1)(void) {$N", 42);
STRING_LITERAL(T839829468_680, "static #TNimNode $1[$2];$n", 26);
STRING_LITERAL(T839829468_681, "static #TNimType $1[$2];$n", 26);
STRING_LITERAL(T839829468_682, "\011TFrame FR; FR.len = 0;$N", 25);
STRING_LITERAL(T839829468_683, "}$N$N", 5);
STRING_LITERAL(T839829468_684, "N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N", 46);
STRING_LITERAL(T839829468_685, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump"
"f */$N/* The generated code is subject to the original license. "
"*/$N", 131);
STRING_LITERAL(T839829468_686, "0.15.0", 6);
STRING_LITERAL(T839829468_687, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump"
"f */$N/* The generated code is subject to the original license. "
"*/$N/* Compiled for: $2, $3, $4 */$N/* Command for C compiler:$n"
" $5 */$N", 201);
extern NIM_CONST TY175082 Os_175068_4151366050;
extern NIM_CONST TY175510 Cpu_175496_4151366050;
STRING_LITERAL(T839829468_688, "#define NIM_INTBITS $1", 22);
STRING_LITERAL(T839829468_689, "typedef struct {$1} NimThreadVars;$n", 36);
STRING_LITERAL(T839829468_690, "#include \"nimbase.h\"", 20);
STRING_LITERAL(T839829468_691, "#include \"$1\"$N", 15);
STRING_LITERAL(T839829468_692, "#include $1$N", 13);
STRING_LITERAL(T839829468_693, "extern \"C\"", 10);
STRING_LITERAL(T839829468_694, "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n", 61);
STRING_LITERAL(T839829468_695, "__$1__", 6);
STRING_LITERAL(T839829468_696, "#ifndef $1$n#define $1$n", 24);
STRING_LITERAL(T839829468_697, "N_CDECL(void, NimMain)(void);$n", 31);
STRING_LITERAL(T839829468_698, "#endif /* $1 */$n", 17);
Tcgen527027* generatedheader_530201_839829468;
extern TNimType NTI527015; /* BModule */
Ropeobj177006* indent_530655_839829468;
extern TNimType NTI177004; /* Rope */
extern Gcheap49418 gch_49458_1689653243;
Ropeobj177006* nimtv_536656_839829468;
Ttypeseq290836* nimtvdeps_536674_839829468;
extern TNimType NTI290836; /* TTypeSeq */
Intset266030 nimtvdeclared_536675_839829468;
extern TNimType NTI266030; /* IntSet */
NI breakpointid_546860_839829468;
Ropeobj177006* gbreakpoints_546861_839829468;
extern TY527153* gmodules_527170_3723162438;
extern TNimType NTI527027; /* TCGen */
extern Debuginfo201009 gdebuginfo_201470_1926258066;
extern Toption168009Set goptions_168128_2607990831;
extern TNimType NTI290804; /* TSymSeq */
extern Tglobaloption168013Set gglobaloptions_168130_2607990831;
extern NimStringDesc* headerfile_168138_2607990831;
extern NimStringDesc* gprojectfull_168211_2607990831;
extern Tcommands168076 gcmd_168132_2607990831;
extern NI gerrorcounter_190072_155036129;
extern Ropeobj177006* rnl_177903_2381377266;
extern NI gforwardedprocscounter_527171_3723162438;
extern TNimType NTI290244; /* TTypeKind */
extern TNimType NTI201017; /* seq[(string, int)] */
extern Tsystemcc271002 ccompiler_271431_2528170400;
extern NimStringDesc* tnl_175644_4151366050;
extern NI floatsize_175642_4151366050;
extern Tgcmode168080 gselectedgc_168133_2607990831;
extern TNimType NTI290020; /* TNodeKind */
extern TNimType NTI134602; /* seq[string] */
extern TNimType NTI290435; /* TSymKind */
extern TNimType NTI290816; /* TLoc */
extern NI intsize_175641_4151366050;
extern TNimType NTI290524; /* TMagic */
extern TNimType NTI189350; /* seq[Rope] */
extern TNimType NTI290796; /* TNodeSeq */
extern Ropeobj177006* mainmodprocs_527148_3723162438;
extern Ropeobj177006* maindatinit_527151_3723162438;
extern Ropeobj177006* mainmodinit_527149_3723162438;
extern Ropeobj177006* othermodsinit_527150_3723162438;
extern Tsystemos175004 targetos_175629_4151366050;
extern TY189612* fileinfos_189629_155036129;
extern Tsystemcpu175452 targetcpu_175627_4151366050;
extern Ropeobj177006* gmapping_527152_3723162438;
N_NIMCALL(void, T839829468_2)(void) {
nimGCvisit((void*)generatedheader_530201_839829468, 0);
}
N_NIMCALL(void, T839829468_3)(void) {
nimGCvisit((void*)indent_530655_839829468, 0);
}
static N_INLINE(Cell46904*, usrtocell_51040_1689653243)(void* usr0) {
Cell46904* result0;
result0 = (Cell46904*)0;
result0 = ((Cell46904*) ((NI)((NU32)(((NI) (usr0))) - (NU32)(((NI)sizeof(Cell46904))))));
return result0;
}
static N_INLINE(void, rtladdzct_52201_1689653243)(Cell46904* c0) {
addzct_51017_1689653243((&gch_49458_1689653243.zct), c0);
}
static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0) {
{
Cell46904* c0;
if (!!((src0 == NIM_NIL))) goto LA3;
c0 = usrtocell_51040_1689653243(src0);
(*c0).refcount += ((NI) 8);
}
LA3: ;
{
Cell46904* c0;
if (!!(((*dest0) == NIM_NIL))) goto LA7;
c0 = usrtocell_51040_1689653243((*dest0));
{
(*c0).refcount -= ((NI) 8);
if (!((NU32)((*c0).refcount) < (NU32)(((NI) 8)))) goto LA11;
rtladdzct_52201_1689653243(c0);
}
LA11: ;
}
LA7: ;
(*dest0) = src0;
}
N_NIMCALL(void, T839829468_5)(void) {
nimGCvisit((void*)nimtv_536656_839829468, 0);
}
N_NIMCALL(void, T839829468_6)(void) {
nimGCvisit((void*)nimtvdeps_536674_839829468, 0);
}
static N_INLINE(void, nimGCunrefNoCycle)(void* p0) {
Cell46904* c0;
c0 = usrtocell_51040_1689653243(p0);
{
(*c0).refcount -= ((NI) 8);
if (!((NU32)((*c0).refcount) < (NU32)(((NI) 8)))) goto LA3;
rtladdzct_52201_1689653243(c0);
}
LA3: ;
}
N_NIMCALL(void, T839829468_7)(void) {
nimGCvisit((void*)nimtvdeclared_536675_839829468.head, 0);
nimGCvisit((void*)nimtvdeclared_536675_839829468.data, 0);
}
N_NIMCALL(void, T839829468_8)(void) {
nimGCvisit((void*)gbreakpoints_546861_839829468, 0);
}
N_NIMCALL(Tcgen527027*, getcgenmodule_530226_839829468)(Tsym290834* s0) {
Tcgen527027* result0;
result0 = (Tcgen527027*)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (((NI) 0) <= (*s0).position);
if (!(LOC3)) goto LA4;
LOC3 = ((*s0).position < (gmodules_527170_3723162438 ? gmodules_527170_3723162438->Sup.len : 0));
LA4: ;
if (!LOC3) goto LA5;
result0 = gmodules_527170_3723162438->data[(*s0).position];
}
goto LA1;
LA5: ;
{
result0 = NIM_NIL;
}
LA1: ;
return result0;
}
static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0) {
void* LOC1;
LOC1 = (void*)0;
LOC1 = memcpy(dest0, source0, ((size_t) (size0)));
}
static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0) {
copymem_7485_1689653243(((void*) ((&(*dest0).data[((*dest0).Sup.len)- 0]))), ((void*) ((*src0).data)), ((NI) ((NI)((*src0).Sup.len + ((NI) 1)))));
(*dest0).Sup.len += (*src0).Sup.len;
}
N_NIMCALL(NU32, hashowner_530977_839829468)(Tsym290834* s0) {
NU32 result0;
Tsym290834* m0;
Tsym290834* p0;
result0 = (NU32)0;
m0 = s0;
{
while (1) {
if (!!(((*m0).kind == ((Tsymkind290435) 6)))) goto LA2;
m0 = (*m0).owner;
} LA2: ;
}
p0 = (*m0).owner;
result0 = register_201121_1926258066((&gdebuginfo_201470_1926258066), (*(*p0).name).s, (*(*m0).name).s);
return result0;
}
static N_INLINE(void, incref_53019_1689653243)(Cell46904* c0) {
(*c0).refcount = (NI)((NU32)((*c0).refcount) + (NU32)(((NI) 8)));
}
static N_INLINE(void, decref_52601_1689653243)(Cell46904* c0) {
{
(*c0).refcount -= ((NI) 8);
if (!((NU32)((*c0).refcount) < (NU32)(((NI) 8)))) goto LA3;
rtladdzct_52201_1689653243(c0);
}
LA3: ;
}
static N_INLINE(void, asgnRef)(void** dest0, void* src0) {
{
Cell46904* LOC5;
if (!!((src0 == NIM_NIL))) goto LA3;
LOC5 = (Cell46904*)0;
LOC5 = usrtocell_51040_1689653243(src0);
incref_53019_1689653243(LOC5);
}
LA3: ;
{
Cell46904* LOC10;
if (!!(((*dest0) == NIM_NIL))) goto LA8;
LOC10 = (Cell46904*)0;
LOC10 = usrtocell_51040_1689653243((*dest0));
decref_52601_1689653243(LOC10);
}
LA8: ;
(*dest0) = src0;
}
N_NIMCALL(Toption168009Set, initprocoptions_560635_839829468)(Tcgen527027* m0) {
Toption168009Set result0;
memset((void*)(&result0), 0, sizeof(result0));
{
if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0)) goto LA3;
result0 = (goptions_168128_2607990831 & ~ 32768);
}
goto LA1;
LA3: ;
{
result0 = goptions_168128_2607990831;
}
LA1: ;
return result0;
}
N_NIMCALL(Tcproc527021*, newpreinitproc_560625_839829468)(Tcgen527027* m0) {
Tcproc527021* result0;
result0 = (Tcproc527021*)0;
result0 = newproc_527206_3723162438(NIM_NIL, m0);
(*result0).labels = ((NI) 100000);
return result0;
}
N_NIMCALL(Tcproc527021*, newpostinitproc_560630_839829468)(Tcgen527027* m0) {
Tcproc527021* result0;
result0 = (Tcproc527021*)0;
result0 = newproc_527206_3723162438(NIM_NIL, m0);
(*result0).labels = ((NI) 200000);
return result0;
}
N_NIMCALL(Ropeobj177006*, gettempname_531596_839829468)(Tcgen527027* m0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
result0 = (Ropeobj177006*)0;
LOC1 = (Ropeobj177006*)0;
LOC1 = rope_177401_2381377266(((NI64) ((*m0).labels)));
result0 = HEX26_177418_2381377266((*m0).tmpbase, LOC1);
(*m0).labels += ((NI) 1);
return result0;
}
N_NIMCALL(Tcgen527027*, rawnewmodule_560663_839829468)(Tsym290834* module0, NimStringDesc* filename0) {
Tcgen527027* result0;
NimStringDesc* LOC1;
NU32 LOC2;
NimStringDesc* LOC3;
NimStringDesc* LOC4;
NimStringDesc* LOC5;
result0 = (Tcgen527027*)0;
result0 = (Tcgen527027*) newObj((&NTI527015), sizeof(Tcgen527027));
(*result0).Sup.Sup.m_type = (&NTI527027);
LOC1 = (NimStringDesc*)0;
LOC2 = (NU32)0;
LOC2 = hashowner_530977_839829468(module0);
LOC3 = (NimStringDesc*)0;
LOC3 = HEX24_8401_1689653243(((NU64) (LOC2)));
LOC1 = rawNewString(LOC3->Sup.len + 2);
appendString(LOC1, ((NimStringDesc*) &T839829468_11));
appendString(LOC1, LOC3);
appendString(LOC1, ((NimStringDesc*) &T839829468_12));
asgnRefNoCycle((void**) (&(*result0).tmpbase), rope_177277_2381377266(LOC1));
initlinkedlist_147031_3771138726((&(*result0).headerfiles));
initintset_266885_2627731572((&(*result0).declaredthings));
initintset_266885_2627731572((&(*result0).declaredprotos));
LOC4 = (NimStringDesc*)0;
LOC4 = (*result0).cfilename; (*result0).cfilename = copyStringRC1(filename0);
if (LOC4) nimGCunrefNoCycle(LOC4);
LOC5 = (NimStringDesc*)0;
LOC5 = (*result0).filename; (*result0).filename = copyStringRC1(filename0);
if (LOC5) nimGCunrefNoCycle(LOC5);
initidtable_294019_850551059((&(*result0).typecache));
initidtable_294019_850551059((&(*result0).forwtypecache));
asgnRefNoCycle((void**) (&(*result0).module), module0);
initintset_266885_2627731572((&(*result0).typeinfomarker));
asgnRef((void**) (&(*result0).initproc), newproc_527206_3723162438(NIM_NIL, result0));
(*(*result0).initproc).options = initprocoptions_560635_839829468(result0);
asgnRef((void**) (&(*result0).preinitproc), newpreinitproc_560625_839829468(result0));
asgnRef((void**) (&(*result0).postinitproc), newpostinitproc_560630_839829468(result0));
initnodetable_294085_850551059((&(*result0).datacache));
if ((*result0).typestack) nimGCunrefNoCycle((*result0).typestack);
(*result0).typestack = (Ttypeseq290836*) newSeqRC1((&NTI290836), 0);
if ((*result0).forwardedprocs) nimGCunrefNoCycle((*result0).forwardedprocs);
(*result0).forwardedprocs = (Tsymseq290804*) newSeqRC1((&NTI290804), 0);
asgnRefNoCycle((void**) (&(*result0).typenodesname), gettempname_531596_839829468(result0));
asgnRefNoCycle((void**) (&(*result0).nimtypesname), gettempname_531596_839829468(result0));
{
if (!(((*module0).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0)) goto LA8;
(*result0).flags |= ((NU8)1)<<((((Codegenflag527025) 0))%(sizeof(NU8)*8));
(*(*result0).preinitproc).options &= ~(((NU32)1) << ((((Toption168009) 15)) % (sizeof(NU32)*8)));
(*(*result0).postinitproc).options &= ~(((NU32)1) << ((((Toption168009) 15)) % (sizeof(NU32)*8)));
}
LA8: ;
return result0;
}
N_NIMCALL(Tcgen527027*, rawnewmodule_561038_839829468)(Tsym290834* module0) {
Tcgen527027* result0;
NimStringDesc* LOC1;
result0 = (Tcgen527027*)0;
LOC1 = (NimStringDesc*)0;
LOC1 = tofullpath_190264_155036129(((NI32) ((*module0).position)));
result0 = rawnewmodule_560663_839829468(module0, LOC1);
return result0;
}
N_NIMCALL(Tcgen527027*, newmodule_561045_839829468)(Tsym290834* module0) {
Tcgen527027* result0;
result0 = (Tcgen527027*)0;
{
Tcgen527027* LOC3;
NimStringDesc* LOC6;
LOC3 = (Tcgen527027*)0;
LOC3 = getcgenmodule_530226_839829468(module0);
if (!!((LOC3 == NIM_NIL))) goto LA4;
LOC6 = (NimStringDesc*)0;
LOC6 = HEX24_194185_1689653243(T839829468_9);
internalerror_194113_155036129(LOC6);
}
LA4: ;
result0 = rawnewmodule_561038_839829468(module0);
{
if (!((gmodules_527170_3723162438 ? gmodules_527170_3723162438->Sup.len : 0) <= (*module0).position)) goto LA9;
gmodules_527170_3723162438 = (TY527153*) setLengthSeq(&(gmodules_527170_3723162438)->Sup, sizeof(Tcgen527027*), ((NI) ((NI)((*module0).position + ((NI) 1)))));
}
LA9: ;
asgnRef((void**) (&gmodules_527170_3723162438->data[(*module0).position]), result0);
{
if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 2))&63U)))!=0)) goto LA13;
{
NimStringDesc* LOC19;
NimStringDesc* LOC20;
if (!(((*module0).flags &(1U<<((NU)(((Tsymflag290184) 25))&31U)))!=0)) goto LA17;
LOC19 = (NimStringDesc*)0;
LOC20 = (NimStringDesc*)0;
LOC20 = tofilename_190260_155036129(((NI32) ((*module0).position)));
LOC19 = rawNewString(LOC20->Sup.len + 28);
appendString(LOC19, ((NimStringDesc*) &T839829468_13));
appendString(LOC19, LOC20);
internalerror_194113_155036129(LOC19);
}
LA17: ;
}
LA13: ;
return result0;
}
N_NIMCALL(Tpasscontext339002*, myopen_561115_839829468)(Tsym290834* module0) {
Tpasscontext339002* result0;
Tcgen527027* LOC1;
result0 = (Tpasscontext339002*)0;
LOC1 = (Tcgen527027*)0;
LOC1 = newmodule_561045_839829468(module0);
result0 = &LOC1->Sup;
{
NIM_BOOL LOC4;
NimStringDesc* f0;
NimStringDesc* LOC13;
NimStringDesc* LOC14;
LOC4 = (NIM_BOOL)0;
LOC4 = ((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 27))&63U)))!=0);
if (!(LOC4)) goto LA5;
LOC4 = (generatedheader_530201_839829468 == NIM_NIL);
LA5: ;
if (!LOC4) goto LA6;
{
if (!(((NI) 0) < (headerfile_168138_2607990831 ? headerfile_168138_2607990831->Sup.len : 0))) goto LA10;
f0 = headerfile_168138_2607990831;
}
goto LA8;
LA10: ;
{
f0 = gprojectfull_168211_2607990831;
}
LA8: ;
LOC13 = (NimStringDesc*)0;
LOC13 = completecfilepath_271854_2528170400(f0, NIM_TRUE);
LOC14 = (NimStringDesc*)0;
LOC14 = noschangeFileExt(LOC13, ((NimStringDesc*) &T839829468_14));
asgnRef((void**) (&generatedheader_530201_839829468), rawnewmodule_560663_839829468(module0, LOC14));
(*generatedheader_530201_839829468).flags |= ((NU8)1)<<((((Codegenflag527025) 3))%(sizeof(NU8)*8));
}
LA6: ;
return result0;
}
N_NIMCALL(NimStringDesc*, getcfile_561204_839829468)(Tcgen527027* m0) {
NimStringDesc* result0;
NimStringDesc* ext0;
NimStringDesc* LOC13;
NimStringDesc* LOC14;
result0 = (NimStringDesc*)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC3) goto LA4;
LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA4: ;
if (!LOC3) goto LA5;
ext0 = copyString(((NimStringDesc*) &T839829468_15));
}
goto LA1;
LA5: ;
{
NIM_BOOL LOC8;
LOC8 = (NIM_BOOL)0;
LOC8 = (gcmd_168132_2607990831 == ((Tcommands168076) 3));
if (LOC8) goto LA9;
LOC8 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 28))&31U)))!=0);
LA9: ;
if (!LOC8) goto LA10;
ext0 = copyString(((NimStringDesc*) &T839829468_16));
}
goto LA1;
LA10: ;
{
ext0 = copyString(((NimStringDesc*) &T839829468_17));
}
LA1: ;
LOC13 = (NimStringDesc*)0;
LOC13 = withpackagename_169065_2607990831((*m0).cfilename);
LOC14 = (NimStringDesc*)0;
LOC14 = completecfilepath_271854_2528170400(LOC13, NIM_TRUE);
result0 = noschangeFileExt(LOC14, ext0);
return result0;
}
N_NIMCALL(Tpasscontext339002*, myopencached_561249_839829468)(Tsym290834* module0, Trodreader330021* rd0) {
Tpasscontext339002* result0;
Tcgen527027* m0;
NimStringDesc* LOC1;
result0 = (Tpasscontext339002*)0;
m0 = newmodule_561045_839829468(module0);
LOC1 = (NimStringDesc*)0;
LOC1 = getcfile_561204_839829468(m0);
readmergeinfo_528613_2760143328(LOC1, m0);
result0 = &m0->Sup;
return result0;
}
static N_INLINE(NIM_BOOL, skipcodegen_339085_2355241294)(Tnode290802* n0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
result0 = (((NI) 0) < gerrorcounter_190072_155036129);
return result0;
}
N_NIMCALL(void, fillloc_530282_839829468)(Tloc290816* a0, Tlockind290808 k0, Ttype290840* typ0, Ropeobj177006* r0, Tstorageloc290812 s0) {
{
if (!((*a0).k == ((Tlockind290808) 0))) goto LA3;
(*a0).k = k0;
unsureAsgnRef((void**) (&(*a0).t), typ0);
(*a0).s = s0;
{
if (!((*a0).r == NIM_NIL)) goto LA7;
unsureAsgnRef((void**) (&(*a0).r), r0);
}
LA7: ;
}
LA3: ;
}
N_NIMCALL(NIM_BOOL, iskeyword_530960_839829468)(Tident197010* w0) {
NIM_BOOL result0;
{ result0 = (NIM_BOOL)0;
switch ((*w0).Sup.id) {
case ((NI) 200) ... ((NI) 262):
case ((NI) 4) ... ((NI) 70):
case ((NI) 138):
{
result0 = NIM_TRUE;
goto BeforeRet;
}
break;
default:
{
result0 = NIM_FALSE;
goto BeforeRet;
}
break;
}
}BeforeRet: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, manglename_531205_839829468)(Tsym290834* s0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = (*s0).loc.r;
{
NIM_BOOL keeporigname0;
NIM_BOOL LOC5;
NIM_BOOL LOC6;
NIM_BOOL LOC9;
NimStringDesc* LOC10;
if (!(result0 == NIM_NIL)) goto LA3;
LOC5 = (NIM_BOOL)0;
LOC6 = (NIM_BOOL)0;
LOC6 = ((2824 &(1U<<((NU)((*s0).kind)&31U)))!=0);
if (!(LOC6)) goto LA7;
LOC6 = ((IL64(2149580812) & (*s0).flags) == 0);
LA7: ;
LOC5 = LOC6;
if (!(LOC5)) goto LA8;
LOC9 = (NIM_BOOL)0;
LOC9 = iskeyword_530960_839829468((*s0).name);
LOC5 = !(LOC9);
LA8: ;
keeporigname0 = LOC5;
LOC10 = (NimStringDesc*)0;
LOC10 = mangle_526847_2036603609((*(*s0).name).s);
result0 = rope_177277_2381377266(LOC10);
{
if (!keeporigname0) goto LA13;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_18));
}
goto LA11;
LA13: ;
{
TY531289 LOC16;
Ropeobj177006* LOC17;
Ropeobj177006* LOC18;
TY531289 LOC19;
Ropeobj177006* LOC20;
NU32 LOC21;
Ropeobj177006* LOC22;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC17 = (Ropeobj177006*)0;
LOC17 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_12), LOC16, 0);
add_177482_2381377266(&result0, LOC17);
LOC18 = (Ropeobj177006*)0;
LOC18 = rope_177401_2381377266(((NI64) ((*s0).Sup.id)));
add_177482_2381377266(&result0, LOC18);
memset((void*)LOC19, 0, sizeof(LOC19));
LOC20 = (Ropeobj177006*)0;
LOC20 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_12), LOC19, 0);
add_177482_2381377266(&result0, LOC20);
LOC21 = (NU32)0;
LOC21 = hashowner_530977_839829468(s0);
LOC22 = (Ropeobj177006*)0;
LOC22 = rope_177401_2381377266(((NI64) (LOC21)));
add_177482_2381377266(&result0, LOC22);
}
LA11: ;
asgnRefNoCycle((void**) (&(*s0).loc.r), result0);
}
LA3: ;
return result0;
}
N_NIMCALL(void, fillprocloc_537201_839829468)(Tsym290834* sym0) {
{
Ropeobj177006* LOC5;
if (!((*sym0).loc.k == ((Tlockind290808) 0))) goto LA3;
LOC5 = (Ropeobj177006*)0;
LOC5 = manglename_531205_839829468(sym0);
fillloc_530282_839829468((&(*sym0).loc), ((Tlockind290808) 7), (*sym0).typ, LOC5, ((Tstorageloc290812) 2));
}
LA3: ;
}
N_NIMCALL(void, useheader_530369_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
{
NimStringDesc* LOC5;
NIM_BOOL LOC6;
if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 6))&15U)))!=0)) goto LA3;
LOC5 = (NimStringDesc*)0;
LOC5 = getstr_295230_850551059((*(*sym0).annex).path);
LOC6 = (NIM_BOOL)0;
LOC6 = includestr_147249_3771138726((&(*m0).headerfiles), LOC5);
}
LA3: ;
}
static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0) {
(*dest0).data[((*dest0).Sup.len)- 0] = c0;
(*dest0).data[((NI)((*dest0).Sup.len + ((NI) 1)))- 0] = 0;
(*dest0).Sup.len += ((NI) 1);
}
N_NIMCALL(NIM_BOOL, isactivated_559431_839829468)(Tsym290834* prc0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
result0 = !(((*prc0).typ == NIM_NIL));
return result0;
}
N_NIMCALL(void, addforwardedproc_530203_839829468)(Tcgen527027* m0, Tsym290834* prc0) {
(*m0).forwardedprocs = (Tsymseq290804*) incrSeqV2(&((*m0).forwardedprocs)->Sup, sizeof(Tsym290834*));
asgnRefNoCycle((void**) (&(*m0).forwardedprocs->data[(*m0).forwardedprocs->Sup.len]), prc0);
++(*m0).forwardedprocs->Sup.len;
gforwardedprocscounter_527171_3723162438 += ((NI) 1);
}
N_NIMCALL(void, genclinedir_530725_839829468)(Ropeobj177006** r0, NimStringDesc* filename0, NI line0) {
{
TY530811 LOC5;
NimStringDesc* LOC6;
if (!((goptions_168128_2607990831 &(1U<<((NU)(((Toption168009) 10))&31U)))!=0)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC6 = (NimStringDesc*)0;
LOC6 = makesinglelinecstring_526835_2036603609(filename0);
LOC5[0] = rope_177277_2381377266(LOC6);
LOC5[1] = rope_177401_2381377266(((NI64) (line0)));
addf_178205_2381377266(r0, ((NimStringDesc*) &T839829468_21), LOC5, 2);
}
LA3: ;
}
static N_INLINE(NI, tolinenumber_190415_155036129)(Tlineinfo189336 info0) {
NI result0;
result0 = (NI)0;
result0 = ((NI) (info0.line));
return result0;
}
N_NIMCALL(NI, safelinenm_530721_839829468)(Tlineinfo189336 info0) {
NI result0;
result0 = (NI)0;
result0 = tolinenumber_190415_155036129(info0);
{
if (!(result0 < ((NI) 0))) goto LA3;
result0 = ((NI) 0);
}
LA3: ;
return result0;
}
N_NIMCALL(void, genclinedir_530813_839829468)(Ropeobj177006** r0, Tlineinfo189336 info0) {
NimStringDesc* LOC1;
NI LOC2;
LOC1 = (NimStringDesc*)0;
LOC1 = tofullpath_190264_155036129(info0.fileindex);
LOC2 = (NI)0;
LOC2 = safelinenm_530721_839829468(info0);
genclinedir_530725_839829468(r0, LOC1, LOC2);
}
N_NIMCALL(Tctypekind527007, mapsettype_531389_839829468)(Ttype290840* typ0) {
Tctypekind527007 result0;
NI64 LOC1;
result0 = (Tctypekind527007)0;
LOC1 = (NI64)0;
LOC1 = getsize_318135_3876443242(typ0);
switch (((NI) (LOC1))) {
case ((NI) 1):
{
result0 = ((Tctypekind527007) 4);
}
break;
case ((NI) 2):
{
result0 = ((Tctypekind527007) 5);
}
break;
case ((NI) 4):
{
result0 = ((Tctypekind527007) 6);
}
break;
case ((NI) 8):
{
result0 = ((Tctypekind527007) 7);
}
break;
default:
{
result0 = ((Tctypekind527007) 17);
}
break;
}
return result0;
}
N_NIMCALL(Tctypekind527007, maptype_531393_839829468)(Ttype290840* typ0) {
Tctypekind527007 result0;
result0 = (Tctypekind527007)0;
switch ((*typ0).kind) {
case ((Ttypekind290244) 0):
case ((Ttypekind290244) 7):
{
result0 = ((Tctypekind527007) 0);
}
break;
case ((Ttypekind290244) 1):
{
result0 = ((Tctypekind527007) 2);
}
break;
case ((Ttypekind290244) 2):
{
result0 = ((Tctypekind527007) 1);
}
break;
case ((Ttypekind290244) 19):
{
result0 = mapsettype_531389_839829468(typ0);
}
break;
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 4):
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 48):
{
result0 = ((Tctypekind527007) 17);
}
break;
case ((Ttypekind290244) 17):
case ((Ttypekind290244) 18):
{
result0 = ((Tctypekind527007) 19);
}
break;
case ((Ttypekind290244) 10):
case ((Ttypekind290244) 11):
case ((Ttypekind290244) 12):
case ((Ttypekind290244) 13):
case ((Ttypekind290244) 15):
case ((Ttypekind290244) 46):
case ((Ttypekind290244) 47):
case ((Ttypekind290244) 49):
case ((Ttypekind290244) 8):
{
Ttype290840* LOC8;
LOC8 = (Ttype290840*)0;
LOC8 = lastson_293377_850551059(typ0);
result0 = maptype_531393_839829468(LOC8);
}
break;
case ((Ttypekind290244) 14):
{
{
NI64 LOC12;
LOC12 = (NI64)0;
LOC12 = firstord_318001_3876443242(typ0);
if (!(LOC12 < IL64(0))) goto LA13;
result0 = ((Tctypekind527007) 6);
}
goto LA10;
LA13: ;
{
NI64 LOC16;
LOC16 = (NI64)0;
LOC16 = getsize_318135_3876443242(typ0);
switch (((NI) (LOC16))) {
case ((NI) 1):
{
result0 = ((Tctypekind527007) 13);
}
break;
case ((NI) 2):
{
result0 = ((Tctypekind527007) 14);
}
break;
case ((NI) 4):
{
result0 = ((Tctypekind527007) 6);
}
break;
case ((NI) 8):
{
result0 = ((Tctypekind527007) 7);
}
break;
default:
{
internalerror_194113_155036129(((NimStringDesc*) &T839829468_25));
}
break;
}
}
LA10: ;
}
break;
case ((Ttypekind290244) 20):
{
result0 = maptype_531393_839829468((*typ0).sons->data[((NI) 0)]);
}
break;
case ((Ttypekind290244) 21):
case ((Ttypekind290244) 23):
case ((Ttypekind290244) 22):
{
Ttype290840* base0;
Ttype290840* LOC24;
LOC24 = (Ttype290840*)0;
LOC24 = lastson_293377_850551059(typ0);
base0 = skiptypes_294099_850551059(LOC24, IL64(211106232576256));
switch ((*base0).kind) {
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 4):
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 48):
{
result0 = ((Tctypekind527007) 18);
}
break;
default:
{
result0 = ((Tctypekind527007) 20);
}
break;
}
}
break;
case ((Ttypekind290244) 26):
{
result0 = ((Tctypekind527007) 20);
}
break;
case ((Ttypekind290244) 24):
{
result0 = ((Tctypekind527007) 22);
}
break;
case ((Ttypekind290244) 25):
{
{
if (!!(((*typ0).callconv == ((Tcallingconvention290002) 8)))) goto LA32;
result0 = ((Tctypekind527007) 23);
}
goto LA30;
LA32: ;
{
result0 = ((Tctypekind527007) 19);
}
LA30: ;
}
break;
case ((Ttypekind290244) 28):
{
result0 = ((Tctypekind527007) 21);
}
break;
case ((Ttypekind290244) 29):
{
result0 = ((Tctypekind527007) 24);
}
break;
case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44):
{
result0 = ((Tctypekind527007) ((NI)(((NI) ((NI)(((NI) ((*typ0).kind)) - ((NI) 31)))) + ((NI) 3))));
}
break;
case ((Ttypekind290244) 59):
{
{
Ttype290840* LOC43;
if (!!(((*typ0).n == NIM_NIL))) goto LA41;
LOC43 = (Ttype290840*)0;
LOC43 = lastson_293377_850551059(typ0);
result0 = maptype_531393_839829468(LOC43);
}
goto LA39;
LA41: ;
{
internalerror_194113_155036129(((NimStringDesc*) &T839829468_25));
}
LA39: ;
}
break;
default:
{
internalerror_194113_155036129(((NimStringDesc*) &T839829468_25));
}
break;
}
return result0;
}
N_NIMCALL(NIM_BOOL, isimportedcpptype_531476_839829468)(Ttype290840* t0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC1 = !(((*t0).sym == NIM_NIL));
if (!(LOC1)) goto LA2;
LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(NIM_BOOL, needscomplexassignment_531509_839829468)(Ttype290840* typ0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
result0 = containsgarbagecollectedref_318117_3876443242(typ0);
return result0;
}
static N_INLINE(NIM_BOOL, isobjlackingtypefield_531513_839829468)(Ttype290840* typ0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
NIM_BOOL LOC3;
NIM_BOOL LOC4;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC1 = ((*typ0).kind == ((Ttypekind290244) 17));
if (!(LOC1)) goto LA2;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0);
if (!(LOC4)) goto LA5;
LOC4 = ((*typ0).sons->data[((NI) 0)] == NIM_NIL);
LA5: ;
LOC3 = LOC4;
if (LOC3) goto LA6;
LOC3 = ispureobject_318138_3876443242(typ0);
LA6: ;
LOC1 = LOC3;
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(NIM_BOOL, isinvalidreturntype_531548_839829468)(Ttype290840* rettype0) {
NIM_BOOL result0;
{ result0 = (NIM_BOOL)0;
{
if (!(rettype0 == NIM_NIL)) goto LA3;
result0 = NIM_TRUE;
}
goto LA1;
LA3: ;
{
Tctypekind527007 LOC6;
LOC6 = (Tctypekind527007)0;
LOC6 = maptype_531393_839829468(rettype0);
switch (LOC6) {
case ((Tctypekind527007) 17):
{
Ttype290840* LOC8;
LOC8 = (Ttype290840*)0;
LOC8 = skiptypes_294099_850551059(rettype0, IL64(211106232576256));
result0 = !(((*LOC8).kind == ((Ttypekind290244) 23) || (*LOC8).kind == ((Ttypekind290244) 22) || (*LOC8).kind == ((Ttypekind290244) 21)));
}
break;
case ((Tctypekind527007) 19):
{
Ttype290840* t0;
NIM_BOOL LOC16;
NIM_BOOL LOC18;
NIM_BOOL LOC20;
t0 = skiptypes_294099_850551059(rettype0, IL64(211106232576256));
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = isimportedcpptype_531476_839829468(rettype0);
if (LOC12) goto LA13;
LOC12 = isimportedcpptype_531476_839829468(t0);
LA13: ;
if (!LOC12) goto LA14;
result0 = NIM_FALSE;
goto BeforeRet;
}
LA14: ;
LOC16 = (NIM_BOOL)0;
LOC16 = needscomplexassignment_531509_839829468(t0);
if (LOC16) goto LA17;
LOC18 = (NIM_BOOL)0;
LOC18 = ((*t0).kind == ((Ttypekind290244) 17));
if (!(LOC18)) goto LA19;
LOC20 = (NIM_BOOL)0;
LOC20 = isobjlackingtypefield_531513_839829468(t0);
LOC18 = !(LOC20);
LA19: ;
LOC16 = LOC18;
LA17: ;
result0 = LOC16;
}
break;
default:
{
result0 = NIM_FALSE;
}
break;
}
}
LA1: ;
}BeforeRet: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, typename_531292_839829468)(Ttype290840* typ0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NimStringDesc* LOC5;
if (!!(((*typ0).sym == NIM_NIL))) goto LA3;
LOC5 = (NimStringDesc*)0;
LOC5 = mangle_526847_2036603609((*(*(*typ0).sym).name).s);
result0 = rope_177277_2381377266(LOC5);
}
goto LA1;
LA3: ;
{
TY531289 LOC7;
memset((void*)LOC7, 0, sizeof(LOC7));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_28), LOC7, 0);
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, gettypename_531313_839829468)(Ttype290840* typ0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = !(((*typ0).sym == NIM_NIL));
if (!(LOC3)) goto LA4;
LOC3 = !(((96 & (*(*typ0).sym).flags) == 0));
LA4: ;
if (!LOC3) goto LA5;
result0 = (*(*typ0).sym).loc.r;
}
goto LA1;
LA5: ;
{
{
Ropeobj177006* LOC12;
Ropeobj177006* LOC13;
if (!((*typ0).loc.r == NIM_NIL)) goto LA10;
LOC12 = (Ropeobj177006*)0;
LOC12 = typename_531292_839829468(typ0);
LOC13 = (Ropeobj177006*)0;
LOC13 = rope_177401_2381377266(((NI64) ((*typ0).Sup.id)));
asgnRefNoCycle((void**) (&(*typ0).loc.r), HEX26_177418_2381377266(LOC12, LOC13));
}
LA10: ;
result0 = (*typ0).loc.r;
}
LA1: ;
{
NimStringDesc* LOC18;
if (!(result0 == NIM_NIL)) goto LA16;
LOC18 = (NimStringDesc*)0;
LOC18 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI290244))->Sup.len + 13);
appendString(LOC18, ((NimStringDesc*) &T839829468_29));
appendString(LOC18, reprEnum((NI)(*typ0).kind, (&NTI290244)));
internalerror_194113_155036129(LOC18);
}
LA16: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, typenameorliteral_531898_839829468)(Ttype290840* t0, NimStringDesc* literal0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NIM_BOOL LOC3;
NIM_BOOL LOC4;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = !(((*t0).sym == NIM_NIL));
if (!(LOC4)) goto LA5;
LOC4 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0);
LA5: ;
LOC3 = LOC4;
if (!(LOC3)) goto LA6;
LOC3 = ((*(*t0).sym).magic == ((Tmagic290524) 0));
LA6: ;
if (!LOC3) goto LA7;
result0 = gettypename_531313_839829468(t0);
}
goto LA1;
LA7: ;
{
result0 = rope_177277_2381377266(literal0);
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, getsimpletypedesc_531936_839829468)(Tcgen527027* m0, Ttype290840* typ0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
switch ((*typ0).kind) {
case ((Ttypekind290244) 26):
{
result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_30));
}
break;
case ((Ttypekind290244) 28):
{
Ropeobj177006* LOC3;
LOC3 = (Ropeobj177006*)0;
LOC3 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_31));
result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_32));
}
break;
case ((Ttypekind290244) 29):
{
result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_33));
}
break;
case ((Ttypekind290244) 1):
{
result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_34));
}
break;
case ((Ttypekind290244) 2):
{
result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_35));
}
break;
case ((Ttypekind290244) 5):
{
result0 = typenameorliteral_531898_839829468(typ0, ((NimStringDesc*) &T839829468_18));
}
break;
case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44):
{
result0 = typenameorliteral_531898_839829468(typ0, Numericaltypetostr_531941_839829468[((*typ0).kind)- 31]);
}
break;
case ((Ttypekind290244) 13):
case ((Ttypekind290244) 20):
case ((Ttypekind290244) 15):
{
result0 = getsimpletypedesc_531936_839829468(m0, (*typ0).sons->data[((NI) 0)]);
}
break;
case ((Ttypekind290244) 59):
{
{
Ttype290840* LOC15;
if (!!(((*typ0).n == NIM_NIL))) goto LA13;
LOC15 = (Ttype290840*)0;
LOC15 = lastson_293377_850551059(typ0);
result0 = getsimpletypedesc_531936_839829468(m0, LOC15);
}
goto LA11;
LA13: ;
{
internalerror_194113_155036129(((NimStringDesc*) &T839829468_50));
}
LA11: ;
}
break;
case ((Ttypekind290244) 11):
{
Ttype290840* LOC18;
LOC18 = (Ttype290840*)0;
LOC18 = lastson_293377_850551059(typ0);
result0 = getsimpletypedesc_531936_839829468(m0, LOC18);
}
break;
default:
{
result0 = NIM_NIL;
}
break;
}
return result0;
}
N_NIMCALL(Ropeobj177006*, cachegettype_531591_839829468)(Tidtable290850 tab0, Ttype290840* key0) {
Ropeobj177006* result0;
Tidobj197004* LOC1;
TNimObject* LOC2;
result0 = (Ropeobj177006*)0;
LOC1 = (Tidobj197004*)0;
LOC1 = &key0->Sup;
LOC2 = (TNimObject*)0;
LOC2 = idtableget_297086_2984716966(tab0, LOC1);
result0 = ((Ropeobj177006*) (LOC2));
return result0;
}
N_NIMCALL(Ropeobj177006*, gettypepre_531972_839829468)(Tcgen527027* m0, Ttype290840* typ0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
if (!(typ0 == NIM_NIL)) goto LA3;
result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_26));
}
goto LA1;
LA3: ;
{
result0 = getsimpletypedesc_531936_839829468(m0, typ0);
{
if (!(result0 == NIM_NIL)) goto LA8;
result0 = cachegettype_531591_839829468((*m0).typecache, typ0);
}
LA8: ;
}
LA1: ;
return result0;
}
N_NIMCALL(NIM_BOOL, isimportedtype_531449_839829468)(Ttype290840* t0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC1 = !(((*t0).sym == NIM_NIL));
if (!(LOC1)) goto LA2;
LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0);
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(NimStringDesc*, getforwardstructformat_532015_839829468)(Tcgen527027* m0) {
NimStringDesc* result0;
result0 = (NimStringDesc*)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC3) goto LA4;
LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA4: ;
if (!LOC3) goto LA5;
result0 = copyString(((NimStringDesc*) &T839829468_54));
}
goto LA1;
LA5: ;
{
result0 = copyString(((NimStringDesc*) &T839829468_55));
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, structorunion_532001_839829468)(Ttype290840* t0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag290431) 1))&31U)))!=0)) goto LA3;
result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_56));
}
goto LA1;
LA3: ;
{
result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_57));
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, gettypeforward_532039_839829468)(Tcgen527027* m0, Ttype290840* typ0) {
Ropeobj177006* result0;
{ result0 = (Ropeobj177006*)0;
result0 = cachegettype_531591_839829468((*m0).forwtypecache, typ0);
{
if (!!((result0 == NIM_NIL))) goto LA3;
goto BeforeRet;
}
LA3: ;
result0 = gettypepre_531972_839829468(m0, typ0);
{
if (!!((result0 == NIM_NIL))) goto LA7;
goto BeforeRet;
}
LA7: ;
switch ((*typ0).kind) {
case ((Ttypekind290244) 24):
case ((Ttypekind290244) 18):
case ((Ttypekind290244) 17):
{
Tidobj197004* LOC17;
TNimObject* LOC18;
result0 = gettypename_531313_839829468(typ0);
{
NIM_BOOL LOC12;
NimStringDesc* LOC15;
TY530811 LOC16;
LOC12 = (NIM_BOOL)0;
LOC12 = isimportedtype_531449_839829468(typ0);
if (!!(LOC12)) goto LA13;
LOC15 = (NimStringDesc*)0;
LOC15 = getforwardstructformat_532015_839829468(m0);
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = structorunion_532001_839829468(typ0);
LOC16[1] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 2))- 0], LOC15, LOC16, 2);
}
LA13: ;
LOC17 = (Tidobj197004*)0;
LOC17 = &typ0->Sup;
LOC18 = (TNimObject*)0;
LOC18 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).forwtypecache), LOC17, LOC18);
}
break;
default:
{
NimStringDesc* LOC20;
LOC20 = (NimStringDesc*)0;
LOC20 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI290244))->Sup.len + 16);
appendString(LOC20, ((NimStringDesc*) &T839829468_58));
appendString(LOC20, reprEnum((NI)(*typ0).kind, (&NTI290244)));
appendChar(LOC20, 41);
internalerror_194113_155036129(LOC20);
}
break;
}
}BeforeRet: ;
return result0;
}
N_NIMCALL(void, pushtype_531958_839829468)(Tcgen527027* m0, Ttype290840* typ0) {
(*m0).typestack = (Ttypeseq290836*) incrSeqV2(&((*m0).typestack)->Sup, sizeof(Ttype290840*));
asgnRefNoCycle((void**) (&(*m0).typestack->data[(*m0).typestack->Sup.len]), typ0);
++(*m0).typestack->Sup.len;
}
N_NIMCALL(Ropeobj177006*, gettypedescweak_532079_839829468)(Tcgen527027* m0, Ttype290840* t0, Intset266030* check0) {
Ropeobj177006* result0;
Ttype290840* etb0;
result0 = (Ropeobj177006*)0;
etb0 = skiptypes_294099_850551059(t0, IL64(211106232576256));
switch ((*etb0).kind) {
case ((Ttypekind290244) 17):
case ((Ttypekind290244) 18):
{
{
NIM_BOOL LOC4;
LOC4 = (NIM_BOOL)0;
LOC4 = isimportedcpptype_531476_839829468(etb0);
if (!(LOC4)) goto LA5;
LOC4 = ((*t0).kind == ((Ttypekind290244) 11));
LA5: ;
if (!LOC4) goto LA6;
result0 = gettypedescaux_531503_839829468(m0, t0, check0);
}
goto LA2;
LA6: ;
{
Ttype290840* x0;
x0 = getuniquetype_526640_2036603609(etb0);
result0 = gettypeforward_532039_839829468(m0, x0);
pushtype_531958_839829468(m0, x0);
}
LA2: ;
}
break;
case ((Ttypekind290244) 24):
{
Ttype290840* x0;
Ropeobj177006* LOC10;
x0 = getuniquetype_526640_2036603609(etb0);
LOC10 = (Ropeobj177006*)0;
LOC10 = gettypeforward_532039_839829468(m0, x0);
result0 = HEX26_177447_2381377266(LOC10, ((NimStringDesc*) &T839829468_53));
pushtype_531958_839829468(m0, x0);
}
break;
default:
{
result0 = gettypedescaux_531503_839829468(m0, t0, check0);
}
break;
}
return result0;
}
static N_INLINE(NI, len_291081_850551059)(Tnode290802* n0) {
NI result0;
result0 = (NI)0;
{
if (!(*n0).kindU.S6.sons == 0) goto LA3;
result0 = ((NI) 0);
}
goto LA1;
LA3: ;
{
result0 = ((*n0).kindU.S6.sons ? (*n0).kindU.S6.sons->Sup.len : 0);
}
LA1: ;
return result0;
}
N_NIMCALL(void, appcg_530632_839829468)(Tcgen527027* m0, Ropeobj177006** c0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) {
Ropeobj177006* LOC1;
LOC1 = (Ropeobj177006*)0;
LOC1 = ropecg_530407_839829468(m0, frmt0, args0, args0Len0);
add_177482_2381377266(c0, LOC1);
}
N_NIMCALL(NIM_BOOL, scancppgenericslot_532827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0) {
NIM_BOOL result0;
NI begin0;
{ result0 = (NIM_BOOL)0;
(*cursor0) += ((NI) 1);
begin0 = (*cursor0);
{
while (1) {
if (!((NU8)(pat0->data[(*cursor0)]) == (NU8)(42))) goto LA2;
(*cursor0) += ((NI) 1);
} LA2: ;
}
{
if (!(((NU8)(pat0->data[(*cursor0)])) >= ((NU8)(48)) && ((NU8)(pat0->data[(*cursor0)])) <= ((NU8)(57)))) goto LA5;
(*outidx0) = ((NI) ((NI)(((NI) (((NU8)(pat0->data[(*cursor0)])))) - ((NI) 48))));
(*outstars0) = (NI)((*cursor0) - begin0);
(*cursor0) += ((NI) 1);
result0 = NIM_TRUE;
goto BeforeRet;
}
goto LA3;
LA5: ;
{
result0 = NIM_FALSE;
goto BeforeRet;
}
LA3: ;
}BeforeRet: ;
return result0;
}
N_NIMCALL(Ttype290840*, resolvestarsincpptype_532891_839829468)(Ttype290840* typ0, NI idx0, NI stars0) {
Ttype290840* result0;
result0 = (Ttype290840*)0;
{
NI LOC3;
LOC3 = (NI)0;
LOC3 = len_293339_850551059(typ0);
if (!(LOC3 <= idx0)) goto LA4;
internalerror_194113_155036129(((NimStringDesc*) &T839829468_81));
}
LA4: ;
result0 = (*typ0).sons->data[idx0];
{
NI i_532906_839829468;
NI res_532931_839829468;
i_532906_839829468 = (NI)0;
res_532931_839829468 = ((NI) 1);
{
while (1) {
if (!(res_532931_839829468 <= stars0)) goto LA8;
i_532906_839829468 = res_532931_839829468;
{
NIM_BOOL LOC11;
NI LOC13;
LOC11 = (NIM_BOOL)0;
LOC11 = !((result0 == NIM_NIL));
if (!(LOC11)) goto LA12;
LOC13 = (NI)0;
LOC13 = len_293339_850551059(result0);
LOC11 = (((NI) 0) < LOC13);
LA12: ;
if (!LOC11) goto LA14;
{
if (!((*result0).kind == ((Ttypekind290244) 11))) goto LA18;
result0 = (*result0).sons->data[((NI) 1)];
}
goto LA16;
LA18: ;
{
result0 = elemtype_318394_3876443242(result0);
}
LA16: ;
}
LA14: ;
res_532931_839829468 += ((NI) 1);
} LA8: ;
}
}
return result0;
}
N_NIMCALL(NimStringDesc*, manglefield_530973_839829468)(Tident197010* name0) {
NimStringDesc* result0;
result0 = (NimStringDesc*)0;
result0 = mangle_526847_2036603609((*name0).s);
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = iskeyword_530960_839829468(name0);
if (!LOC3) goto LA4;
result0->data[((NI) 0)] = nsuToUpperAsciiChar(result0->data[((NI) 0)]);
}
LA4: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, manglerecfieldname_532361_839829468)(Tsym290834* field0, Ttype290840* rectype0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = !(((*rectype0).sym == NIM_NIL));
if (!(LOC3)) goto LA4;
LOC3 = !(((96 & (*(*rectype0).sym).flags) == 0));
LA4: ;
if (!LOC3) goto LA5;
result0 = (*field0).loc.r;
}
goto LA1;
LA5: ;
{
NimStringDesc* LOC8;
LOC8 = (NimStringDesc*)0;
LOC8 = manglefield_530973_839829468((*field0).name);
result0 = rope_177277_2381377266(LOC8);
}
LA1: ;
{
if (!(result0 == NIM_NIL)) goto LA11;
internalerror_194100_155036129((*field0).info, ((NimStringDesc*) &T839829468_96));
}
LA11: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, genrecordfieldsaux_532421_839829468)(Tcgen527027* m0, Tnode290802* n0, Ropeobj177006* accessexpr0, Ttype290840* rectype0, Intset266030* check0) {
Ropeobj177006* result0;
Ropeobj177006* ae0;
Ropeobj177006* uname0;
Ropeobj177006* sname0;
Ropeobj177006* a0;
Tnode290802* k0;
Tsym290834* field0;
{ result0 = (Ropeobj177006*)0;
ae0 = (Ropeobj177006*)0;
uname0 = (Ropeobj177006*)0;
sname0 = (Ropeobj177006*)0;
a0 = (Ropeobj177006*)0;
k0 = (Tnode290802*)0;
field0 = (Tsym290834*)0;
result0 = NIM_NIL;
switch ((*n0).kind) {
case ((Tnodekind290020) 138):
{
{
NI i_532447_839829468;
NI HEX3Atmp_532620_839829468;
NI LOC3;
NI res_532623_839829468;
i_532447_839829468 = (NI)0;
HEX3Atmp_532620_839829468 = (NI)0;
LOC3 = (NI)0;
LOC3 = sonslen_293351_850551059(n0);
HEX3Atmp_532620_839829468 = (NI)(LOC3 - ((NI) 1));
res_532623_839829468 = ((NI) 0);
{
while (1) {
Ropeobj177006* LOC6;
if (!(res_532623_839829468 <= HEX3Atmp_532620_839829468)) goto LA5;
i_532447_839829468 = res_532623_839829468;
LOC6 = (Ropeobj177006*)0;
LOC6 = genrecordfieldsaux_532421_839829468(m0, (*n0).kindU.S6.sons->data[i_532447_839829468], accessexpr0, rectype0, check0);
add_177482_2381377266(&result0, LOC6);
res_532623_839829468 += ((NI) 1);
} LA5: ;
}
}
}
break;
case ((Tnodekind290020) 139):
{
Ropeobj177006* LOC12;
NimStringDesc* LOC13;
NimStringDesc* LOC14;
Ropeobj177006* unionbody0;
{
if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)))) goto LA10;
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_89));
}
LA10: ;
LOC12 = (Ropeobj177006*)0;
LOC12 = genrecordfieldsaux_532421_839829468(m0, (*n0).kindU.S6.sons->data[((NI) 0)], accessexpr0, rectype0, check0);
add_177482_2381377266(&result0, LOC12);
LOC13 = (NimStringDesc*)0;
LOC14 = (NimStringDesc*)0;
LOC14 = mangle_526847_2036603609((*(*(*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s);
LOC13 = rawNewString(LOC14->Sup.len + 1);
appendString(LOC13, LOC14);
appendChar(LOC13, 85);
uname0 = rope_177277_2381377266(LOC13);
{
TY530811 LOC19;
if (!!((accessexpr0 == NIM_NIL))) goto LA17;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = accessexpr0;
LOC19[1] = uname0;
ae0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC19, 2);
}
goto LA15;
LA17: ;
{
ae0 = uname0;
}
LA15: ;
unionbody0 = NIM_NIL;
{
NI i_532491_839829468;
NI HEX3Atmp_532629_839829468;
NI LOC22;
NI res_532632_839829468;
i_532491_839829468 = (NI)0;
HEX3Atmp_532629_839829468 = (NI)0;
LOC22 = (NI)0;
LOC22 = sonslen_293351_850551059(n0);
HEX3Atmp_532629_839829468 = (NI)(LOC22 - ((NI) 1));
res_532632_839829468 = ((NI) 1);
{
while (1) {
if (!(res_532632_839829468 <= HEX3Atmp_532629_839829468)) goto LA24;
i_532491_839829468 = res_532632_839829468;
switch ((*(*n0).kindU.S6.sons->data[i_532491_839829468]).kind) {
case ((Tnodekind290020) 85):
case ((Tnodekind290020) 88):
{
k0 = lastson_293364_850551059((*n0).kindU.S6.sons->data[i_532491_839829468]);
{
Ropeobj177006* LOC30;
TY530811 LOC31;
Ropeobj177006* LOC32;
if (!!(((*k0).kind == ((Tnodekind290020) 3)))) goto LA28;
LOC30 = (Ropeobj177006*)0;
LOC30 = rope_177401_2381377266(((NI64) (i_532491_839829468)));
sname0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_91), LOC30);
memset((void*)LOC31, 0, sizeof(LOC31));
LOC31[0] = ae0;
LOC31[1] = sname0;
LOC32 = (Ropeobj177006*)0;
LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC31, 2);
a0 = genrecordfieldsaux_532421_839829468(m0, k0, LOC32, rectype0, check0);
{
TY177507 LOC37;
if (!!((a0 == NIM_NIL))) goto LA35;
add_177487_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_92));
add_177482_2381377266(&unionbody0, a0);
memset((void*)LOC37, 0, sizeof(LOC37));
LOC37[0] = sname0;
addf_178205_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_93), LOC37, 1);
}
LA35: ;
}
goto LA26;
LA28: ;
{
Ropeobj177006* LOC39;
LOC39 = (Ropeobj177006*)0;
LOC39 = genrecordfieldsaux_532421_839829468(m0, k0, ae0, rectype0, check0);
add_177482_2381377266(&unionbody0, LOC39);
}
LA26: ;
}
break;
default:
{
internalerror_194113_155036129(((NimStringDesc*) &T839829468_94));
}
break;
}
res_532632_839829468 += ((NI) 1);
} LA24: ;
}
}
{
TY530811 LOC45;
if (!!((unionbody0 == NIM_NIL))) goto LA43;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC45[0] = unionbody0;
LOC45[1] = uname0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_95), LOC45, 2);
}
LA43: ;
}
break;
case ((Tnodekind290020) 3):
{
field0 = (*n0).kindU.S4.sym;
{
if (!((*(*field0).typ).kind == ((Ttypekind290244) 62))) goto LA49;
goto BeforeRet;
}
LA49: ;
sname0 = manglerecfieldname_532361_839829468(field0, rectype0);
{
TY530811 LOC55;
if (!!((accessexpr0 == NIM_NIL))) goto LA53;
memset((void*)LOC55, 0, sizeof(LOC55));
LOC55[0] = accessexpr0;
LOC55[1] = sname0;
ae0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC55, 2);
}
goto LA51;
LA53: ;
{
ae0 = sname0;
}
LA51: ;
fillloc_530282_839829468((&(*field0).loc), ((Tlockind290808) 5), (*field0).typ, ae0, ((Tstorageloc290812) 0));
{
NIM_BOOL LOC59;
Ttype290840* fieldtype0;
LOC59 = (NIM_BOOL)0;
LOC59 = isimportedcpptype_531476_839829468(rectype0);
if (!!(LOC59)) goto LA60;
fieldtype0 = skiptypes_294099_850551059((*field0).loc.t, IL64(211106232576256));
{
NIM_BOOL LOC64;
TY530811 LOC68;
Ttype290840* LOC69;
LOC64 = (NIM_BOOL)0;
LOC64 = ((*fieldtype0).kind == ((Ttypekind290244) 16));
if (!(LOC64)) goto LA65;
LOC64 = (((*fieldtype0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0);
LA65: ;
if (!LOC64) goto LA66;
memset((void*)LOC68, 0, sizeof(LOC68));
LOC69 = (Ttype290840*)0;
LOC69 = elemtype_318394_3876443242(fieldtype0);
LOC68[0] = gettypedescaux_531503_839829468(m0, LOC69, check0);
LOC68[1] = sname0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_97), LOC68, 2);
}
goto LA62;
LA66: ;
{
TY530811 LOC73;
if (!((*fieldtype0).kind == ((Ttypekind290244) 24))) goto LA71;
memset((void*)LOC73, 0, sizeof(LOC73));
LOC73[0] = gettypedescweak_532079_839829468(m0, (*field0).loc.t, check0);
LOC73[1] = sname0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC73, 2);
}
goto LA62;
LA71: ;
{
TY533238 LOC77;
NimStringDesc* LOC78;
if (!!(((*field0).kindU.S4.bitsize == ((NI) 0)))) goto LA75;
memset((void*)LOC77, 0, sizeof(LOC77));
LOC77[0] = gettypedescaux_531503_839829468(m0, (*field0).loc.t, check0);
LOC77[1] = sname0;
LOC78 = (NimStringDesc*)0;
LOC78 = nimIntToStr((*field0).kindU.S4.bitsize);
LOC77[2] = rope_177277_2381377266(LOC78);
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_98), LOC77, 3);
}
goto LA62;
LA75: ;
{
TY530811 LOC80;
memset((void*)LOC80, 0, sizeof(LOC80));
LOC80[0] = gettypedescaux_531503_839829468(m0, (*field0).loc.t, check0);
LOC80[1] = sname0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC80, 2);
}
LA62: ;
}
LA60: ;
}
break;
default:
{
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_99));
}
break;
}
}BeforeRet: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, getrecordfields_532636_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = genrecordfieldsaux_532421_839829468(m0, (*typ0).n, NIM_NIL, typ0, check0);
return result0;
}
N_NIMCALL(Ropeobj177006*, getrecorddesc_532643_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0) {
Ropeobj177006* result0;
NIM_BOOL hasfield0;
Ropeobj177006* attribute0;
TY533238 LOC6;
Ropeobj177006* desc0;
NimStringDesc* LOC46;
result0 = (Ropeobj177006*)0;
hasfield0 = NIM_FALSE;
{
if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 21))&31U)))!=0)) goto LA3;
attribute0 = rope_177277_2381377266(Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field19);
}
goto LA1;
LA3: ;
{
attribute0 = NIM_NIL;
}
LA1: ;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = structorunion_532001_839829468(typ0);
LOC6[1] = name0;
LOC6[2] = attribute0;
result0 = ropecg_530407_839829468(m0, Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field18, LOC6, 3);
{
if (!((*typ0).kind == ((Ttypekind290244) 17))) goto LA9;
{
if (!((*typ0).sons->data[((NI) 0)] == NIM_NIL)) goto LA13;
{
NIM_BOOL LOC17;
NIM_BOOL LOC18;
TY531289 LOC23;
LOC17 = (NIM_BOOL)0;
LOC18 = (NIM_BOOL)0;
LOC18 = !(((*typ0).sym == NIM_NIL));
if (!(LOC18)) goto LA19;
LOC18 = (((*(*typ0).sym).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0);
LA19: ;
LOC17 = LOC18;
if (LOC17) goto LA20;
LOC17 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0);
LA20: ;
if (!LOC17) goto LA21;
memset((void*)LOC23, 0, sizeof(LOC23));
appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_85), LOC23, 0);
}
goto LA15;
LA21: ;
{
TY530811 LOC25;
memset((void*)LOC25, 0, sizeof(LOC25));
LOC25[0] = name0;
LOC25[1] = attribute0;
appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_86), LOC25, 2);
hasfield0 = NIM_TRUE;
}
LA15: ;
}
goto LA11;
LA13: ;
{
NIM_BOOL LOC27;
TY177507 LOC31;
Ttype290840* LOC32;
LOC27 = (NIM_BOOL)0;
LOC27 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC27) goto LA28;
LOC27 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA28: ;
if (!LOC27) goto LA29;
memset((void*)LOC31, 0, sizeof(LOC31));
LOC32 = (Ttype290840*)0;
LOC32 = skiptypes_294099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360));
LOC31[0] = gettypedescaux_531503_839829468(m0, LOC32, check0);
appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_87), LOC31, 1);
hasfield0 = NIM_TRUE;
}
goto LA11;
LA29: ;
{
TY177507 LOC34;
Ttype290840* LOC35;
memset((void*)LOC34, 0, sizeof(LOC34));
LOC35 = (Ttype290840*)0;
LOC35 = skiptypes_294099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360));
LOC34[0] = gettypedescaux_531503_839829468(m0, LOC35, check0);
appcg_530632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_88), LOC34, 1);
hasfield0 = NIM_TRUE;
}
LA11: ;
}
goto LA7;
LA9: ;
{
TY177507 LOC37;
memset((void*)LOC37, 0, sizeof(LOC37));
LOC37[0] = name0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_85), LOC37, 1);
}
LA7: ;
desc0 = getrecordfields_532636_839829468(m0, typ0, check0);
{
NIM_BOOL LOC40;
TY531289 LOC44;
LOC40 = (NIM_BOOL)0;
LOC40 = (desc0 == NIM_NIL);
if (!(LOC40)) goto LA41;
LOC40 = !(hasfield0);
LA41: ;
if (!LOC40) goto LA42;
memset((void*)LOC44, 0, sizeof(LOC44));
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_100), LOC44, 0);
}
goto LA38;
LA42: ;
{
add_177482_2381377266(&result0, desc0);
}
LA38: ;
LOC46 = (NimStringDesc*)0;
LOC46 = rawNewString(tnl_175644_4151366050->Sup.len + 2);
appendString(LOC46, ((NimStringDesc*) &T839829468_101));
appendString(LOC46, tnl_175644_4151366050);
add_177487_2381377266(&result0, LOC46);
return result0;
}
N_NIMCALL(Ropeobj177006*, gettupledesc_532777_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0, Intset266030* check0) {
Ropeobj177006* result0;
TY530811 LOC1;
Ropeobj177006* desc0;
NimStringDesc* LOC13;
result0 = (Ropeobj177006*)0;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = structorunion_532001_839829468(typ0);
LOC1[1] = name0;
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_102), LOC1, 2);
desc0 = NIM_NIL;
{
NI i_532799_839829468;
NI HEX3Atmp_532820_839829468;
NI LOC3;
NI res_532823_839829468;
i_532799_839829468 = (NI)0;
HEX3Atmp_532820_839829468 = (NI)0;
LOC3 = (NI)0;
LOC3 = sonslen_293327_850551059(typ0);
HEX3Atmp_532820_839829468 = (NI)(LOC3 - ((NI) 1));
res_532823_839829468 = ((NI) 0);
{
while (1) {
TY530811 LOC6;
if (!(res_532823_839829468 <= HEX3Atmp_532820_839829468)) goto LA5;
i_532799_839829468 = res_532823_839829468;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = gettypedescaux_531503_839829468(m0, (*typ0).sons->data[i_532799_839829468], check0);
LOC6[1] = rope_177401_2381377266(((NI64) (i_532799_839829468)));
addf_178205_2381377266(&desc0, ((NimStringDesc*) &T839829468_103), LOC6, 2);
res_532823_839829468 += ((NI) 1);
} LA5: ;
}
}
{
NimStringDesc* LOC11;
if (!(desc0 == NIM_NIL)) goto LA9;
LOC11 = (NimStringDesc*)0;
LOC11 = rawNewString(tnl_175644_4151366050->Sup.len + 11);
appendString(LOC11, ((NimStringDesc*) &T839829468_104));
appendString(LOC11, tnl_175644_4151366050);
add_177487_2381377266(&result0, LOC11);
}
goto LA7;
LA9: ;
{
add_177482_2381377266(&result0, desc0);
}
LA7: ;
LOC13 = (NimStringDesc*)0;
LOC13 = rawNewString(tnl_175644_4151366050->Sup.len + 2);
appendString(LOC13, ((NimStringDesc*) &T839829468_101));
appendString(LOC13, tnl_175644_4151366050);
add_177487_2381377266(&result0, LOC13);
return result0;
}
N_NIMCALL(Ropeobj177006*, gettypedescaux_531503_839829468)(Tcgen527027* m0, Ttype290840* typ0, Intset266030* check0) {
Ropeobj177006* result0;
Ttype290840* t_532942_839829468;
{ result0 = (Ropeobj177006*)0;
t_532942_839829468 = getuniquetype_526640_2036603609(typ0);
{
if (!(t_532942_839829468 == NIM_NIL)) goto LA3;
internalerror_194113_155036129(((NimStringDesc*) &T839829468_27));
}
LA3: ;
{
if (!!(((*t_532942_839829468).sym == NIM_NIL))) goto LA7;
useheader_530369_839829468(m0, (*t_532942_839829468).sym);
}
LA7: ;
result0 = gettypepre_531972_839829468(m0, t_532942_839829468);
{
if (!!((result0 == NIM_NIL))) goto LA11;
goto BeforeRet;
}
LA11: ;
{
NIM_BOOL LOC15;
LOC15 = (NIM_BOOL)0;
LOC15 = containsorincl_266862_2627731572(check0, (*t_532942_839829468).Sup.id);
if (!LOC15) goto LA16;
{
NIM_BOOL LOC20;
NimStringDesc* LOC24;
NimStringDesc* LOC25;
LOC20 = (NIM_BOOL)0;
LOC20 = isimportedcpptype_531476_839829468(typ0);
if (LOC20) goto LA21;
LOC20 = isimportedcpptype_531476_839829468(t_532942_839829468);
LA21: ;
if (!!(LOC20)) goto LA22;
LOC24 = (NimStringDesc*)0;
LOC25 = (NimStringDesc*)0;
LOC25 = typetostring_318017_3876443242(typ0, ((Tprefereddesc318011) 0));
LOC24 = rawNewString(LOC25->Sup.len + 28);
appendString(LOC24, ((NimStringDesc*) &T839829468_51));
appendString(LOC24, LOC25);
internalerror_194113_155036129(LOC24);
}
LA22: ;
}
LA16: ;
switch ((*t_532942_839829468).kind) {
case ((Ttypekind290244) 22):
case ((Ttypekind290244) 21):
case ((Ttypekind290244) 23):
{
NimStringDesc* star0;
Ttype290840* et0;
Ttype290840* LOC38;
Ttype290840* etb0;
{
NIM_BOOL LOC29;
NIM_BOOL LOC30;
NIM_BOOL LOC33;
LOC29 = (NIM_BOOL)0;
LOC30 = (NIM_BOOL)0;
LOC30 = ((*t_532942_839829468).kind == ((Ttypekind290244) 23));
if (!(LOC30)) goto LA31;
LOC30 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0));
LA31: ;
LOC29 = LOC30;
if (!(LOC29)) goto LA32;
LOC33 = (NIM_BOOL)0;
LOC33 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC33) goto LA34;
LOC33 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA34: ;
LOC29 = LOC33;
LA32: ;
if (!LOC29) goto LA35;
star0 = copyString(((NimStringDesc*) &T839829468_52));
}
goto LA27;
LA35: ;
{
star0 = copyString(((NimStringDesc*) &T839829468_53));
}
LA27: ;
LOC38 = (Ttype290840*)0;
LOC38 = skiptypes_294099_850551059(typ0, IL64(211106232576256));
et0 = lastson_293377_850551059(LOC38);
etb0 = skiptypes_294099_850551059(et0, IL64(211106232576256));
{
if (!((*etb0).kind == ((Ttypekind290244) 4) || (*etb0).kind == ((Ttypekind290244) 16) || (*etb0).kind == ((Ttypekind290244) 27) || (*etb0).kind == ((Ttypekind290244) 48))) goto LA41;
et0 = elemtype_318394_3876443242(etb0);
etb0 = skiptypes_294099_850551059(et0, IL64(211106232576256));
star0->data[((NI) 0)] = 42;
}
LA41: ;
switch ((*etb0).kind) {
case ((Ttypekind290244) 17):
case ((Ttypekind290244) 18):
{
{
NIM_BOOL LOC46;
Ropeobj177006* LOC50;
LOC46 = (NIM_BOOL)0;
LOC46 = isimportedcpptype_531476_839829468(etb0);
if (!(LOC46)) goto LA47;
LOC46 = ((*et0).kind == ((Ttypekind290244) 11));
LA47: ;
if (!LOC46) goto LA48;
LOC50 = (Ropeobj177006*)0;
LOC50 = gettypedescaux_531503_839829468(m0, et0, check0);
result0 = HEX26_177447_2381377266(LOC50, star0);
}
goto LA44;
LA48: ;
{
Ttype290840* x0;
Ropeobj177006* name0;
Tidobj197004* LOC52;
TNimObject* LOC53;
x0 = getuniquetype_526640_2036603609(etb0);
name0 = gettypeforward_532039_839829468(m0, x0);
result0 = HEX26_177447_2381377266(name0, star0);
LOC52 = (Tidobj197004*)0;
LOC52 = &t_532942_839829468->Sup;
LOC53 = (TNimObject*)0;
LOC53 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC52, LOC53);
pushtype_531958_839829468(m0, x0);
}
LA44: ;
}
break;
case ((Ttypekind290244) 24):
{
Ttype290840* x0;
Ropeobj177006* name0;
Ropeobj177006* LOC55;
Tidobj197004* LOC56;
TNimObject* LOC57;
x0 = getuniquetype_526640_2036603609(etb0);
name0 = gettypeforward_532039_839829468(m0, x0);
LOC55 = (Ropeobj177006*)0;
LOC55 = HEX26_177447_2381377266(name0, ((NimStringDesc*) &T839829468_53));
result0 = HEX26_177447_2381377266(LOC55, star0);
LOC56 = (Tidobj197004*)0;
LOC56 = &t_532942_839829468->Sup;
LOC57 = (TNimObject*)0;
LOC57 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC56, LOC57);
pushtype_531958_839829468(m0, x0);
}
break;
default:
{
Ropeobj177006* LOC59;
Tidobj197004* LOC60;
TNimObject* LOC61;
LOC59 = (Ropeobj177006*)0;
LOC59 = gettypedescaux_531503_839829468(m0, et0, check0);
result0 = HEX26_177447_2381377266(LOC59, star0);
LOC60 = (Tidobj197004*)0;
LOC60 = &t_532942_839829468->Sup;
LOC61 = (TNimObject*)0;
LOC61 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC60, LOC61);
}
break;
}
}
break;
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
Ropeobj177006* LOC63;
Tidobj197004* LOC64;
TNimObject* LOC65;
LOC63 = (Ropeobj177006*)0;
LOC63 = gettypedescweak_532079_839829468(m0, (*t_532942_839829468).sons->data[((NI) 0)], check0);
result0 = HEX26_177447_2381377266(LOC63, ((NimStringDesc*) &T839829468_53));
LOC64 = (Tidobj197004*)0;
LOC64 = &t_532942_839829468->Sup;
LOC65 = (TNimObject*)0;
LOC65 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC64, LOC65);
}
break;
case ((Ttypekind290244) 20):
case ((Ttypekind290244) 14):
{
Ttype290840* t0;
{
if (!((*t_532942_839829468).kind == ((Ttypekind290244) 20))) goto LA69;
t0 = lastson_293377_850551059(t_532942_839829468);
}
goto LA67;
LA69: ;
{
t0 = t_532942_839829468;
}
LA67: ;
result0 = cachegettype_531591_839829468((*m0).typecache, t0);
{
if (!(result0 == NIM_NIL)) goto LA74;
result0 = gettypename_531313_839829468(t0);
{
NIM_BOOL LOC78;
NIM_BOOL LOC80;
Tidobj197004* LOC84;
TNimObject* LOC85;
NI size0;
NU32 owner0;
LOC78 = (NIM_BOOL)0;
LOC78 = isimportedcpptype_531476_839829468(t0);
if (LOC78) goto LA79;
LOC80 = (NIM_BOOL)0;
LOC80 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0);
if (!(LOC80)) goto LA81;
LOC80 = ((*(*t0).sym).magic == ((Tmagic290524) 0));
LA81: ;
LOC78 = LOC80;
LA79: ;
if (!!(LOC78)) goto LA82;
LOC84 = (Tidobj197004*)0;
LOC84 = &t0->Sup;
LOC85 = (TNimObject*)0;
LOC85 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC84, LOC85);
size0 = (NI)0;
{
NI64 LOC88;
TY177507 LOC91;
LOC88 = (NI64)0;
LOC88 = firstord_318001_3876443242(t0);
if (!(LOC88 < IL64(0))) goto LA89;
memset((void*)LOC91, 0, sizeof(LOC91));
LOC91[0] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC91, 1);
size0 = ((NI) 4);
}
goto LA86;
LA89: ;
{
NI64 LOC93;
LOC93 = (NI64)0;
LOC93 = getsize_318135_3876443242(t0);
size0 = ((NI) (LOC93));
switch (size0) {
case ((NI) 1):
{
TY177507 LOC95;
memset((void*)LOC95, 0, sizeof(LOC95));
LOC95[0] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_60), LOC95, 1);
}
break;
case ((NI) 2):
{
TY177507 LOC97;
memset((void*)LOC97, 0, sizeof(LOC97));
LOC97[0] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_61), LOC97, 1);
}
break;
case ((NI) 4):
{
TY177507 LOC99;
memset((void*)LOC99, 0, sizeof(LOC99));
LOC99[0] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC99, 1);
}
break;
case ((NI) 8):
{
TY177507 LOC101;
memset((void*)LOC101, 0, sizeof(LOC101));
LOC101[0] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_62), LOC101, 1);
}
break;
default:
{
internalerror_194100_155036129((*(*t0).sym).info, ((NimStringDesc*) &T839829468_63));
}
break;
}
}
LA86: ;
owner0 = hashowner_530977_839829468((*t0).sym);
{
NIM_BOOL LOC105;
TY201017* vals0;
Enumdesc201007 LOC114;
LOC105 = (NIM_BOOL)0;
LOC105 = hasenum_201230_1926258066(gdebuginfo_201470_1926258066, (*(*(*t0).sym).name).s, ((NI) ((*(*t0).sym).info.line)), owner0);
if (!!(LOC105)) goto LA106;
vals0 = (TY201017*) newSeq((&NTI201017), 0);
{
NI i_533144_839829468;
NI HEX3Atmp_533648_839829468;
NI LOC109;
NI res_533651_839829468;
i_533144_839829468 = (NI)0;
HEX3Atmp_533648_839829468 = (NI)0;
LOC109 = (NI)0;
LOC109 = len_291081_850551059((*t0).n);
HEX3Atmp_533648_839829468 = (NI)(LOC109 - ((NI) 1));
res_533651_839829468 = ((NI) 0);
{
while (1) {
Tsym290834* field0;
TY201018 LOC112;
NimStringDesc* LOC113;
if (!(res_533651_839829468 <= HEX3Atmp_533648_839829468)) goto LA111;
i_533144_839829468 = res_533651_839829468;
field0 = (*(*(*t0).n).kindU.S6.sons->data[i_533144_839829468]).kindU.S4.sym;
memset((void*)(&LOC112), 0, sizeof(LOC112));
LOC112.Field0 = copyString((*(*field0).name).s);
LOC112.Field1 = (*field0).position;
vals0 = (TY201017*) incrSeqV2(&(vals0)->Sup, sizeof(TY201018));
LOC113 = (NimStringDesc*)0;
LOC113 = vals0->data[vals0->Sup.len].Field0; vals0->data[vals0->Sup.len].Field0 = copyStringRC1(LOC112.Field0);
if (LOC113) nimGCunrefNoCycle(LOC113);
vals0->data[vals0->Sup.len].Field1 = LOC112.Field1;
++vals0->Sup.len;
res_533651_839829468 += ((NI) 1);
} LA111: ;
}
}
memset((void*)(&LOC114), 0, sizeof(LOC114));
memset((void*)(&LOC114), 0, sizeof(LOC114));
LOC114.size = size0;
LOC114.owner = owner0;
LOC114.id = (*(*t0).sym).Sup.id;
LOC114.name = copyString((*(*(*t0).sym).name).s);
genericSeqAssign((&LOC114.values), vals0, (&NTI201017));
registerenum_201419_1926258066((&gdebuginfo_201470_1926258066), (&LOC114));
}
LA106: ;
}
LA82: ;
}
LA74: ;
}
break;
case ((Ttypekind290244) 25):
{
Tidobj197004* LOC116;
TNimObject* LOC117;
Ropeobj177006* rettype0;
Ropeobj177006* desc0;
result0 = gettypename_531313_839829468(t_532942_839829468);
LOC116 = (Tidobj197004*)0;
LOC116 = &t_532942_839829468->Sup;
LOC117 = (TNimObject*)0;
LOC117 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC116, LOC117);
rettype0 = (Ropeobj177006*)0;
desc0 = (Ropeobj177006*)0;
genprocparams_532115_839829468(m0, t_532942_839829468, &rettype0, &desc0, check0, NIM_TRUE, NIM_TRUE);
{
NIM_BOOL LOC120;
LOC120 = (NIM_BOOL)0;
LOC120 = isimportedtype_531449_839829468(t_532942_839829468);
if (!!(LOC120)) goto LA121;
{
TY533235 LOC127;
if (!!(((*t_532942_839829468).callconv == ((Tcallingconvention290002) 8)))) goto LA125;
memset((void*)LOC127, 0, sizeof(LOC127));
LOC127[0] = rope_177277_2381377266(Callingconvtostr_531585_839829468[((*t_532942_839829468).callconv)- 0]);
LOC127[1] = rettype0;
LOC127[2] = result0;
LOC127[3] = desc0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC127, 4);
}
goto LA123;
LA125: ;
{
TY533238 LOC129;
memset((void*)LOC129, 0, sizeof(LOC129));
LOC129[0] = result0;
LOC129[1] = rettype0;
LOC129[2] = desc0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC129, 3);
}
LA123: ;
}
LA121: ;
}
break;
case ((Ttypekind290244) 24):
{
Tidobj197004* LOC144;
Ropeobj177006* LOC145;
TNimObject* LOC146;
result0 = cachegettype_531591_839829468((*m0).forwtypecache, t_532942_839829468);
{
Tidobj197004* LOC142;
TNimObject* LOC143;
if (!(result0 == NIM_NIL)) goto LA133;
result0 = gettypename_531313_839829468(t_532942_839829468);
{
NIM_BOOL LOC137;
NimStringDesc* LOC140;
TY530811 LOC141;
LOC137 = (NIM_BOOL)0;
LOC137 = isimportedtype_531449_839829468(t_532942_839829468);
if (!!(LOC137)) goto LA138;
LOC140 = (NimStringDesc*)0;
LOC140 = getforwardstructformat_532015_839829468(m0);
memset((void*)LOC141, 0, sizeof(LOC141));
LOC141[0] = structorunion_532001_839829468(t_532942_839829468);
LOC141[1] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 2))- 0], LOC140, LOC141, 2);
}
LA138: ;
LOC142 = (Tidobj197004*)0;
LOC142 = &t_532942_839829468->Sup;
LOC143 = (TNimObject*)0;
LOC143 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).forwtypecache), LOC142, LOC143);
}
LA133: ;
LOC144 = (Tidobj197004*)0;
LOC144 = &t_532942_839829468->Sup;
LOC145 = (Ropeobj177006*)0;
LOC145 = HEX26_177447_2381377266(result0, ((NimStringDesc*) &T839829468_53));
LOC146 = (TNimObject*)0;
LOC146 = &LOC145->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC144, LOC146);
{
NIM_BOOL LOC149;
LOC149 = (NIM_BOOL)0;
LOC149 = isimportedtype_531449_839829468(t_532942_839829468);
if (!!(LOC149)) goto LA150;
{
Ttype290840* LOC154;
NimStringDesc* LOC157;
NimStringDesc* LOC158;
TY530811 LOC166;
LOC154 = (Ttype290840*)0;
LOC154 = skiptypes_294099_850551059((*t_532942_839829468).sons->data[((NI) 0)], IL64(211106232576256));
if (!!(((*LOC154).kind == ((Ttypekind290244) 3)))) goto LA155;
LOC157 = (NimStringDesc*)0;
LOC158 = (NimStringDesc*)0;
{
NIM_BOOL LOC161;
LOC161 = (NIM_BOOL)0;
LOC161 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC161) goto LA162;
LOC161 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA162: ;
if (!LOC161) goto LA163;
LOC158 = copyString(((NimStringDesc*) &T839829468_76));
}
goto LA159;
LA163: ;
{
LOC158 = copyString(((NimStringDesc*) &T839829468_77));
}
LA159: ;
LOC157 = rawNewString(LOC158->Sup.len + 31);
appendString(LOC157, LOC158);
appendString(LOC157, ((NimStringDesc*) &T839829468_78));
memset((void*)LOC166, 0, sizeof(LOC166));
LOC166[0] = gettypedescaux_531503_839829468(m0, (*t_532942_839829468).sons->data[((NI) 0)], check0);
LOC166[1] = result0;
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 4))- 0], LOC157, LOC166, 2);
}
goto LA152;
LA155: ;
{
result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_79));
}
LA152: ;
}
LA150: ;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_53));
}
break;
case ((Ttypekind290244) 4):
case ((Ttypekind290244) 16):
{
NI64 n0;
Tidobj197004* LOC173;
TNimObject* LOC174;
n0 = lengthord_318007_3876443242(t_532942_839829468);
{
if (!(n0 <= IL64(0))) goto LA171;
n0 = IL64(1);
}
LA171: ;
result0 = gettypename_531313_839829468(t_532942_839829468);
LOC173 = (Tidobj197004*)0;
LOC173 = &t_532942_839829468->Sup;
LOC174 = (TNimObject*)0;
LOC174 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC173, LOC174);
{
NIM_BOOL LOC177;
Ropeobj177006* foo0;
TY533238 LOC180;
LOC177 = (NIM_BOOL)0;
LOC177 = isimportedtype_531449_839829468(t_532942_839829468);
if (!!(LOC177)) goto LA178;
foo0 = gettypedescaux_531503_839829468(m0, (*t_532942_839829468).sons->data[((NI) 1)], check0);
memset((void*)LOC180, 0, sizeof(LOC180));
LOC180[0] = foo0;
LOC180[1] = result0;
LOC180[2] = rope_177401_2381377266(n0);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_80), LOC180, 3);
}
LA178: ;
}
break;
case ((Ttypekind290244) 17):
case ((Ttypekind290244) 18):
{
{
NIM_BOOL LOC184;
Ropeobj177006* cppname0;
NI i0;
NI chunkstart0;
Ropeobj177006* LOC226;
LOC184 = (NIM_BOOL)0;
LOC184 = isimportedcpptype_531476_839829468(t_532942_839829468);
if (!(LOC184)) goto LA185;
LOC184 = ((*typ0).kind == ((Ttypekind290244) 11));
LA185: ;
if (!LOC184) goto LA186;
cppname0 = gettypename_531313_839829468(t_532942_839829468);
i0 = ((NI) 0);
chunkstart0 = ((NI) 0);
{
while (1) {
if (!(i0 < ((*cppname0).data ? (*cppname0).data->Sup.len : 0))) goto LA189;
{
NI chunkend0;
NI idx0;
NI stars0;
if (!((NU8)((*cppname0).data->data[i0]) == (NU8)(39))) goto LA192;
chunkend0 = (i0 - 1);
idx0 = (NI)0;
stars0 = (NI)0;
{
NIM_BOOL LOC196;
NimStringDesc* LOC199;
Ttype290840* typeinslot0;
LOC196 = (NIM_BOOL)0;
LOC196 = scancppgenericslot_532827_839829468((*cppname0).data, (&i0), (&idx0), (&stars0));
if (!LOC196) goto LA197;
LOC199 = (NimStringDesc*)0;
LOC199 = copyStrLast((*cppname0).data, chunkstart0, chunkend0);
add_177487_2381377266(&result0, LOC199);
chunkstart0 = i0;
typeinslot0 = resolvestarsincpptype_532891_839829468(typ0, (NI)(idx0 + ((NI) 1)), stars0);
{
NIM_BOOL LOC202;
TY531289 LOC206;
Ropeobj177006* LOC207;
LOC202 = (NIM_BOOL)0;
LOC202 = (typeinslot0 == NIM_NIL);
if (LOC202) goto LA203;
LOC202 = ((*typeinslot0).kind == ((Ttypekind290244) 62));
LA203: ;
if (!LOC202) goto LA204;
memset((void*)LOC206, 0, sizeof(LOC206));
LOC207 = (Ropeobj177006*)0;
LOC207 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_26), LOC206, 0);
add_177482_2381377266(&result0, LOC207);
}
goto LA200;
LA204: ;
{
Ropeobj177006* LOC209;
LOC209 = (Ropeobj177006*)0;
LOC209 = gettypedescaux_531503_839829468(m0, typeinslot0, check0);
add_177482_2381377266(&result0, LOC209);
}
LA200: ;
}
LA197: ;
}
goto LA190;
LA192: ;
{
i0 += ((NI) 1);
}
LA190: ;
} LA189: ;
}
{
NimStringDesc* LOC215;
if (!!((chunkstart0 == ((NI) 0)))) goto LA213;
LOC215 = (NimStringDesc*)0;
LOC215 = copyStr((*cppname0).data, chunkstart0);
add_177487_2381377266(&result0, LOC215);
}
goto LA211;
LA213: ;
{
result0 = HEX26_177447_2381377266(cppname0, ((NimStringDesc*) &T839829468_82));
{
NI i_533516_839829468;
NI HEX3Atmp_533664_839829468;
NI LOC218;
NI res_533667_839829468;
i_533516_839829468 = (NI)0;
HEX3Atmp_533664_839829468 = (NI)0;
LOC218 = (NI)0;
LOC218 = len_293339_850551059(typ0);
HEX3Atmp_533664_839829468 = (NI)(LOC218 - ((NI) 2));
res_533667_839829468 = ((NI) 1);
{
while (1) {
Ropeobj177006* LOC225;
if (!(res_533667_839829468 <= HEX3Atmp_533664_839829468)) goto LA220;
i_533516_839829468 = res_533667_839829468;
{
if (!(((NI) 1) < i_533516_839829468)) goto LA223;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_83));
}
LA223: ;
LOC225 = (Ropeobj177006*)0;
LOC225 = gettypedescaux_531503_839829468(m0, (*typ0).sons->data[i_533516_839829468], check0);
add_177482_2381377266(&result0, LOC225);
res_533667_839829468 += ((NI) 1);
} LA220: ;
}
}
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_84));
}
LA211: ;
LOC226 = (Ropeobj177006*)0;
LOC226 = getrecorddesc_532643_839829468(m0, t_532942_839829468, result0, check0);
}
goto LA182;
LA186: ;
{
Tidobj197004* LOC241;
TNimObject* LOC242;
Ropeobj177006* recdesc0;
result0 = cachegettype_531591_839829468((*m0).forwtypecache, t_532942_839829468);
{
Tidobj197004* LOC239;
TNimObject* LOC240;
if (!(result0 == NIM_NIL)) goto LA230;
result0 = gettypename_531313_839829468(t_532942_839829468);
{
NIM_BOOL LOC234;
NimStringDesc* LOC237;
TY530811 LOC238;
LOC234 = (NIM_BOOL)0;
LOC234 = isimportedtype_531449_839829468(t_532942_839829468);
if (!!(LOC234)) goto LA235;
LOC237 = (NimStringDesc*)0;
LOC237 = getforwardstructformat_532015_839829468(m0);
memset((void*)LOC238, 0, sizeof(LOC238));
LOC238[0] = structorunion_532001_839829468(t_532942_839829468);
LOC238[1] = result0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 2))- 0], LOC237, LOC238, 2);
}
LA235: ;
LOC239 = (Tidobj197004*)0;
LOC239 = &t_532942_839829468->Sup;
LOC240 = (TNimObject*)0;
LOC240 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).forwtypecache), LOC239, LOC240);
}
LA230: ;
LOC241 = (Tidobj197004*)0;
LOC241 = &t_532942_839829468->Sup;
LOC242 = (TNimObject*)0;
LOC242 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC241, LOC242);
{
if (!!(((*t_532942_839829468).kind == ((Ttypekind290244) 18)))) goto LA245;
recdesc0 = getrecorddesc_532643_839829468(m0, t_532942_839829468, result0, check0);
}
goto LA243;
LA245: ;
{
recdesc0 = gettupledesc_532777_839829468(m0, t_532942_839829468, result0, check0);
}
LA243: ;
{
NIM_BOOL LOC250;
LOC250 = (NIM_BOOL)0;
LOC250 = isimportedtype_531449_839829468(t_532942_839829468);
if (!!(LOC250)) goto LA251;
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], recdesc0);
}
LA251: ;
}
LA182: ;
}
break;
case ((Ttypekind290244) 19):
{
Ttype290840* LOC254;
Ropeobj177006* LOC255;
Tidobj197004* LOC256;
TNimObject* LOC257;
LOC254 = (Ttype290840*)0;
LOC254 = lastson_293377_850551059(t_532942_839829468);
LOC255 = (Ropeobj177006*)0;
LOC255 = gettypename_531313_839829468(LOC254);
result0 = HEX26_177447_2381377266(LOC255, ((NimStringDesc*) &T839829468_105));
LOC256 = (Tidobj197004*)0;
LOC256 = &t_532942_839829468->Sup;
LOC257 = (TNimObject*)0;
LOC257 = &result0->Sup;
idtableput_297094_2984716966((&(*m0).typecache), LOC256, LOC257);
{
NIM_BOOL LOC260;
NI s0;
NI64 LOC263;
LOC260 = (NIM_BOOL)0;
LOC260 = isimportedtype_531449_839829468(t_532942_839829468);
if (!!(LOC260)) goto LA261;
LOC263 = (NI64)0;
LOC263 = getsize_318135_3876443242(t_532942_839829468);
s0 = ((NI) (LOC263));
switch (s0) {
case ((NI) 1):
case ((NI) 2):
case ((NI) 4):
case ((NI) 8):
{
TY530811 LOC265;
memset((void*)LOC265, 0, sizeof(LOC265));
LOC265[0] = result0;
LOC265[1] = rope_177401_2381377266(((NI64) ((NI)(s0 * ((NI) 8)))));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_106), LOC265, 2);
}
break;
default:
{
TY530811 LOC267;
NI64 LOC268;
memset((void*)LOC267, 0, sizeof(LOC267));
LOC267[0] = result0;
LOC268 = (NI64)0;
LOC268 = getsize_318135_3876443242(t_532942_839829468);
LOC267[1] = rope_177401_2381377266(LOC268);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_107), LOC267, 2);
}
break;
}
}
LA261: ;
}
break;
case ((Ttypekind290244) 11):
case ((Ttypekind290244) 13):
case ((Ttypekind290244) 15):
case ((Ttypekind290244) 46):
case ((Ttypekind290244) 47):
case ((Ttypekind290244) 49):
case ((Ttypekind290244) 8):
{
Ttype290840* LOC270;
LOC270 = (Ttype290840*)0;
LOC270 = lastson_293377_850551059(t_532942_839829468);
result0 = gettypedescaux_531503_839829468(m0, LOC270, check0);
}
break;
default:
{
NimStringDesc* LOC272;
LOC272 = (NimStringDesc*)0;
LOC272 = rawNewString(reprEnum((NI)(*t_532942_839829468).kind, (&NTI290244))->Sup.len + 16);
appendString(LOC272, ((NimStringDesc*) &T839829468_108));
appendString(LOC272, reprEnum((NI)(*t_532942_839829468).kind, (&NTI290244)));
appendChar(LOC272, 41);
internalerror_194113_155036129(LOC272);
result0 = NIM_NIL;
}
break;
}
excl_266841_2627731572(check0, (*t_532942_839829468).Sup.id);
}BeforeRet: ;
return result0;
}
static N_INLINE(NIM_BOOL, iscompiletimeonly_326706_3876443242)(Ttype290840* t0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
result0 = ((*t0).kind == ((Ttypekind290244) 8) || (*t0).kind == ((Ttypekind290244) 59));
return result0;
}
N_NIMCALL(Tstorageloc290812, paramstorageloc_532098_839829468)(Tsym290834* param0) {
Tstorageloc290812 result0;
result0 = (Tstorageloc290812)0;
{
Ttype290840* LOC3;
LOC3 = (Ttype290840*)0;
LOC3 = skiptypes_294099_850551059((*param0).typ, 8388864);
if (!!(((*LOC3).kind == ((Ttypekind290244) 16) || (*LOC3).kind == ((Ttypekind290244) 27) || (*LOC3).kind == ((Ttypekind290244) 48) || (*LOC3).kind == ((Ttypekind290244) 4)))) goto LA4;
result0 = ((Tstorageloc290812) 2);
}
goto LA1;
LA4: ;
{
result0 = ((Tstorageloc290812) 0);
}
LA1: ;
return result0;
}
N_NIMCALL(NIM_BOOL, ccgintroducedptr_531609_839829468)(Tsym290834* s0) {
NIM_BOOL result0;
Ttype290840* pt0;
{ result0 = (NIM_BOOL)0;
pt0 = skiptypes_294099_850551059((*s0).typ, IL64(211106232576256));
{
if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag290431) 13))&31U)))!=0)) goto LA3;
result0 = NIM_TRUE;
goto BeforeRet;
}
goto LA1;
LA3: ;
{
if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag290431) 12))&31U)))!=0)) goto LA6;
result0 = NIM_FALSE;
goto BeforeRet;
}
goto LA1;
LA6: ;
LA1: ;
switch ((*pt0).kind) {
case ((Ttypekind290244) 17):
{
{
NIM_BOOL LOC11;
NI64 LOC13;
LOC11 = (NIM_BOOL)0;
LOC11 = (((*s0).options &(1U<<((NU)(((Toption168009) 18))&31U)))!=0);
if (LOC11) goto LA12;
LOC13 = (NI64)0;
LOC13 = getsize_318135_3876443242(pt0);
LOC11 = (((NI64) ((NI)(floatsize_175642_4151366050 * ((NI) 2)))) < LOC13);
LA12: ;
if (!LOC11) goto LA14;
result0 = NIM_TRUE;
}
goto LA9;
LA14: ;
{
NIM_BOOL LOC17;
LOC17 = (NIM_BOOL)0;
LOC17 = (((*pt0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0);
if (!(LOC17)) goto LA18;
LOC17 = ((*pt0).sons->data[((NI) 0)] == NIM_NIL);
LA18: ;
if (!LOC17) goto LA19;
result0 = NIM_FALSE;
}
goto LA9;
LA19: ;
{
result0 = NIM_TRUE;
}
LA9: ;
}
break;
case ((Ttypekind290244) 18):
{
NIM_BOOL LOC23;
NI64 LOC24;
LOC23 = (NIM_BOOL)0;
LOC24 = (NI64)0;
LOC24 = getsize_318135_3876443242(pt0);
LOC23 = (((NI64) ((NI)(floatsize_175642_4151366050 * ((NI) 2)))) < LOC24);
if (LOC23) goto LA25;
LOC23 = (((*s0).options &(1U<<((NU)(((Toption168009) 18))&31U)))!=0);
LA25: ;
result0 = LOC23;
}
break;
default:
{
result0 = NIM_FALSE;
}
break;
}
}BeforeRet: ;
return result0;
}
N_NIMCALL(Tctypekind527007, mapreturntype_531445_839829468)(Ttype290840* typ0) {
Tctypekind527007 result0;
result0 = (Tctypekind527007)0;
result0 = maptype_531393_839829468(typ0);
return result0;
}
N_NIMCALL(void, genprocparams_532115_839829468)(Tcgen527027* m0, Ttype290840* t0, Ropeobj177006** rettype0, Ropeobj177006** params0, Intset266030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0) {
unsureAsgnRef((void**) (&(*params0)), NIM_NIL);
{
NIM_BOOL LOC3;
TY531289 LOC7;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*t0).sons->data[((NI) 0)] == NIM_NIL);
if (LOC3) goto LA4;
LOC3 = isinvalidreturntype_531548_839829468((*t0).sons->data[((NI) 0)]);
LA4: ;
if (!LOC3) goto LA5;
memset((void*)LOC7, 0, sizeof(LOC7));
unsureAsgnRef((void**) (&(*rettype0)), HEX25_177905_2381377266(((NimStringDesc*) &T839829468_26), LOC7, 0));
}
goto LA1;
LA5: ;
{
unsureAsgnRef((void**) (&(*rettype0)), gettypedescaux_531503_839829468(m0, (*t0).sons->data[((NI) 0)], check0));
}
LA1: ;
{
NI i_532152_839829468;
NI HEX3Atmp_532353_839829468;
NI LOC10;
NI res_532356_839829468;
i_532152_839829468 = (NI)0;
HEX3Atmp_532353_839829468 = (NI)0;
LOC10 = (NI)0;
LOC10 = sonslen_293351_850551059((*t0).n);
HEX3Atmp_532353_839829468 = (NI)(LOC10 - ((NI) 1));
res_532356_839829468 = ((NI) 1);
{
while (1) {
if (!(res_532356_839829468 <= HEX3Atmp_532353_839829468)) goto LA12;
i_532152_839829468 = res_532356_839829468;
{
Tsym290834* param0;
Ropeobj177006* LOC29;
Tstorageloc290812 LOC30;
TY531289 LOC45;
Ropeobj177006* LOC46;
Ttype290840* arr0;
NI j0;
{
if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_532152_839829468]).kind == ((Tnodekind290020) 3)))) goto LA16;
internalerror_194100_155036129((*(*t0).n).info, ((NimStringDesc*) &T839829468_109));
}
LA16: ;
param0 = (*(*(*t0).n).kindU.S6.sons->data[i_532152_839829468]).kindU.S4.sym;
{
NIM_BOOL LOC20;
LOC20 = (NIM_BOOL)0;
LOC20 = iscompiletimeonly_326706_3876443242((*param0).typ);
if (!LOC20) goto LA21;
goto LA13;
}
LA21: ;
{
TY531289 LOC27;
Ropeobj177006* LOC28;
if (!!(((*params0) == NIM_NIL))) goto LA25;
memset((void*)LOC27, 0, sizeof(LOC27));
LOC28 = (Ropeobj177006*)0;
LOC28 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC27, 0);
add_177482_2381377266(params0, LOC28);
}
LA25: ;
LOC29 = (Ropeobj177006*)0;
LOC29 = manglename_531205_839829468(param0);
LOC30 = (Tstorageloc290812)0;
LOC30 = paramstorageloc_532098_839829468(param0);
fillloc_530282_839829468((&(*param0).loc), ((Tlockind290808) 4), (*param0).typ, LOC29, LOC30);
{
NIM_BOOL LOC33;
Ropeobj177006* LOC36;
TY531289 LOC37;
Ropeobj177006* LOC38;
LOC33 = (NIM_BOOL)0;
LOC33 = ccgintroducedptr_531609_839829468(param0);
if (!LOC33) goto LA34;
LOC36 = (Ropeobj177006*)0;
LOC36 = gettypedescweak_532079_839829468(m0, (*param0).typ, check0);
add_177482_2381377266(params0, LOC36);
memset((void*)LOC37, 0, sizeof(LOC37));
LOC38 = (Ropeobj177006*)0;
LOC38 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_53), LOC37, 0);
add_177482_2381377266(params0, LOC38);
(*param0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 0))%(sizeof(NU16)*8));
(*param0).loc.s = ((Tstorageloc290812) 0);
}
goto LA31;
LA34: ;
{
Ropeobj177006* LOC42;
if (!weakdep0) goto LA40;
LOC42 = (Ropeobj177006*)0;
LOC42 = gettypedescweak_532079_839829468(m0, (*param0).typ, check0);
add_177482_2381377266(params0, LOC42);
}
goto LA31;
LA40: ;
{
Ropeobj177006* LOC44;
LOC44 = (Ropeobj177006*)0;
LOC44 = gettypedescaux_531503_839829468(m0, (*param0).typ, check0);
add_177482_2381377266(params0, LOC44);
}
LA31: ;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC46 = (Ropeobj177006*)0;
LOC46 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC45, 0);
add_177482_2381377266(params0, LOC46);
add_177482_2381377266(params0, (*param0).loc.r);
arr0 = (*param0).typ;
{
if (!((*arr0).kind == ((Ttypekind290244) 23))) goto LA49;
arr0 = (*arr0).sons->data[((NI) 0)];
}
LA49: ;
j0 = ((NI) 0);
{
while (1) {
TY530811 LOC57;
if (!((*arr0).kind == ((Ttypekind290244) 27) || (*arr0).kind == ((Ttypekind290244) 48))) goto LA52;
{
if (!((*(*param0).typ).kind == ((Ttypekind290244) 23))) goto LA55;
(*param0).loc.s = ((Tstorageloc290812) 0);
}
LA55: ;
memset((void*)LOC57, 0, sizeof(LOC57));
LOC57[0] = (*param0).loc.r;
LOC57[1] = rope_177401_2381377266(((NI64) (j0)));
addf_178205_2381377266(params0, ((NimStringDesc*) &T839829468_112), LOC57, 2);
j0 += ((NI) 1);
arr0 = (*arr0).sons->data[((NI) 0)];
} LA52: ;
}
} LA13: ;
res_532356_839829468 += ((NI) 1);
} LA12: ;
}
}
{
NIM_BOOL LOC60;
Ttype290840* arr0;
TY531289 LOC76;
LOC60 = (NIM_BOOL)0;
LOC60 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL));
if (!(LOC60)) goto LA61;
LOC60 = isinvalidreturntype_531548_839829468((*t0).sons->data[((NI) 0)]);
LA61: ;
if (!LOC60) goto LA62;
arr0 = (*t0).sons->data[((NI) 0)];
{
if (!!(((*params0) == NIM_NIL))) goto LA66;
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_110));
}
LA66: ;
{
Tctypekind527007 LOC70;
Ropeobj177006* LOC73;
LOC70 = (Tctypekind527007)0;
LOC70 = mapreturntype_531445_839829468((*t0).sons->data[((NI) 0)]);
if (!!((LOC70 == ((Tctypekind527007) 17)))) goto LA71;
LOC73 = (Ropeobj177006*)0;
LOC73 = gettypedescweak_532079_839829468(m0, arr0, check0);
add_177482_2381377266(params0, LOC73);
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_53));
}
goto LA68;
LA71: ;
{
Ropeobj177006* LOC75;
LOC75 = (Ropeobj177006*)0;
LOC75 = gettypedescaux_531503_839829468(m0, arr0, check0);
add_177482_2381377266(params0, LOC75);
}
LA68: ;
memset((void*)LOC76, 0, sizeof(LOC76));
addf_178205_2381377266(params0, ((NimStringDesc*) &T839829468_113), LOC76, 0);
}
LA62: ;
{
NIM_BOOL LOC79;
LOC79 = (NIM_BOOL)0;
LOC79 = ((*t0).callconv == ((Tcallingconvention290002) 8));
if (!(LOC79)) goto LA80;
LOC79 = declareenvironment0;
LA80: ;
if (!LOC79) goto LA81;
{
if (!!(((*params0) == NIM_NIL))) goto LA85;
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_110));
}
LA85: ;
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_114));
}
LA81: ;
{
if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0)) goto LA89;
{
if (!!(((*params0) == NIM_NIL))) goto LA93;
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_110));
}
LA93: ;
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_115));
}
LA89: ;
{
if (!((*params0) == NIM_NIL)) goto LA97;
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_116));
}
goto LA95;
LA97: ;
{
add_177487_2381377266(params0, ((NimStringDesc*) &T839829468_117));
}
LA95: ;
unsureAsgnRef((void**) (&(*params0)), HEX26_177452_2381377266(((NimStringDesc*) &T839829468_118), (*params0)));
}
N_NIMCALL(Ropeobj177006*, genprocheader_533867_839829468)(Tcgen527027* m0, Tsym290834* prc0) {
Ropeobj177006* result0;
Ropeobj177006* rettype0;
Ropeobj177006* params0;
Intset266030 check0;
Ropeobj177006* LOC13;
result0 = (Ropeobj177006*)0;
rettype0 = (Ropeobj177006*)0;
params0 = (Ropeobj177006*)0;
genclinedir_530813_839829468(&result0, (*prc0).info);
{
if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 5))&15U)))!=0)) goto LA3;
{
if (!(((*m0).flags &(1U<<((NU)(((Codegenflag527025) 3))&7U)))!=0)) goto LA7;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_22));
}
goto LA5;
LA7: ;
{
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_23));
}
LA5: ;
}
goto LA1;
LA3: ;
{
if (!((*(*prc0).typ).callconv == ((Tcallingconvention290002) 5))) goto LA11;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_24));
}
goto LA1;
LA11: ;
LA1: ;
memset((void*)(&check0), 0, sizeof(check0));
chckNil((void*)(&check0));
memset((void*)(&check0), 0, sizeof(check0));
initintset_266885_2627731572((&check0));
LOC13 = (Ropeobj177006*)0;
LOC13 = manglename_531205_839829468(prc0);
fillloc_530282_839829468((&(*prc0).loc), ((Tlockind290808) 7), (*prc0).typ, LOC13, ((Tstorageloc290812) 0));
genprocparams_532115_839829468(m0, (*prc0).typ, &rettype0, ¶ms0, (&check0), NIM_TRUE, NIM_FALSE);
{
TY533235 LOC18;
if (!(*prc0).constraint == 0) goto LA16;
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = rope_177277_2381377266(Callingconvtostr_531585_839829468[((*(*prc0).typ).callconv)- 0]);
LOC18[1] = rettype0;
LOC18[2] = (*prc0).loc.r;
LOC18[3] = params0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_119), LOC18, 4);
}
goto LA14;
LA16: ;
{
TY533238 LOC20;
memset((void*)LOC20, 0, sizeof(LOC20));
LOC20[0] = rettype0;
LOC20[1] = (*prc0).loc.r;
LOC20[2] = params0;
result0 = HEX25_177905_2381377266((*(*prc0).constraint).kindU.S3.strval, LOC20, 3);
}
LA14: ;
return result0;
}
static N_INLINE(Tnode290802*, HEX5BHEX5D_291238_850551059)(Tnode290802* n0, NI i0) {
Tnode290802* result0;
result0 = (Tnode290802*)0;
result0 = (*n0).kindU.S6.sons->data[i0];
return result0;
}
N_NIMCALL(Tnode290802*, easyresultasgn_558191_839829468)(Tnode290802* n0) {
Tnode290802* result0;
{ result0 = (Tnode290802*)0;
switch ((*n0).kind) {
case ((Tnodekind290020) 115):
case ((Tnodekind290020) 126):
{
NI i0;
i0 = ((NI) 0);
{
while (1) {
NIM_BOOL LOC4;
NI LOC5;
Tnode290802* LOC7;
LOC4 = (NIM_BOOL)0;
LOC5 = (NI)0;
LOC5 = len_291081_850551059(n0);
LOC4 = (i0 < LOC5);
if (!(LOC4)) goto LA6;
LOC7 = (Tnode290802*)0;
LOC7 = HEX5BHEX5D_291238_850551059(n0, i0);
LOC4 = ((*LOC7).kind == ((Tnodekind290020) 1) || (*LOC7).kind >= ((Tnodekind290020) 79) && (*LOC7).kind <= ((Tnodekind290020) 81) || (*LOC7).kind == ((Tnodekind290020) 84) || (*LOC7).kind == ((Tnodekind290020) 98) || (*LOC7).kind == ((Tnodekind290020) 101) || (*LOC7).kind == ((Tnodekind290020) 125));
LA6: ;
if (!LOC4) goto LA3;
i0 += ((NI) 1);
} LA3: ;
}
{
NI LOC10;
Tnode290802* LOC13;
LOC10 = (NI)0;
LOC10 = len_291081_850551059(n0);
if (!(i0 < LOC10)) goto LA11;
LOC13 = (Tnode290802*)0;
LOC13 = HEX5BHEX5D_291238_850551059(n0, i0);
result0 = easyresultasgn_558191_839829468(LOC13);
}
LA11: ;
}
break;
case ((Tnodekind290020) 73):
case ((Tnodekind290020) 74):
{
{
NIM_BOOL LOC17;
Tnode290802* LOC18;
Tnode290802* LOC20;
LOC17 = (NIM_BOOL)0;
LOC18 = (Tnode290802*)0;
LOC18 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0));
LOC17 = ((*LOC18).kind == ((Tnodekind290020) 3));
if (!(LOC17)) goto LA19;
LOC20 = (Tnode290802*)0;
LOC20 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0));
LOC17 = (((Tsymkind290435) 11) == (*(*LOC20).kindU.S4.sym).kind);
LA19: ;
if (!LOC17) goto LA21;
(*n0).flags |= ((NU16)1)<<((((Tnodeflag290427) 14))%(sizeof(NU16)*8));
result0 = HEX5BHEX5D_291238_850551059(n0, ((NI) 1));
goto BeforeRet;
}
LA21: ;
}
break;
case ((Tnodekind290020) 109):
{
{
NI LOC26;
Tnode290802* LOC29;
LOC26 = (NI)0;
LOC26 = len_291081_850551059(n0);
if (!(((NI) 0) < LOC26)) goto LA27;
LOC29 = (Tnode290802*)0;
LOC29 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0));
result0 = easyresultasgn_558191_839829468(LOC29);
{
if (!!((result0 == NIM_NIL))) goto LA32;
(*n0).flags |= ((NU16)1)<<((((Tnodeflag290427) 14))%(sizeof(NU16)*8));
}
LA32: ;
}
LA27: ;
}
break;
default:
{
}
break;
}
}BeforeRet: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, gettypedesc_533671_839829468)(Tcgen527027* m0, Ttype290840* typ0) {
Ropeobj177006* result0;
Intset266030 check0;
result0 = (Ropeobj177006*)0;
memset((void*)(&check0), 0, sizeof(check0));
chckNil((void*)(&check0));
memset((void*)(&check0), 0, sizeof(check0));
initintset_266885_2627731572((&check0));
result0 = gettypedescaux_531503_839829468(m0, typ0, (&check0));
return result0;
}
N_NIMCALL(Ropeobj177006*, localvardecl_536532_839829468)(Tcproc527021* p0, Tsym290834* s0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
Ropeobj177006* LOC5;
if (!((*s0).loc.k == ((Tlockind290808) 0))) goto LA3;
LOC5 = (Ropeobj177006*)0;
LOC5 = manglename_531205_839829468(s0);
fillloc_530282_839829468((&(*s0).loc), ((Tlockind290808) 2), (*s0).typ, LOC5, ((Tstorageloc290812) 2));
{
if (!((*s0).kind == ((Tsymkind290435) 9))) goto LA8;
(*s0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 2))%(sizeof(NU16)*8));
}
LA8: ;
}
LA3: ;
result0 = gettypedesc_533671_839829468((*p0).module, (*s0).loc.t);
{
if (!(*s0).constraint == 0) goto LA12;
{
if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 8))&31U)))!=0)) goto LA16;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_121));
}
LA16: ;
{
if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 7))&31U)))!=0)) goto LA20;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_122));
}
LA20: ;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_111));
add_177482_2381377266(&result0, (*s0).loc.r);
}
goto LA10;
LA12: ;
{
TY530811 LOC23;
memset((void*)LOC23, 0, sizeof(LOC23));
LOC23[0] = result0;
LOC23[1] = (*s0).loc.r;
result0 = HEX25_177905_2381377266((*(*s0).constraint).kindU.S3.strval, LOC23, 2);
}
LA10: ;
return result0;
}
N_NIMCALL(void, initloc_530273_839829468)(Tloc290816* result0, Tlockind290808 k0, Ttype290840* typ0, Tstorageloc290812 s0) {
(*result0).k = k0;
(*result0).s = s0;
unsureAsgnRef((void**) (&(*result0).t), typ0);
unsureAsgnRef((void**) (&(*result0).r), NIM_NIL);
(*result0).flags = 0;
}
N_NIMCALL(void, initlocexprsingleuse_537289_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0) {
initloc_530273_839829468(result0, ((Tlockind290808) 0), (*e0).typ, ((Tstorageloc290812) 0));
(*result0).flags |= ((NU16)1)<<((((Tlocflag290810) 8))%(sizeof(NU16)*8));
expr_537248_839829468(p0, e0, result0);
}
static N_INLINE(Ropeobj177006**, s_527179_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0) {
Ropeobj177006** result0;
result0 = (Ropeobj177006**)0;
result0 = &(*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].sections[(s0)- 0];
return result0;
}
N_NIMCALL(Ropeobj177006*, indentline_530656_839829468)(Tcproc527021* p0, Ropeobj177006* r0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = r0;
{
NI i_530680_839829468;
NI HEX3Atmp_530683_839829468;
NI res_530686_839829468;
i_530680_839829468 = (NI)0;
HEX3Atmp_530683_839829468 = (NI)0;
HEX3Atmp_530683_839829468 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1));
res_530686_839829468 = ((NI) 0);
{
while (1) {
if (!(res_530686_839829468 <= HEX3Atmp_530683_839829468)) goto LA3;
i_530680_839829468 = res_530686_839829468;
prepend_177893_2381377266(&result0, indent_530655_839829468);
res_530686_839829468 += ((NI) 1);
} LA3: ;
}
}
return result0;
}
N_NIMCALL(void, linefmt_530714_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) {
Ropeobj177006** LOC1;
Ropeobj177006* LOC2;
Ropeobj177006* LOC3;
LOC1 = (Ropeobj177006**)0;
LOC1 = s_527179_3723162438(p0, s0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, frmt0, args0, args0Len0);
LOC3 = (Ropeobj177006*)0;
LOC3 = indentline_530656_839829468(p0, LOC2);
add_177482_2381377266(LOC1, LOC3);
}
N_NIMCALL(Ropeobj177006*, rdloc_536188_839829468)(Tloc290816 a0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = a0.r;
{
TY177507 LOC5;
if (!((a0.flags &(1U<<((NU)(((Tlocflag290810) 0))&15U)))!=0)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = result0;
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC5, 1);
}
LA3: ;
return result0;
}
N_NIMCALL(void, line_530690_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, Ropeobj177006* r0) {
Ropeobj177006** LOC1;
Ropeobj177006* LOC2;
LOC1 = (Ropeobj177006**)0;
LOC1 = s_527179_3723162438(p0, s0);
LOC2 = (Ropeobj177006*)0;
LOC2 = indentline_530656_839829468(p0, r0);
add_177482_2381377266(LOC1, LOC2);
}
N_NIMCALL(void, linef_530700_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) {
Ropeobj177006** LOC1;
Ropeobj177006* LOC2;
Ropeobj177006* LOC3;
LOC1 = (Ropeobj177006**)0;
LOC1 = s_527179_3723162438(p0, s0);
LOC2 = (Ropeobj177006*)0;
LOC2 = HEX25_177905_2381377266(frmt0, args0, args0Len0);
LOC3 = (Ropeobj177006*)0;
LOC3 = indentline_530656_839829468(p0, LOC2);
add_177482_2381377266(LOC1, LOC3);
}
N_NIMCALL(void, gentypeinfoauxbase_533960_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0, Ropeobj177006* base0) {
NI nimtypekind0;
Ropeobj177006* size0;
TY533235 LOC17;
NI flags0;
Ropeobj177006* LOC33;
TY530811 LOC34;
NimStringDesc* LOC35;
nimtypekind0 = (NI)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = isobjlackingtypefield_531513_839829468(typ0);
if (!LOC3) goto LA4;
nimtypekind0 = ((NI) 18);
}
goto LA1;
LA4: ;
{
nimtypekind0 = ((NI) ((*typ0).kind));
}
LA1: ;
size0 = (Ropeobj177006*)0;
{
if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0)) goto LA9;
size0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_133));
}
goto LA7;
LA9: ;
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC12) goto LA13;
LOC12 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA13: ;
if (!LOC12) goto LA14;
size0 = gettypedesc_533671_839829468(m0, origtype0);
}
goto LA7;
LA14: ;
{
size0 = gettypedesc_533671_839829468(m0, typ0);
}
LA7: ;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = name0;
LOC17[1] = size0;
LOC17[2] = rope_177401_2381377266(((NI64) (nimtypekind0)));
LOC17[3] = base0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_134), LOC17, 4);
flags0 = ((NI) 0);
{
NIM_BOOL LOC20;
LOC20 = (NIM_BOOL)0;
LOC20 = containsgarbagecollectedref_318117_3876443242(typ0);
if (!!(LOC20)) goto LA21;
flags0 = (NI)(flags0 | ((NI) 1));
}
LA21: ;
{
NIM_BOOL LOC25;
LOC25 = (NIM_BOOL)0;
LOC25 = canformacycle_318123_3876443242(typ0);
if (!!(LOC25)) goto LA26;
flags0 = (NI)(flags0 | ((NI) 2));
}
LA26: ;
{
TY530811 LOC32;
if (!!((flags0 == ((NI) 0)))) goto LA30;
memset((void*)LOC32, 0, sizeof(LOC32));
LOC32[0] = name0;
LOC32[1] = rope_177401_2381377266(((NI64) (flags0)));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_135), LOC32, 2);
}
LA30: ;
LOC33 = (Ropeobj177006*)0;
LOC33 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_129));
memset((void*)LOC34, 0, sizeof(LOC34));
LOC34[0] = name0;
LOC35 = (NimStringDesc*)0;
LOC35 = typetostring_318017_3876443242(typ0, ((Tprefereddesc318011) 0));
LOC34[1] = rope_177277_2381377266(LOC35);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_136), LOC34, 2);
}
N_NIMCALL(Ropeobj177006*, getnimnode_533945_839829468)(Tcgen527027* m0) {
Ropeobj177006* result0;
TY530811 LOC1;
result0 = (Ropeobj177006*)0;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = (*m0).typenodesname;
LOC1[1] = rope_177401_2381377266(((NI64) ((*m0).typenodes)));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_138), LOC1, 2);
(*m0).typenodes += ((NI) 1);
return result0;
}
N_NIMCALL(void, gentupleinfo_534549_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) {
Ropeobj177006* LOC1;
Ropeobj177006* expr0;
NI length0;
TY530811 LOC15;
LOC1 = (Ropeobj177006*)0;
LOC1 = rope_177277_2381377266(((NimStringDesc*) &T839829468_18));
gentypeinfoauxbase_533960_839829468(m0, typ0, typ0, name0, LOC1);
expr0 = getnimnode_533945_839829468(m0);
length0 = sonslen_293327_850551059(typ0);
{
Ropeobj177006* tmp0;
TY530811 LOC6;
TY533238 LOC12;
if (!(((NI) 0) < length0)) goto LA4;
tmp0 = gettempname_531596_839829468(m0);
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = tmp0;
LOC6[1] = rope_177401_2381377266(((NI64) (length0)));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC6, 2);
{
NI i_534571_839829468;
NI HEX3Atmp_534590_839829468;
NI res_534593_839829468;
i_534571_839829468 = (NI)0;
HEX3Atmp_534590_839829468 = (NI)0;
HEX3Atmp_534590_839829468 = (NI)(length0 - ((NI) 1));
res_534593_839829468 = ((NI) 0);
{
while (1) {
Ttype290840* a0;
Ropeobj177006* tmp20;
TY533238 LOC10;
TY533235 LOC11;
if (!(res_534593_839829468 <= HEX3Atmp_534590_839829468)) goto LA9;
i_534571_839829468 = res_534593_839829468;
a0 = (*typ0).sons->data[i_534571_839829468];
tmp20 = getnimnode_533945_839829468(m0);
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = tmp0;
LOC10[1] = rope_177401_2381377266(((NI64) (i_534571_839829468)));
LOC10[2] = tmp20;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC10, 3);
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = tmp20;
LOC11[1] = gettypedesc_533671_839829468(m0, typ0);
LOC11[2] = rope_177401_2381377266(((NI64) (i_534571_839829468)));
LOC11[3] = gentypeinfo_533941_839829468(m0, a0);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_141), LOC11, 4);
res_534593_839829468 += ((NI) 1);
} LA9: ;
}
}
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = expr0;
LOC12[1] = rope_177401_2381377266(((NI64) (length0)));
LOC12[2] = tmp0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC12, 3);
}
goto LA2;
LA4: ;
{
TY530811 LOC14;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = expr0;
LOC14[1] = rope_177401_2381377266(((NI64) (length0)));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC14, 2);
}
LA2: ;
memset((void*)LOC15, 0, sizeof(LOC15));
LOC15[0] = name0;
LOC15[1] = expr0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC15, 2);
}
N_NIMCALL(Ttype290840*, fakeclosuretype_535010_839829468)(Tsym290834* owner0) {
Ttype290840* result0;
Ttype290840* LOC1;
Ttype290840* r0;
Ttype290840* LOC2;
result0 = (Ttype290840*)0;
result0 = newtype_293107_850551059(((Ttypekind290244) 18), owner0);
LOC1 = (Ttype290840*)0;
LOC1 = newtype_293107_850551059(((Ttypekind290244) 26), owner0);
rawaddson_294394_850551059(result0, LOC1);
r0 = newtype_293107_850551059(((Ttypekind290244) 22), owner0);
LOC2 = (Ttype290840*)0;
LOC2 = newtype_293107_850551059(((Ttypekind290244) 18), owner0);
rawaddson_294394_850551059(r0, LOC2);
rawaddson_294394_850551059(result0, r0);
return result0;
}
N_NIMCALL(void, gentypeinfoaux_534027_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0) {
Ropeobj177006* base0;
base0 = (Ropeobj177006*)0;
{
NIM_BOOL LOC3;
NI LOC4;
Ttype290840* x0;
LOC3 = (NIM_BOOL)0;
LOC4 = (NI)0;
LOC4 = sonslen_293327_850551059(typ0);
LOC3 = (((NI) 0) < LOC4);
if (!(LOC3)) goto LA5;
LOC3 = !(((*typ0).sons->data[((NI) 0)] == NIM_NIL));
LA5: ;
if (!LOC3) goto LA6;
x0 = (*typ0).sons->data[((NI) 0)];
{
if (!((*typ0).kind == ((Ttypekind290244) 17))) goto LA10;
x0 = skiptypes_294099_850551059(x0, IL64(211106247215360));
}
LA10: ;
base0 = gentypeinfo_533941_839829468(m0, x0);
}
goto LA1;
LA6: ;
{
base0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_18));
}
LA1: ;
gentypeinfoauxbase_533960_839829468(m0, typ0, origtype0, name0, base0);
}
static N_INLINE(NIM_BOOL, iscomplexvaluetype_536317_839829468)(Ttype290840* t0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
NIM_BOOL LOC3;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC1 = ((*t0).kind == ((Ttypekind290244) 16) || (*t0).kind == ((Ttypekind290244) 4) || (*t0).kind == ((Ttypekind290244) 19) || (*t0).kind == ((Ttypekind290244) 18) || (*t0).kind == ((Ttypekind290244) 17));
if (LOC1) goto LA2;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*t0).kind == ((Ttypekind290244) 25));
if (!(LOC3)) goto LA4;
LOC3 = ((*t0).callconv == ((Tcallingconvention290002) 8));
LA4: ;
LOC1 = LOC3;
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, usestringh_530345_839829468)(Tcgen527027* m0) {
{
NIM_BOOL LOC5;
if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 4))&7U)))!=0))) goto LA3;
(*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 4))%(sizeof(NU8)*8));
LOC5 = (NIM_BOOL)0;
LOC5 = includestr_147249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_151));
}
LA3: ;
}
N_NIMCALL(Ropeobj177006*, addrloc_536204_839829468)(Tloc290816 a0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = a0.r;
{
NIM_BOOL LOC3;
Tctypekind527007 LOC5;
Ropeobj177006* LOC8;
LOC3 = (NIM_BOOL)0;
LOC3 = !(((a0.flags &(1U<<((NU)(((Tlocflag290810) 0))&15U)))!=0));
if (!(LOC3)) goto LA4;
LOC5 = (Tctypekind527007)0;
LOC5 = maptype_531393_839829468(a0.t);
LOC3 = !((LOC5 == ((Tctypekind527007) 17)));
LA4: ;
if (!LOC3) goto LA6;
LOC8 = (Ropeobj177006*)0;
LOC8 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_128), result0);
result0 = HEX26_177447_2381377266(LOC8, ((NimStringDesc*) &T839829468_117));
}
LA6: ;
return result0;
}
N_NIMCALL(void, genobjectinit_536242_839829468)(Tcproc527021* p0, Tcprocsection527011 section0, Ttype290840* t0, Tloc290816 a0, NIM_BOOL takeaddr0) {
Ttypefieldresult318145 LOC1;
LOC1 = (Ttypefieldresult318145)0;
LOC1 = analyseobjectwithtypefield_318149_3876443242(t0);
switch (LOC1) {
case ((Ttypefieldresult318145) 0):
{
}
break;
case ((Ttypefieldresult318145) 1):
{
Ropeobj177006* r0;
Ttype290840* s0;
TY530811 LOC19;
r0 = rdloc_536188_839829468(a0);
{
TY177507 LOC8;
if (!!(takeaddr0)) goto LA6;
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = r0;
r0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC8, 1);
}
LA6: ;
s0 = skiptypes_294099_850551059(t0, IL64(211106232576256));
{
NIM_BOOL LOC11;
LOC11 = (NIM_BOOL)0;
LOC11 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC11) goto LA12;
LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA12: ;
if (!!(LOC11)) goto LA13;
{
while (1) {
NIM_BOOL LOC17;
LOC17 = (NIM_BOOL)0;
LOC17 = ((*s0).kind == ((Ttypekind290244) 17));
if (!(LOC17)) goto LA18;
LOC17 = !(((*s0).sons->data[((NI) 0)] == NIM_NIL));
LA18: ;
if (!LOC17) goto LA16;
add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153));
s0 = skiptypes_294099_850551059((*s0).sons->data[((NI) 0)], IL64(211106247215360));
} LA16: ;
}
}
LA13: ;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = r0;
LOC19[1] = gentypeinfo_533941_839829468((*p0).module, t0);
linefmt_530714_839829468(p0, section0, ((NimStringDesc*) &T839829468_154), LOC19, 2);
}
break;
case ((Ttypefieldresult318145) 2):
{
Ropeobj177006* r0;
TY530811 LOC26;
{
if (!takeaddr0) goto LA23;
r0 = addrloc_536204_839829468(a0);
}
goto LA21;
LA23: ;
{
r0 = rdloc_536188_839829468(a0);
}
LA21: ;
memset((void*)LOC26, 0, sizeof(LOC26));
LOC26[0] = r0;
LOC26[1] = gentypeinfo_533941_839829468((*p0).module, t0);
linefmt_530714_839829468(p0, section0, ((NimStringDesc*) &T839829468_155), LOC26, 2);
}
break;
}
}
N_NIMCALL(void, constructloc_536388_839829468)(Tcproc527021* p0, Tloc290816 loc0, NIM_BOOL istemp0) {
Ttype290840* typ0;
typ0 = skiptypes_294099_850551059(loc0.t, IL64(211106233624832));
{
NIM_BOOL LOC3;
TY530811 LOC6;
LOC3 = (NIM_BOOL)0;
LOC3 = iscomplexvaluetype_536317_839829468(typ0);
if (!!(LOC3)) goto LA4;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = rdloc_536188_839829468(loc0);
LOC6[1] = gettypedesc_533671_839829468((*p0).module, typ0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_150), LOC6, 2);
}
goto LA1;
LA4: ;
{
{
NIM_BOOL LOC10;
LOC10 = (NIM_BOOL)0;
LOC10 = !(istemp0);
if (LOC10) goto LA11;
LOC10 = containsgarbagecollectedref_318117_3876443242(loc0.t);
LA11: ;
if (!LOC10) goto LA12;
{
NIM_BOOL LOC16;
TY530811 LOC19;
LOC16 = (NIM_BOOL)0;
LOC16 = isimportedcpptype_531476_839829468(typ0);
if (!!(LOC16)) goto LA17;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = addrloc_536204_839829468(loc0);
LOC19[1] = rdloc_536188_839829468(loc0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_152), LOC19, 2);
}
LA17: ;
}
LA12: ;
genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), loc0.t, loc0, NIM_TRUE);
}
LA1: ;
}
N_NIMCALL(void, gettemp_535032_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816* result0, NIM_BOOL needsinit0) {
Ropeobj177006* LOC1;
TY530811 LOC2;
(*p0).labels += ((NI) 1);
LOC1 = (Ropeobj177006*)0;
LOC1 = rope_177401_2381377266(((NI64) ((*p0).labels)));
unsureAsgnRef((void**) (&(*result0).r), HEX26_177452_2381377266(((NimStringDesc*) &T839829468_149), LOC1));
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC2[1] = (*result0).r;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_54), LOC2, 2);
(*result0).k = ((Tlockind290808) 1);
unsureAsgnRef((void**) (&(*result0).t), t0);
(*result0).s = ((Tstorageloc290812) 2);
(*result0).flags = 0;
constructloc_536388_839829468(p0, (*result0), !(needsinit0));
}
static N_INLINE(Ropeobj177006*, parentobj_535257_839829468)(Ropeobj177006* accessor0, Tcgen527027* m0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NIM_BOOL LOC3;
TY177507 LOC7;
LOC3 = (NIM_BOOL)0;
LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC3) goto LA4;
LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA4: ;
if (!!(LOC3)) goto LA5;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = accessor0;
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_161), LOC7, 1);
}
goto LA1;
LA5: ;
{
result0 = accessor0;
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, intliteral_537270_839829468)(NI64 i0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (IL64(-2147483648) < i0);
if (!(LOC3)) goto LA4;
LOC3 = (i0 <= IL64(2147483647));
LA4: ;
if (!LOC3) goto LA5;
result0 = rope_177401_2381377266(i0);
}
goto LA1;
LA5: ;
{
TY531289 LOC10;
if (!(i0 == IL64(-2147483648))) goto LA8;
memset((void*)LOC10, 0, sizeof(LOC10));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_166), LOC10, 0);
}
goto LA1;
LA8: ;
{
TY177507 LOC14;
if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA12;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = rope_177401_2381377266(i0);
result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC14, 1);
}
goto LA1;
LA12: ;
{
TY531289 LOC16;
memset((void*)LOC16, 0, sizeof(LOC16));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_168), LOC16, 0);
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, int64literal_547430_839829468)(NI64 i0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
TY177507 LOC5;
if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rope_177401_2381377266(i0);
result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC5, 1);
}
goto LA1;
LA3: ;
{
TY531289 LOC7;
memset((void*)LOC7, 0, sizeof(LOC7));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_168), LOC7, 0);
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, uint64literal_547442_839829468)(NU64 i0) {
Ropeobj177006* result0;
NimStringDesc* LOC1;
NimStringDesc* LOC2;
result0 = (Ropeobj177006*)0;
LOC1 = (NimStringDesc*)0;
LOC2 = (NimStringDesc*)0;
LOC2 = HEX24_8401_1689653243(i0);
LOC1 = rawNewString(LOC2->Sup.len + 3);
appendString(LOC1, LOC2);
appendString(LOC1, ((NimStringDesc*) &T839829468_171));
result0 = rope_177277_2381377266(LOC1);
return result0;
}
N_NIMCALL(Ropeobj177006*, getstrlit_547468_839829468)(Tcgen527027* m0, NimStringDesc* s0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
TY533238 LOC2;
result0 = (Ropeobj177006*)0;
LOC1 = (Ropeobj177006*)0;
LOC1 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_79));
result0 = gettempname_531596_839829468(m0);
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = result0;
LOC2[1] = makecstring_189638_155036129(s0);
LOC2[2] = rope_177401_2381377266(((NI64) ((s0 ? s0->Sup.len : 0))));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_177), LOC2, 3);
return result0;
}
N_NIMCALL(Ropeobj177006*, genliteral_547476_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* ty0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
if (!(ty0 == NIM_NIL)) goto LA3;
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_165));
}
LA3: ;
switch ((*n0).kind) {
case ((Tnodekind290020) 5) ... ((Tnodekind290020) 15):
{
Ttype290840* LOC6;
LOC6 = (Ttype290840*)0;
LOC6 = skiptypes_294099_850551059(ty0, IL64(211106242013440));
switch ((*LOC6).kind) {
case ((Ttypekind290244) 2):
case ((Ttypekind290244) 5):
{
result0 = intliteral_537270_839829468((*n0).kindU.S1.intval);
}
break;
case ((Ttypekind290244) 1):
{
{
TY531289 LOC13;
if (!!(((*n0).kindU.S1.intval == IL64(0)))) goto LA11;
memset((void*)LOC13, 0, sizeof(LOC13));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_169), LOC13, 0);
}
goto LA9;
LA11: ;
{
TY531289 LOC15;
memset((void*)LOC15, 0, sizeof(LOC15));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_170), LOC15, 0);
}
LA9: ;
}
break;
case ((Ttypekind290244) 35):
{
result0 = int64literal_547430_839829468((*n0).kindU.S1.intval);
}
break;
case ((Ttypekind290244) 44):
{
result0 = uint64literal_547442_839829468(((NU64) ((*n0).kindU.S1.intval)));
}
break;
default:
{
TY530811 LOC19;
Ttype290840* LOC20;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC20 = (Ttype290840*)0;
LOC20 = skiptypes_294099_850551059(ty0, IL64(211106242013440));
LOC19[0] = gettypedesc_533671_839829468((*p0).module, LOC20);
LOC19[1] = intliteral_537270_839829468((*n0).kindU.S1.intval);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_172), LOC19, 2);
}
break;
}
}
break;
case ((Tnodekind290020) 23):
{
Ttype290840* t0;
t0 = skiptypes_294099_850551059(ty0, IL64(211106242013440));
{
NIM_BOOL LOC24;
NI id0;
Ropeobj177006* LOC28;
LOC24 = (NIM_BOOL)0;
LOC24 = ((*t0).kind == ((Ttypekind290244) 25));
if (!(LOC24)) goto LA25;
LOC24 = ((*t0).callconv == ((Tcallingconvention290002) 8));
LA25: ;
if (!LOC24) goto LA26;
id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels)));
LOC28 = (Ropeobj177006*)0;
LOC28 = rope_177401_2381377266(((NI64) (id0)));
result0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC28);
{
TY530811 LOC33;
if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA31;
(*(*p0).module).labels += ((NI) 1);
memset((void*)LOC33, 0, sizeof(LOC33));
LOC33[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC33[1] = result0;
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_173), LOC33, 2);
}
LA31: ;
}
goto LA22;
LA26: ;
{
result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_174));
}
LA22: ;
}
break;
case ((Tnodekind290020) 20) ... ((Tnodekind290020) 22):
{
{
TY531289 LOC40;
if (!(*n0).kindU.S3.strval == 0) goto LA38;
memset((void*)LOC40, 0, sizeof(LOC40));
result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_175), LOC40, 0);
}
goto LA36;
LA38: ;
{
Ttype290840* LOC42;
NI id0;
LOC42 = (Ttype290840*)0;
LOC42 = skiptypes_294099_850551059(ty0, IL64(211106242013440));
if (!((*LOC42).kind == ((Ttypekind290244) 28))) goto LA43;
id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels)));
{
TY177507 LOC49;
if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA47;
memset((void*)LOC49, 0, sizeof(LOC49));
LOC49[0] = getstrlit_547468_839829468((*p0).module, (*n0).kindU.S3.strval);
result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_176), LOC49, 1);
}
goto LA45;
LA47: ;
{
TY530811 LOC51;
memset((void*)LOC51, 0, sizeof(LOC51));
LOC51[0] = (*(*p0).module).tmpbase;
LOC51[1] = rope_177401_2381377266(((NI64) (id0)));
result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_178), LOC51, 2);
}
LA45: ;
}
goto LA36;
LA43: ;
{
result0 = makecstring_189638_155036129((*n0).kindU.S3.strval);
}
LA36: ;
}
break;
case ((Tnodekind290020) 16) ... ((Tnodekind290020) 18):
{
NimStringDesc* LOC54;
LOC54 = (NimStringDesc*)0;
LOC54 = tostrmaxprecision_296007_3471544153((*n0).kindU.S2.floatval);
result0 = rope_177277_2381377266(LOC54);
}
break;
default:
{
NimStringDesc* LOC56;
LOC56 = (NimStringDesc*)0;
LOC56 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI290020))->Sup.len + 12);
appendString(LOC56, ((NimStringDesc*) &T839829468_179));
appendString(LOC56, reprEnum((NI)(*n0).kind, (&NTI290020)));
appendChar(LOC56, 41);
internalerror_194100_155036129((*n0).info, LOC56);
result0 = NIM_NIL;
}
break;
}
return result0;
}
N_NIMCALL(Ropeobj177006*, genliteral_537273_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = genliteral_547476_839829468(p0, n0, (*n0).typ);
return result0;
}
N_NIMCALL(void, gencaserange_535028_839829468)(Tcproc527021* p0, Tnode290802* branch0) {
NI length0;
length0 = len_291081_850551059(branch0);
{
NI j_545676_839829468;
NI HEX3Atmp_545717_839829468;
NI res_545720_839829468;
j_545676_839829468 = (NI)0;
HEX3Atmp_545717_839829468 = (NI)0;
HEX3Atmp_545717_839829468 = (NI)(length0 - ((NI) 2));
res_545720_839829468 = ((NI) 0);
{
while (1) {
if (!(res_545720_839829468 <= HEX3Atmp_545717_839829468)) goto LA3;
j_545676_839829468 = res_545720_839829468;
{
Tnode290802* LOC6;
LOC6 = (Tnode290802*)0;
LOC6 = HEX5BHEX5D_291238_850551059(branch0, j_545676_839829468);
if (!((*LOC6).kind == ((Tnodekind290020) 44))) goto LA7;
{
TY530811 LOC13;
Tnode290802* LOC14;
Tnode290802* LOC15;
Tnode290802* LOC16;
Tnode290802* LOC17;
if (!((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 0))&7U)))!=0)) goto LA11;
memset((void*)LOC13, 0, sizeof(LOC13));
LOC14 = (Tnode290802*)0;
LOC14 = HEX5BHEX5D_291238_850551059(branch0, j_545676_839829468);
LOC15 = (Tnode290802*)0;
LOC15 = HEX5BHEX5D_291238_850551059(LOC14, ((NI) 0));
LOC13[0] = genliteral_537273_839829468(p0, LOC15);
LOC16 = (Tnode290802*)0;
LOC16 = HEX5BHEX5D_291238_850551059(branch0, j_545676_839829468);
LOC17 = (Tnode290802*)0;
LOC17 = HEX5BHEX5D_291238_850551059(LOC16, ((NI) 1));
LOC13[1] = genliteral_537273_839829468(p0, LOC17);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_164), LOC13, 2);
}
goto LA9;
LA11: ;
{
Tnode290802* v0;
Tnode290802* LOC19;
Tnode290802* LOC20;
LOC19 = (Tnode290802*)0;
LOC19 = HEX5BHEX5D_291238_850551059(branch0, j_545676_839829468);
LOC20 = (Tnode290802*)0;
LOC20 = HEX5BHEX5D_291238_850551059(LOC19, ((NI) 0));
v0 = copynode_294528_850551059(LOC20);
{
while (1) {
Tnode290802* LOC23;
Tnode290802* LOC24;
TY177507 LOC25;
LOC23 = (Tnode290802*)0;
LOC23 = HEX5BHEX5D_291238_850551059(branch0, j_545676_839829468);
LOC24 = (Tnode290802*)0;
LOC24 = HEX5BHEX5D_291238_850551059(LOC23, ((NI) 1));
if (!((*v0).kindU.S1.intval <= (*LOC24).kindU.S1.intval)) goto LA22;
memset((void*)LOC25, 0, sizeof(LOC25));
LOC25[0] = genliteral_537273_839829468(p0, v0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_180), LOC25, 1);
(*v0).kindU.S1.intval += ((NI) 1);
} LA22: ;
}
}
LA9: ;
}
goto LA4;
LA7: ;
{
TY177507 LOC27;
Tnode290802* LOC28;
memset((void*)LOC27, 0, sizeof(LOC27));
LOC28 = (Tnode290802*)0;
LOC28 = HEX5BHEX5D_291238_850551059(branch0, j_545676_839829468);
LOC27[0] = genliteral_537273_839829468(p0, LOC28);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_180), LOC27, 1);
}
LA4: ;
res_545720_839829468 += ((NI) 1);
} LA3: ;
}
}
}
N_NIMCALL(void, gentraverseproc_535039_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Tnode290802* n0) {
{ {
if (!(n0 == NIM_NIL)) goto LA3;
goto BeforeRet;
}
LA3: ;
switch ((*n0).kind) {
case ((Tnodekind290020) 138):
{
{
NI i_535068_839829468;
NI HEX3Atmp_535239_839829468;
NI LOC7;
NI res_535242_839829468;
i_535068_839829468 = (NI)0;
HEX3Atmp_535239_839829468 = (NI)0;
LOC7 = (NI)0;
LOC7 = sonslen_293351_850551059(n0);
HEX3Atmp_535239_839829468 = (NI)(LOC7 - ((NI) 1));
res_535242_839829468 = ((NI) 0);
{
while (1) {
if (!(res_535242_839829468 <= HEX3Atmp_535239_839829468)) goto LA9;
i_535068_839829468 = res_535242_839829468;
gentraverseproc_535039_839829468(c0, accessor0, (*n0).kindU.S6.sons->data[i_535068_839829468]);
res_535242_839829468 += ((NI) 1);
} LA9: ;
}
}
}
break;
case ((Tnodekind290020) 139):
{
Tcproc527021* p0;
Tsym290834* disc0;
TY530811 LOC15;
TY531289 LOC28;
{
if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)))) goto LA13;
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_162));
}
LA13: ;
p0 = (*c0).p;
disc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
memset((void*)LOC15, 0, sizeof(LOC15));
LOC15[0] = accessor0;
LOC15[1] = (*disc0).loc.r;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_163), LOC15, 2);
{
NI i_535098_839829468;
NI HEX3Atmp_535249_839829468;
NI LOC17;
NI res_535252_839829468;
i_535098_839829468 = (NI)0;
HEX3Atmp_535249_839829468 = (NI)0;
LOC17 = (NI)0;
LOC17 = sonslen_293351_850551059(n0);
HEX3Atmp_535249_839829468 = (NI)(LOC17 - ((NI) 1));
res_535252_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* branch0;
Tnode290802* LOC26;
TY531289 LOC27;
if (!(res_535252_839829468 <= HEX3Atmp_535249_839829468)) goto LA19;
i_535098_839829468 = res_535252_839829468;
branch0 = (*n0).kindU.S6.sons->data[i_535098_839829468];
{
if (!((*branch0).kind == ((Tnodekind290020) 85))) goto LA22;
gencaserange_535028_839829468((*c0).p, branch0);
}
goto LA20;
LA22: ;
{
TY531289 LOC25;
memset((void*)LOC25, 0, sizeof(LOC25));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_181), LOC25, 0);
}
LA20: ;
LOC26 = (Tnode290802*)0;
LOC26 = lastson_293364_850551059(branch0);
gentraverseproc_535039_839829468(c0, accessor0, LOC26);
memset((void*)LOC27, 0, sizeof(LOC27));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_182), LOC27, 0);
res_535252_839829468 += ((NI) 1);
} LA19: ;
}
}
memset((void*)LOC28, 0, sizeof(LOC28));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_183), LOC28, 0);
}
break;
case ((Tnodekind290020) 3):
{
Tsym290834* field0;
TY530811 LOC34;
Ropeobj177006* LOC35;
field0 = (*n0).kindU.S4.sym;
{
if (!((*field0).loc.t == NIM_NIL)) goto LA32;
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184));
}
LA32: ;
memset((void*)LOC34, 0, sizeof(LOC34));
LOC34[0] = accessor0;
LOC34[1] = (*field0).loc.r;
LOC35 = (Ropeobj177006*)0;
LOC35 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC34, 2);
gentraverseproc_535022_839829468(c0, LOC35, (*field0).loc.t);
}
break;
default:
{
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184));
}
break;
}
}BeforeRet: ;
}
N_NIMCALL(void, linecg_530707_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) {
Ropeobj177006** LOC1;
Ropeobj177006* LOC2;
Ropeobj177006* LOC3;
LOC1 = (Ropeobj177006**)0;
LOC1 = s_527179_3723162438(p0, s0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, frmt0, args0, args0Len0);
LOC3 = (Ropeobj177006*)0;
LOC3 = indentline_530656_839829468(p0, LOC2);
add_177482_2381377266(LOC1, LOC3);
}
N_NIMCALL(void, gentraverseproc_535022_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ_535027_839829468) {
Ttype290840* typ_535302_839829468;
Tcproc527021* p0;
{ {
if (!(typ_535027_839829468 == NIM_NIL)) goto LA3;
goto BeforeRet;
}
LA3: ;
typ_535302_839829468 = getuniquetype_526640_2036603609(typ_535027_839829468);
p0 = (*c0).p;
switch ((*typ_535302_839829468).kind) {
case ((Ttypekind290244) 11):
case ((Ttypekind290244) 10):
case ((Ttypekind290244) 8):
{
Ttype290840* LOC6;
LOC6 = (Ttype290840*)0;
LOC6 = lastson_293377_850551059(typ_535302_839829468);
gentraverseproc_535022_839829468(c0, accessor0, LOC6);
}
break;
case ((Ttypekind290244) 4):
case ((Ttypekind290244) 16):
{
NI64 arraysize0;
Tloc290816 i0;
Ttype290840* LOC8;
TY530811 LOC9;
TY530811 LOC10;
Ropeobj177006* LOC11;
TY531289 LOC12;
arraysize0 = lengthord_318007_3876443242((*typ_535302_839829468).sons->data[((NI) 0)]);
memset((void*)(&i0), 0, sizeof(i0));
LOC8 = (Ttype290840*)0;
LOC8 = getsystype_336150_3937434831(((Ttypekind290244) 31));
gettemp_535032_839829468(p0, LOC8, (&i0), NIM_FALSE);
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = i0.r;
LOC9[1] = rope_177401_2381377266(arraysize0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_159), LOC9, 2);
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = accessor0;
LOC10[1] = i0.r;
LOC11 = (Ropeobj177006*)0;
LOC11 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC10, 2);
gentraverseproc_535022_839829468(c0, LOC11, (*typ_535302_839829468).sons->data[((NI) 1)]);
memset((void*)LOC12, 0, sizeof(LOC12));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC12, 0);
}
break;
case ((Ttypekind290244) 17):
{
{
NI i_535325_839829468;
NI HEX3Atmp_535384_839829468;
NI LOC15;
NI res_535387_839829468;
i_535325_839829468 = (NI)0;
HEX3Atmp_535384_839829468 = (NI)0;
LOC15 = (NI)0;
LOC15 = sonslen_293327_850551059(typ_535302_839829468);
HEX3Atmp_535384_839829468 = (NI)(LOC15 - ((NI) 1));
res_535387_839829468 = ((NI) 0);
{
while (1) {
Ttype290840* x0;
Ropeobj177006* LOC22;
if (!(res_535387_839829468 <= HEX3Atmp_535384_839829468)) goto LA17;
i_535325_839829468 = res_535387_839829468;
x0 = (*typ_535302_839829468).sons->data[i_535325_839829468];
{
if (!!((x0 == NIM_NIL))) goto LA20;
x0 = skiptypes_294099_850551059(x0, IL64(211106247215360));
}
LA20: ;
LOC22 = (Ropeobj177006*)0;
LOC22 = parentobj_535257_839829468(accessor0, (*(*c0).p).module);
gentraverseproc_535022_839829468(c0, LOC22, x0);
res_535387_839829468 += ((NI) 1);
} LA17: ;
}
}
{
if (!!(((*typ_535302_839829468).n == NIM_NIL))) goto LA25;
gentraverseproc_535039_839829468(c0, accessor0, (*typ_535302_839829468).n);
}
LA25: ;
}
break;
case ((Ttypekind290244) 18):
{
Ttype290840* typ0;
typ0 = getuniquetype_526640_2036603609(typ_535302_839829468);
{
NI i_535363_839829468;
NI HEX3Atmp_535392_839829468;
NI LOC29;
NI res_535395_839829468;
i_535363_839829468 = (NI)0;
HEX3Atmp_535392_839829468 = (NI)0;
LOC29 = (NI)0;
LOC29 = sonslen_293327_850551059(typ0);
HEX3Atmp_535392_839829468 = (NI)(LOC29 - ((NI) 1));
res_535395_839829468 = ((NI) 0);
{
while (1) {
TY530811 LOC32;
Ropeobj177006* LOC33;
if (!(res_535395_839829468 <= HEX3Atmp_535392_839829468)) goto LA31;
i_535363_839829468 = res_535395_839829468;
memset((void*)LOC32, 0, sizeof(LOC32));
LOC32[0] = accessor0;
LOC32[1] = rope_177401_2381377266(((NI64) (i_535363_839829468)));
LOC33 = (Ropeobj177006*)0;
LOC33 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_185), LOC32, 2);
gentraverseproc_535022_839829468(c0, LOC33, (*typ0).sons->data[i_535363_839829468]);
res_535395_839829468 += ((NI) 1);
} LA31: ;
}
}
}
break;
case ((Ttypekind290244) 22):
case ((Ttypekind290244) 28):
case ((Ttypekind290244) 24):
{
TY177507 LOC35;
memset((void*)LOC35, 0, sizeof(LOC35));
LOC35[0] = accessor0;
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), (*c0).visitorfrmt, LOC35, 1);
}
break;
case ((Ttypekind290244) 25):
{
{
TY177507 LOC41;
TY177507 LOC42;
if (!((*typ_535302_839829468).callconv == ((Tcallingconvention290002) 8))) goto LA39;
memset((void*)LOC41, 0, sizeof(LOC41));
memset((void*)LOC42, 0, sizeof(LOC42));
LOC42[0] = accessor0;
LOC41[0] = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_186), LOC42, 1);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), (*c0).visitorfrmt, LOC41, 1);
}
LA39: ;
}
break;
default:
{
}
break;
}
}BeforeRet: ;
}
N_NIMCALL(void, gentraverseprocseq_535399_839829468)(Ttraversalclosure535019* c0, Ropeobj177006* accessor0, Ttype290840* typ0) {
Tcproc527021* p0;
Tloc290816 i0;
Ttype290840* LOC1;
TY533238 LOC2;
NimStringDesc* LOC3;
TY530811 LOC11;
Ropeobj177006* LOC12;
TY531289 LOC13;
p0 = (*c0).p;
memset((void*)(&i0), 0, sizeof(i0));
LOC1 = (Ttype290840*)0;
LOC1 = getsystype_336150_3937434831(((Ttypekind290244) 31));
gettemp_535032_839829468(p0, LOC1, (&i0), NIM_FALSE);
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = i0.r;
LOC2[1] = accessor0;
LOC3 = (NimStringDesc*)0;
{
NIM_BOOL LOC6;
LOC6 = (NIM_BOOL)0;
LOC6 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC6) goto LA7;
LOC6 = (((*(*(*(*c0).p).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA7: ;
if (!LOC6) goto LA8;
LOC3 = copyString(((NimStringDesc*) &T839829468_157));
}
goto LA4;
LA8: ;
{
LOC3 = copyString(((NimStringDesc*) &T839829468_158));
}
LA4: ;
LOC2[2] = rope_177277_2381377266(LOC3);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_156), LOC2, 3);
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = accessor0;
LOC11[1] = i0.r;
LOC12 = (Ropeobj177006*)0;
LOC12 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_187), LOC11, 2);
gentraverseproc_535022_839829468(c0, LOC12, (*typ0).sons->data[((NI) 0)]);
memset((void*)LOC13, 0, sizeof(LOC13));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC13, 0);
}
N_NIMCALL(Ropeobj177006*, gentraverseproc_535632_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttypeinforeason535016 reason0) {
Ropeobj177006* result0;
Ttraversalclosure535019 c0;
Tcproc527021* p0;
Ropeobj177006* header0;
TY177507 LOC3;
Ropeobj177006* t0;
TY177507 LOC4;
TY177507 LOC5;
Ropeobj177006* generatedproc0;
TY533235 LOC20;
Ropeobj177006** LOC21;
Ropeobj177006** LOC22;
Ropeobj177006** LOC23;
TY177507 LOC24;
result0 = (Ropeobj177006*)0;
memset((void*)(&c0), 0, sizeof(c0));
p0 = newproc_527206_3723162438(NIM_NIL, m0);
result0 = gettempname_531596_839829468(m0);
switch (reason0) {
case ((Ttypeinforeason535016) 0):
{
c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_145));
}
break;
default:
{
}
break;
}
memset((void*)LOC3, 0, sizeof(LOC3));
LOC3[0] = result0;
header0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_146), LOC3, 1);
t0 = gettypedesc_533671_839829468(m0, typ0);
memset((void*)LOC4, 0, sizeof(LOC4));
LOC4[0] = t0;
linef_530700_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_147), LOC4, 1);
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = t0;
linef_530700_839829468(p0, ((Tcprocsection527011) 1), ((NimStringDesc*) &T839829468_148), LOC5, 1);
c0.p = p0;
{
Ropeobj177006* LOC10;
if (!((*typ0).kind == ((Ttypekind290244) 24))) goto LA8;
LOC10 = (Ropeobj177006*)0;
LOC10 = rope_177277_2381377266(((NimStringDesc*) &T839829468_188));
gentraverseprocseq_535399_839829468((&c0), LOC10, typ0);
}
goto LA6;
LA8: ;
{
{
Ttype290840* LOC14;
Ropeobj177006* LOC17;
LOC14 = (Ttype290840*)0;
LOC14 = skiptypes_294099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106232576256));
if (!((*LOC14).kind == ((Ttypekind290244) 4) || (*LOC14).kind == ((Ttypekind290244) 16))) goto LA15;
LOC17 = (Ropeobj177006*)0;
LOC17 = rope_177277_2381377266(((NimStringDesc*) &T839829468_188));
gentraverseproc_535022_839829468((&c0), LOC17, (*typ0).sons->data[((NI) 0)]);
}
goto LA12;
LA15: ;
{
Ropeobj177006* LOC19;
LOC19 = (Ropeobj177006*)0;
LOC19 = rope_177277_2381377266(((NimStringDesc*) &T839829468_189));
gentraverseproc_535022_839829468((&c0), LOC19, (*typ0).sons->data[((NI) 0)]);
}
LA12: ;
}
LA6: ;
memset((void*)LOC20, 0, sizeof(LOC20));
LOC20[0] = header0;
LOC21 = (Ropeobj177006**)0;
LOC21 = s_527179_3723162438(p0, ((Tcprocsection527011) 0));
LOC20[1] = (*LOC21);
LOC22 = (Ropeobj177006**)0;
LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 1));
LOC20[2] = (*LOC22);
LOC23 = (Ropeobj177006**)0;
LOC23 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
LOC20[3] = (*LOC23);
generatedproc0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_190), LOC20, 4);
memset((void*)LOC24, 0, sizeof(LOC24));
LOC24[0] = header0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC24, 1);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], generatedproc0);
return result0;
}
N_NIMCALL(void, genarrayinfo_535005_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) {
Ropeobj177006* LOC1;
LOC1 = (Ropeobj177006*)0;
LOC1 = gentypeinfo_533941_839829468(m0, (*typ0).sons->data[((NI) 1)]);
gentypeinfoauxbase_533960_839829468(m0, typ0, typ0, name0, LOC1);
}
N_NIMCALL(void, gensetinfo_534867_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) {
Ropeobj177006* tmp0;
TY533238 LOC1;
NI64 LOC2;
gentypeinfoaux_534027_839829468(m0, typ0, typ0, name0);
tmp0 = getnimnode_533945_839829468(m0);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = tmp0;
LOC2 = (NI64)0;
LOC2 = firstord_318001_3876443242(typ0);
LOC1[1] = rope_177401_2381377266(LOC2);
LOC1[2] = name0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_193), LOC1, 3);
}
N_NIMCALL(void, genenuminfo_534597_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ropeobj177006* name0) {
Ropeobj177006* nodeptrs0;
NI length0;
TY530811 LOC1;
Ropeobj177006* enumnames0;
Ropeobj177006* specialcases0;
NI firstnimnode0;
NIM_BOOL hasholes0;
Ropeobj177006* enumarray0;
Ropeobj177006* counter0;
TY177507 LOC24;
TY533238 LOC25;
TY534847 LOC26;
TY533235 LOC27;
gentypeinfoaux_534027_839829468(m0, typ0, typ0, name0);
nodeptrs0 = gettempname_531596_839829468(m0);
length0 = sonslen_293351_850551059((*typ0).n);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = nodeptrs0;
LOC1[1] = rope_177401_2381377266(((NI64) (length0)));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC1, 2);
enumnames0 = (Ropeobj177006*)0;
specialcases0 = (Ropeobj177006*)0;
firstnimnode0 = (*m0).typenodes;
hasholes0 = NIM_FALSE;
{
NI i_534622_839829468;
NI HEX3Atmp_534860_839829468;
NI res_534863_839829468;
i_534622_839829468 = (NI)0;
HEX3Atmp_534860_839829468 = (NI)0;
HEX3Atmp_534860_839829468 = (NI)(length0 - ((NI) 1));
res_534863_839829468 = ((NI) 0);
{
while (1) {
Tsym290834* field0;
Ropeobj177006* elemnode0;
if (!(res_534863_839829468 <= HEX3Atmp_534860_839829468)) goto LA4;
i_534622_839829468 = res_534863_839829468;
field0 = (*(*(*typ0).n).kindU.S6.sons->data[i_534622_839829468]).kindU.S4.sym;
elemnode0 = getnimnode_533945_839829468(m0);
{
Ropeobj177006* LOC9;
if (!((*field0).ast == NIM_NIL)) goto LA7;
LOC9 = (Ropeobj177006*)0;
LOC9 = makecstring_189638_155036129((*(*field0).name).s);
add_177482_2381377266(&enumnames0, LOC9);
}
goto LA5;
LA7: ;
{
Ropeobj177006* LOC11;
LOC11 = (Ropeobj177006*)0;
LOC11 = makecstring_189638_155036129((*(*field0).ast).kindU.S3.strval);
add_177482_2381377266(&enumnames0, LOC11);
}
LA5: ;
{
NimStringDesc* LOC16;
if (!(i_534622_839829468 < (NI)(length0 - ((NI) 1)))) goto LA14;
LOC16 = (NimStringDesc*)0;
LOC16 = rawNewString(tnl_175644_4151366050->Sup.len + 2);
appendString(LOC16, ((NimStringDesc*) &T839829468_110));
appendString(LOC16, tnl_175644_4151366050);
add_177487_2381377266(&enumnames0, LOC16);
}
LA14: ;
{
NIM_BOOL LOC19;
TY530811 LOC23;
LOC19 = (NIM_BOOL)0;
LOC19 = !(((*field0).position == i_534622_839829468));
if (LOC19) goto LA20;
LOC19 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 5))&31U)))!=0);
LA20: ;
if (!LOC19) goto LA21;
memset((void*)LOC23, 0, sizeof(LOC23));
LOC23[0] = elemnode0;
LOC23[1] = rope_177401_2381377266(((NI64) ((*field0).position)));
addf_178205_2381377266(&specialcases0, ((NimStringDesc*) &T839829468_194), LOC23, 2);
hasholes0 = NIM_TRUE;
}
LA21: ;
res_534863_839829468 += ((NI) 1);
} LA4: ;
}
}
enumarray0 = gettempname_531596_839829468(m0);
counter0 = gettempname_531596_839829468(m0);
memset((void*)LOC24, 0, sizeof(LOC24));
LOC24[0] = counter0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_195), LOC24, 1);
memset((void*)LOC25, 0, sizeof(LOC25));
LOC25[0] = enumarray0;
LOC25[1] = rope_177401_2381377266(((NI64) (length0)));
LOC25[2] = enumnames0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_196), LOC25, 3);
memset((void*)LOC26, 0, sizeof(LOC26));
LOC26[0] = counter0;
LOC26[1] = rope_177401_2381377266(((NI64) (length0)));
LOC26[2] = (*m0).typenodesname;
LOC26[3] = rope_177401_2381377266(((NI64) (firstnimnode0)));
LOC26[4] = enumarray0;
LOC26[5] = nodeptrs0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_197), LOC26, 6);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], specialcases0);
memset((void*)LOC27, 0, sizeof(LOC27));
LOC27[0] = getnimnode_533945_839829468(m0);
LOC27[1] = rope_177401_2381377266(((NI64) (length0)));
LOC27[2] = nodeptrs0;
LOC27[3] = name0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_198), LOC27, 4);
{
TY177507 LOC32;
if (!hasholes0) goto LA30;
memset((void*)LOC32, 0, sizeof(LOC32));
LOC32[0] = name0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_199), LOC32, 1);
}
LA30: ;
}
N_NIMCALL(Ropeobj177006*, discriminatortablename_534057_839829468)(Tcgen527027* m0, Ttype290840* objtype_534060_839829468, Tsym290834* d0) {
Ropeobj177006* result0;
Ttype290840* objtype0;
TY530811 LOC8;
NimStringDesc* LOC9;
result0 = (Ropeobj177006*)0;
objtype0 = objtype_534060_839829468;
{
while (1) {
Tsym290834* LOC3;
LOC3 = (Tsym290834*)0;
LOC3 = lookupinrecord_297119_2984716966((*objtype0).n, (*d0).name);
if (!(LOC3 == NIM_NIL)) goto LA2;
objtype0 = (*objtype0).sons->data[((NI) 0)];
} LA2: ;
}
{
if (!((*objtype0).sym == NIM_NIL)) goto LA6;
internalerror_194100_155036129((*d0).info, ((NimStringDesc*) &T839829468_200));
}
LA6: ;
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rope_177401_2381377266(((NI64) ((*objtype0).Sup.id)));
LOC9 = (NimStringDesc*)0;
LOC9 = mangle_526847_2036603609((*(*d0).name).s);
LOC8[1] = rope_177277_2381377266(LOC9);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_201), LOC8, 2);
return result0;
}
N_NIMCALL(void, genobjectfields_534104_839829468)(Tcgen527027* m0, Ttype290840* typ0, Tnode290802* n0, Ropeobj177006* expr0) {
switch ((*n0).kind) {
case ((Tnodekind290020) 138):
{
NI L0;
L0 = sonslen_293351_850551059(n0);
{
if (!(L0 == ((NI) 1))) goto LA4;
genobjectfields_534104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[((NI) 0)], expr0);
}
goto LA2;
LA4: ;
{
Ropeobj177006* tmp0;
TY530811 LOC9;
TY533238 LOC14;
if (!(((NI) 0) < L0)) goto LA7;
tmp0 = gettempname_531596_839829468(m0);
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = tmp0;
LOC9[1] = rope_177401_2381377266(((NI64) (L0)));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC9, 2);
{
NI i_534127_839829468;
NI HEX3Atmp_534482_839829468;
NI res_534485_839829468;
i_534127_839829468 = (NI)0;
HEX3Atmp_534482_839829468 = (NI)0;
HEX3Atmp_534482_839829468 = (NI)(L0 - ((NI) 1));
res_534485_839829468 = ((NI) 0);
{
while (1) {
Ropeobj177006* tmp20;
TY533238 LOC13;
if (!(res_534485_839829468 <= HEX3Atmp_534482_839829468)) goto LA12;
i_534127_839829468 = res_534485_839829468;
tmp20 = getnimnode_533945_839829468(m0);
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = tmp0;
LOC13[1] = rope_177401_2381377266(((NI64) (i_534127_839829468)));
LOC13[2] = tmp20;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC13, 3);
genobjectfields_534104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[i_534127_839829468], tmp20);
res_534485_839829468 += ((NI) 1);
} LA12: ;
}
}
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = expr0;
LOC14[1] = rope_177401_2381377266(((NI64) (L0)));
LOC14[2] = tmp0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC14, 3);
}
goto LA2;
LA7: ;
{
TY530811 LOC16;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = expr0;
LOC16[1] = rope_177401_2381377266(((NI64) (L0)));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC16, 2);
}
LA2: ;
}
break;
case ((Tnodekind290020) 139):
{
Tsym290834* field0;
Ropeobj177006* tmp0;
NI64 L0;
TY534401 LOC18;
TY530811 LOC19;
field0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
tmp0 = discriminatortablename_534057_839829468(m0, typ0, field0);
L0 = lengthord_318007_3876443242((*field0).typ);
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = expr0;
LOC18[1] = gettypedesc_533671_839829468(m0, typ0);
LOC18[2] = (*field0).loc.r;
LOC18[3] = gentypeinfo_533941_839829468(m0, (*field0).typ);
LOC18[4] = makecstring_189638_155036129((*(*field0).name).s);
LOC18[5] = tmp0;
LOC18[6] = rope_177401_2381377266(L0);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_202), LOC18, 7);
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = tmp0;
LOC19[1] = rope_177401_2381377266((NI64)(L0 + IL64(1)));
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_203), LOC19, 2);
{
NI i_534421_839829468;
NI HEX3Atmp_534499_839829468;
NI LOC21;
NI res_534502_839829468;
i_534421_839829468 = (NI)0;
HEX3Atmp_534499_839829468 = (NI)0;
LOC21 = (NI)0;
LOC21 = sonslen_293351_850551059(n0);
HEX3Atmp_534499_839829468 = (NI)(LOC21 - ((NI) 1));
res_534502_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* b0;
Ropeobj177006* tmp20;
Tnode290802* LOC24;
if (!(res_534502_839829468 <= HEX3Atmp_534499_839829468)) goto LA23;
i_534421_839829468 = res_534502_839829468;
b0 = (*n0).kindU.S6.sons->data[i_534421_839829468];
tmp20 = getnimnode_533945_839829468(m0);
LOC24 = (Tnode290802*)0;
LOC24 = lastson_293364_850551059(b0);
genobjectfields_534104_839829468(m0, typ0, LOC24, tmp20);
switch ((*b0).kind) {
case ((Tnodekind290020) 85):
{
{
NI LOC28;
LOC28 = (NI)0;
LOC28 = sonslen_293351_850551059(b0);
if (!(LOC28 < ((NI) 2))) goto LA29;
internalerror_194100_155036129((*b0).info, ((NimStringDesc*) &T839829468_204));
}
LA29: ;
{
NI j_534436_839829468;
NI HEX3Atmp_534492_839829468;
NI LOC32;
NI res_534495_839829468;
j_534436_839829468 = (NI)0;
HEX3Atmp_534492_839829468 = (NI)0;
LOC32 = (NI)0;
LOC32 = sonslen_293351_850551059(b0);
HEX3Atmp_534492_839829468 = (NI)(LOC32 - ((NI) 2));
res_534495_839829468 = ((NI) 0);
{
while (1) {
if (!(res_534495_839829468 <= HEX3Atmp_534492_839829468)) goto LA34;
j_534436_839829468 = res_534495_839829468;
{
NI x0;
NI64 LOC39;
NI y0;
NI64 LOC40;
if (!((*(*b0).kindU.S6.sons->data[j_534436_839829468]).kind == ((Tnodekind290020) 44))) goto LA37;
LOC39 = (NI64)0;
LOC39 = getordvalue_318129_3876443242((*(*b0).kindU.S6.sons->data[j_534436_839829468]).kindU.S6.sons->data[((NI) 0)]);
x0 = ((NI) (LOC39));
LOC40 = (NI64)0;
LOC40 = getordvalue_318129_3876443242((*(*b0).kindU.S6.sons->data[j_534436_839829468]).kindU.S6.sons->data[((NI) 1)]);
y0 = ((NI) (LOC40));
{
while (1) {
TY533238 LOC43;
if (!(x0 <= y0)) goto LA42;
memset((void*)LOC43, 0, sizeof(LOC43));
LOC43[0] = tmp0;
LOC43[1] = rope_177401_2381377266(((NI64) (x0)));
LOC43[2] = tmp20;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC43, 3);
x0 += ((NI) 1);
} LA42: ;
}
}
goto LA35;
LA37: ;
{
TY533238 LOC45;
NI64 LOC46;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC45[0] = tmp0;
LOC46 = (NI64)0;
LOC46 = getordvalue_318129_3876443242((*b0).kindU.S6.sons->data[j_534436_839829468]);
LOC45[1] = rope_177401_2381377266(LOC46);
LOC45[2] = tmp20;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC45, 3);
}
LA35: ;
res_534495_839829468 += ((NI) 1);
} LA34: ;
}
}
}
break;
case ((Tnodekind290020) 88):
{
TY533238 LOC48;
memset((void*)LOC48, 0, sizeof(LOC48));
LOC48[0] = tmp0;
LOC48[1] = rope_177401_2381377266(L0);
LOC48[2] = tmp20;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC48, 3);
}
break;
default:
{
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_205));
}
break;
}
res_534502_839829468 += ((NI) 1);
} LA23: ;
}
}
}
break;
case ((Tnodekind290020) 3):
{
Tsym290834* field0;
field0 = (*n0).kindU.S4.sym;
{
TY534475 LOC55;
if (!((*field0).kindU.S4.bitsize == ((NI) 0))) goto LA53;
memset((void*)LOC55, 0, sizeof(LOC55));
LOC55[0] = expr0;
LOC55[1] = gettypedesc_533671_839829468(m0, typ0);
LOC55[2] = (*field0).loc.r;
LOC55[3] = gentypeinfo_533941_839829468(m0, (*field0).typ);
LOC55[4] = makecstring_189638_155036129((*(*field0).name).s);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_206), LOC55, 5);
}
LA53: ;
}
break;
default:
{
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_207));
}
break;
}
}
N_NIMCALL(void, genobjectinfo_534506_839829468)(Tcgen527027* m0, Ttype290840* typ0, Ttype290840* origtype0, Ropeobj177006* name0) {
Ropeobj177006* tmp0;
TY530811 LOC12;
Ttype290840* t0;
{
if (!((*typ0).kind == ((Ttypekind290244) 17))) goto LA3;
gentypeinfoaux_534027_839829468(m0, typ0, origtype0, name0);
}
goto LA1;
LA3: ;
{
Ropeobj177006* LOC6;
LOC6 = (Ropeobj177006*)0;
LOC6 = rope_177277_2381377266(((NimStringDesc*) &T839829468_18));
gentypeinfoauxbase_533960_839829468(m0, typ0, origtype0, name0, LOC6);
}
LA1: ;
tmp0 = getnimnode_533945_839829468(m0);
{
NIM_BOOL LOC9;
LOC9 = (NIM_BOOL)0;
LOC9 = isimportedcpptype_531476_839829468(typ0);
if (!!(LOC9)) goto LA10;
genobjectfields_534104_839829468(m0, typ0, (*typ0).n, tmp0);
}
LA10: ;
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = name0;
LOC12[1] = tmp0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC12, 2);
t0 = (*typ0).sons->data[((NI) 0)];
{
while (1) {
if (!!((t0 == NIM_NIL))) goto LA14;
t0 = skiptypes_294099_850551059(t0, IL64(211106247215360));
(*t0).flags |= ((NU32)1)<<((((Ttypeflag290431) 5))%(sizeof(NU32)*8));
t0 = (*t0).sons->data[((NI) 0)];
} LA14: ;
}
}
N_NIMCALL(void, gendeepcopyproc_536066_839829468)(Tcgen527027* m0, Tsym290834* s0, Ropeobj177006* result0) {
TY530811 LOC1;
genproc_530951_839829468(m0, s0);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = result0;
LOC1[1] = (*s0).loc.r;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_208), LOC1, 2);
}
N_NIMCALL(Ropeobj177006*, gentypeinfo_533941_839829468)(Tcgen527027* m0, Ttype290840* t_533944_839829468) {
Ropeobj177006* result0;
Ttype290840* origtype0;
Ttype290840* t0;
TY177507 LOC1;
Tsym290834* owner0;
Ttype290840* LOC12;
Ropeobj177006* LOC66;
Ropeobj177006* LOC67;
Ropeobj177006* LOC68;
{ result0 = (Ropeobj177006*)0;
origtype0 = t_533944_839829468;
t0 = getuniquetype_526640_2036603609(t_533944_839829468);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rope_177401_2381377266(((NI64) ((*t0).Sup.id)));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_127), LOC1, 1);
{
NIM_BOOL LOC4;
Ropeobj177006* LOC7;
Ropeobj177006* LOC8;
Ropeobj177006* LOC9;
LOC4 = (NIM_BOOL)0;
LOC4 = containsorincl_266862_2627731572((&(*m0).typeinfomarker), (*t0).Sup.id);
if (!LOC4) goto LA5;
LOC7 = (Ropeobj177006*)0;
LOC7 = rope_177277_2381377266(((NimStringDesc*) &T839829468_128));
LOC8 = (Ropeobj177006*)0;
LOC8 = HEX26_177418_2381377266(LOC7, result0);
LOC9 = (Ropeobj177006*)0;
LOC9 = rope_177277_2381377266(((NimStringDesc*) &T839829468_117));
result0 = HEX26_177418_2381377266(LOC8, LOC9);
goto BeforeRet;
}
LA5: ;
{
while (1) {
if (!((*t0).kind == ((Ttypekind290244) 13))) goto LA11;
t0 = lastson_293377_850551059(t0);
} LA11: ;
}
LOC12 = (Ttype290840*)0;
LOC12 = skiptypes_294099_850551059(t0, IL64(211106247256320));
owner0 = getmodule_297123_2984716966((*LOC12).owner);
{
Tcgen527027* LOC17;
Ropeobj177006* LOC18;
Ropeobj177006* LOC19;
Ropeobj177006* LOC20;
TY530811 LOC21;
NimStringDesc* LOC22;
Ropeobj177006* LOC23;
Ropeobj177006* LOC24;
Ropeobj177006* LOC25;
if (!!((owner0 == (*m0).module))) goto LA15;
LOC17 = (Tcgen527027*)0;
LOC17 = bmod_527201_3723162438(owner0);
LOC18 = (Ropeobj177006*)0;
LOC18 = gentypeinfo_533941_839829468(LOC17, t0);
LOC19 = (Ropeobj177006*)0;
LOC19 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_129));
LOC20 = (Ropeobj177006*)0;
LOC20 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_130));
memset((void*)LOC21, 0, sizeof(LOC21));
LOC21[0] = result0;
LOC22 = (NimStringDesc*)0;
LOC22 = typetostring_318017_3876443242(t0, ((Tprefereddesc318011) 0));
LOC21[1] = rope_177277_2381377266(LOC22);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_131), LOC21, 2);
LOC23 = (Ropeobj177006*)0;
LOC23 = rope_177277_2381377266(((NimStringDesc*) &T839829468_128));
LOC24 = (Ropeobj177006*)0;
LOC24 = HEX26_177418_2381377266(LOC23, result0);
LOC25 = (Ropeobj177006*)0;
LOC25 = rope_177277_2381377266(((NimStringDesc*) &T839829468_117));
result0 = HEX26_177418_2381377266(LOC24, LOC25);
goto BeforeRet;
}
LA15: ;
switch ((*t0).kind) {
case ((Ttypekind290244) 3):
case ((Ttypekind290244) 62):
{
result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_132));
}
break;
case ((Ttypekind290244) 26):
case ((Ttypekind290244) 1):
case ((Ttypekind290244) 2):
case ((Ttypekind290244) 29):
case ((Ttypekind290244) 28):
case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44):
case ((Ttypekind290244) 23):
{
Ropeobj177006* LOC28;
LOC28 = (Ropeobj177006*)0;
LOC28 = rope_177277_2381377266(((NimStringDesc*) &T839829468_132));
gentypeinfoauxbase_533960_839829468(m0, t0, t0, result0, LOC28);
}
break;
case ((Ttypekind290244) 59):
{
{
Ttype290840* LOC34;
if (!!(((*t0).n == NIM_NIL))) goto LA32;
LOC34 = (Ttype290840*)0;
LOC34 = lastson_293377_850551059(t0);
result0 = gentypeinfo_533941_839829468(m0, LOC34);
}
goto LA30;
LA32: ;
{
NimStringDesc* LOC36;
LOC36 = (NimStringDesc*)0;
LOC36 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI290244))->Sup.len + 13);
appendString(LOC36, ((NimStringDesc*) &T839829468_137));
appendString(LOC36, reprEnum((NI)(*t0).kind, (&NTI290244)));
appendChar(LOC36, 41);
internalerror_194113_155036129(LOC36);
}
LA30: ;
}
break;
case ((Ttypekind290244) 25):
{
{
Ropeobj177006* LOC42;
if (!!(((*t0).callconv == ((Tcallingconvention290002) 8)))) goto LA40;
LOC42 = (Ropeobj177006*)0;
LOC42 = rope_177277_2381377266(((NimStringDesc*) &T839829468_132));
gentypeinfoauxbase_533960_839829468(m0, t0, t0, result0, LOC42);
}
goto LA38;
LA40: ;
{
Ttype290840* LOC44;
LOC44 = (Ttype290840*)0;
LOC44 = fakeclosuretype_535010_839829468((*t0).owner);
gentupleinfo_534549_839829468(m0, LOC44, result0);
}
LA38: ;
}
break;
case ((Ttypekind290244) 24):
case ((Ttypekind290244) 22):
{
gentypeinfoaux_534027_839829468(m0, t0, t0, result0);
{
Ropeobj177006* markerproc0;
TY530811 LOC50;
if (!(((Tgcmode168080) 4) <= gselectedgc_168133_2607990831)) goto LA48;
markerproc0 = gentraverseproc_535632_839829468(m0, t0, ((Ttypeinforeason535016) 0));
memset((void*)LOC50, 0, sizeof(LOC50));
LOC50[0] = result0;
LOC50[1] = markerproc0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_192), LOC50, 2);
}
LA48: ;
}
break;
case ((Ttypekind290244) 21):
case ((Ttypekind290244) 20):
{
gentypeinfoaux_534027_839829468(m0, t0, t0, result0);
}
break;
case ((Ttypekind290244) 4):
case ((Ttypekind290244) 16):
{
genarrayinfo_535005_839829468(m0, t0, result0);
}
break;
case ((Ttypekind290244) 19):
{
gensetinfo_534867_839829468(m0, t0, result0);
}
break;
case ((Ttypekind290244) 14):
{
genenuminfo_534597_839829468(m0, t0, result0);
}
break;
case ((Ttypekind290244) 17):
{
genobjectinfo_534506_839829468(m0, t0, origtype0, result0);
}
break;
case ((Ttypekind290244) 18):
{
gentupleinfo_534549_839829468(m0, t0, result0);
}
break;
default:
{
NimStringDesc* LOC58;
LOC58 = (NimStringDesc*)0;
LOC58 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI290244))->Sup.len + 13);
appendString(LOC58, ((NimStringDesc*) &T839829468_137));
appendString(LOC58, reprEnum((NI)(*t0).kind, (&NTI290244)));
appendChar(LOC58, 41);
internalerror_194113_155036129(LOC58);
}
break;
}
{
if (!!(((*t0).deepcopy == NIM_NIL))) goto LA61;
gendeepcopyproc_536066_839829468(m0, (*t0).deepcopy, result0);
}
goto LA59;
LA61: ;
{
if (!!(((*origtype0).deepcopy == NIM_NIL))) goto LA64;
gendeepcopyproc_536066_839829468(m0, (*origtype0).deepcopy, result0);
}
goto LA59;
LA64: ;
LA59: ;
LOC66 = (Ropeobj177006*)0;
LOC66 = rope_177277_2381377266(((NimStringDesc*) &T839829468_128));
LOC67 = (Ropeobj177006*)0;
LOC67 = HEX26_177418_2381377266(LOC66, result0);
LOC68 = (Ropeobj177006*)0;
LOC68 = rope_177277_2381377266(((NimStringDesc*) &T839829468_117));
result0 = HEX26_177418_2381377266(LOC67, LOC68);
}BeforeRet: ;
return result0;
}
N_NIMCALL(void, localdebuginfo_536449_839829468)(Tcproc527021* p0, Tsym290834* s0) {
Ropeobj177006* a0;
TY533235 LOC16;
NimStringDesc* LOC17;
{ {
if (!!(((163840 & (*p0).options) == 163840))) goto LA3;
goto BeforeRet;
}
LA3: ;
{
Ttype290840* LOC7;
LOC7 = (Ttype290840*)0;
LOC7 = skiptypes_294099_850551059((*s0).typ, IL64(211106240964864));
if (!((*LOC7).kind == ((Ttypekind290244) 27) || (*LOC7).kind == ((Ttypekind290244) 48))) goto LA8;
goto BeforeRet;
}
LA8: ;
a0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_52), (*s0).loc.r);
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = ((*s0).kind == ((Tsymkind290435) 3));
if (!(LOC12)) goto LA13;
LOC12 = ccgintroducedptr_531609_839829468(s0);
LA13: ;
if (!LOC12) goto LA14;
a0 = (*s0).loc.r;
}
LA14: ;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rope_177401_2381377266(((NI64) ((*p0).maxframelen)));
LOC17 = (NimStringDesc*)0;
LOC17 = nsuNormalize((*(*s0).name).s);
LOC16[1] = makecstring_189638_155036129(LOC17);
LOC16[2] = a0;
LOC16[3] = gentypeinfo_533941_839829468((*p0).module, (*s0).loc.t);
linef_530700_839829468(p0, ((Tcprocsection527011) 1), ((NimStringDesc*) &T839829468_126), LOC16, 4);
(*p0).maxframelen += ((NI) 1);
(*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].framelen += ((NI) 1);
}BeforeRet: ;
}
N_NIMCALL(void, assignlocalvar_536614_839829468)(Tcproc527021* p0, Tsym290834* s0) {
Ropeobj177006* decl0;
Ropeobj177006* LOC1;
Ropeobj177006* LOC2;
LOC1 = (Ropeobj177006*)0;
LOC1 = localvardecl_536532_839829468(p0, s0);
LOC2 = (Ropeobj177006*)0;
LOC2 = HEX26_177447_2381377266(LOC1, ((NimStringDesc*) &T839829468_125));
decl0 = HEX26_177447_2381377266(LOC2, tnl_175644_4151366050);
line_530690_839829468(p0, ((Tcprocsection527011) 0), decl0);
localdebuginfo_536449_839829468(p0, s0);
}
N_NIMCALL(void, initlocalvar_536398_839829468)(Tcproc527021* p0, Tsym290834* v0, NIM_BOOL immediateasgn0) {
{
if (!!((((*v0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0))) goto LA3;
{
if (!!(immediateasgn0)) goto LA7;
constructloc_536388_839829468(p0, (*v0).loc, NIM_FALSE);
}
LA7: ;
}
LA3: ;
}
N_NIMCALL(void, fillresult_531865_839829468)(Tsym290834* param0) {
TY531289 LOC1;
Ropeobj177006* LOC2;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC2 = (Ropeobj177006*)0;
LOC2 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_210), LOC1, 0);
fillloc_530282_839829468((&(*param0).loc), ((Tlockind290808) 4), (*param0).typ, LOC2, ((Tstorageloc290812) 2));
{
NIM_BOOL LOC5;
Tctypekind527007 LOC6;
LOC5 = (NIM_BOOL)0;
LOC6 = (Tctypekind527007)0;
LOC6 = mapreturntype_531445_839829468((*param0).typ);
LOC5 = !((LOC6 == ((Tctypekind527007) 17)));
if (!(LOC5)) goto LA7;
LOC5 = isinvalidreturntype_531548_839829468((*param0).typ);
LA7: ;
if (!LOC5) goto LA8;
(*param0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 0))%(sizeof(NU16)*8));
(*param0).loc.s = ((Tstorageloc290812) 0);
}
LA8: ;
}
N_NIMCALL(void, assignparam_536994_839829468)(Tcproc527021* p0, Tsym290834* s0) {
localdebuginfo_536449_839829468(p0, s0);
}
N_NIMCALL(void, closuresetup_558158_839829468)(Tcproc527021* p0, Tsym290834* prc0) {
Tnode290802* ls0;
Tnode290802* LOC5;
Tsym290834* env0;
TY530811 LOC10;
{ {
if (!!((((*(*prc0).typ).flags &(1U<<((NU)(((Ttypeflag290431) 11))&31U)))!=0))) goto LA3;
goto BeforeRet;
}
LA3: ;
LOC5 = (Tnode290802*)0;
LOC5 = HEX5BHEX5D_291238_850551059((*prc0).ast, ((NI) 3));
ls0 = lastson_293364_850551059(LOC5);
{
if (!!(((*ls0).kind == ((Tnodekind290020) 3)))) goto LA8;
internalerror_194100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_211));
}
LA8: ;
env0 = (*ls0).kindU.S4.sym;
assignlocalvar_536614_839829468(p0, env0);
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = rdloc_536188_839829468((*env0).loc);
LOC10[1] = gettypedesc_533671_839829468((*p0).module, (*env0).typ);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_212), LOC10, 2);
}BeforeRet: ;
}
N_NIMCALL(Ropeobj177006*, initgcframe_536435_839829468)(Tcproc527021* p0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
TY177507 LOC5;
if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = (*p0).gcframetype;
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_217), LOC5, 1);
}
LA3: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, initframe_558140_839829468)(Tcproc527021* p0, Ropeobj177006* procname0, Ropeobj177006* filename0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
result0 = (Ropeobj177006*)0;
LOC1 = (Ropeobj177006*)0;
LOC1 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_218));
{
Ropeobj177006* LOC6;
TY533235 LOC7;
if (!(((NI) 0) < (*p0).maxframelen)) goto LA4;
LOC6 = (Ropeobj177006*)0;
LOC6 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_219));
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = procname0;
LOC7[1] = filename0;
LOC7[2] = rope_177401_2381377266(((NI64) ((*p0).maxframelen)));
LOC7[3] = rope_177401_2381377266(((NI64) ((*p0).blocks->data[((NI) 0)].framelen)));
result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_220), LOC7, 4);
}
goto LA2;
LA4: ;
{
TY530811 LOC9;
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = procname0;
LOC9[1] = filename0;
result0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_221), LOC9, 2);
}
LA2: ;
return result0;
}
N_NIMCALL(void, appcg_530648_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) {
Ropeobj177006** LOC1;
Ropeobj177006* LOC2;
LOC1 = (Ropeobj177006**)0;
LOC1 = s_527179_3723162438(p0, s0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, frmt0, args0, args0Len0);
add_177482_2381377266(LOC1, LOC2);
}
N_NIMCALL(Ropeobj177006*, deinitgcframe_536441_839829468)(Tcproc527021* p0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
TY531289 LOC5;
if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_225), LOC5, 0);
}
LA3: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, deinitframe_558150_839829468)(Tcproc527021* p0) {
Ropeobj177006* result0;
TY531289 LOC1;
result0 = (Ropeobj177006*)0;
memset((void*)LOC1, 0, sizeof(LOC1));
result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_226), LOC1, 0);
return result0;
}
N_NIMCALL(void, genprocaux_558284_839829468)(Tcgen527027* m0, Tsym290834* prc0) {
Tcproc527021* p0;
Ropeobj177006* header0;
Ropeobj177006* returnstmt0;
Tnode290802* LOC51;
Ropeobj177006* generatedproc0;
p0 = newproc_527206_3723162438(prc0, m0);
header0 = genprocheader_533867_839829468(m0, prc0);
returnstmt0 = NIM_NIL;
{
NIM_BOOL LOC3;
Tsym290834* res0;
LOC3 = (NIM_BOOL)0;
LOC3 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0));
if (!(LOC3)) goto LA4;
LOC3 = !(((*(*prc0).typ).sons->data[((NI) 0)] == NIM_NIL));
LA4: ;
if (!LOC3) goto LA5;
{
NI LOC9;
LOC9 = (NI)0;
LOC9 = len_291081_850551059((*prc0).ast);
if (!(LOC9 <= ((NI) 7))) goto LA10;
internalerror_194100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_120));
}
LA10: ;
res0 = (*(*(*prc0).ast).kindU.S6.sons->data[((NI) 7)]).kindU.S4.sym;
{
NIM_BOOL LOC14;
TY177507 LOC34;
LOC14 = (NIM_BOOL)0;
LOC14 = isinvalidreturntype_531548_839829468((*(*prc0).typ).sons->data[((NI) 0)]);
if (!!(LOC14)) goto LA15;
{
if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA19;
(*res0).flags |= ((NU32)1)<<((((Tsymflag290184) 12))%(sizeof(NU32)*8));
}
LA19: ;
{
NIM_BOOL LOC23;
NIM_BOOL LOC24;
NIM_BOOL LOC26;
Tnode290802* val0;
Tnode290802* LOC29;
Ropeobj177006* decl0;
Tloc290816 a0;
TY530811 LOC32;
LOC23 = (NIM_BOOL)0;
LOC24 = (NIM_BOOL)0;
LOC24 = (((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0);
if (!(LOC24)) goto LA25;
LOC26 = (NIM_BOOL)0;
LOC26 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC26) goto LA27;
LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA27: ;
LOC24 = LOC26;
LA25: ;
LOC23 = LOC24;
if (!(LOC23)) goto LA28;
LOC29 = (Tnode290802*)0;
LOC29 = getbody_333227_1724185294(prc0);
val0 = easyresultasgn_558191_839829468(LOC29);
LOC23 = !((val0 == NIM_NIL));
LA28: ;
if (!LOC23) goto LA30;
decl0 = localvardecl_536532_839829468(p0, res0);
memset((void*)(&a0), 0, sizeof(a0));
initlocexprsingleuse_537289_839829468(p0, val0, (&a0));
memset((void*)LOC32, 0, sizeof(LOC32));
LOC32[0] = decl0;
LOC32[1] = rdloc_536188_839829468(a0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC32, 2);
}
goto LA21;
LA30: ;
{
assignlocalvar_536614_839829468(p0, res0);
initlocalvar_536398_839829468(p0, res0, NIM_FALSE);
}
LA21: ;
memset((void*)LOC34, 0, sizeof(LOC34));
LOC34[0] = rdloc_536188_839829468((*res0).loc);
returnstmt0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_209), LOC34, 1);
}
goto LA12;
LA15: ;
{
fillresult_531865_839829468(res0);
assignparam_536994_839829468(p0, res0);
{
Ttype290840* LOC38;
LOC38 = (Ttype290840*)0;
LOC38 = skiptypes_294099_850551059((*res0).typ, IL64(211106232576256));
if (!((*LOC38).kind == ((Ttypekind290244) 16))) goto LA39;
(*res0).loc.s = ((Tstorageloc290812) 0);
}
LA39: ;
}
LA12: ;
}
LA5: ;
{
NI i_558627_839829468;
NI HEX3Atmp_558743_839829468;
NI LOC42;
NI res_558746_839829468;
i_558627_839829468 = (NI)0;
HEX3Atmp_558743_839829468 = (NI)0;
LOC42 = (NI)0;
LOC42 = sonslen_293351_850551059((*(*prc0).typ).n);
HEX3Atmp_558743_839829468 = (NI)(LOC42 - ((NI) 1));
res_558746_839829468 = ((NI) 1);
{
while (1) {
if (!(res_558746_839829468 <= HEX3Atmp_558743_839829468)) goto LA44;
i_558627_839829468 = res_558746_839829468;
{
Tsym290834* param0;
param0 = (*(*(*(*prc0).typ).n).kindU.S6.sons->data[i_558627_839829468]).kindU.S4.sym;
{
NIM_BOOL LOC48;
LOC48 = (NIM_BOOL)0;
LOC48 = iscompiletimeonly_326706_3876443242((*param0).typ);
if (!LOC48) goto LA49;
goto LA45;
}
LA49: ;
assignparam_536994_839829468(p0, param0);
} LA45: ;
res_558746_839829468 += ((NI) 1);
} LA44: ;
}
}
closuresetup_558158_839829468(p0, prc0);
LOC51 = (Tnode290802*)0;
LOC51 = getbody_333227_1724185294(prc0);
genstmts_537244_839829468(p0, LOC51);
generatedproc0 = (Ropeobj177006*)0;
{
if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 14))&31U)))!=0)) goto LA54;
{
if (!((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 6))&7U)))!=0)) goto LA58;
header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_213), header0);
}
LA58: ;
}
LA54: ;
{
TY533235 LOC68;
Ropeobj177006** LOC69;
Ropeobj177006** LOC70;
Ropeobj177006** LOC71;
if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0)) goto LA62;
{
if (!((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 6))&7U)))!=0)) goto LA66;
header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_214), header0);
}
LA66: ;
memset((void*)LOC68, 0, sizeof(LOC68));
LOC68[0] = header0;
LOC69 = (Ropeobj177006**)0;
LOC69 = s_527179_3723162438(p0, ((Tcprocsection527011) 0));
LOC68[1] = (*LOC69);
LOC70 = (Ropeobj177006**)0;
LOC70 = s_527179_3723162438(p0, ((Tcprocsection527011) 1));
LOC68[2] = (*LOC70);
LOC71 = (Ropeobj177006**)0;
LOC71 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
LOC68[3] = (*LOC71);
generatedproc0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_215), LOC68, 4);
}
goto LA60;
LA62: ;
{
TY177507 LOC73;
Ropeobj177006* LOC74;
Ropeobj177006** LOC93;
Ropeobj177006** LOC94;
Ropeobj177006* LOC101;
TY531289 LOC107;
Ropeobj177006* LOC108;
memset((void*)LOC73, 0, sizeof(LOC73));
LOC73[0] = header0;
generatedproc0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_216), LOC73, 1);
LOC74 = (Ropeobj177006*)0;
LOC74 = initgcframe_536435_839829468(p0);
add_177482_2381377266(&generatedproc0, LOC74);
{
Ropeobj177006** LOC79;
Ropeobj177006* procname0;
Ropeobj177006* LOC80;
Ropeobj177006* LOC81;
if (!(((*prc0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA77;
LOC79 = (Ropeobj177006**)0;
LOC79 = s_527179_3723162438(p0, ((Tcprocsection527011) 0));
add_177482_2381377266(&generatedproc0, (*LOC79));
procname0 = makecstring_189638_155036129((*(*prc0).name).s);
LOC80 = (Ropeobj177006*)0;
LOC80 = quotedfilename_194818_155036129((*prc0).info);
LOC81 = (Ropeobj177006*)0;
LOC81 = initframe_558140_839829468(p0, procname0, LOC80);
add_177482_2381377266(&generatedproc0, LOC81);
}
goto LA75;
LA77: ;
{
Ropeobj177006** LOC83;
LOC83 = (Ropeobj177006**)0;
LOC83 = s_527179_3723162438(p0, ((Tcprocsection527011) 0));
add_177482_2381377266(&generatedproc0, (*LOC83));
}
LA75: ;
{
TY531289 LOC88;
if (!(((*prc0).options &(1U<<((NU)(((Toption168009) 19))&31U)))!=0)) goto LA86;
memset((void*)LOC88, 0, sizeof(LOC88));
appcg_530648_839829468(p0, ((Tcprocsection527011) 1), ((NimStringDesc*) &T839829468_222), LOC88, 0);
}
LA86: ;
{
if (!(*p0).beforeretneeded) goto LA91;
add_177487_2381377266(&generatedproc0, ((NimStringDesc*) &T839829468_223));
}
LA91: ;
LOC93 = (Ropeobj177006**)0;
LOC93 = s_527179_3723162438(p0, ((Tcprocsection527011) 1));
add_177482_2381377266(&generatedproc0, (*LOC93));
LOC94 = (Ropeobj177006**)0;
LOC94 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177482_2381377266(&generatedproc0, (*LOC94));
{
TY531289 LOC99;
Ropeobj177006* LOC100;
if (!(*p0).beforeretneeded) goto LA97;
memset((void*)LOC99, 0, sizeof(LOC99));
LOC100 = (Ropeobj177006*)0;
LOC100 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_224), LOC99, 0);
add_177482_2381377266(&generatedproc0, LOC100);
}
LA97: ;
LOC101 = (Ropeobj177006*)0;
LOC101 = deinitgcframe_536441_839829468(p0);
add_177482_2381377266(&generatedproc0, LOC101);
{
Ropeobj177006* LOC106;
if (!(((*prc0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA104;
LOC106 = (Ropeobj177006*)0;
LOC106 = deinitframe_558150_839829468(p0);
add_177482_2381377266(&generatedproc0, LOC106);
}
LA104: ;
add_177482_2381377266(&generatedproc0, returnstmt0);
memset((void*)LOC107, 0, sizeof(LOC107));
LOC108 = (Ropeobj177006*)0;
LOC108 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_227), LOC107, 0);
add_177482_2381377266(&generatedproc0, LOC108);
}
LA60: ;
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], generatedproc0);
}
N_NIMCALL(Tcgen527027*, findpendingmodule_530241_839829468)(Tcgen527027* m0, Tsym290834* s0) {
Tcgen527027* result0;
Tsym290834* ms0;
result0 = (Tcgen527027*)0;
ms0 = getmodule_297123_2984716966(s0);
result0 = gmodules_527170_3723162438->data[(*ms0).position];
return result0;
}
N_NIMCALL(NIM_BOOL, isgetprocaddr_557442_839829468)(Tlib290820* lib0) {
NIM_BOOL result0;
Tnode290802* n0;
NIM_BOOL LOC1;
NIM_BOOL LOC2;
result0 = (NIM_BOOL)0;
n0 = (*lib0).path;
LOC1 = (NIM_BOOL)0;
LOC2 = (NIM_BOOL)0;
LOC2 = ((*n0).kind == ((Tnodekind290020) 27) || (*n0).kind == ((Tnodekind290020) 29) || (*n0).kind == ((Tnodekind290020) 30) || (*n0).kind == ((Tnodekind290020) 31) || (*n0).kind == ((Tnodekind290020) 26) || (*n0).kind == ((Tnodekind290020) 28) || (*n0).kind == ((Tnodekind290020) 32));
if (!(LOC2)) goto LA3;
LOC2 = !(((*n0).typ == NIM_NIL));
LA3: ;
LOC1 = LOC2;
if (!(LOC1)) goto LA4;
LOC1 = ((*(*n0).typ).kind == ((Ttypekind290244) 26) || (*(*n0).typ).kind == ((Ttypekind290244) 25));
LA4: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, initlocexpr_537283_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* result0) {
initloc_530273_839829468(result0, ((Tlockind290808) 0), (*e0).typ, ((Tstorageloc290812) 0));
expr_537248_839829468(p0, e0, result0);
}
N_NIMCALL(void, loaddynamiclib_557480_839829468)(Tcgen527027* m0, Tlib290820* lib0) {
{
Ropeobj177006* tmp0;
TY177507 LOC5;
if (!!((*lib0).generated)) goto LA3;
(*lib0).generated = NIM_TRUE;
tmp0 = gettempname_531596_839829468(m0);
asgnRefNoCycle((void**) (&(*lib0).name), tmp0);
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = tmp0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_228), LOC5, 1);
{
TY134602* s0;
Ropeobj177006* loadlib0;
TY530811 LOC18;
if (!((*(*lib0).path).kind >= ((Tnodekind290020) 20) && (*(*lib0).path).kind <= ((Tnodekind290020) 22))) goto LA8;
s0 = (TY134602*) newSeq((&NTI134602), 0);
libcandidates_169605_2607990831((*(*lib0).path).kindU.S3.strval, (&s0));
rawmessage_192612_155036129(((Tmsgkind189002) 286), (*(*lib0).path).kindU.S3.strval);
loadlib0 = NIM_NIL;
{
NI i_557847_839829468;
NI HEX3Atmp_557902_839829468;
NI res_557905_839829468;
i_557847_839829468 = (NI)0;
HEX3Atmp_557902_839829468 = (NI)0;
HEX3Atmp_557902_839829468 = (s0 ? (s0->Sup.len-1) : -1);
res_557905_839829468 = ((NI) 0);
{
while (1) {
TY530811 LOC17;
if (!(res_557905_839829468 <= HEX3Atmp_557902_839829468)) goto LA12;
i_557847_839829468 = res_557905_839829468;
(*m0).labels += ((NI) 1);
{
if (!(((NI) 0) < i_557847_839829468)) goto LA15;
add_177487_2381377266(&loadlib0, ((NimStringDesc*) &T839829468_229));
}
LA15: ;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = tmp0;
LOC17[1] = getstrlit_547468_839829468(m0, s0->data[i_557847_839829468]);
appcg_530632_839829468(m0, &loadlib0, ((NimStringDesc*) &T839829468_230), LOC17, 2);
res_557905_839829468 += ((NI) 1);
} LA12: ;
}
}
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = loadlib0;
LOC18[1] = getstrlit_547468_839829468(m0, (*(*lib0).path).kindU.S3.strval);
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_231), LOC18, 2);
}
goto LA6;
LA8: ;
{
Tcproc527021* p0;
Tloc290816 dest0;
Ropeobj177006** LOC20;
Ropeobj177006** LOC21;
Ropeobj177006** LOC22;
TY530811 LOC23;
p0 = newproc_527206_3723162438(NIM_NIL, m0);
(*p0).options = ((*p0).options & ~ 163840);
memset((void*)(&dest0), 0, sizeof(dest0));
initlocexpr_537283_839829468(p0, (*lib0).path, (&dest0));
LOC20 = (Ropeobj177006**)0;
LOC20 = s_527179_3723162438(p0, ((Tcprocsection527011) 0));
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], (*LOC20));
LOC21 = (Ropeobj177006**)0;
LOC21 = s_527179_3723162438(p0, ((Tcprocsection527011) 1));
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 16))- 0], (*LOC21));
LOC22 = (Ropeobj177006**)0;
LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 16))- 0], (*LOC22));
memset((void*)LOC23, 0, sizeof(LOC23));
LOC23[0] = tmp0;
LOC23[1] = rdloc_536188_839829468(dest0);
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_232), LOC23, 2);
}
LA6: ;
}
LA3: ;
{
if (!((*lib0).name == NIM_NIL)) goto LA26;
internalerror_194113_155036129(((NimStringDesc*) &T839829468_233));
}
LA26: ;
}
N_NIMCALL(Ropeobj177006*, mangledynlibproc_536816_839829468)(Tsym290834* sym0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 16))&31U)))!=0)) goto LA3;
result0 = rope_177277_2381377266((*(*sym0).name).s);
}
goto LA1;
LA3: ;
{
TY177507 LOC6;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = rope_177401_2381377266(((NI64) ((*sym0).Sup.id)));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_234), LOC6, 1);
}
LA1: ;
return result0;
}
N_NIMCALL(void, symindynamiclib_557929_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
Tlib290820* lib0;
NIM_BOOL iscall0;
Ropeobj177006* extname0;
Ropeobj177006* tmp0;
TY530811 LOC43;
lib0 = (*sym0).annex;
iscall0 = isgetprocaddr_557442_839829468(lib0);
extname0 = (*sym0).loc.r;
{
if (!!(iscall0)) goto LA3;
loaddynamiclib_557480_839829468(m0, lib0);
}
LA3: ;
tmp0 = mangledynlibproc_536816_839829468(sym0);
asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0);
asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL);
(*m0).labels += ((NI) 2);
{
Tnode290802* n0;
Tloc290816 a0;
Tnode290802* LOC9;
Ropeobj177006* params0;
Ropeobj177006* LOC10;
Ropeobj177006* load0;
TY533235 LOC17;
NimStringDesc* LOC18;
Tnode290802* last0;
NimStringDesc* idx0;
if (!iscall0) goto LA7;
n0 = (*lib0).path;
memset((void*)(&a0), 0, sizeof(a0));
LOC9 = (Tnode290802*)0;
LOC9 = HEX5BHEX5D_291238_850551059(n0, ((NI) 0));
initlocexpr_537283_839829468((*m0).initproc, LOC9, (&a0));
LOC10 = (Ropeobj177006*)0;
LOC10 = rdloc_536188_839829468(a0);
params0 = HEX26_177447_2381377266(LOC10, ((NimStringDesc*) &T839829468_118));
{
NI i_557964_839829468;
NI HEX3Atmp_558025_839829468;
NI LOC12;
NI res_558028_839829468;
i_557964_839829468 = (NI)0;
HEX3Atmp_558025_839829468 = (NI)0;
LOC12 = (NI)0;
LOC12 = len_291081_850551059(n0);
HEX3Atmp_558025_839829468 = (NI)(LOC12 - ((NI) 2));
res_558028_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* LOC15;
Ropeobj177006* LOC16;
if (!(res_558028_839829468 <= HEX3Atmp_558025_839829468)) goto LA14;
i_557964_839829468 = res_558028_839829468;
LOC15 = (Tnode290802*)0;
LOC15 = HEX5BHEX5D_291238_850551059(n0, i_557964_839829468);
initlocexpr_537283_839829468((*m0).initproc, LOC15, (&a0));
LOC16 = (Ropeobj177006*)0;
LOC16 = rdloc_536188_839829468(a0);
add_177482_2381377266(¶ms0, LOC16);
add_177487_2381377266(¶ms0, ((NimStringDesc*) &T839829468_110));
res_558028_839829468 += ((NI) 1);
} LA14: ;
}
}
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = tmp0;
LOC17[1] = gettypedesc_533671_839829468(m0, (*sym0).typ);
LOC17[2] = params0;
LOC18 = (NimStringDesc*)0;
LOC18 = HEX24_177856_2381377266(extname0);
LOC17[3] = makecstring_189638_155036129(LOC18);
load0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_235), LOC17, 4);
last0 = lastson_293364_850551059(n0);
{
if (!((*last0).kind == ((Tnodekind290020) 58))) goto LA21;
last0 = (*last0).kindU.S6.sons->data[((NI) 1)];
}
LA21: ;
{
NimStringDesc* LOC27;
if (!!(((*last0).kind == ((Tnodekind290020) 20)))) goto LA25;
LOC27 = (NimStringDesc*)0;
LOC27 = HEX24_194185_1689653243(T839829468_236);
internalerror_194113_155036129(LOC27);
}
LA25: ;
idx0 = (*last0).kindU.S3.strval;
{
Ropeobj177006** LOC32;
if (!((idx0 ? idx0->Sup.len : 0) == ((NI) 0))) goto LA30;
LOC32 = (Ropeobj177006**)0;
LOC32 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 2));
add_177482_2381377266(LOC32, load0);
}
goto LA28;
LA30: ;
{
NIM_BOOL LOC34;
LOC34 = (NIM_BOOL)0;
LOC34 = ((idx0 ? idx0->Sup.len : 0) == ((NI) 1));
if (!(LOC34)) goto LA35;
LOC34 = (((NU8)(idx0->data[((NI) 0)])) >= ((NU8)(48)) && ((NU8)(idx0->data[((NI) 0)])) <= ((NU8)(57)));
LA35: ;
if (!LOC34) goto LA36;
add_177482_2381377266(&(*m0).extensionloaders[(((NU8)(idx0->data[((NI) 0)])))- 48], load0);
}
goto LA28;
LA36: ;
{
NimStringDesc* LOC39;
LOC39 = (NimStringDesc*)0;
LOC39 = rawNewString(idx0->Sup.len + 13);
appendString(LOC39, ((NimStringDesc*) &T839829468_237));
appendString(LOC39, idx0);
internalerror_194100_155036129((*sym0).info, LOC39);
}
LA28: ;
}
goto LA5;
LA7: ;
{
TY533235 LOC41;
NimStringDesc* LOC42;
memset((void*)LOC41, 0, sizeof(LOC41));
LOC41[0] = tmp0;
LOC41[1] = gettypedesc_533671_839829468(m0, (*sym0).typ);
LOC41[2] = (*lib0).name;
LOC42 = (NimStringDesc*)0;
LOC42 = HEX24_177856_2381377266(extname0);
LOC41[3] = makecstring_189638_155036129(LOC42);
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_238), LOC41, 4);
}
LA5: ;
memset((void*)LOC43, 0, sizeof(LOC43));
LOC43[0] = (*sym0).loc.r;
LOC43[1] = gettypedesc_533671_839829468(m0, (*sym0).loc.t);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_239), LOC43, 2);
}
N_NIMCALL(void, symindynamiclibpartial_558071_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
asgnRefNoCycle((void**) (&(*sym0).loc.r), mangledynlibproc_536816_839829468(sym0));
asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL);
}
N_NIMCALL(void, genprocnoforward_558906_839829468)(Tcgen527027* m0, Tsym290834* prc0) {
{ fillprocloc_537201_839829468(prc0);
useheader_530369_839829468(m0, prc0);
{
Ropeobj177006* LOC5;
if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 7))&15U)))!=0)) goto LA3;
LOC5 = (Ropeobj177006*)0;
LOC5 = cgsym_530403_839829468(m0, (*(*prc0).name).s);
goto BeforeRet;
}
LA3: ;
genprocprototype_537254_839829468(m0, prc0);
{
if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA8;
}
goto LA6;
LA8: ;
{
if (!((*(*prc0).typ).callconv == ((Tcallingconvention290002) 5))) goto LA11;
{
NIM_BOOL LOC15;
LOC15 = (NIM_BOOL)0;
LOC15 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*prc0).Sup.id);
if (!!(LOC15)) goto LA16;
genprocaux_558284_839829468(m0, prc0);
}
LA16: ;
}
goto LA6;
LA11: ;
{
Tcgen527027* q0;
if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA19;
q0 = findpendingmodule_530241_839829468(m0, prc0);
{
NIM_BOOL LOC23;
NIM_BOOL LOC25;
LOC23 = (NIM_BOOL)0;
LOC23 = !((q0 == NIM_NIL));
if (!(LOC23)) goto LA24;
LOC25 = (NIM_BOOL)0;
LOC25 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id);
LOC23 = !(LOC25);
LA24: ;
if (!LOC23) goto LA26;
symindynamiclib_557929_839829468(q0, prc0);
}
goto LA21;
LA26: ;
{
symindynamiclibpartial_558071_839829468(m0, prc0);
}
LA21: ;
}
goto LA6;
LA19: ;
{
Tcgen527027* q0;
if (!!((((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0))) goto LA30;
q0 = findpendingmodule_530241_839829468(m0, prc0);
{
NIM_BOOL LOC34;
NIM_BOOL LOC36;
LOC34 = (NIM_BOOL)0;
LOC34 = !((q0 == NIM_NIL));
if (!(LOC34)) goto LA35;
LOC36 = (NIM_BOOL)0;
LOC36 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id);
LOC34 = !(LOC36);
LA35: ;
if (!LOC34) goto LA37;
genprocaux_558284_839829468(q0, prc0);
}
LA37: ;
}
goto LA6;
LA30: ;
LA6: ;
}BeforeRet: ;
}
N_NIMCALL(void, genproc_530951_839829468)(Tcgen527027* m0, Tsym290834* prc0) {
{ {
NIM_BOOL LOC3;
NIM_BOOL LOC5;
LOC3 = (NIM_BOOL)0;
LOC3 = (((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 26))&31U)))!=0);
if (LOC3) goto LA4;
LOC5 = (NIM_BOOL)0;
LOC5 = isactivated_559431_839829468(prc0);
LOC3 = !(LOC5);
LA4: ;
if (!LOC3) goto LA6;
goto BeforeRet;
}
LA6: ;
fillprocloc_537201_839829468(prc0);
{
if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 4))&31U)))!=0)) goto LA10;
addforwardedproc_530203_839829468(m0, prc0);
}
goto LA8;
LA10: ;
{
genprocnoforward_558906_839829468(m0, prc0);
{
NIM_BOOL LOC15;
NIM_BOOL LOC16;
LOC15 = (NIM_BOOL)0;
LOC16 = (NIM_BOOL)0;
LOC16 = ((65600 & (*prc0).flags) == 64);
if (!(LOC16)) goto LA17;
LOC16 = !((generatedheader_530201_839829468 == NIM_NIL));
LA17: ;
LOC15 = LOC16;
if (!(LOC15)) goto LA18;
LOC15 = !((((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0));
LA18: ;
if (!LOC15) goto LA19;
genprocprototype_537254_839829468(generatedheader_530201_839829468, prc0);
{
if (!((*(*prc0).typ).callconv == ((Tcallingconvention290002) 5))) goto LA23;
{
NIM_BOOL LOC27;
LOC27 = (NIM_BOOL)0;
LOC27 = containsorincl_266862_2627731572((&(*generatedheader_530201_839829468).declaredthings), (*prc0).Sup.id);
if (!!(LOC27)) goto LA28;
genprocaux_558284_839829468(generatedheader_530201_839829468, prc0);
}
LA28: ;
}
LA23: ;
}
LA19: ;
}
LA8: ;
}BeforeRet: ;
}
static N_INLINE(NIM_BOOL, emulatedthreadvars_530949_839829468)(void) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
result0 = ((71303168 & ~ gglobaloptions_168130_2607990831)==0);
return result0;
}
N_NIMCALL(void, declarethreadvar_536676_839829468)(Tcgen527027* m0, Tsym290834* s0, NIM_BOOL isextern0) {
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = emulatedthreadvars_530949_839829468();
if (!LOC3) goto LA4;
{
NIM_BOOL LOC8;
TY530811 LOC11;
LOC8 = (NIM_BOOL)0;
LOC8 = containsorincl_266862_2627731572((&nimtvdeclared_536675_839829468), (*s0).Sup.id);
if (!!(LOC8)) goto LA9;
nimtvdeps_536674_839829468 = (Ttypeseq290836*) incrSeqV2(&(nimtvdeps_536674_839829468)->Sup, sizeof(Ttype290840*));
asgnRefNoCycle((void**) (&nimtvdeps_536674_839829468->data[nimtvdeps_536674_839829468->Sup.len]), (*s0).loc.t);
++nimtvdeps_536674_839829468->Sup.len;
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = gettypedesc_533671_839829468(m0, (*s0).loc.t);
LOC11[1] = (*s0).loc.r;
addf_178205_2381377266(&nimtv_536656_839829468, ((NimStringDesc*) &T839829468_54), LOC11, 2);
}
LA9: ;
}
goto LA1;
LA4: ;
{
Ropeobj177006* LOC21;
TY177507 LOC22;
{
if (!isextern0) goto LA15;
add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_240));
}
LA15: ;
{
if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 22))&63U)))!=0)) goto LA19;
add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_241));
}
LA19: ;
LOC21 = (Ropeobj177006*)0;
LOC21 = gettypedesc_533671_839829468(m0, (*s0).loc.t);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], LOC21);
memset((void*)LOC22, 0, sizeof(LOC22));
LOC22[0] = (*s0).loc.r;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC22, 1);
}
LA1: ;
}
N_NIMCALL(void, genvarprototypeaux_542254_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
Ropeobj177006* LOC1;
{ useheader_530369_839829468(m0, sym0);
LOC1 = (Ropeobj177006*)0;
LOC1 = manglename_531205_839829468(sym0);
fillloc_530282_839829468((&(*sym0).loc), ((Tlockind290808) 3), (*sym0).typ, LOC1, ((Tstorageloc290812) 3));
{
NIM_BOOL LOC4;
LOC4 = (NIM_BOOL)0;
LOC4 = (((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0);
if (LOC4) goto LA5;
LOC4 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id);
LA5: ;
if (!LOC4) goto LA6;
goto BeforeRet;
}
LA6: ;
{
if (!!(((*(*sym0).owner).Sup.id == (*(*m0).module).Sup.id))) goto LA10;
{
if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0)) goto LA14;
declarethreadvar_536676_839829468(m0, sym0, NIM_TRUE);
}
goto LA12;
LA14: ;
{
Ropeobj177006* LOC17;
TY177507 LOC30;
add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_240));
LOC17 = (Ropeobj177006*)0;
LOC17 = gettypedesc_533671_839829468(m0, (*sym0).loc.t);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], LOC17);
{
if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA20;
add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_53));
}
LA20: ;
{
if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 8))&31U)))!=0)) goto LA24;
add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_121));
}
LA24: ;
{
if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 7))&31U)))!=0)) goto LA28;
add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_122));
}
LA28: ;
memset((void*)LOC30, 0, sizeof(LOC30));
LOC30[0] = (*sym0).loc.r;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC30, 1);
}
LA12: ;
}
LA10: ;
}BeforeRet: ;
}
N_NIMCALL(void, genvarprototype_537236_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
genvarprototypeaux_542254_839829468(m0, sym0);
}
N_NIMCALL(Ropeobj177006*, cgsym_530403_839829468)(Tcgen527027* m0, NimStringDesc* name0) {
Ropeobj177006* result0;
Tsym290834* sym0;
result0 = (Ropeobj177006*)0;
sym0 = getcompilerproc_336746_3937434831(name0);
{
if (!!((sym0 == NIM_NIL))) goto LA3;
switch ((*sym0).kind) {
case ((Tsymkind290435) 12):
case ((Tsymkind290435) 13):
case ((Tsymkind290435) 15):
case ((Tsymkind290435) 14):
{
genproc_530951_839829468(m0, sym0);
}
break;
case ((Tsymkind290435) 8):
case ((Tsymkind290435) 11):
case ((Tsymkind290435) 9):
{
genvarprototype_537236_839829468(m0, sym0);
}
break;
case ((Tsymkind290435) 7):
{
Ropeobj177006* LOC8;
LOC8 = (Ropeobj177006*)0;
LOC8 = gettypedesc_533671_839829468(m0, (*sym0).typ);
}
break;
default:
{
NimStringDesc* LOC10;
LOC10 = (NimStringDesc*)0;
LOC10 = rawNewString(name0->Sup.len + reprEnum((NI)(*sym0).kind, (&NTI290435))->Sup.len + 9);
appendString(LOC10, ((NimStringDesc*) &T839829468_243));
appendString(LOC10, name0);
appendString(LOC10, ((NimStringDesc*) &T839829468_244));
appendString(LOC10, reprEnum((NI)(*sym0).kind, (&NTI290435)));
internalerror_194113_155036129(LOC10);
}
break;
}
}
goto LA1;
LA3: ;
{
rawmessage_192612_155036129(((Tmsgkind189002) 68), name0);
}
LA1: ;
result0 = (*sym0).loc.r;
return result0;
}
N_NIMCALL(Ropeobj177006*, ropecg_530407_839829468)(Tcgen527027* m0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) {
Ropeobj177006* result0;
NI i0;
NI length0;
NI num0;
result0 = (Ropeobj177006*)0;
i0 = ((NI) 0);
length0 = (frmt0 ? frmt0->Sup.len : 0);
result0 = NIM_NIL;
num0 = ((NI) 0);
{
while (1) {
NI start0;
if (!(i0 < length0)) goto LA2;
{
if (!((NU8)(frmt0->data[i0]) == (NU8)(36))) goto LA5;
i0 += ((NI) 1);
switch (((NU8)(frmt0->data[i0]))) {
case 36:
{
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_19));
i0 += ((NI) 1);
}
break;
case 35:
{
i0 += ((NI) 1);
add_177482_2381377266(&result0, args0[num0]);
num0 += ((NI) 1);
}
break;
case 48 ... 57:
{
NI j0;
j0 = ((NI) 0);
{
while (1) {
j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48));
i0 += ((NI) 1);
{
NIM_BOOL LOC14;
LOC14 = (NIM_BOOL)0;
LOC14 = (length0 <= i0);
if (LOC14) goto LA15;
LOC14 = !((((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57))));
LA15: ;
if (!LOC14) goto LA16;
goto LA10;
}
LA16: ;
}
} LA10: ;
num0 = j0;
{
NimStringDesc* LOC22;
NimStringDesc* LOC23;
if (!((NI)((args0Len0-1) + ((NI) 1)) < j0)) goto LA20;
LOC22 = (NimStringDesc*)0;
LOC23 = (NimStringDesc*)0;
LOC23 = nimIntToStr(j0);
LOC22 = rawNewString(LOC23->Sup.len + 30);
appendString(LOC22, ((NimStringDesc*) &T839829468_20));
appendString(LOC22, LOC23);
internalerror_194113_155036129(LOC22);
}
LA20: ;
add_177482_2381377266(&result0, args0[(NI)(j0 - ((NI) 1))]);
}
break;
case 110:
{
{
if (!!(((goptions_168128_2607990831 &(1U<<((NU)(((Toption168009) 10))&31U)))!=0))) goto LA27;
add_177482_2381377266(&result0, rnl_177903_2381377266);
}
LA27: ;
i0 += ((NI) 1);
}
break;
case 78:
{
add_177482_2381377266(&result0, rnl_177903_2381377266);
i0 += ((NI) 1);
}
break;
default:
{
NimStringDesc* LOC31;
LOC31 = (NimStringDesc*)0;
LOC31 = rawNewString(31);
appendString(LOC31, ((NimStringDesc*) &T839829468_20));
appendChar(LOC31, frmt0->data[i0]);
internalerror_194113_155036129(LOC31);
}
break;
}
}
goto LA3;
LA5: ;
{
NIM_BOOL LOC33;
NI j0;
NimStringDesc* ident0;
Ropeobj177006* LOC39;
LOC33 = (NIM_BOOL)0;
LOC33 = ((NU8)(frmt0->data[i0]) == (NU8)(35));
if (!(LOC33)) goto LA34;
LOC33 = (((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(97)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(122)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(65)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(90)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(95)));
LA34: ;
if (!LOC33) goto LA35;
i0 += ((NI) 1);
j0 = i0;
{
while (1) {
if (!(((NU8)(frmt0->data[j0])) >= ((NU8)(97)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(122)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(65)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(90)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(57)) || ((NU8)(frmt0->data[j0])) == ((NU8)(95)))) goto LA38;
j0 += ((NI) 1);
} LA38: ;
}
ident0 = copyStrLast(frmt0, i0, (NI)(j0 - ((NI) 1)));
i0 = j0;
LOC39 = (Ropeobj177006*)0;
LOC39 = cgsym_530403_839829468(m0, ident0);
add_177482_2381377266(&result0, LOC39);
}
goto LA3;
LA35: ;
{
NIM_BOOL LOC41;
NI j0;
NimStringDesc* LOC47;
Ropeobj177006* LOC48;
LOC41 = (NIM_BOOL)0;
LOC41 = ((NU8)(frmt0->data[i0]) == (NU8)(35));
if (!(LOC41)) goto LA42;
LOC41 = ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(36));
LA42: ;
if (!LOC41) goto LA43;
i0 += ((NI) 2);
j0 = ((NI) 0);
{
while (1) {
if (!(((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57)))) goto LA46;
j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48));
i0 += ((NI) 1);
} LA46: ;
}
LOC47 = (NimStringDesc*)0;
LOC47 = HEX24_177856_2381377266(args0[(NI)(j0 - ((NI) 1))]);
LOC48 = (Ropeobj177006*)0;
LOC48 = cgsym_530403_839829468(m0, LOC47);
add_177482_2381377266(&result0, LOC48);
}
goto LA3;
LA43: ;
LA3: ;
start0 = i0;
{
while (1) {
if (!(i0 < length0)) goto LA50;
{
NIM_BOOL LOC53;
LOC53 = (NIM_BOOL)0;
LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(36)));
if (!(LOC53)) goto LA54;
LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(35)));
LA54: ;
if (!LOC53) goto LA55;
i0 += ((NI) 1);
}
goto LA51;
LA55: ;
{
goto LA49;
}
LA51: ;
} LA50: ;
} LA49: ;
{
NimStringDesc* LOC62;
if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA60;
LOC62 = (NimStringDesc*)0;
LOC62 = copyStrLast(frmt0, start0, (NI)(i0 - ((NI) 1)));
add_177487_2381377266(&result0, LOC62);
}
LA60: ;
} LA2: ;
}
return result0;
}
static N_INLINE(NIM_BOOL, crossescppboundary_558754_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
NIM_BOOL LOC2;
Tsym290834* LOC4;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC2 = (NIM_BOOL)0;
LOC2 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
if (!(LOC2)) goto LA3;
LOC4 = (Tsym290834*)0;
LOC4 = getmodule_297123_2984716966(sym0);
LOC2 = !((((*LOC4).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0));
LA3: ;
LOC1 = LOC2;
if (!(LOC1)) goto LA5;
LOC1 = !((gcmd_168132_2607990831 == ((Tcommands168076) 2)));
LA5: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, genprocprototype_537254_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
{ useheader_530369_839829468(m0, sym0);
{
if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA3;
goto BeforeRet;
}
LA3: ;
{
if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA7;
{
NIM_BOOL LOC11;
Tsym290834* LOC12;
NIM_BOOL LOC14;
TY530811 LOC17;
Ropeobj177006* LOC18;
LOC11 = (NIM_BOOL)0;
LOC12 = (Tsym290834*)0;
LOC12 = getmodule_297123_2984716966(sym0);
LOC11 = !(((*LOC12).Sup.id == (*(*m0).module).Sup.id));
if (!(LOC11)) goto LA13;
LOC14 = (NIM_BOOL)0;
LOC14 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id);
LOC11 = !(LOC14);
LA13: ;
if (!LOC11) goto LA15;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = gettypedesc_533671_839829468(m0, (*sym0).loc.t);
LOC17[1] = mangledynlibproc_536816_839829468(sym0);
LOC18 = (Ropeobj177006*)0;
LOC18 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_245), LOC17, 2);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], LOC18);
}
LA15: ;
}
goto LA5;
LA7: ;
{
NIM_BOOL LOC20;
Ropeobj177006* header0;
TY177507 LOC47;
Ropeobj177006* LOC48;
LOC20 = (NIM_BOOL)0;
LOC20 = containsorincl_266862_2627731572((&(*m0).declaredprotos), (*sym0).Sup.id);
if (!!(LOC20)) goto LA21;
header0 = genprocheader_533867_839829468(m0, sym0);
{
NIM_BOOL LOC25;
LOC25 = (NIM_BOOL)0;
LOC25 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 14))&31U)))!=0);
if (!(LOC25)) goto LA26;
LOC25 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 6))&7U)))!=0);
LA26: ;
if (!LOC25) goto LA27;
header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_213), header0);
}
LA27: ;
{
NIM_BOOL LOC31;
LOC31 = (NIM_BOOL)0;
LOC31 = !(((*(*sym0).typ).callconv == ((Tcallingconvention290002) 5)));
if (!(LOC31)) goto LA32;
LOC31 = crossescppboundary_558754_839829468(m0, sym0);
LA32: ;
if (!LOC31) goto LA33;
header0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_246), header0);
}
LA33: ;
{
NIM_BOOL LOC37;
LOC37 = (NIM_BOOL)0;
LOC37 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0);
if (!(LOC37)) goto LA38;
LOC37 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 7))&7U)))!=0);
LA38: ;
if (!LOC37) goto LA39;
add_177487_2381377266(&header0, ((NimStringDesc*) &T839829468_247));
}
LA39: ;
{
NIM_BOOL LOC43;
LOC43 = (NIM_BOOL)0;
LOC43 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 14))&31U)))!=0);
if (!(LOC43)) goto LA44;
LOC43 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 7))&7U)))!=0);
LA44: ;
if (!LOC43) goto LA45;
add_177487_2381377266(&header0, ((NimStringDesc*) &T839829468_248));
}
LA45: ;
memset((void*)LOC47, 0, sizeof(LOC47));
LOC47[0] = header0;
LOC48 = (Ropeobj177006*)0;
LOC48 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_191), LOC47, 1);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], LOC48);
}
goto LA5;
LA21: ;
LA5: ;
}BeforeRet: ;
}
static N_INLINE(NIM_BOOL, usesnativegc_168177_2607990831)(void) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
result0 = (((Tgcmode168080) 5) <= gselectedgc_168133_2607990831);
return result0;
}
N_NIMCALL(void, genrefassign_536311_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0) {
{
NIM_BOOL LOC3;
NIM_BOOL LOC5;
TY530811 LOC8;
LOC3 = (NIM_BOOL)0;
LOC3 = (dest0.s == ((Tstorageloc290812) 2));
if (LOC3) goto LA4;
LOC5 = (NIM_BOOL)0;
LOC5 = usesnativegc_168177_2607990831();
LOC3 = !(LOC5);
LA4: ;
if (!LOC3) goto LA6;
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rdloc_536188_839829468(dest0);
LOC8[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC8, 2);
}
goto LA1;
LA6: ;
{
if (!(dest0.s == ((Tstorageloc290812) 3))) goto LA10;
{
NIM_BOOL LOC14;
TY530811 LOC17;
LOC14 = (NIM_BOOL)0;
LOC14 = canformacycle_318123_3876443242(dest0.t);
if (!LOC14) goto LA15;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = addrloc_536204_839829468(dest0);
LOC17[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_249), LOC17, 2);
}
goto LA12;
LA15: ;
{
TY530811 LOC19;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = addrloc_536204_839829468(dest0);
LOC19[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_250), LOC19, 2);
}
LA12: ;
}
goto LA1;
LA10: ;
{
TY530811 LOC21;
memset((void*)LOC21, 0, sizeof(LOC21));
LOC21[0] = addrloc_536204_839829468(dest0);
LOC21[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_251), LOC21, 2);
}
LA1: ;
}
N_NIMCALL(void, optasgnloc_547788_839829468)(Tloc290816 a0, Ttype290840* t0, Ropeobj177006* field0, Tloc290816* Result) {
Ropeobj177006* LOC1;
Ropeobj177006* LOC2;
(*Result).k = ((Tlockind290808) 5);
(*Result).s = a0.s;
unsureAsgnRef((void**) (&(*Result).t), t0);
LOC1 = (Ropeobj177006*)0;
LOC1 = rdloc_536188_839829468(a0);
LOC2 = (Ropeobj177006*)0;
LOC2 = HEX26_177447_2381377266(LOC1, ((NimStringDesc*) &T839829468_257));
unsureAsgnRef((void**) (&(*Result).r), HEX26_177418_2381377266(LOC2, field0));
}
N_NIMCALL(void, genoptasgntuple_548001_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0) {
Tassignmentflag536302Set newflags0;
Ttype290840* t_548053_839829468;
Ttype290840* LOC9;
{
if (!(src0.s == ((Tstorageloc290812) 1))) goto LA3;
newflags0 = (flags0 | 1);
}
goto LA1;
LA3: ;
{
if (!(((*dest0.t).flags &(1U<<((NU)(((Ttypeflag290431) 6))&31U)))!=0)) goto LA6;
newflags0 = (flags0 & ~ 1);
}
goto LA1;
LA6: ;
{
newflags0 = flags0;
}
LA1: ;
LOC9 = (Ttype290840*)0;
LOC9 = skiptypes_294099_850551059(dest0.t, IL64(211106232576256));
t_548053_839829468 = getuniquetype_526640_2036603609(LOC9);
{
NI i_548071_839829468;
NI HEX3Atmp_548077_839829468;
NI LOC11;
NI res_548080_839829468;
i_548071_839829468 = (NI)0;
HEX3Atmp_548077_839829468 = (NI)0;
LOC11 = (NI)0;
LOC11 = len_293339_850551059(t_548053_839829468);
HEX3Atmp_548077_839829468 = (LOC11 - 1);
res_548080_839829468 = ((NI) 0);
{
while (1) {
Ttype290840* t0;
Ropeobj177006* field0;
TY177507 LOC14;
Tloc290816 LOC15;
Tloc290816 LOC16;
if (!(res_548080_839829468 <= HEX3Atmp_548077_839829468)) goto LA13;
i_548071_839829468 = res_548080_839829468;
t0 = (*t_548053_839829468).sons->data[i_548071_839829468];
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = rope_177401_2381377266(((NI64) (i_548071_839829468)));
field0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_260), LOC14, 1);
memset((void*)(&LOC15), 0, sizeof(LOC15));
optasgnloc_547788_839829468(dest0, t0, field0, (&LOC15));
memset((void*)(&LOC16), 0, sizeof(LOC16));
optasgnloc_547788_839829468(src0, t0, field0, (&LOC16));
genassignment_537264_839829468(p0, LOC15, LOC16, newflags0);
res_548080_839829468 += ((NI) 1);
} LA13: ;
}
}
}
N_NIMCALL(void, gengenericasgn_548167_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0) {
{
NIM_BOOL LOC3;
Ttype290840* LOC5;
LOC3 = (NIM_BOOL)0;
LOC3 = !(((flags0 &(1U<<((NU)(((Tassignmentflag536302) 0))&7U)))!=0));
if (LOC3) goto LA4;
LOC5 = (Ttype290840*)0;
LOC5 = skiptypes_294099_850551059(dest0.t, IL64(211106242013440));
LOC3 = (((*LOC5).flags &(1U<<((NU)(((Ttypeflag290431) 6))&31U)))!=0);
LA4: ;
if (!LOC3) goto LA6;
{
NIM_BOOL LOC10;
NIM_BOOL LOC12;
TY533238 LOC15;
LOC10 = (NIM_BOOL)0;
LOC10 = (dest0.s == ((Tstorageloc290812) 2));
if (LOC10) goto LA11;
LOC12 = (NIM_BOOL)0;
LOC12 = usesnativegc_168177_2607990831();
LOC10 = !(LOC12);
LA11: ;
if (!LOC10) goto LA13;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC15, 0, sizeof(LOC15));
LOC15[0] = addrloc_536204_839829468(dest0);
LOC15[1] = addrloc_536204_839829468(src0);
LOC15[2] = rdloc_536188_839829468(dest0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_261), LOC15, 3);
}
goto LA8;
LA13: ;
{
TY533238 LOC17;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = addrloc_536204_839829468(dest0);
LOC17[1] = addrloc_536204_839829468(src0);
LOC17[2] = gentypeinfo_533941_839829468((*p0).module, dest0.t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_262), LOC17, 3);
}
LA8: ;
}
goto LA1;
LA6: ;
{
TY533238 LOC19;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = addrloc_536204_839829468(dest0);
LOC19[1] = addrloc_536204_839829468(src0);
LOC19[2] = gentypeinfo_533941_839829468((*p0).module, dest0.t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_263), LOC19, 3);
}
LA1: ;
}
N_NIMCALL(NI, asgncomplexity_547750_839829468)(Tnode290802* n0) {
NI result0;
result0 = (NI)0;
{
if (!!((n0 == NIM_NIL))) goto LA3;
switch ((*n0).kind) {
case ((Tnodekind290020) 3):
{
result0 = ((NI) 1);
}
break;
case ((Tnodekind290020) 139):
{
result0 = ((NI) 100);
}
break;
case ((Tnodekind290020) 138):
{
{
Tnode290802* t_547767_839829468;
t_547767_839829468 = (Tnode290802*)0;
{
NI i_547781_839829468;
NI HEX3Atmp_547783_839829468;
NI LOC10;
NI res_547785_839829468;
i_547781_839829468 = (NI)0;
HEX3Atmp_547783_839829468 = (NI)0;
LOC10 = (NI)0;
LOC10 = len_291081_850551059(n0);
HEX3Atmp_547783_839829468 = (LOC10 - 1);
res_547785_839829468 = ((NI) 0);
{
while (1) {
NI LOC13;
if (!(res_547785_839829468 <= HEX3Atmp_547783_839829468)) goto LA12;
i_547781_839829468 = res_547785_839829468;
t_547767_839829468 = (*n0).kindU.S6.sons->data[i_547781_839829468];
LOC13 = (NI)0;
LOC13 = asgncomplexity_547750_839829468(t_547767_839829468);
result0 += LOC13;
res_547785_839829468 += ((NI) 1);
} LA12: ;
}
}
}
}
break;
default:
{
}
break;
}
}
LA3: ;
return result0;
}
N_NIMCALL(void, genoptasgnobject_548084_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0, Tnode290802* t0) {
Tassignmentflag536302Set newflags0;
{ {
if (!(t0 == NIM_NIL)) goto LA3;
goto BeforeRet;
}
LA3: ;
{
if (!(src0.s == ((Tstorageloc290812) 1))) goto LA7;
newflags0 = (flags0 | 1);
}
goto LA5;
LA7: ;
{
if (!(((*dest0.t).flags &(1U<<((NU)(((Ttypeflag290431) 6))&31U)))!=0)) goto LA10;
newflags0 = (flags0 & ~ 1);
}
goto LA5;
LA10: ;
{
newflags0 = flags0;
}
LA5: ;
switch ((*t0).kind) {
case ((Tnodekind290020) 3):
{
Tsym290834* field0;
Tloc290816 LOC14;
Tloc290816 LOC15;
field0 = (*t0).kindU.S4.sym;
memset((void*)(&LOC14), 0, sizeof(LOC14));
optasgnloc_547788_839829468(dest0, (*field0).typ, (*field0).loc.r, (&LOC14));
memset((void*)(&LOC15), 0, sizeof(LOC15));
optasgnloc_547788_839829468(src0, (*field0).typ, (*field0).loc.r, (&LOC15));
genassignment_537264_839829468(p0, LOC14, LOC15, newflags0);
}
break;
case ((Tnodekind290020) 138):
{
{
Tnode290802* child_548155_839829468;
child_548155_839829468 = (Tnode290802*)0;
{
NI i_548160_839829468;
NI HEX3Atmp_548162_839829468;
NI LOC19;
NI res_548164_839829468;
i_548160_839829468 = (NI)0;
HEX3Atmp_548162_839829468 = (NI)0;
LOC19 = (NI)0;
LOC19 = len_291081_850551059(t0);
HEX3Atmp_548162_839829468 = (LOC19 - 1);
res_548164_839829468 = ((NI) 0);
{
while (1) {
if (!(res_548164_839829468 <= HEX3Atmp_548162_839829468)) goto LA21;
i_548160_839829468 = res_548164_839829468;
child_548155_839829468 = (*t0).kindU.S6.sons->data[i_548160_839829468];
genoptasgnobject_548084_839829468(p0, dest0, src0, newflags0, child_548155_839829468);
res_548164_839829468 += ((NI) 1);
} LA21: ;
}
}
}
}
break;
default:
{
}
break;
}
}BeforeRet: ;
}
N_NIMCALL(void, genassignment_537264_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0, Tassignmentflag536302Set flags0) {
Ttype290840* ty0;
{ {
NIM_BOOL LOC3;
TY530811 LOC7;
LOC3 = (NIM_BOOL)0;
LOC3 = !((src0.t == NIM_NIL));
if (!(LOC3)) goto LA4;
LOC3 = ((*src0.t).kind == ((Ttypekind290244) 21));
LA4: ;
if (!LOC3) goto LA5;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = rdloc_536188_839829468(dest0);
LOC7[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC7, 2);
goto BeforeRet;
}
LA5: ;
ty0 = skiptypes_294099_850551059(dest0.t, IL64(211106233624832));
switch ((*ty0).kind) {
case ((Ttypekind290244) 22):
{
genrefassign_536311_839829468(p0, dest0, src0, flags0);
}
break;
case ((Ttypekind290244) 24):
{
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = !(((flags0 &(1U<<((NU)(((Tassignmentflag536302) 0))&7U)))!=0));
if (!(LOC12)) goto LA13;
LOC12 = !((src0.s == ((Tstorageloc290812) 1)));
LA13: ;
if (!LOC12) goto LA14;
genrefassign_536311_839829468(p0, dest0, src0, flags0);
}
goto LA10;
LA14: ;
{
TY533238 LOC17;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = addrloc_536204_839829468(dest0);
LOC17[1] = rdloc_536188_839829468(src0);
LOC17[2] = gentypeinfo_533941_839829468((*p0).module, dest0.t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_252), LOC17, 3);
}
LA10: ;
}
break;
case ((Ttypekind290244) 28):
{
{
NIM_BOOL LOC21;
LOC21 = (NIM_BOOL)0;
LOC21 = !(((flags0 &(1U<<((NU)(((Tassignmentflag536302) 0))&7U)))!=0));
if (!(LOC21)) goto LA22;
LOC21 = !((src0.s == ((Tstorageloc290812) 1)));
LA22: ;
if (!LOC21) goto LA23;
genrefassign_536311_839829468(p0, dest0, src0, flags0);
}
goto LA19;
LA23: ;
{
{
NIM_BOOL LOC28;
NIM_BOOL LOC30;
TY530811 LOC33;
LOC28 = (NIM_BOOL)0;
LOC28 = (dest0.s == ((Tstorageloc290812) 2));
if (LOC28) goto LA29;
LOC30 = (NIM_BOOL)0;
LOC30 = usesnativegc_168177_2607990831();
LOC28 = !(LOC30);
LA29: ;
if (!LOC28) goto LA31;
memset((void*)LOC33, 0, sizeof(LOC33));
LOC33[0] = rdloc_536188_839829468(dest0);
LOC33[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_253), LOC33, 2);
}
goto LA26;
LA31: ;
{
Tloc290816 tmp0;
TY533238 LOC37;
TY177507 LOC38;
if (!(dest0.s == ((Tstorageloc290812) 3))) goto LA35;
memset((void*)(&tmp0), 0, sizeof(tmp0));
gettemp_535032_839829468(p0, ty0, (&tmp0), NIM_FALSE);
memset((void*)LOC37, 0, sizeof(LOC37));
LOC37[0] = rdloc_536188_839829468(dest0);
LOC37[1] = rdloc_536188_839829468(src0);
LOC37[2] = rdloc_536188_839829468(tmp0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_254), LOC37, 3);
memset((void*)LOC38, 0, sizeof(LOC38));
LOC38[0] = rdloc_536188_839829468(tmp0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_255), LOC38, 1);
}
goto LA26;
LA35: ;
{
TY530811 LOC40;
memset((void*)LOC40, 0, sizeof(LOC40));
LOC40[0] = addrloc_536204_839829468(dest0);
LOC40[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_256), LOC40, 2);
}
LA26: ;
}
LA19: ;
}
break;
case ((Ttypekind290244) 25):
{
{
NIM_BOOL LOC44;
Tloc290816 a0;
Ropeobj177006* LOC47;
Tloc290816 LOC48;
Tloc290816 b0;
Ropeobj177006* LOC49;
Tloc290816 LOC50;
TY530811 LOC51;
LOC44 = (NIM_BOOL)0;
LOC44 = needscomplexassignment_531509_839829468(dest0.t);
if (!LOC44) goto LA45;
memset((void*)(&a0), 0, sizeof(a0));
LOC47 = (Ropeobj177006*)0;
LOC47 = rope_177277_2381377266(((NimStringDesc*) &T839829468_258));
memset((void*)(&LOC48), 0, sizeof(LOC48));
optasgnloc_547788_839829468(dest0, dest0.t, LOC47, (&LOC48));
memcpy((void*)(&a0), (NIM_CONST void*)(&LOC48), sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
LOC49 = (Ropeobj177006*)0;
LOC49 = rope_177277_2381377266(((NimStringDesc*) &T839829468_258));
memset((void*)(&LOC50), 0, sizeof(LOC50));
optasgnloc_547788_839829468(src0, dest0.t, LOC49, (&LOC50));
memcpy((void*)(&b0), (NIM_CONST void*)(&LOC50), sizeof(b0));
genrefassign_536311_839829468(p0, a0, b0, flags0);
memset((void*)LOC51, 0, sizeof(LOC51));
LOC51[0] = rdloc_536188_839829468(dest0);
LOC51[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_259), LOC51, 2);
}
goto LA42;
LA45: ;
{
TY530811 LOC53;
memset((void*)LOC53, 0, sizeof(LOC53));
LOC53[0] = rdloc_536188_839829468(dest0);
LOC53[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC53, 2);
}
LA42: ;
}
break;
case ((Ttypekind290244) 18):
{
{
NIM_BOOL LOC57;
LOC57 = (NIM_BOOL)0;
LOC57 = needscomplexassignment_531509_839829468(dest0.t);
if (!LOC57) goto LA58;
{
NI LOC62;
LOC62 = (NI)0;
LOC62 = len_293339_850551059(dest0.t);
if (!(LOC62 <= ((NI) 4))) goto LA63;
genoptasgntuple_548001_839829468(p0, dest0, src0, flags0);
}
goto LA60;
LA63: ;
{
gengenericasgn_548167_839829468(p0, dest0, src0, flags0);
}
LA60: ;
}
goto LA55;
LA58: ;
{
TY530811 LOC67;
memset((void*)LOC67, 0, sizeof(LOC67));
LOC67[0] = rdloc_536188_839829468(dest0);
LOC67[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC67, 2);
}
LA55: ;
}
break;
case ((Ttypekind290244) 17):
{
{
NIM_BOOL LOC71;
TY530811 LOC74;
LOC71 = (NIM_BOOL)0;
LOC71 = isimportedcpptype_531476_839829468(ty0);
if (!LOC71) goto LA72;
memset((void*)LOC74, 0, sizeof(LOC74));
LOC74[0] = rdloc_536188_839829468(dest0);
LOC74[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC74, 2);
}
goto LA69;
LA72: ;
{
NIM_BOOL LOC76;
LOC76 = (NIM_BOOL)0;
LOC76 = isobjlackingtypefield_531513_839829468(ty0);
if (!!(LOC76)) goto LA77;
gengenericasgn_548167_839829468(p0, dest0, src0, flags0);
}
goto LA69;
LA77: ;
{
NIM_BOOL LOC80;
LOC80 = (NIM_BOOL)0;
LOC80 = needscomplexassignment_531509_839829468(ty0);
if (!LOC80) goto LA81;
{
NIM_BOOL LOC85;
NI LOC87;
Ropeobj177006* LOC90;
LOC85 = (NIM_BOOL)0;
LOC85 = (*ty0).sons->data[((NI) 0)] == 0;
if (!(LOC85)) goto LA86;
LOC87 = (NI)0;
LOC87 = asgncomplexity_547750_839829468((*ty0).n);
LOC85 = (LOC87 <= ((NI) 4));
LA86: ;
if (!LOC85) goto LA88;
LOC90 = (Ropeobj177006*)0;
LOC90 = gettypedesc_533671_839829468((*p0).module, ty0);
ty0 = getuniquetype_526640_2036603609(ty0);
{
NimStringDesc* LOC95;
if (!!(!(((*ty0).n == NIM_NIL)))) goto LA93;
LOC95 = (NimStringDesc*)0;
LOC95 = HEX24_194185_1689653243(T839829468_264);
internalerror_194113_155036129(LOC95);
}
LA93: ;
genoptasgnobject_548084_839829468(p0, dest0, src0, flags0, (*ty0).n);
}
goto LA83;
LA88: ;
{
gengenericasgn_548167_839829468(p0, dest0, src0, flags0);
}
LA83: ;
}
goto LA69;
LA81: ;
{
TY530811 LOC98;
memset((void*)LOC98, 0, sizeof(LOC98));
LOC98[0] = rdloc_536188_839829468(dest0);
LOC98[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC98, 2);
}
LA69: ;
}
break;
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
{
NIM_BOOL LOC102;
LOC102 = (NIM_BOOL)0;
LOC102 = needscomplexassignment_531509_839829468(dest0.t);
if (!LOC102) goto LA103;
gengenericasgn_548167_839829468(p0, dest0, src0, flags0);
}
goto LA100;
LA103: ;
{
TY533238 LOC106;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC106, 0, sizeof(LOC106));
LOC106[0] = rdloc_536188_839829468(dest0);
LOC106[1] = rdloc_536188_839829468(src0);
LOC106[2] = gettypedesc_533671_839829468((*p0).module, ty0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_261), LOC106, 3);
}
LA100: ;
}
break;
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
{
NIM_BOOL LOC110;
TY533238 LOC113;
LOC110 = (NIM_BOOL)0;
LOC110 = needscomplexassignment_531509_839829468(dest0.t);
if (!LOC110) goto LA111;
memset((void*)LOC113, 0, sizeof(LOC113));
LOC113[0] = addrloc_536204_839829468(dest0);
LOC113[1] = addrloc_536204_839829468(src0);
LOC113[2] = gentypeinfo_533941_839829468((*p0).module, dest0.t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_266), LOC113, 3);
}
goto LA108;
LA111: ;
{
TY530811 LOC115;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC115, 0, sizeof(LOC115));
LOC115[0] = rdloc_536188_839829468(dest0);
LOC115[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_267), LOC115, 2);
}
LA108: ;
}
break;
case ((Ttypekind290244) 19):
{
{
Tctypekind527007 LOC119;
TY533238 LOC122;
NI64 LOC123;
LOC119 = (Tctypekind527007)0;
LOC119 = maptype_531393_839829468(ty0);
if (!(LOC119 == ((Tctypekind527007) 17))) goto LA120;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC122, 0, sizeof(LOC122));
LOC122[0] = rdloc_536188_839829468(dest0);
LOC122[1] = rdloc_536188_839829468(src0);
LOC123 = (NI64)0;
LOC123 = getsize_318135_3876443242(dest0.t);
LOC122[2] = rope_177401_2381377266(LOC123);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_268), LOC122, 3);
}
goto LA117;
LA120: ;
{
TY530811 LOC125;
memset((void*)LOC125, 0, sizeof(LOC125));
LOC125[0] = rdloc_536188_839829468(dest0);
LOC125[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC125, 2);
}
LA117: ;
}
break;
case ((Ttypekind290244) 21):
case ((Ttypekind290244) 26):
case ((Ttypekind290244) 2):
case ((Ttypekind290244) 1):
case ((Ttypekind290244) 14):
case ((Ttypekind290244) 29):
case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44):
case ((Ttypekind290244) 20):
case ((Ttypekind290244) 23):
{
TY530811 LOC127;
memset((void*)LOC127, 0, sizeof(LOC127));
LOC127[0] = rdloc_536188_839829468(dest0);
LOC127[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC127, 2);
}
break;
default:
{
NimStringDesc* LOC129;
LOC129 = (NimStringDesc*)0;
LOC129 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI290244))->Sup.len + 15);
appendString(LOC129, ((NimStringDesc*) &T839829468_269));
appendString(LOC129, reprEnum((NI)(*ty0).kind, (&NTI290244)));
internalerror_194113_155036129(LOC129);
}
break;
}
}BeforeRet: ;
}
N_NIMCALL(void, putlocintodest_537258_839829468)(Tcproc527021* p0, Tloc290816* d0, Tloc290816 s0) {
{
if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3;
{
if (!(((*d0).flags &(1U<<((NU)(((Tlocflag290810) 2))&15U)))!=0)) goto LA7;
genassignment_537264_839829468(p0, (*d0), s0, 0);
}
goto LA5;
LA7: ;
{
genassignment_537264_839829468(p0, (*d0), s0, 1);
}
LA5: ;
}
goto LA1;
LA3: ;
{
genericAssign((void*)(&(*d0)), (void*)(&s0), (&NTI290816));
}
LA1: ;
}
N_NIMCALL(NIM_BOOL, issimpleconst_530311_839829468)(Ttype290840* typ0) {
NIM_BOOL result0;
Ttype290840* t0;
NIM_BOOL LOC1;
NIM_BOOL LOC3;
result0 = (NIM_BOOL)0;
t0 = skiptypes_294099_850551059(typ0, IL64(211106240964864));
LOC1 = (NIM_BOOL)0;
LOC1 = !(((*t0).kind == ((Ttypekind290244) 18) || (*t0).kind == ((Ttypekind290244) 17) || (*t0).kind == ((Ttypekind290244) 16) || (*t0).kind == ((Ttypekind290244) 4) || (*t0).kind == ((Ttypekind290244) 19) || (*t0).kind == ((Ttypekind290244) 24)));
if (!(LOC1)) goto LA2;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*t0).kind == ((Ttypekind290244) 25));
if (!(LOC3)) goto LA4;
LOC3 = ((*t0).callconv == ((Tcallingconvention290002) 8));
LA4: ;
LOC1 = !(LOC3);
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, putintodest_548468_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0, Tstorageloc290812 s0) {
Tloc290816 a0;
memset((void*)(&a0), 0, sizeof(a0));
{
if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3;
initloc_530273_839829468((&a0), ((Tlockind290808) 6), t0, s0);
a0.r = r0;
{
if (!(((*d0).flags &(1U<<((NU)(((Tlocflag290810) 2))&15U)))!=0)) goto LA7;
genassignment_537264_839829468(p0, (*d0), a0, 0);
}
goto LA5;
LA7: ;
{
genassignment_537264_839829468(p0, (*d0), a0, 1);
}
LA5: ;
}
goto LA1;
LA3: ;
{
(*d0).k = ((Tlockind290808) 6);
unsureAsgnRef((void**) (&(*d0).t), t0);
unsureAsgnRef((void**) (&(*d0).r), r0);
}
LA1: ;
}
N_NIMCALL(NI64, bitsettoword_547578_839829468)(Tbitset337004* s0, NI size0) {
NI64 result0;
result0 = (NI64)0;
result0 = IL64(0);
{
NI j_547612_839829468;
NI HEX3Atmp_547622_839829468;
NI res_547625_839829468;
j_547612_839829468 = (NI)0;
HEX3Atmp_547622_839829468 = (NI)0;
HEX3Atmp_547622_839829468 = (NI)(size0 - ((NI) 1));
res_547625_839829468 = ((NI) 0);
{
while (1) {
if (!(res_547625_839829468 <= HEX3Atmp_547622_839829468)) goto LA3;
j_547612_839829468 = res_547625_839829468;
{
if (!(j_547612_839829468 < (s0 ? s0->Sup.len : 0))) goto LA6;
result0 = (NI64)(result0 | (NI64)((NU64)(((NI64)(NU64)(NU8)(s0->data[j_547612_839829468]))) << (NU64)(((NI64) ((NI)(j_547612_839829468 * ((NI) 8)))))));
}
LA6: ;
res_547625_839829468 += ((NI) 1);
} LA3: ;
}
}
return result0;
}
N_NIMCALL(Ropeobj177006*, genrawsetdata_547629_839829468)(Tbitset337004* cs0, NI size0) {
Ropeobj177006* result0;
NimStringDesc* frmt0;
result0 = (Ropeobj177006*)0;
frmt0 = (NimStringDesc*)0;
{
TY531289 LOC5;
if (!(((NI) 8) < size0)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_273), LOC5, 0);
{
NI i_547649_839829468;
NI HEX3Atmp_547657_839829468;
NI res_547660_839829468;
i_547649_839829468 = (NI)0;
HEX3Atmp_547657_839829468 = (NI)0;
HEX3Atmp_547657_839829468 = (NI)(size0 - ((NI) 1));
res_547660_839829468 = ((NI) 0);
{
while (1) {
TY177507 LOC19;
NimStringDesc* LOC20;
if (!(res_547660_839829468 <= HEX3Atmp_547657_839829468)) goto LA8;
i_547649_839829468 = res_547660_839829468;
{
if (!(i_547649_839829468 < (NI)(size0 - ((NI) 1)))) goto LA11;
{
if (!(((NI) ((NI)((NI)(i_547649_839829468 + ((NI) 1)) % ((NI) 8)))) == ((NI) 0))) goto LA15;
frmt0 = copyString(((NimStringDesc*) &T839829468_274));
}
goto LA13;
LA15: ;
{
frmt0 = copyString(((NimStringDesc*) &T839829468_275));
}
LA13: ;
}
goto LA9;
LA11: ;
{
frmt0 = copyString(((NimStringDesc*) &T839829468_276));
}
LA9: ;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC20 = (NimStringDesc*)0;
LOC20 = nsuToHex(((NI64)(NU64)(NU8)(cs0->data[i_547649_839829468])), ((NI) 2));
LOC19[0] = rope_177277_2381377266(LOC20);
addf_178205_2381377266(&result0, frmt0, LOC19, 1);
res_547660_839829468 += ((NI) 1);
} LA8: ;
}
}
}
goto LA1;
LA3: ;
{
NI64 LOC22;
LOC22 = (NI64)0;
LOC22 = bitsettoword_547578_839829468(cs0, size0);
result0 = intliteral_537270_839829468(LOC22);
}
LA1: ;
return result0;
}
N_NIMCALL(void, appcg_530640_839829468)(Tcgen527027* m0, Tcfilesection527005 s0, NimStringDesc* frmt0, Ropeobj177006** args0, NI args0Len0) {
Ropeobj177006* LOC1;
LOC1 = (Ropeobj177006*)0;
LOC1 = ropecg_530407_839829468(m0, frmt0, args0, args0Len0);
add_177482_2381377266(&(*m0).s[(s0)- 0], LOC1);
}
N_NIMCALL(Ropeobj177006*, genconstseq_557371_839829468)(Tcproc527021* p0, Tnode290802* n0, Ttype290840* t0) {
Ropeobj177006* result0;
Ropeobj177006* data0;
TY177507 LOC1;
NI LOC2;
TY533235 LOC18;
NI LOC19;
TY530811 LOC20;
result0 = (Ropeobj177006*)0;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC2 = (NI)0;
LOC2 = len_291081_850551059(n0);
LOC1[0] = rope_177401_2381377266(((NI64) (LOC2)));
data0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_277), LOC1, 1);
{
NI LOC5;
LOC5 = (NI)0;
LOC5 = len_291081_850551059(n0);
if (!(((NI) 0) < LOC5)) goto LA6;
add_177487_2381377266(&data0, ((NimStringDesc*) &T839829468_278));
{
NI i_557395_839829468;
NI HEX3Atmp_557411_839829468;
NI LOC9;
NI res_557414_839829468;
i_557395_839829468 = (NI)0;
HEX3Atmp_557411_839829468 = (NI)0;
LOC9 = (NI)0;
LOC9 = len_291081_850551059(n0);
HEX3Atmp_557411_839829468 = (NI)(LOC9 - ((NI) 1));
res_557414_839829468 = ((NI) 0);
{
while (1) {
Ropeobj177006* LOC17;
if (!(res_557414_839829468 <= HEX3Atmp_557411_839829468)) goto LA11;
i_557395_839829468 = res_557414_839829468;
{
TY531289 LOC16;
if (!(((NI) 0) < i_557395_839829468)) goto LA14;
memset((void*)LOC16, 0, sizeof(LOC16));
addf_178205_2381377266(&data0, ((NimStringDesc*) &T839829468_279), LOC16, 0);
}
LA14: ;
LOC17 = (Ropeobj177006*)0;
LOC17 = genconstexpr_552849_839829468(p0, (*n0).kindU.S6.sons->data[i_557395_839829468]);
add_177482_2381377266(&data0, LOC17);
res_557414_839829468 += ((NI) 1);
} LA11: ;
}
}
add_177487_2381377266(&data0, ((NimStringDesc*) &T839829468_280));
}
LA6: ;
add_177487_2381377266(&data0, ((NimStringDesc*) &T839829468_280));
result0 = gettempname_531596_839829468((*p0).module);
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = gettypedesc_533671_839829468((*p0).module, (*t0).sons->data[((NI) 0)]);
LOC19 = (NI)0;
LOC19 = len_291081_850551059(n0);
LOC18[1] = rope_177401_2381377266(((NI64) (LOC19)));
LOC18[2] = result0;
LOC18[3] = data0;
appcg_530640_839829468((*p0).module, ((Tcfilesection527005) 8), ((NimStringDesc*) &T839829468_281), LOC18, 4);
memset((void*)LOC20, 0, sizeof(LOC20));
LOC20[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC20[1] = result0;
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_282), LOC20, 2);
return result0;
}
N_NIMCALL(Ropeobj177006*, gennamedconstexpr_557284_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
if (!((*n0).kind == ((Tnodekind290020) 34))) goto LA3;
result0 = genconstexpr_552849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]);
}
goto LA1;
LA3: ;
{
result0 = genconstexpr_552849_839829468(p0, n0);
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, genconstsimplelist_557299_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
NI length0;
TY531289 LOC10;
result0 = (Ropeobj177006*)0;
length0 = sonslen_293351_850551059(n0);
result0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_223));
{
NI i_557333_839829468;
NI HEX3Atmp_557362_839829468;
NI HEX3Atmp_557363_839829468;
NI res_557366_839829468;
i_557333_839829468 = (NI)0;
HEX3Atmp_557362_839829468 = (NI)0;
HEX3Atmp_557363_839829468 = (NI)0;
HEX3Atmp_557362_839829468 = ((*n0).kind == ((Tnodekind290020) 38));
HEX3Atmp_557363_839829468 = (NI)(length0 - ((NI) 2));
res_557366_839829468 = ((NI) (HEX3Atmp_557362_839829468));
{
while (1) {
TY177507 LOC4;
if (!(res_557366_839829468 <= HEX3Atmp_557363_839829468)) goto LA3;
i_557333_839829468 = res_557366_839829468;
memset((void*)LOC4, 0, sizeof(LOC4));
LOC4[0] = gennamedconstexpr_557284_839829468(p0, (*n0).kindU.S6.sons->data[i_557333_839829468]);
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_283), LOC4, 1);
res_557366_839829468 += ((NI) 1);
} LA3: ;
}
}
{
Ropeobj177006* LOC9;
if (!(((NI) (((*n0).kind == ((Tnodekind290020) 38)))) < length0)) goto LA7;
LOC9 = (Ropeobj177006*)0;
LOC9 = gennamedconstexpr_557284_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))]);
add_177482_2381377266(&result0, LOC9);
}
LA7: ;
memset((void*)LOC10, 0, sizeof(LOC10));
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_160), LOC10, 0);
return result0;
}
N_NIMCALL(Ropeobj177006*, genconstexpr_552849_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
switch ((*n0).kind) {
case ((Tnodekind290020) 58):
case ((Tnodekind290020) 59):
{
result0 = genconstexpr_552849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]);
}
break;
case ((Tnodekind290020) 39):
{
Tbitset337004* cs0;
NI64 LOC3;
cs0 = (Tbitset337004*)0;
tobitset_338001_452470228(n0, (&cs0));
LOC3 = (NI64)0;
LOC3 = getsize_318135_3876443242((*n0).typ);
result0 = genrawsetdata_547629_839829468(cs0, ((NI) (LOC3)));
}
break;
case ((Tnodekind290020) 41):
case ((Tnodekind290020) 37):
case ((Tnodekind290020) 155):
case ((Tnodekind290020) 38):
{
Ttype290840* t0;
t0 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256));
{
if (!((*t0).kind == ((Ttypekind290244) 24))) goto LA7;
result0 = genconstseq_557371_839829468(p0, n0, t0);
}
goto LA5;
LA7: ;
{
result0 = genconstsimplelist_557299_839829468(p0, n0);
}
LA5: ;
}
break;
default:
{
Tloc290816 d0;
memset((void*)(&d0), 0, sizeof(d0));
initlocexpr_537283_839829468(p0, n0, (&d0));
result0 = rdloc_536188_839829468(d0);
}
break;
}
return result0;
}
N_NIMCALL(void, requestconstimpl_537240_839829468)(Tcproc527021* p0, Tsym290834* sym0) {
Tcgen527027* m0;
Tcgen527027* q0;
{ m0 = (*p0).module;
useheader_530369_839829468(m0, sym0);
{
Ropeobj177006* LOC5;
if (!((*sym0).loc.k == ((Tlockind290808) 0))) goto LA3;
LOC5 = (Ropeobj177006*)0;
LOC5 = manglename_531205_839829468(sym0);
fillloc_530282_839829468((&(*sym0).loc), ((Tlockind290808) 8), (*sym0).typ, LOC5, ((Tstorageloc290812) 1));
}
LA3: ;
{
if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA8;
goto BeforeRet;
}
LA8: ;
q0 = findpendingmodule_530241_839829468(m0, sym0);
{
NIM_BOOL LOC12;
NIM_BOOL LOC14;
TY533238 LOC17;
LOC12 = (NIM_BOOL)0;
LOC12 = !((q0 == NIM_NIL));
if (!(LOC12)) goto LA13;
LOC14 = (NIM_BOOL)0;
LOC14 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*sym0).Sup.id);
LOC12 = !(LOC14);
LA13: ;
if (!LOC12) goto LA15;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = gettypedesc_533671_839829468(q0, (*sym0).typ);
LOC17[1] = (*sym0).loc.r;
LOC17[2] = genconstexpr_552849_839829468((*q0).initproc, (*sym0).ast);
addf_178205_2381377266(&(*q0).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3);
}
LA15: ;
{
NIM_BOOL LOC20;
NIM_BOOL LOC22;
Ropeobj177006* headerdecl0;
TY530811 LOC25;
LOC20 = (NIM_BOOL)0;
LOC20 = !((q0 == m0));
if (!(LOC20)) goto LA21;
LOC22 = (NIM_BOOL)0;
LOC22 = containsorincl_266862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id);
LOC20 = !(LOC22);
LA21: ;
if (!LOC20) goto LA23;
memset((void*)LOC25, 0, sizeof(LOC25));
LOC25[0] = gettypedesc_533671_839829468(m0, (*sym0).loc.t);
LOC25[1] = (*sym0).loc.r;
headerdecl0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_284), LOC25, 2);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 8))- 0], headerdecl0);
{
NIM_BOOL LOC28;
LOC28 = (NIM_BOOL)0;
LOC28 = (((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 6))&31U)))!=0);
if (!(LOC28)) goto LA29;
LOC28 = !((generatedheader_530201_839829468 == NIM_NIL));
LA29: ;
if (!LOC28) goto LA30;
add_177482_2381377266(&(*generatedheader_530201_839829468).s[(((Tcfilesection527005) 8))- 0], headerdecl0);
}
LA30: ;
}
LA23: ;
}BeforeRet: ;
}
N_NIMCALL(void, gencomplexconst_556249_839829468)(Tcproc527021* p0, Tsym290834* sym0, Tloc290816* d0) {
requestconstimpl_537240_839829468(p0, sym0);
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
static N_INLINE(Ropeobj177006**, procsec_527194_3723162438)(Tcproc527021* p0, Tcprocsection527011 s0) {
Ropeobj177006** result0;
result0 = (Ropeobj177006**)0;
result0 = &(*p0).blocks->data[((NI) 0)].sections[(s0)- 0];
return result0;
}
N_NIMCALL(void, accessthreadlocalvar_530945_839829468)(Tcproc527021* p0, Tsym290834* s0) {
{
NIM_BOOL LOC3;
Ropeobj177006** LOC7;
TY531289 LOC8;
Ropeobj177006** LOC9;
TY531289 LOC10;
Ropeobj177006* LOC11;
LOC3 = (NIM_BOOL)0;
LOC3 = emulatedthreadvars_530949_839829468();
if (!(LOC3)) goto LA4;
LOC3 = !((*p0).threadvaraccessed);
LA4: ;
if (!LOC3) goto LA5;
(*p0).threadvaraccessed = NIM_TRUE;
(*(*p0).module).flags |= ((NU8)1)<<((((Codegenflag527025) 1))%(sizeof(NU8)*8));
LOC7 = (Ropeobj177006**)0;
LOC7 = procsec_527194_3723162438(p0, ((Tcprocsection527011) 0));
memset((void*)LOC8, 0, sizeof(LOC8));
addf_178205_2381377266(LOC7, ((NimStringDesc*) &T839829468_286), LOC8, 0);
LOC9 = (Ropeobj177006**)0;
LOC9 = procsec_527194_3723162438(p0, ((Tcprocsection527011) 1));
memset((void*)LOC10, 0, sizeof(LOC10));
LOC11 = (Ropeobj177006*)0;
LOC11 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_287), LOC10, 0);
add_177482_2381377266(LOC9, LOC11);
}
LA5: ;
}
static N_INLINE(NIM_BOOL, isemptytype_295440_850551059)(Ttype290840* t0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC1 = (t0 == NIM_NIL);
if (LOC1) goto LA2;
LOC1 = ((*t0).kind == ((Ttypekind290244) 62) || (*t0).kind == ((Ttypekind290244) 7));
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, putdataintodest_548436_839829468)(Tcproc527021* p0, Tloc290816* d0, Ttype290840* t0, Ropeobj177006* r0) {
Tloc290816 a0;
memset((void*)(&a0), 0, sizeof(a0));
{
if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3;
initloc_530273_839829468((&a0), ((Tlockind290808) 8), t0, ((Tstorageloc290812) 1));
a0.r = r0;
{
if (!(((*d0).flags &(1U<<((NU)(((Tlocflag290810) 2))&15U)))!=0)) goto LA7;
genassignment_537264_839829468(p0, (*d0), a0, 0);
}
goto LA5;
LA7: ;
{
genassignment_537264_839829468(p0, (*d0), a0, 1);
}
LA5: ;
}
goto LA1;
LA3: ;
{
(*d0).k = ((Tlockind290808) 8);
unsureAsgnRef((void**) (&(*d0).t), t0);
unsureAsgnRef((void**) (&(*d0).r), r0);
}
LA1: ;
}
N_NIMCALL(NIM_BOOL, freshlineinfo_530818_839829468)(Tcproc527021* p0, Tlineinfo189336 info0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = !(((*p0).lastlineinfo.line == info0.line));
if (LOC3) goto LA4;
LOC3 = !(((*p0).lastlineinfo.fileindex == info0.fileindex));
LA4: ;
if (!LOC3) goto LA5;
(*p0).lastlineinfo.line = info0.line;
(*p0).lastlineinfo.fileindex = info0.fileindex;
result0 = NIM_TRUE;
}
LA5: ;
return result0;
}
N_NIMCALL(void, genlinedir_530823_839829468)(Tcproc527021* p0, Tnode290802* t0) {
NI line0;
Ropeobj177006** LOC11;
NimStringDesc* LOC12;
line0 = safelinenm_530721_839829468((*t0).info);
{
Ropeobj177006** LOC5;
TY531289 LOC6;
Ropeobj177006* LOC7;
Ropeobj177006* LOC8;
Ropeobj177006* LOC9;
Ropeobj177006* LOC10;
if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 28))&63U)))!=0)) goto LA3;
LOC5 = (Ropeobj177006**)0;
LOC5 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
memset((void*)LOC6, 0, sizeof(LOC6));
LOC7 = (Ropeobj177006*)0;
LOC7 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_293), LOC6, 0);
LOC8 = (Ropeobj177006*)0;
LOC8 = sourceline_190068_155036129((*t0).info);
LOC9 = (Ropeobj177006*)0;
LOC9 = HEX26_177418_2381377266(LOC7, LOC8);
LOC10 = (Ropeobj177006*)0;
LOC10 = HEX26_177418_2381377266(LOC9, rnl_177903_2381377266);
add_177482_2381377266(LOC5, LOC10);
}
LA3: ;
LOC11 = (Ropeobj177006**)0;
LOC11 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
LOC12 = (NimStringDesc*)0;
LOC12 = tofullpath_190264_155036129((*t0).info.fileindex);
genclinedir_530725_839829468(LOC11, LOC12, line0);
{
NIM_BOOL LOC15;
NIM_BOOL LOC17;
LOC15 = (NIM_BOOL)0;
LOC15 = ((163840 & (*p0).options) == 163840);
if (!(LOC15)) goto LA16;
LOC17 = (NIM_BOOL)0;
LOC17 = ((*p0).prc == NIM_NIL);
if (LOC17) goto LA18;
LOC17 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0));
LA18: ;
LOC15 = LOC17;
LA16: ;
if (!LOC15) goto LA19;
{
NIM_BOOL LOC23;
TY530811 LOC26;
NimStringDesc* LOC27;
LOC23 = (NIM_BOOL)0;
LOC23 = freshlineinfo_530818_839829468(p0, (*t0).info);
if (!LOC23) goto LA24;
memset((void*)LOC26, 0, sizeof(LOC26));
LOC26[0] = rope_177401_2381377266(((NI64) (line0)));
LOC27 = (NimStringDesc*)0;
LOC27 = tofilename_190260_155036129((*t0).info.fileindex);
LOC26[1] = makecstring_189638_155036129(LOC27);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_294), LOC26, 2);
}
LA24: ;
}
goto LA13;
LA19: ;
{
NIM_BOOL LOC29;
NIM_BOOL LOC30;
NIM_BOOL LOC32;
LOC29 = (NIM_BOOL)0;
LOC30 = (NIM_BOOL)0;
LOC30 = ((98304 & (*p0).options) == 98304);
if (!(LOC30)) goto LA31;
LOC32 = (NIM_BOOL)0;
LOC32 = ((*p0).prc == NIM_NIL);
if (LOC32) goto LA33;
LOC32 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0));
LA33: ;
LOC30 = LOC32;
LA31: ;
LOC29 = LOC30;
if (!(LOC29)) goto LA34;
LOC29 = (((NI32) 0) <= (*t0).info.fileindex);
LA34: ;
if (!LOC29) goto LA35;
{
NIM_BOOL LOC39;
TY530811 LOC42;
LOC39 = (NIM_BOOL)0;
LOC39 = freshlineinfo_530818_839829468(p0, (*t0).info);
if (!LOC39) goto LA40;
memset((void*)LOC42, 0, sizeof(LOC42));
LOC42[0] = rope_177401_2381377266(((NI64) (line0)));
LOC42[1] = quotedfilename_194818_155036129((*t0).info);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_295), LOC42, 2);
}
LA40: ;
}
goto LA13;
LA35: ;
LA13: ;
}
N_NIMCALL(Ropeobj177006*, getlabel_537217_839829468)(Tcproc527021* p0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
result0 = (Ropeobj177006*)0;
(*p0).labels += ((NI) 1);
LOC1 = (Ropeobj177006*)0;
LOC1 = rope_177401_2381377266(((NI64) ((*p0).labels)));
result0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC1);
return result0;
}
N_NIMCALL(void, fixlabel_537230_839829468)(Tcproc527021* p0, Ropeobj177006* labl0) {
TY177507 LOC1;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = labl0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_299), LOC1, 1);
}
N_NIMCALL(void, genandor_552311_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) {
Ropeobj177006* L0;
Tloc290816 tmp0;
L0 = (Ropeobj177006*)0;
memset((void*)(&tmp0), 0, sizeof(tmp0));
gettemp_535032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE);
(*p0).splitdecls += ((NI) 1);
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0));
L0 = getlabel_537217_839829468(p0);
{
TY530811 LOC5;
if (!(m0 == ((Tmagic290524) 127))) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(tmp0);
LOC5[1] = L0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_297), LOC5, 2);
}
goto LA1;
LA3: ;
{
TY530811 LOC7;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = rdloc_536188_839829468(tmp0);
LOC7[1] = L0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_298), LOC7, 2);
}
LA1: ;
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&tmp0));
fixlabel_537230_839829468(p0, L0);
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA10;
genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI290816));
}
goto LA8;
LA10: ;
{
genassignment_537264_839829468(p0, (*d0), tmp0, 0);
}
LA8: ;
(*p0).splitdecls -= ((NI) 1);
}
N_NIMCALL(void, unaryarith_550646_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) {
Tloc290816 a0;
Ttype290840* t0;
TY533238 LOC1;
NI64 LOC2;
Ropeobj177006* LOC3;
memset((void*)(&a0), 0, sizeof(a0));
t0 = (Ttype290840*)0;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468(a0);
LOC2 = (NI64)0;
LOC2 = getsize_318135_3876443242(t0);
LOC1[1] = rope_177401_2381377266((NI64)(LOC2 * IL64(8)));
LOC1[2] = getsimpletypedesc_531936_839829468((*p0).module, (*e0).typ);
LOC3 = (Ropeobj177006*)0;
LOC3 = HEX25_177905_2381377266(unarithtab_550653_839829468[(op0)- 99], LOC1, 3);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC3, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, unaryarithoverflow_549633_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) {
Tloc290816 a0;
Ttype290840* t0;
TY530811 LOC7;
NI64 LOC8;
Ropeobj177006* LOC9;
memset((void*)(&a0), 0, sizeof(a0));
t0 = (Ttype290840*)0;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832));
{
TY530811 LOC5;
NI64 LOC6;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(a0);
LOC6 = (NI64)0;
LOC6 = firstord_318001_3876443242(t0);
LOC5[1] = intliteral_537270_839829468(LOC6);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_317), LOC5, 2);
}
LA3: ;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = rdloc_536188_839829468(a0);
LOC8 = (NI64)0;
LOC8 = getsize_318135_3876443242(t0);
LOC7[1] = rope_177401_2381377266((NI64)(LOC8 * IL64(8)));
LOC9 = (Ropeobj177006*)0;
LOC9 = HEX25_177905_2381377266(opr_549640_839829468[(m0)- 96], LOC7, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC9, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, binaryarith_549819_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) {
Tloc290816 a0;
Tloc290816 b0;
NI64 s0;
NI64 LOC1;
NI64 LOC2;
TY533235 LOC3;
Ropeobj177006* LOC4;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
s0 = (NI64)0;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
LOC1 = (NI64)0;
LOC1 = getsize_318135_3876443242(a0.t);
LOC2 = (NI64)0;
LOC2 = getsize_318135_3876443242(b0.t);
s0 = (NI64)(((LOC1 >= LOC2) ? LOC1 : LOC2) * IL64(8));
memset((void*)LOC3, 0, sizeof(LOC3));
LOC3[0] = rdloc_536188_839829468(a0);
LOC3[1] = rdloc_536188_839829468(b0);
LOC3[2] = rope_177401_2381377266(s0);
LOC3[3] = getsimpletypedesc_531936_839829468((*p0).module, (*e0).typ);
LOC4 = (Ropeobj177006*)0;
LOC4 = HEX25_177905_2381377266(binarithtab_549826_839829468[(op0)- 52], LOC3, 4);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC4, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, binaryfloatarith_554728_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) {
{
Tloc290816 a0;
Tloc290816 b0;
TY533235 LOC5;
Tnode290802* LOC6;
Ropeobj177006* LOC7;
if (!!(((384 & (*p0).options) == 0))) goto LA3;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rope_177277_2381377266(opr_554762_839829468[(m0)- 52]);
LOC5[1] = rdloc_536188_839829468(a0);
LOC5[2] = rdloc_536188_839829468(b0);
LOC6 = (Tnode290802*)0;
LOC6 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1));
LOC5[3] = getsimpletypedesc_531936_839829468((*p0).module, (*LOC6).typ);
LOC7 = (Ropeobj177006*)0;
LOC7 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_319), LOC5, 4);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc290812) 0));
{
TY177507 LOC12;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 7))&31U)))!=0)) goto LA10;
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = rdloc_536188_839829468((*d0));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_323), LOC12, 1);
}
LA10: ;
{
TY177507 LOC17;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 8))&31U)))!=0)) goto LA15;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = rdloc_536188_839829468((*d0));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_324), LOC17, 1);
}
LA15: ;
}
goto LA1;
LA3: ;
{
binaryarith_549819_839829468(p0, e0, d0, m0);
}
LA1: ;
}
N_NIMCALL(void, geneqproc_550214_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
{
Ttype290840* LOC3;
TY530811 LOC6;
Ropeobj177006* LOC7;
LOC3 = (Ttype290840*)0;
LOC3 = skiptypes_294099_850551059(a0.t, IL64(211106232576256));
if (!((*LOC3).callconv == ((Tcallingconvention290002) 8))) goto LA4;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = rdloc_536188_839829468(a0);
LOC6[1] = rdloc_536188_839829468(b0);
LOC7 = (Ropeobj177006*)0;
LOC7 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_352), LOC6, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc290812) 0));
}
goto LA1;
LA4: ;
{
TY530811 LOC9;
Ropeobj177006* LOC10;
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = rdloc_536188_839829468(a0);
LOC9[1] = rdloc_536188_839829468(b0);
LOC10 = (Ropeobj177006*)0;
LOC10 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_341), LOC9, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC10, ((Tstorageloc290812) 0));
}
LA1: ;
}
N_NIMCALL(Ropeobj177006*, rdcharloc_536227_839829468)(Tloc290816 a0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = rdloc_536188_839829468(a0);
{
Ttype290840* LOC3;
TY177507 LOC6;
LOC3 = (Ttype290840*)0;
LOC3 = skiptypes_294099_850551059(a0.t, IL64(211106233624832));
if (!((*LOC3).kind == ((Ttypekind290244) 2))) goto LA4;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = result0;
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_358), LOC6, 1);
}
LA4: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, binaryarithoverflowraw_549235_839829468)(Tcproc527021* p0, Ttype290840* t0, Tloc290816 a0, Tloc290816 b0, NimStringDesc* frmt0) {
Ropeobj177006* result0;
NI64 size0;
Ropeobj177006* storage0;
TY530811 LOC6;
TY533238 LOC7;
result0 = (Ropeobj177006*)0;
size0 = getsize_318135_3876443242(t0);
{
if (!(size0 < ((NI64) (intsize_175641_4151366050)))) goto LA3;
storage0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_36));
}
goto LA1;
LA3: ;
{
storage0 = gettypedesc_533671_839829468((*p0).module, t0);
}
LA1: ;
result0 = gettempname_531596_839829468((*p0).module);
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = storage0;
LOC6[1] = result0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_54), LOC6, 2);
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = result0;
LOC7[1] = rdcharloc_536227_839829468(a0);
LOC7[2] = rdcharloc_536227_839829468(b0);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC7, 3);
{
NIM_BOOL LOC10;
TY533238 LOC14;
NI64 LOC15;
NI64 LOC16;
LOC10 = (NIM_BOOL)0;
LOC10 = (size0 < ((NI64) (intsize_175641_4151366050)));
if (LOC10) goto LA11;
LOC10 = ((*t0).kind == ((Ttypekind290244) 20) || (*t0).kind == ((Ttypekind290244) 14));
LA11: ;
if (!LOC10) goto LA12;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = result0;
LOC15 = (NI64)0;
LOC15 = firstord_318001_3876443242(t0);
LOC14[1] = intliteral_537270_839829468(LOC15);
LOC16 = (NI64)0;
LOC16 = lastord_318004_3876443242(t0);
LOC14[2] = intliteral_537270_839829468(LOC16);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_359), LOC14, 3);
}
LA12: ;
return result0;
}
N_NIMCALL(void, binaryarithoverflow_549262_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 m0) {
Tloc290816 a0;
Tloc290816 b0;
Ttype290840* t0;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832));
{
Ropeobj177006* res0;
TY533238 LOC5;
if (!!((((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0))) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC5[1] = rdloc_536188_839829468(a0);
LOC5[2] = rdloc_536188_839829468(b0);
res0 = HEX25_177905_2381377266(opr_549279_839829468[(m0)- 45], LOC5, 3);
putintodest_548468_839829468(p0, d0, (*e0).typ, res0, ((Tstorageloc290812) 0));
}
goto LA1;
LA3: ;
{
Ropeobj177006* res0;
NimStringDesc* LOC7;
TY530811 LOC13;
Ropeobj177006* LOC14;
LOC7 = (NimStringDesc*)0;
{
if (!((*t0).kind == ((Ttypekind290244) 35))) goto LA10;
LOC7 = copyString(prc64_549274_839829468[(m0)- 45]);
}
goto LA8;
LA10: ;
{
LOC7 = copyString(prc_549269_839829468[(m0)- 45]);
}
LA8: ;
res0 = binaryarithoverflowraw_549235_839829468(p0, t0, a0, b0, LOC7);
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC13[1] = res0;
LOC14 = (Ropeobj177006*)0;
LOC14 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_370), LOC13, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC14, ((Tstorageloc290812) 0));
}
LA1: ;
}
N_NIMCALL(Ropeobj177006*, lenfield_537305_839829468)(Tcproc527021* p0) {
Ropeobj177006* result0;
NimStringDesc* LOC1;
result0 = (Ropeobj177006*)0;
LOC1 = (NimStringDesc*)0;
{
NIM_BOOL LOC4;
LOC4 = (NIM_BOOL)0;
LOC4 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC4) goto LA5;
LOC4 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA5: ;
if (!LOC4) goto LA6;
LOC1 = copyString(((NimStringDesc*) &T839829468_157));
}
goto LA2;
LA6: ;
{
LOC1 = copyString(((NimStringDesc*) &T839829468_158));
}
LA2: ;
result0 = rope_177277_2381377266(LOC1);
return result0;
}
N_NIMCALL(void, gcusage_552439_839829468)(Tnode290802* n0) {
{
NimStringDesc* LOC5;
if (!(gselectedgc_168133_2607990831 == ((Tgcmode168080) 0))) goto LA3;
LOC5 = (NimStringDesc*)0;
LOC5 = rendertree_309044_382274130(n0, 0);
message_194095_155036129((*n0).info, ((Tmsgkind189002) 263), LOC5);
}
LA3: ;
}
N_NIMCALL(void, genrepr_553339_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Ttype290840* t0;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440));
switch ((*t0).kind) {
case ((Ttypekind290244) 31) ... ((Ttypekind290244) 35):
case ((Ttypekind290244) 40) ... ((Ttypekind290244) 44):
{
TY177507 LOC2;
Ropeobj177006* LOC3;
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = rdloc_536188_839829468(a0);
LOC3 = (Ropeobj177006*)0;
LOC3 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_371), LOC2, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC3, a0.s);
}
break;
case ((Ttypekind290244) 36) ... ((Ttypekind290244) 39):
{
TY177507 LOC5;
Ropeobj177006* LOC6;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(a0);
LOC6 = (Ropeobj177006*)0;
LOC6 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_372), LOC5, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC6, a0.s);
}
break;
case ((Ttypekind290244) 1):
{
TY177507 LOC8;
Ropeobj177006* LOC9;
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rdloc_536188_839829468(a0);
LOC9 = (Ropeobj177006*)0;
LOC9 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_373), LOC8, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC9, a0.s);
}
break;
case ((Ttypekind290244) 2):
{
TY177507 LOC11;
Ropeobj177006* LOC12;
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = rdloc_536188_839829468(a0);
LOC12 = (Ropeobj177006*)0;
LOC12 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_374), LOC11, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC12, a0.s);
}
break;
case ((Ttypekind290244) 14):
case ((Ttypekind290244) 15):
{
TY530811 LOC14;
Ropeobj177006* LOC15;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = rdloc_536188_839829468(a0);
LOC14[1] = gentypeinfo_533941_839829468((*p0).module, t0);
LOC15 = (Ropeobj177006*)0;
LOC15 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_375), LOC14, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC15, a0.s);
}
break;
case ((Ttypekind290244) 28):
{
TY177507 LOC17;
Ropeobj177006* LOC18;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = rdloc_536188_839829468(a0);
LOC18 = (Ropeobj177006*)0;
LOC18 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_376), LOC17, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC18, a0.s);
}
break;
case ((Ttypekind290244) 19):
{
TY530811 LOC20;
Ropeobj177006* LOC21;
memset((void*)LOC20, 0, sizeof(LOC20));
LOC20[0] = addrloc_536204_839829468(a0);
LOC20[1] = gentypeinfo_533941_839829468((*p0).module, t0);
LOC21 = (Ropeobj177006*)0;
LOC21 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_377), LOC20, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC21, a0.s);
}
break;
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
Tloc290816 b0;
TY530811 LOC34;
Ttype290840* LOC35;
Ropeobj177006* LOC36;
memset((void*)(&b0), 0, sizeof(b0));
switch ((*a0.t).kind) {
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
TY177507 LOC24;
Ropeobj177006* LOC25;
memset((void*)LOC24, 0, sizeof(LOC24));
LOC24[0] = rdloc_536188_839829468(a0);
LOC25 = (Ropeobj177006*)0;
LOC25 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_378), LOC24, 1);
putintodest_548468_839829468(p0, (&b0), (*e0).typ, LOC25, a0.s);
}
break;
case ((Ttypekind290244) 28):
case ((Ttypekind290244) 24):
{
TY530811 LOC27;
Ropeobj177006* LOC28;
memset((void*)LOC27, 0, sizeof(LOC27));
LOC27[0] = rdloc_536188_839829468(a0);
LOC27[1] = lenfield_537305_839829468(p0);
LOC28 = (Ropeobj177006*)0;
LOC28 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_379), LOC27, 2);
putintodest_548468_839829468(p0, (&b0), (*e0).typ, LOC28, a0.s);
}
break;
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
TY530811 LOC30;
NI64 LOC31;
Ropeobj177006* LOC32;
memset((void*)LOC30, 0, sizeof(LOC30));
LOC30[0] = rdloc_536188_839829468(a0);
LOC31 = (NI64)0;
LOC31 = lengthord_318007_3876443242(a0.t);
LOC30[1] = rope_177401_2381377266(LOC31);
LOC32 = (Ropeobj177006*)0;
LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_380), LOC30, 2);
putintodest_548468_839829468(p0, (&b0), (*e0).typ, LOC32, a0.s);
}
break;
default:
{
internalerror_194100_155036129((*(*e0).kindU.S6.sons->data[((NI) 0)]).info, ((NimStringDesc*) &T839829468_381));
}
break;
}
memset((void*)LOC34, 0, sizeof(LOC34));
LOC34[0] = rdloc_536188_839829468(b0);
LOC35 = (Ttype290840*)0;
LOC35 = elemtype_318394_3876443242(t0);
LOC34[1] = gentypeinfo_533941_839829468((*p0).module, LOC35);
LOC36 = (Ropeobj177006*)0;
LOC36 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_382), LOC34, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC36, a0.s);
}
break;
case ((Ttypekind290244) 29):
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
case ((Ttypekind290244) 22):
case ((Ttypekind290244) 21):
case ((Ttypekind290244) 26):
case ((Ttypekind290244) 5):
case ((Ttypekind290244) 24):
{
TY530811 LOC38;
Ropeobj177006* LOC39;
memset((void*)LOC38, 0, sizeof(LOC38));
LOC38[0] = rdloc_536188_839829468(a0);
LOC38[1] = gentypeinfo_533941_839829468((*p0).module, t0);
LOC39 = (Ropeobj177006*)0;
LOC39 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC38, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC39, a0.s);
}
break;
case ((Ttypekind290244) 3):
case ((Ttypekind290244) 62):
{
localerror_194085_155036129((*e0).info, ((NimStringDesc*) &T839829468_384));
}
break;
default:
{
TY530811 LOC42;
Ropeobj177006* LOC43;
memset((void*)LOC42, 0, sizeof(LOC42));
LOC42[0] = addrloc_536204_839829468(a0);
LOC42[1] = gentypeinfo_533941_839829468((*p0).module, t0);
LOC43 = (Ropeobj177006*)0;
LOC43 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC42, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC43, a0.s);
}
break;
}
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, gengettypeinfo_553383_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Ttype290840* t0;
Ropeobj177006* LOC1;
t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440));
LOC1 = (Ropeobj177006*)0;
LOC1 = gentypeinfo_533941_839829468((*p0).module, t0);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC1, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, genswap_553638_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Tloc290816 tmp0;
Ttype290840* LOC1;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
memset((void*)(&tmp0), 0, sizeof(tmp0));
LOC1 = (Ttype290840*)0;
LOC1 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864));
gettemp_535032_839829468(p0, LOC1, (&tmp0), NIM_FALSE);
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
genassignment_537264_839829468(p0, tmp0, a0, 0);
genassignment_537264_839829468(p0, a0, b0, 0);
genassignment_537264_839829468(p0, b0, tmp0, 0);
}
N_NIMCALL(void, unaryexpr_549209_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
TY177507 LOC1;
Ropeobj177006* LOC2;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468(a0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, binarystmt_548501_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
Tloc290816 b0;
TY530811 LOC5;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
{
if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3;
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_387));
}
LA3: ;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(a0);
LOC5[1] = rdloc_536188_839829468(b0);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC5, 2);
}
N_NIMCALL(void, genstrconcat_552452_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 tmp0;
NI L0;
Ropeobj177006* appends0;
Ropeobj177006* lens0;
TY533238 LOC21;
Ropeobj177006** LOC22;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&tmp0), 0, sizeof(tmp0));
gettemp_535032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE);
L0 = ((NI) 0);
appends0 = NIM_NIL;
lens0 = NIM_NIL;
{
NI i_552475_839829468;
NI HEX3Atmp_552547_839829468;
NI LOC2;
NI res_552550_839829468;
i_552475_839829468 = (NI)0;
HEX3Atmp_552547_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(e0);
HEX3Atmp_552547_839829468 = (NI)(LOC2 - ((NI) 2));
res_552550_839829468 = ((NI) 0);
{
while (1) {
if (!(res_552550_839829468 <= HEX3Atmp_552547_839829468)) goto LA4;
i_552475_839829468 = res_552550_839829468;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))], (&a0));
{
Ttype290840* LOC7;
TY530811 LOC10;
Ropeobj177006* LOC11;
LOC7 = (Ttype290840*)0;
LOC7 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).typ, IL64(211106242013440));
if (!((*LOC7).kind == ((Ttypekind290244) 2))) goto LA8;
L0 += ((NI) 1);
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = tmp0.r;
LOC10[1] = rdloc_536188_839829468(a0);
LOC11 = (Ropeobj177006*)0;
LOC11 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2);
add_177482_2381377266(&appends0, LOC11);
}
goto LA5;
LA8: ;
{
TY530811 LOC19;
Ropeobj177006* LOC20;
{
if (!((*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kind >= ((Tnodekind290020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kind <= ((Tnodekind290020) 22))) goto LA15;
L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_552475_839829468 + ((NI) 1))]).kindU.S3.strval->Sup.len : 0);
}
goto LA13;
LA15: ;
{
TY530811 LOC18;
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = rdloc_536188_839829468(a0);
LOC18[1] = lenfield_537305_839829468(p0);
addf_178205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2);
}
LA13: ;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = tmp0.r;
LOC19[1] = rdloc_536188_839829468(a0);
LOC20 = (Ropeobj177006*)0;
LOC20 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2);
add_177482_2381377266(&appends0, LOC20);
}
LA5: ;
res_552550_839829468 += ((NI) 1);
} LA4: ;
}
}
memset((void*)LOC21, 0, sizeof(LOC21));
LOC21[0] = tmp0.r;
LOC21[1] = lens0;
LOC21[2] = rope_177401_2381377266(((NI64) (L0)));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_393), LOC21, 3);
LOC22 = (Ropeobj177006**)0;
LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177482_2381377266(LOC22, appends0);
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA25;
genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI290816));
}
goto LA23;
LA25: ;
{
genassignment_537264_839829468(p0, (*d0), tmp0, 0);
}
LA23: ;
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, genstrappend_552554_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 dest0;
Ropeobj177006* appends0;
Ropeobj177006* lens0;
NI L0;
TY533238 LOC21;
Ropeobj177006** LOC22;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&dest0), 0, sizeof(dest0));
appends0 = (Ropeobj177006*)0;
lens0 = (Ropeobj177006*)0;
L0 = ((NI) 0);
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&dest0));
{
NI i_552615_839829468;
NI HEX3Atmp_552676_839829468;
NI LOC2;
NI res_552679_839829468;
i_552615_839829468 = (NI)0;
HEX3Atmp_552676_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(e0);
HEX3Atmp_552676_839829468 = (NI)(LOC2 - ((NI) 3));
res_552679_839829468 = ((NI) 0);
{
while (1) {
if (!(res_552679_839829468 <= HEX3Atmp_552676_839829468)) goto LA4;
i_552615_839829468 = res_552679_839829468;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))], (&a0));
{
Ttype290840* LOC7;
TY530811 LOC10;
Ropeobj177006* LOC11;
LOC7 = (Ttype290840*)0;
LOC7 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).typ, IL64(211106242013440));
if (!((*LOC7).kind == ((Ttypekind290244) 2))) goto LA8;
L0 += ((NI) 1);
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = rdloc_536188_839829468(dest0);
LOC10[1] = rdloc_536188_839829468(a0);
LOC11 = (Ropeobj177006*)0;
LOC11 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2);
add_177482_2381377266(&appends0, LOC11);
}
goto LA5;
LA8: ;
{
TY530811 LOC19;
Ropeobj177006* LOC20;
{
if (!((*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kind >= ((Tnodekind290020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kind <= ((Tnodekind290020) 22))) goto LA15;
L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_552615_839829468 + ((NI) 2))]).kindU.S3.strval->Sup.len : 0);
}
goto LA13;
LA15: ;
{
TY530811 LOC18;
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = rdloc_536188_839829468(a0);
LOC18[1] = lenfield_537305_839829468(p0);
addf_178205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2);
}
LA13: ;
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = rdloc_536188_839829468(dest0);
LOC19[1] = rdloc_536188_839829468(a0);
LOC20 = (Ropeobj177006*)0;
LOC20 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2);
add_177482_2381377266(&appends0, LOC20);
}
LA5: ;
res_552679_839829468 += ((NI) 1);
} LA4: ;
}
}
memset((void*)LOC21, 0, sizeof(LOC21));
LOC21[0] = rdloc_536188_839829468(dest0);
LOC21[1] = lens0;
LOC21[2] = rope_177401_2381377266(((NI64) (L0)));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_395), LOC21, 3);
LOC22 = (Ropeobj177006**)0;
LOC22 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177482_2381377266(LOC22, appends0);
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, genseqelemappend_552683_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
NimStringDesc* seqappendpattern0;
Tloc290816 a0;
Tloc290816 b0;
Tloc290816 dest0;
Ttype290840* bt0;
TY533238 LOC8;
Ttype290840* LOC9;
TY530811 LOC10;
TY530811 LOC11;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC3) goto LA4;
LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA4: ;
if (!!(LOC3)) goto LA5;
seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_396));
}
goto LA1;
LA5: ;
{
seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_397));
}
LA1: ;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
memset((void*)(&dest0), 0, sizeof(dest0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
bt0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 2)]).typ, IL64(211106240964864));
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rdloc_536188_839829468(a0);
LOC9 = (Ttype290840*)0;
LOC9 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864));
LOC8[1] = gettypedesc_533671_839829468((*p0).module, LOC9);
LOC8[2] = gettypedesc_533671_839829468((*p0).module, bt0);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), seqappendpattern0, LOC8, 3);
initloc_530273_839829468((&dest0), ((Tlockind290808) 6), bt0, ((Tstorageloc290812) 3));
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = rdloc_536188_839829468(a0);
LOC10[1] = lenfield_537305_839829468(p0);
dest0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_398), LOC10, 2);
genassignment_537264_839829468(p0, dest0, b0, 3);
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = rdloc_536188_839829468(a0);
LOC11[1] = lenfield_537305_839829468(p0);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_399), LOC11, 2);
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, binaryexpr_548549_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
Tloc290816 b0;
TY530811 LOC1;
Ropeobj177006* LOC2;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468(a0);
LOC1[1] = rdloc_536188_839829468(b0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, genstrequals_554666_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 x0;
Tnode290802* a0;
Tnode290802* b0;
memset((void*)(&x0), 0, sizeof(x0));
a0 = (*e0).kindU.S6.sons->data[((NI) 1)];
b0 = (*e0).kindU.S6.sons->data[((NI) 2)];
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*a0).kind == ((Tnodekind290020) 23));
if (LOC3) goto LA4;
LOC3 = ((*b0).kind == ((Tnodekind290020) 23));
LA4: ;
if (!LOC3) goto LA5;
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341));
}
goto LA1;
LA5: ;
{
NIM_BOOL LOC8;
TY530811 LOC12;
Ropeobj177006* LOC13;
LOC8 = (NIM_BOOL)0;
LOC8 = ((*a0).kind >= ((Tnodekind290020) 20) && (*a0).kind <= ((Tnodekind290020) 22));
if (!(LOC8)) goto LA9;
LOC8 = (((*a0).kindU.S3.strval) && ((*a0).kindU.S3.strval)->Sup.len == 0);
LA9: ;
if (!LOC8) goto LA10;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&x0));
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = rdloc_536188_839829468(x0);
LOC12[1] = lenfield_537305_839829468(p0);
LOC13 = (Ropeobj177006*)0;
LOC13 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC12, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC13, ((Tstorageloc290812) 0));
}
goto LA1;
LA10: ;
{
NIM_BOOL LOC15;
TY530811 LOC19;
Ropeobj177006* LOC20;
LOC15 = (NIM_BOOL)0;
LOC15 = ((*b0).kind >= ((Tnodekind290020) 20) && (*b0).kind <= ((Tnodekind290020) 22));
if (!(LOC15)) goto LA16;
LOC15 = (((*b0).kindU.S3.strval) && ((*b0).kindU.S3.strval)->Sup.len == 0);
LA16: ;
if (!LOC15) goto LA17;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&x0));
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = rdloc_536188_839829468(x0);
LOC19[1] = lenfield_537305_839829468(p0);
LOC20 = (Ropeobj177006*)0;
LOC20 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC19, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC20, ((Tstorageloc290812) 0));
}
goto LA1;
LA17: ;
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_401));
}
LA1: ;
}
N_NIMCALL(void, genisnil_550620_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Ttype290840* t0;
t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832));
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*t0).kind == ((Ttypekind290244) 25));
if (!(LOC3)) goto LA4;
LOC3 = ((*t0).callconv == ((Tcallingconvention290002) 8));
LA4: ;
if (!LOC3) goto LA5;
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_404));
}
goto LA1;
LA5: ;
{
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_405));
}
LA1: ;
}
N_NIMCALL(void, gendollar_553391_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
TY177507 LOC1;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468(a0);
a0.r = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 1);
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA4;
gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE);
}
LA4: ;
genassignment_537264_839829468(p0, (*d0), a0, 0);
gcusage_552439_839829468(n0);
}
N_NIMCALL(Ropeobj177006*, genofhelper_553139_839829468)(Tcproc527021* p0, Ttype290840* dest0, Ropeobj177006* a0) {
Ropeobj177006* result0;
Ropeobj177006* ti0;
result0 = (Ropeobj177006*)0;
ti0 = gentypeinfo_533941_839829468((*p0).module, dest0);
{
NIM_BOOL LOC3;
NIM_BOOL LOC5;
TY530811 LOC9;
LOC3 = (NIM_BOOL)0;
LOC3 = (((*dest0).flags &(1U<<((NU)(((Ttypeflag290431) 2))&31U)))!=0);
if (LOC3) goto LA4;
LOC5 = (NIM_BOOL)0;
LOC5 = (((*(*p0).module).flags &(1U<<((NU)(((Codegenflag527025) 5))&7U)))!=0);
if (!(LOC5)) goto LA6;
LOC5 = !((((*dest0).flags &(1U<<((NU)(((Ttypeflag290431) 5))&31U)))!=0));
LA6: ;
LOC3 = LOC5;
LA4: ;
if (!LOC3) goto LA7;
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = a0;
LOC9[1] = ti0;
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_414), LOC9, 2);
}
goto LA1;
LA7: ;
{
Ropeobj177006* LOC11;
Ropeobj177006* cache0;
Ropeobj177006* LOC12;
TY177507 LOC13;
TY533238 LOC14;
LOC11 = (Ropeobj177006*)0;
LOC11 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_129));
(*(*p0).module).labels += ((NI) 1);
LOC12 = (Ropeobj177006*)0;
LOC12 = rope_177401_2381377266(((NI64) ((*(*p0).module).labels)));
cache0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_415), LOC12);
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = cache0;
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_416), LOC13, 1);
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = a0;
LOC14[1] = ti0;
LOC14[2] = cache0;
result0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_417), LOC14, 3);
}
LA1: ;
return result0;
}
N_NIMCALL(void, genof_553201_839829468)(Tcproc527021* p0, Tnode290802* x0, Ttype290840* typ0, Tloc290816* d0) {
Tloc290816 a0;
Ttype290840* dest0;
Ropeobj177006* r0;
Ropeobj177006* nilcheck0;
Ttype290840* t0;
Ttype290840* LOC41;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, x0, (&a0));
dest0 = skiptypes_294099_850551059(typ0, IL64(211106247256320));
r0 = rdloc_536188_839829468(a0);
nilcheck0 = NIM_NIL;
t0 = skiptypes_294099_850551059(a0.t, IL64(211106232576256));
{
while (1) {
Ttype290840* LOC16;
if (!((*t0).kind == ((Ttypekind290244) 23) || (*t0).kind == ((Ttypekind290244) 21) || (*t0).kind == ((Ttypekind290244) 22))) goto LA2;
{
if (!!(((*t0).kind == ((Ttypekind290244) 23)))) goto LA5;
nilcheck0 = r0;
}
LA5: ;
{
NIM_BOOL LOC9;
NIM_BOOL LOC11;
TY177507 LOC15;
LOC9 = (NIM_BOOL)0;
LOC9 = !(((*t0).kind == ((Ttypekind290244) 23)));
if (LOC9) goto LA10;
LOC11 = (NIM_BOOL)0;
LOC11 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC11) goto LA12;
LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA12: ;
LOC9 = !(LOC11);
LA10: ;
if (!LOC9) goto LA13;
memset((void*)LOC15, 0, sizeof(LOC15));
LOC15[0] = r0;
r0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC15, 1);
}
LA13: ;
LOC16 = (Ttype290840*)0;
LOC16 = lastson_293377_850551059(t0);
t0 = skiptypes_294099_850551059(LOC16, IL64(211106232576256));
} LA2: ;
}
{
NIM_BOOL LOC19;
LOC19 = (NIM_BOOL)0;
LOC19 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC19) goto LA20;
LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA20: ;
if (!!(LOC19)) goto LA21;
{
while (1) {
NIM_BOOL LOC25;
TY531289 LOC27;
Ropeobj177006* LOC28;
LOC25 = (NIM_BOOL)0;
LOC25 = ((*t0).kind == ((Ttypekind290244) 17));
if (!(LOC25)) goto LA26;
LOC25 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL));
LA26: ;
if (!LOC25) goto LA24;
memset((void*)LOC27, 0, sizeof(LOC27));
LOC28 = (Ropeobj177006*)0;
LOC28 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_153), LOC27, 0);
add_177482_2381377266(&r0, LOC28);
t0 = skiptypes_294099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360));
} LA24: ;
}
}
LA21: ;
{
NIM_BOOL LOC31;
LOC31 = (NIM_BOOL)0;
LOC31 = isobjlackingtypefield_531513_839829468(t0);
if (!LOC31) goto LA32;
globalerror_194071_155036129((*x0).info, ((Tmsgkind189002) 4), ((NimStringDesc*) &T839829468_412));
}
LA32: ;
{
TY530811 LOC38;
if (!!((nilcheck0 == NIM_NIL))) goto LA36;
memset((void*)LOC38, 0, sizeof(LOC38));
LOC38[0] = nilcheck0;
LOC38[1] = genofhelper_553139_839829468(p0, dest0, r0);
r0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_413), LOC38, 2);
}
goto LA34;
LA36: ;
{
TY177507 LOC40;
memset((void*)LOC40, 0, sizeof(LOC40));
LOC40[0] = genofhelper_553139_839829468(p0, dest0, r0);
r0 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_418), LOC40, 1);
}
LA34: ;
LOC41 = (Ttype290840*)0;
LOC41 = getsystype_336150_3937434831(((Ttypekind290244) 1));
putintodest_548468_839829468(p0, d0, LOC41, r0, a0.s);
}
N_NIMCALL(void, genof_553331_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
genof_553201_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (*(*n0).kindU.S6.sons->data[((NI) 2)]).typ, d0);
}
N_NIMCALL(void, rawgennew_552741_839829468)(Tcproc527021* p0, Tloc290816 a0, Ropeobj177006* sizeexpr_552745_839829468) {
Ropeobj177006* sizeexpr0;
Ttype290840* reftype0;
Tloc290816 b0;
TY533238 args0;
Ttype290840* bt0;
sizeexpr0 = sizeexpr_552745_839829468;
reftype0 = skiptypes_294099_850551059(a0.t, IL64(211106242013440));
memset((void*)(&b0), 0, sizeof(b0));
initloc_530273_839829468((&b0), ((Tlockind290808) 6), a0.t, ((Tstorageloc290812) 3));
{
TY177507 LOC5;
Ttype290840* LOC6;
if (!sizeexpr0 == 0) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC6 = (Ttype290840*)0;
LOC6 = skiptypes_294099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832));
LOC5[0] = gettypedesc_533671_839829468((*p0).module, LOC6);
sizeexpr0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_419), LOC5, 1);
}
LA3: ;
memset((void*)args0, 0, sizeof(args0));
args0[0] = gettypedesc_533671_839829468((*p0).module, reftype0);
args0[1] = gentypeinfo_533941_839829468((*p0).module, reftype0);
args0[2] = sizeexpr0;
{
NIM_BOOL LOC9;
TY530811 LOC21;
LOC9 = (NIM_BOOL)0;
LOC9 = (a0.s == ((Tstorageloc290812) 3));
if (!(LOC9)) goto LA10;
LOC9 = usesnativegc_168177_2607990831();
LA10: ;
if (!LOC9) goto LA11;
{
NIM_BOOL LOC15;
TY177507 LOC18;
LOC15 = (NIM_BOOL)0;
LOC15 = canformacycle_318123_3876443242(a0.t);
if (!LOC15) goto LA16;
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = rdloc_536188_839829468(a0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_420), LOC18, 1);
}
goto LA13;
LA16: ;
{
TY177507 LOC20;
memset((void*)LOC20, 0, sizeof(LOC20));
LOC20[0] = rdloc_536188_839829468(a0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_255), LOC20, 1);
}
LA13: ;
b0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_421), args0, 3);
memset((void*)LOC21, 0, sizeof(LOC21));
LOC21[0] = rdloc_536188_839829468(a0);
LOC21[1] = rdloc_536188_839829468(b0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC21, 2);
}
goto LA7;
LA11: ;
{
b0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_422), args0, 3);
genassignment_537264_839829468(p0, a0, b0, 0);
}
LA7: ;
bt0 = skiptypes_294099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832));
genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), bt0, a0, NIM_FALSE);
}
N_NIMCALL(void, gennew_552782_839829468)(Tcproc527021* p0, Tnode290802* e0) {
Tloc290816 a0;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
{
NI LOC3;
Tloc290816 se0;
Ropeobj177006* LOC6;
LOC3 = (NI)0;
LOC3 = len_291081_850551059(e0);
if (!(LOC3 == ((NI) 3))) goto LA4;
memset((void*)(&se0), 0, sizeof(se0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&se0));
LOC6 = (Ropeobj177006*)0;
LOC6 = rdloc_536188_839829468(se0);
rawgennew_552741_839829468(p0, a0, LOC6);
}
goto LA1;
LA4: ;
{
rawgennew_552741_839829468(p0, a0, NIM_NIL);
}
LA1: ;
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, gennewfinalize_553110_839829468)(Tcproc527021* p0, Tnode290802* e0) {
Tloc290816 a0;
Tloc290816 b0;
Tloc290816 f0;
Ttype290840* reftype0;
Ttype290840* bt0;
Ropeobj177006* ti0;
TY530811 LOC1;
TY533238 LOC2;
Ttype290840* LOC3;
Ttype290840* LOC4;
Ttype290840* LOC5;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
memset((void*)(&f0), 0, sizeof(f0));
reftype0 = (Ttype290840*)0;
bt0 = (Ttype290840*)0;
ti0 = (Ropeobj177006*)0;
reftype0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&f0));
initloc_530273_839829468((&b0), ((Tlockind290808) 6), a0.t, ((Tstorageloc290812) 3));
ti0 = gentypeinfo_533941_839829468((*p0).module, reftype0);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = ti0;
LOC1[1] = rdloc_536188_839829468(f0);
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 14))- 0], ((NimStringDesc*) &T839829468_423), LOC1, 2);
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = gettypedesc_533671_839829468((*p0).module, reftype0);
LOC2[1] = ti0;
LOC3 = (Ttype290840*)0;
LOC3 = lastson_293377_850551059(reftype0);
LOC4 = (Ttype290840*)0;
LOC4 = skiptypes_294099_850551059(LOC3, IL64(211106233624832));
LOC2[2] = gettypedesc_533671_839829468((*p0).module, LOC4);
b0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_424), LOC2, 3);
genassignment_537264_839829468(p0, a0, b0, 0);
LOC5 = (Ttype290840*)0;
LOC5 = lastson_293377_850551059(reftype0);
bt0 = skiptypes_294099_850551059(LOC5, IL64(211106233624832));
genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), bt0, a0, NIM_FALSE);
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, gennewseqaux_552795_839829468)(Tcproc527021* p0, Tloc290816 dest0, Ropeobj177006* length0) {
Ttype290840* seqtype0;
TY533238 args0;
Tloc290816 call0;
seqtype0 = skiptypes_294099_850551059(dest0.t, IL64(211106242013440));
memset((void*)args0, 0, sizeof(args0));
args0[0] = gettypedesc_533671_839829468((*p0).module, seqtype0);
args0[1] = gentypeinfo_533941_839829468((*p0).module, seqtype0);
args0[2] = length0;
memset((void*)(&call0), 0, sizeof(call0));
initloc_530273_839829468((&call0), ((Tlockind290808) 6), dest0.t, ((Tstorageloc290812) 3));
{
NIM_BOOL LOC3;
TY530811 LOC15;
LOC3 = (NIM_BOOL)0;
LOC3 = (dest0.s == ((Tstorageloc290812) 3));
if (!(LOC3)) goto LA4;
LOC3 = usesnativegc_168177_2607990831();
LA4: ;
if (!LOC3) goto LA5;
{
NIM_BOOL LOC9;
TY177507 LOC12;
LOC9 = (NIM_BOOL)0;
LOC9 = canformacycle_318123_3876443242(dest0.t);
if (!LOC9) goto LA10;
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = rdloc_536188_839829468(dest0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_420), LOC12, 1);
}
goto LA7;
LA10: ;
{
TY177507 LOC14;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = rdloc_536188_839829468(dest0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_255), LOC14, 1);
}
LA7: ;
call0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_425), args0, 3);
memset((void*)LOC15, 0, sizeof(LOC15));
LOC15[0] = rdloc_536188_839829468(dest0);
LOC15[1] = rdloc_536188_839829468(call0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC15, 2);
}
goto LA1;
LA5: ;
{
call0.r = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_426), args0, 3);
genassignment_537264_839829468(p0, dest0, call0, 0);
}
LA1: ;
}
N_NIMCALL(void, gennewseq_552824_839829468)(Tcproc527021* p0, Tnode290802* e0) {
Tloc290816 a0;
Tloc290816 b0;
Ropeobj177006* LOC1;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
LOC1 = (Ropeobj177006*)0;
LOC1 = rdloc_536188_839829468(b0);
gennewseqaux_552795_839829468(p0, a0, LOC1);
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, gennewseqofcap_552836_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Ttype290840* seqtype0;
Tloc290816 a0;
TY533238 LOC1;
Ropeobj177006* LOC2;
seqtype0 = skiptypes_294099_850551059((*e0).typ, IL64(211106242013440));
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = gettypedesc_533671_839829468((*p0).module, seqtype0);
LOC1[1] = gentypeinfo_533941_839829468((*p0).module, seqtype0);
LOC1[2] = rdloc_536188_839829468(a0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_427), LOC1, 3);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0));
gcusage_552439_839829468(e0);
}
N_NIMCALL(Ropeobj177006*, getclosuretype_533683_839829468)(Tcgen527027* m0, Ttype290840* t0, Tclosuretypekind533679 kind0) {
Ropeobj177006* result0;
Intset266030 check0;
Ropeobj177006* rettype0;
Ropeobj177006* desc0;
result0 = (Ropeobj177006*)0;
memset((void*)(&check0), 0, sizeof(check0));
chckNil((void*)(&check0));
memset((void*)(&check0), 0, sizeof(check0));
initintset_266885_2627731572((&check0));
result0 = gettempname_531596_839829468(m0);
rettype0 = (Ropeobj177006*)0;
desc0 = (Ropeobj177006*)0;
genprocparams_532115_839829468(m0, t0, &rettype0, &desc0, (&check0), !((kind0 == ((Tclosuretypekind533679) 0))), NIM_FALSE);
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = isimportedtype_531449_839829468(t0);
if (!!(LOC3)) goto LA4;
{
NIM_BOOL LOC8;
TY533235 LOC12;
LOC8 = (NIM_BOOL)0;
LOC8 = !(((*t0).callconv == ((Tcallingconvention290002) 8)));
if (LOC8) goto LA9;
LOC8 = !((kind0 == ((Tclosuretypekind533679) 2)));
LA9: ;
if (!LOC8) goto LA10;
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = rope_177277_2381377266(Callingconvtostr_531585_839829468[((*t0).callconv)- 0]);
LOC12[1] = rettype0;
LOC12[2] = result0;
LOC12[3] = desc0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC12, 4);
}
goto LA6;
LA10: ;
{
TY533238 LOC14;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = result0;
LOC14[1] = rettype0;
LOC14[2] = desc0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC14, 3);
}
LA6: ;
}
LA4: ;
return result0;
}
N_NIMCALL(void, gensomecast_554480_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Ttype290840* etyp0;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
etyp0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832));
{
NIM_BOOL LOC3;
TY530811 LOC7;
Ropeobj177006* LOC8;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*etyp0).kind == ((Ttypekind290244) 18) || (*etyp0).kind == ((Ttypekind290244) 17) || (*etyp0).kind == ((Ttypekind290244) 16) || (*etyp0).kind == ((Ttypekind290244) 27) || (*etyp0).kind == ((Ttypekind290244) 48) || (*etyp0).kind == ((Ttypekind290244) 4));
if (!(LOC3)) goto LA4;
LOC3 = !(((a0.flags &(1U<<((NU)(((Tlocflag290810) 0))&15U)))!=0));
LA4: ;
if (!LOC3) goto LA5;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = gettypedesc_533671_839829468((*p0).module, (*e0).typ);
LOC7[1] = addrloc_536204_839829468(a0);
LOC8 = (Ropeobj177006*)0;
LOC8 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_429), LOC7, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC8, a0.s);
}
goto LA1;
LA5: ;
{
NIM_BOOL LOC10;
TY530811 LOC14;
Ropeobj177006* LOC15;
LOC10 = (NIM_BOOL)0;
LOC10 = ((*etyp0).kind == ((Ttypekind290244) 25));
if (!(LOC10)) goto LA11;
LOC10 = ((*etyp0).callconv == ((Tcallingconvention290002) 8));
LA11: ;
if (!LOC10) goto LA12;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = getclosuretype_533683_839829468((*p0).module, etyp0, ((Tclosuretypekind533679) 1));
LOC14[1] = rdcharloc_536227_839829468(a0);
LOC15 = (Ropeobj177006*)0;
LOC15 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC14, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC15, a0.s);
}
goto LA1;
LA12: ;
{
TY530811 LOC17;
Ropeobj177006* LOC18;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = gettypedesc_533671_839829468((*p0).module, (*e0).typ);
LOC17[1] = rdcharloc_536227_839829468(a0);
LOC18 = (Ropeobj177006*)0;
LOC18 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC17, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC18, a0.s);
}
LA1: ;
}
N_NIMCALL(void, unaryexprchar_549222_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
TY177507 LOC1;
Ropeobj177006* LOC2;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdcharloc_536227_839829468(a0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, genord_554474_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
unaryexprchar_549222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_301));
}
N_NIMCALL(void, genarraylen_553415_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) {
Tnode290802* a0;
Ttype290840* typ0;
a0 = (*e0).kindU.S6.sons->data[((NI) 1)];
{
if (!((*a0).kind == ((Tnodekind290020) 64))) goto LA3;
a0 = (*a0).kindU.S6.sons->data[((NI) 0)];
}
LA3: ;
typ0 = skiptypes_294099_850551059((*a0).typ, IL64(211106240964864));
switch ((*typ0).kind) {
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
{
if (!(op0 == ((Tmagic290524) 8))) goto LA8;
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_431));
}
goto LA6;
LA8: ;
{
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_432));
}
LA6: ;
}
break;
case ((Ttypekind290244) 29):
{
usestringh_530345_839829468((*p0).module);
{
if (!(op0 == ((Tmagic290524) 8))) goto LA14;
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_433));
}
goto LA12;
LA14: ;
{
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_434));
}
LA12: ;
}
break;
case ((Ttypekind290244) 28):
case ((Ttypekind290244) 24):
{
{
NIM_BOOL LOC20;
LOC20 = (NIM_BOOL)0;
LOC20 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC20) goto LA21;
LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA21: ;
if (!!(LOC20)) goto LA22;
{
if (!(op0 == ((Tmagic290524) 8))) goto LA26;
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_435));
}
goto LA24;
LA26: ;
{
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_436));
}
LA24: ;
}
goto LA18;
LA22: ;
{
{
if (!(op0 == ((Tmagic290524) 8))) goto LA32;
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_437));
}
goto LA30;
LA32: ;
{
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_438));
}
LA30: ;
}
LA18: ;
}
break;
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
{
NI64 LOC40;
Ropeobj177006* LOC41;
if (!(op0 == ((Tmagic290524) 8))) goto LA38;
LOC40 = (NI64)0;
LOC40 = lastord_318004_3876443242(typ0);
LOC41 = (Ropeobj177006*)0;
LOC41 = rope_177401_2381377266(LOC40);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC41, ((Tstorageloc290812) 0));
}
goto LA36;
LA38: ;
{
NI64 LOC43;
Ropeobj177006* LOC44;
LOC43 = (NI64)0;
LOC43 = lengthord_318007_3876443242(typ0);
LOC44 = (Ropeobj177006*)0;
LOC44 = rope_177401_2381377266(LOC43);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC44, ((Tstorageloc290812) 0));
}
LA36: ;
}
break;
default:
{
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_439));
}
break;
}
}
N_NIMCALL(void, unarystmt_548527_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
TY177507 LOC5;
memset((void*)(&a0), 0, sizeof(a0));
{
if (!!(((*d0).k == ((Tlockind290808) 0)))) goto LA3;
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_442));
}
LA3: ;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(a0);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC5, 1);
}
N_NIMCALL(void, gensetlengthstr_553632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
binarystmt_548501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_445));
gcusage_552439_839829468(e0);
}
N_NIMCALL(void, gensetlengthseq_553500_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Ttype290840* t0;
NimStringDesc* setlenpattern0;
TY533235 LOC8;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864));
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC3) goto LA4;
LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA4: ;
if (!!(LOC3)) goto LA5;
setlenpattern0 = copyString(((NimStringDesc*) &T839829468_446));
}
goto LA1;
LA5: ;
{
setlenpattern0 = copyString(((NimStringDesc*) &T839829468_447));
}
LA1: ;
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rdloc_536188_839829468(a0);
LOC8[1] = rdloc_536188_839829468(b0);
LOC8[2] = gettypedesc_533671_839829468((*p0).module, t0);
LOC8[3] = gettypedesc_533671_839829468((*p0).module, (*t0).sons->data[((NI) 0)]);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), setlenpattern0, LOC8, 4);
gcusage_552439_839829468(e0);
}
N_NIMCALL(Ropeobj177006*, rdsetelemloc_553662_839829468)(Tloc290816 a0, Ttype290840* settype0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = rdcharloc_536227_839829468(a0);
{
NI64 LOC3;
TY530811 LOC6;
NI64 LOC7;
LOC3 = (NI64)0;
LOC3 = firstord_318001_3876443242(settype0);
if (!!((LOC3 == IL64(0)))) goto LA4;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = result0;
LOC7 = (NI64)0;
LOC7 = firstord_318001_3876443242(settype0);
LOC6[1] = rope_177401_2381377266(LOC7);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_448), LOC6, 2);
}
LA4: ;
return result0;
}
N_NIMCALL(void, binarystmtinexcl_553857_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
Tloc290816 b0;
TY530811 LOC1;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468(a0);
LOC1[1] = rdsetelemloc_553662_839829468(b0, a0.t);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), frmt0, LOC1, 2);
}
N_NIMCALL(void, binaryexprchar_548809_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NimStringDesc* frmt0) {
Tloc290816 a0;
Tloc290816 b0;
TY530811 LOC1;
Ropeobj177006* LOC2;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdcharloc_536227_839829468(a0);
LOC1[1] = rdcharloc_536227_839829468(b0);
LOC2 = (Ropeobj177006*)0;
LOC2 = ropecg_530407_839829468((*p0).module, frmt0, LOC1, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0));
}
N_NIMCALL(NIM_BOOL, fewcmps_553803_839829468)(Tnode290802* s0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
{
if (!!(((*s0).kind == ((Tnodekind290020) 39)))) goto LA3;
internalerror_194100_155036129((*s0).info, ((NimStringDesc*) &T839829468_463));
}
LA3: ;
{
NIM_BOOL LOC7;
NI64 LOC8;
LOC7 = (NIM_BOOL)0;
LOC8 = (NI64)0;
LOC8 = getsize_318135_3876443242((*s0).typ);
LOC7 = (LOC8 <= ((NI64) (intsize_175641_4151366050)));
if (!(LOC7)) goto LA9;
LOC7 = (((*s0).flags &(1U<<((NU)(((Tnodeflag290427) 4))&15U)))!=0);
LA9: ;
if (!LOC7) goto LA10;
result0 = NIM_FALSE;
}
goto LA5;
LA10: ;
{
Ttype290840* LOC13;
LOC13 = (Ttype290840*)0;
LOC13 = elemtype_318394_3876443242((*s0).typ);
if (!((*LOC13).kind == ((Ttypekind290244) 31) || (*LOC13).kind >= ((Ttypekind290244) 33) && (*LOC13).kind <= ((Ttypekind290244) 35))) goto LA14;
result0 = NIM_TRUE;
}
goto LA5;
LA14: ;
{
NI LOC17;
LOC17 = (NI)0;
LOC17 = sonslen_293351_850551059(s0);
result0 = (LOC17 <= ((NI) 8));
}
LA5: ;
return result0;
}
N_NIMCALL(void, binaryexprin_553837_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0, NimStringDesc* frmt0) {
TY530811 LOC1;
Ropeobj177006* LOC2;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468((*a0));
LOC1[1] = rdsetelemloc_553662_839829468((*b0), (*a0).t);
LOC2 = (Ropeobj177006*)0;
LOC2 = HEX25_177905_2381377266(frmt0, LOC1, 2);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc290812) 0));
}
N_NIMCALL(void, geninexpraux_551496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* a0, Tloc290816* b0, Tloc290816* d0) {
Ttype290840* LOC1;
NI64 LOC2;
LOC1 = (Ttype290840*)0;
LOC1 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864));
LOC2 = (NI64)0;
LOC2 = getsize_318135_3876443242(LOC1);
switch (((NI) (LOC2))) {
case ((NI) 1):
{
binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_467));
}
break;
case ((NI) 2):
{
binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_468));
}
break;
case ((NI) 4):
{
binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_469));
}
break;
case ((NI) 8):
{
binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_470));
}
break;
default:
{
binaryexprin_553837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_471));
}
break;
}
}
N_NIMCALL(void, geninop_554009_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Tloc290816 x0;
Tloc290816 y0;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
memset((void*)(&x0), 0, sizeof(x0));
memset((void*)(&y0), 0, sizeof(y0));
{
NIM_BOOL LOC3;
Tnode290802* ea0;
NI length0;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind290020) 39));
if (!(LOC3)) goto LA4;
LOC3 = fewcmps_553803_839829468((*e0).kindU.S6.sons->data[((NI) 1)]);
LA4: ;
if (!LOC3) goto LA5;
{
if (!((*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 70) || (*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 69))) goto LA9;
ea0 = (*(*e0).kindU.S6.sons->data[((NI) 2)]).kindU.S6.sons->data[((NI) 0)];
}
goto LA7;
LA9: ;
{
ea0 = (*e0).kindU.S6.sons->data[((NI) 2)];
}
LA7: ;
initlocexpr_537283_839829468(p0, ea0, (&a0));
initloc_530273_839829468((&b0), ((Tlockind290808) 6), (*e0).typ, ((Tstorageloc290812) 0));
b0.r = rope_177277_2381377266(((NimStringDesc*) &T839829468_118));
length0 = sonslen_293351_850551059((*e0).kindU.S6.sons->data[((NI) 1)]);
{
NI i_554061_839829468;
NI HEX3Atmp_554412_839829468;
NI res_554415_839829468;
i_554061_839829468 = (NI)0;
HEX3Atmp_554412_839829468 = (NI)0;
HEX3Atmp_554412_839829468 = (NI)(length0 - ((NI) 1));
res_554415_839829468 = ((NI) 0);
{
while (1) {
if (!(res_554415_839829468 <= HEX3Atmp_554412_839829468)) goto LA14;
i_554061_839829468 = res_554415_839829468;
{
TY533238 LOC19;
if (!((*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468]).kind == ((Tnodekind290020) 44))) goto LA17;
initlocexpr_537283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0));
initlocexpr_537283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0));
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = rdcharloc_536227_839829468(a0);
LOC19[1] = rdcharloc_536227_839829468(x0);
LOC19[2] = rdcharloc_536227_839829468(y0);
addf_178205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_464), LOC19, 3);
}
goto LA15;
LA17: ;
{
TY530811 LOC21;
initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_554061_839829468], (&x0));
memset((void*)LOC21, 0, sizeof(LOC21));
LOC21[0] = rdcharloc_536227_839829468(a0);
LOC21[1] = rdcharloc_536227_839829468(x0);
addf_178205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_465), LOC21, 2);
}
LA15: ;
{
if (!(i_554061_839829468 < (NI)(length0 - ((NI) 1)))) goto LA24;
add_177487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_466));
}
LA24: ;
res_554415_839829468 += ((NI) 1);
} LA14: ;
}
}
add_177487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_117));
putintodest_548468_839829468(p0, d0, (*e0).typ, b0.r, ((Tstorageloc290812) 0));
}
goto LA1;
LA5: ;
{
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
geninexpraux_551496_839829468(p0, e0, (&a0), (&b0), d0);
}
LA1: ;
}
N_NIMCALL(void, gensetop_554419_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) {
Tloc290816 a0;
Tloc290816 b0;
Tloc290816 i0;
Ttype290840* settype0;
NI size0;
NI64 LOC1;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
memset((void*)(&i0), 0, sizeof(i0));
settype0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864));
LOC1 = (NI64)0;
LOC1 = getsize_318135_3876443242(settype0);
size0 = ((NI) (LOC1));
switch (size0) {
case ((NI) 1):
case ((NI) 2):
case ((NI) 4):
case ((NI) 8):
{
switch (op0) {
case ((Tmagic290524) 39):
{
NimStringDesc* ts0;
NimStringDesc* LOC4;
NimStringDesc* LOC5;
NimStringDesc* LOC6;
LOC4 = (NimStringDesc*)0;
LOC5 = (NimStringDesc*)0;
LOC5 = nimIntToStr((NI)(size0 * ((NI) 8)));
LOC4 = rawNewString(LOC5->Sup.len + 2);
appendString(LOC4, ((NimStringDesc*) &T839829468_45));
appendString(LOC4, LOC5);
ts0 = LOC4;
LOC6 = (NimStringDesc*)0;
LOC6 = rawNewString(ts0->Sup.len + ts0->Sup.len + 35);
appendString(LOC6, ((NimStringDesc*) &T839829468_449));
appendString(LOC6, ts0);
appendString(LOC6, ((NimStringDesc*) &T839829468_450));
appendString(LOC6, ts0);
appendString(LOC6, ((NimStringDesc*) &T839829468_451));
binarystmtinexcl_553857_839829468(p0, e0, d0, LOC6);
}
break;
case ((Tmagic290524) 40):
{
NimStringDesc* ts0;
NimStringDesc* LOC8;
NimStringDesc* LOC9;
NimStringDesc* LOC10;
LOC8 = (NimStringDesc*)0;
LOC9 = (NimStringDesc*)0;
LOC9 = nimIntToStr((NI)(size0 * ((NI) 8)));
LOC8 = rawNewString(LOC9->Sup.len + 2);
appendString(LOC8, ((NimStringDesc*) &T839829468_45));
appendString(LOC8, LOC9);
ts0 = LOC8;
LOC10 = (NimStringDesc*)0;
LOC10 = rawNewString(ts0->Sup.len + ts0->Sup.len + 42);
appendString(LOC10, ((NimStringDesc*) &T839829468_452));
appendString(LOC10, ts0);
appendString(LOC10, ((NimStringDesc*) &T839829468_453));
appendString(LOC10, ts0);
appendString(LOC10, ((NimStringDesc*) &T839829468_454));
binarystmtinexcl_553857_839829468(p0, e0, d0, LOC10);
}
break;
case ((Tmagic290524) 41):
{
{
if (!(size0 <= ((NI) 4))) goto LA14;
unaryexprchar_549222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_455));
}
goto LA12;
LA14: ;
{
unaryexprchar_549222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_456));
}
LA12: ;
}
break;
case ((Tmagic290524) 133):
{
binaryexprchar_548809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_457));
}
break;
case ((Tmagic290524) 132):
{
binaryexprchar_548809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_458));
}
break;
case ((Tmagic290524) 131):
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341));
}
break;
case ((Tmagic290524) 134):
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_459));
}
break;
case ((Tmagic290524) 135):
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_460));
}
break;
case ((Tmagic290524) 136):
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_461));
}
break;
case ((Tmagic290524) 137):
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_462));
}
break;
case ((Tmagic290524) 148):
{
geninop_554009_839829468(p0, e0, d0);
}
break;
default:
{
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_472));
}
break;
}
}
break;
default:
{
switch (op0) {
case ((Tmagic290524) 39):
{
binarystmtinexcl_553857_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_473));
}
break;
case ((Tmagic290524) 40):
{
binarystmtinexcl_553857_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_474));
}
break;
case ((Tmagic290524) 41):
{
NimStringDesc* LOC30;
NimStringDesc* LOC31;
LOC30 = (NimStringDesc*)0;
LOC31 = (NimStringDesc*)0;
LOC31 = nimIntToStr(size0);
LOC30 = rawNewString(LOC31->Sup.len + 14);
appendString(LOC30, ((NimStringDesc*) &T839829468_475));
appendString(LOC30, LOC31);
appendChar(LOC30, 41);
unaryexprchar_549222_839829468(p0, e0, d0, LOC30);
}
break;
case ((Tmagic290524) 133):
case ((Tmagic290524) 132):
{
Ttype290840* LOC33;
TY534475 LOC39;
LOC33 = (Ttype290840*)0;
LOC33 = getsystype_336150_3937434831(((Ttypekind290244) 31));
gettemp_535032_839829468(p0, LOC33, (&i0), NIM_FALSE);
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
{
Ttype290840* LOC38;
if (!((*d0).k == ((Tlockind290808) 0))) goto LA36;
LOC38 = (Ttype290840*)0;
LOC38 = getsystype_336150_3937434831(((Ttypekind290244) 1));
gettemp_535032_839829468(p0, LOC38, d0, NIM_FALSE);
}
LA36: ;
memset((void*)LOC39, 0, sizeof(LOC39));
LOC39[0] = rdloc_536188_839829468(i0);
LOC39[1] = rope_177401_2381377266(((NI64) (size0)));
LOC39[2] = rdloc_536188_839829468((*d0));
LOC39[3] = rdloc_536188_839829468(a0);
LOC39[4] = rdloc_536188_839829468(b0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), lookupopr_554426_839829468[(op0)- 132], LOC39, 5);
}
break;
case ((Tmagic290524) 131):
{
NimStringDesc* LOC41;
NimStringDesc* LOC42;
usestringh_530345_839829468((*p0).module);
LOC41 = (NimStringDesc*)0;
LOC42 = (NimStringDesc*)0;
LOC42 = nimIntToStr(size0);
LOC41 = rawNewString(LOC42->Sup.len + 21);
appendString(LOC41, ((NimStringDesc*) &T839829468_481));
appendString(LOC41, LOC42);
appendString(LOC41, ((NimStringDesc*) &T839829468_482));
binaryexprchar_548809_839829468(p0, e0, d0, LOC41);
}
break;
case ((Tmagic290524) 134):
case ((Tmagic290524) 135):
case ((Tmagic290524) 136):
case ((Tmagic290524) 137):
{
Ttype290840* LOC44;
TY534847 LOC49;
LOC44 = (Ttype290840*)0;
LOC44 = getsystype_336150_3937434831(((Ttypekind290244) 31));
gettemp_535032_839829468(p0, LOC44, (&i0), NIM_FALSE);
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA47;
gettemp_535032_839829468(p0, a0.t, d0, NIM_FALSE);
}
LA47: ;
memset((void*)LOC49, 0, sizeof(LOC49));
LOC49[0] = rdloc_536188_839829468(i0);
LOC49[1] = rope_177401_2381377266(((NI64) (size0)));
LOC49[2] = rdloc_536188_839829468((*d0));
LOC49[3] = rdloc_536188_839829468(a0);
LOC49[4] = rdloc_536188_839829468(b0);
LOC49[5] = rope_177277_2381377266(lookupopr_554426_839829468[(op0)- 132]);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_483), LOC49, 6);
}
break;
case ((Tmagic290524) 148):
{
geninop_554009_839829468(p0, e0, d0);
}
break;
default:
{
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_484));
}
break;
}
}
break;
}
}
static N_INLINE(Ropeobj177006*, genargstringtocstring_537776_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
Tloc290816 a0;
TY177507 LOC1;
result0 = (Ropeobj177006*)0;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468(a0);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_485), LOC1, 1);
return result0;
}
N_NIMCALL(Ropeobj177006*, openarrayloc_537665_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
Tloc290816 a0;
Tnode290802* q0;
result0 = (Ropeobj177006*)0;
memset((void*)(&a0), 0, sizeof(a0));
q0 = skipconv_326882_3876443242(n0);
{
Tmagic290524 LOC3;
Tloc290816 b0;
Tloc290816 c0;
Tnode290802* LOC6;
Tnode290802* LOC7;
Tnode290802* LOC8;
NimStringDesc* fmt0;
Ttype290840* LOC9;
TY533238 LOC25;
LOC3 = (Tmagic290524)0;
LOC3 = getmagic_316502_2616423590(q0);
if (!(LOC3 == ((Tmagic290524) 139))) goto LA4;
memset((void*)(&b0), 0, sizeof(b0));
memset((void*)(&c0), 0, sizeof(c0));
LOC6 = (Tnode290802*)0;
LOC6 = HEX5BHEX5D_291238_850551059(q0, ((NI) 1));
initlocexpr_537283_839829468(p0, LOC6, (&a0));
LOC7 = (Tnode290802*)0;
LOC7 = HEX5BHEX5D_291238_850551059(q0, ((NI) 2));
initlocexpr_537283_839829468(p0, LOC7, (&b0));
LOC8 = (Tnode290802*)0;
LOC8 = HEX5BHEX5D_291238_850551059(q0, ((NI) 3));
initlocexpr_537283_839829468(p0, LOC8, (&c0));
LOC9 = (Ttype290840*)0;
LOC9 = skiptypes_294099_850551059(a0.t, IL64(211106243062016));
switch ((*LOC9).kind) {
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
fmt0 = copyString(((NimStringDesc*) &T839829468_486));
}
break;
case ((Ttypekind290244) 28):
case ((Ttypekind290244) 24):
{
{
NIM_BOOL LOC14;
Ttype290840* LOC15;
NIM_BOOL LOC17;
LOC14 = (NIM_BOOL)0;
LOC15 = (Ttype290840*)0;
LOC15 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256));
LOC14 = ((*LOC15).kind == ((Ttypekind290244) 23));
if (!(LOC14)) goto LA16;
LOC17 = (NIM_BOOL)0;
LOC17 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC17) goto LA18;
LOC17 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA18: ;
LOC14 = !(LOC17);
LA16: ;
if (!LOC14) goto LA19;
fmt0 = copyString(((NimStringDesc*) &T839829468_487));
}
goto LA12;
LA19: ;
{
fmt0 = copyString(((NimStringDesc*) &T839829468_488));
}
LA12: ;
}
break;
default:
{
NimStringDesc* LOC23;
NimStringDesc* LOC24;
LOC23 = (NimStringDesc*)0;
LOC24 = (NimStringDesc*)0;
LOC24 = typetostring_318017_3876443242(a0.t, ((Tprefereddesc318011) 0));
LOC23 = rawNewString(LOC24->Sup.len + 14);
appendString(LOC23, ((NimStringDesc*) &T839829468_489));
appendString(LOC23, LOC24);
internalerror_194113_155036129(LOC23);
fmt0 = copyString(((NimStringDesc*) &T839829468_490));
}
break;
}
memset((void*)LOC25, 0, sizeof(LOC25));
LOC25[0] = rdloc_536188_839829468(a0);
LOC25[1] = rdloc_536188_839829468(b0);
LOC25[2] = rdloc_536188_839829468(c0);
result0 = HEX25_177905_2381377266(fmt0, LOC25, 3);
}
goto LA1;
LA4: ;
{
Ttype290840* LOC27;
initlocexpr_537283_839829468(p0, n0, (&a0));
LOC27 = (Ttype290840*)0;
LOC27 = skiptypes_294099_850551059(a0.t, IL64(211106240964864));
switch ((*LOC27).kind) {
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
TY177507 LOC29;
memset((void*)LOC29, 0, sizeof(LOC29));
LOC29[0] = rdloc_536188_839829468(a0);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_378), LOC29, 1);
}
break;
case ((Ttypekind290244) 28):
case ((Ttypekind290244) 24):
{
{
NIM_BOOL LOC33;
Ttype290840* LOC34;
NIM_BOOL LOC36;
TY530811 LOC40;
LOC33 = (NIM_BOOL)0;
LOC34 = (Ttype290840*)0;
LOC34 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256));
LOC33 = ((*LOC34).kind == ((Ttypekind290244) 23));
if (!(LOC33)) goto LA35;
LOC36 = (NIM_BOOL)0;
LOC36 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC36) goto LA37;
LOC36 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA37: ;
LOC33 = !(LOC36);
LA35: ;
if (!LOC33) goto LA38;
memset((void*)LOC40, 0, sizeof(LOC40));
LOC40[0] = rdloc_536188_839829468(a0);
LOC40[1] = lenfield_537305_839829468(p0);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_491), LOC40, 2);
}
goto LA31;
LA38: ;
{
TY530811 LOC42;
memset((void*)LOC42, 0, sizeof(LOC42));
LOC42[0] = rdloc_536188_839829468(a0);
LOC42[1] = lenfield_537305_839829468(p0);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_379), LOC42, 2);
}
LA31: ;
}
break;
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
TY530811 LOC44;
NI64 LOC45;
memset((void*)LOC44, 0, sizeof(LOC44));
LOC44[0] = rdloc_536188_839829468(a0);
LOC45 = (NI64)0;
LOC45 = lengthord_318007_3876443242(a0.t);
LOC44[1] = rope_177401_2381377266(LOC45);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_380), LOC44, 2);
}
break;
case ((Ttypekind290244) 21):
case ((Ttypekind290244) 22):
{
Ttype290840* LOC47;
LOC47 = (Ttype290840*)0;
LOC47 = lastson_293377_850551059(a0.t);
switch ((*LOC47).kind) {
case ((Ttypekind290244) 28):
case ((Ttypekind290244) 24):
{
TY530811 LOC49;
memset((void*)LOC49, 0, sizeof(LOC49));
LOC49[0] = rdloc_536188_839829468(a0);
LOC49[1] = lenfield_537305_839829468(p0);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_491), LOC49, 2);
}
break;
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
TY530811 LOC51;
Ttype290840* LOC52;
NI64 LOC53;
memset((void*)LOC51, 0, sizeof(LOC51));
LOC51[0] = rdloc_536188_839829468(a0);
LOC52 = (Ttype290840*)0;
LOC52 = lastson_293377_850551059(a0.t);
LOC53 = (NI64)0;
LOC53 = lengthord_318007_3876443242(LOC52);
LOC51[1] = rope_177401_2381377266(LOC53);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_380), LOC51, 2);
}
break;
default:
{
NimStringDesc* LOC55;
NimStringDesc* LOC56;
LOC55 = (NimStringDesc*)0;
LOC56 = (NimStringDesc*)0;
LOC56 = typetostring_318017_3876443242(a0.t, ((Tprefereddesc318011) 0));
LOC55 = rawNewString(LOC56->Sup.len + 14);
appendString(LOC55, ((NimStringDesc*) &T839829468_489));
appendString(LOC55, LOC56);
internalerror_194113_155036129(LOC55);
}
break;
}
}
break;
default:
{
NimStringDesc* LOC58;
NimStringDesc* LOC59;
LOC58 = (NimStringDesc*)0;
LOC59 = (NimStringDesc*)0;
LOC59 = typetostring_318017_3876443242(a0.t, ((Tprefereddesc318011) 0));
LOC58 = rawNewString(LOC59->Sup.len + 14);
appendString(LOC58, ((NimStringDesc*) &T839829468_489));
appendString(LOC58, LOC59);
internalerror_194113_155036129(LOC58);
}
break;
}
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, genarg_537787_839829468)(Tcproc527021* p0, Tnode290802* n_537790_839829468, Tsym290834* param0, Tnode290802* call0) {
Ropeobj177006* result0;
Tloc290816 a0;
result0 = (Ropeobj177006*)0;
memset((void*)(&a0), 0, sizeof(a0));
{
if (!((*n_537790_839829468).kind == ((Tnodekind290020) 71))) goto LA3;
result0 = genargstringtocstring_537776_839829468(p0, n_537790_839829468);
}
goto LA1;
LA3: ;
{
Ttype290840* LOC6;
Tnode290802* n0;
LOC6 = (Ttype290840*)0;
LOC6 = skiptypes_294099_850551059((*param0).typ, IL64(211106240964864));
if (!((*LOC6).kind == ((Ttypekind290244) 27) || (*LOC6).kind == ((Ttypekind290244) 48))) goto LA7;
{
if (!!(((*n_537790_839829468).kind == ((Tnodekind290020) 64)))) goto LA11;
n0 = n_537790_839829468;
}
goto LA9;
LA11: ;
{
n0 = (*n_537790_839829468).kindU.S6.sons->data[((NI) 0)];
}
LA9: ;
result0 = openarrayloc_537665_839829468(p0, n0);
}
goto LA1;
LA7: ;
{
NIM_BOOL LOC15;
LOC15 = (NIM_BOOL)0;
LOC15 = ccgintroducedptr_531609_839829468(param0);
if (!LOC15) goto LA16;
initlocexpr_537283_839829468(p0, n_537790_839829468, (&a0));
result0 = addrloc_536204_839829468(a0);
}
goto LA1;
LA16: ;
{
NIM_BOOL LOC19;
NIM_BOOL LOC20;
NIM_BOOL LOC21;
Tnode290802* callee0;
LOC19 = (NIM_BOOL)0;
LOC20 = (NIM_BOOL)0;
LOC21 = (NIM_BOOL)0;
LOC21 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC21) goto LA22;
LOC21 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA22: ;
LOC20 = LOC21;
if (!(LOC20)) goto LA23;
LOC20 = ((*(*param0).typ).kind == ((Ttypekind290244) 23));
LA23: ;
LOC19 = LOC20;
if (!(LOC19)) goto LA24;
LOC19 = ((*n_537790_839829468).kind == ((Tnodekind290020) 64));
LA24: ;
if (!LOC19) goto LA25;
initlocexprsingleuse_537289_839829468(p0, (*n_537790_839829468).kindU.S6.sons->data[((NI) 0)], (&a0));
callee0 = (*call0).kindU.S6.sons->data[((NI) 0)];
{
NIM_BOOL LOC29;
NIM_BOOL LOC30;
LOC29 = (NIM_BOOL)0;
LOC30 = (NIM_BOOL)0;
LOC30 = ((*callee0).kind == ((Tnodekind290020) 3));
if (!(LOC30)) goto LA31;
LOC30 = ((134283296 & (*(*callee0).kindU.S4.sym).flags) == 32);
LA31: ;
LOC29 = LOC30;
if (!(LOC29)) goto LA32;
LOC29 = !(((72 & (*(*callee0).kindU.S4.sym).loc.flags) == 0));
LA32: ;
if (!LOC29) goto LA33;
result0 = addrloc_536204_839829468(a0);
}
goto LA27;
LA33: ;
{
result0 = rdloc_536188_839829468(a0);
}
LA27: ;
}
goto LA1;
LA25: ;
{
initlocexprsingleuse_537289_839829468(p0, n_537790_839829468, (&a0));
result0 = rdloc_536188_839829468(a0);
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, genargnoparam_537938_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
Tloc290816 a0;
result0 = (Ropeobj177006*)0;
memset((void*)(&a0), 0, sizeof(a0));
{
if (!((*n0).kind == ((Tnodekind290020) 71))) goto LA3;
result0 = genargstringtocstring_537776_839829468(p0, n0);
}
goto LA1;
LA3: ;
{
initlocexprsingleuse_537289_839829468(p0, n0, (&a0));
result0 = rdloc_536188_839829468(a0);
}
LA1: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, getrawproctype_538459_839829468)(Tcproc527021* p0, Ttype290840* t0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = getclosuretype_533683_839829468((*p0).module, t0, ((Tclosuretypekind533679) 0));
return result0;
}
N_NIMCALL(NIM_BOOL, leftappearsonrightside_537329_839829468)(Tnode290802* le0, Tnode290802* ri0) {
NIM_BOOL result0;
{ result0 = (NIM_BOOL)0;
{
if (!!((le0 == NIM_NIL))) goto LA3;
{
NI i_537364_839829468;
NI HEX3Atmp_537376_839829468;
NI LOC6;
NI res_537379_839829468;
i_537364_839829468 = (NI)0;
HEX3Atmp_537376_839829468 = (NI)0;
LOC6 = (NI)0;
LOC6 = len_291081_850551059(ri0);
HEX3Atmp_537376_839829468 = (LOC6 - 1);
res_537379_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* r0;
if (!(res_537379_839829468 <= HEX3Atmp_537376_839829468)) goto LA8;
i_537364_839829468 = res_537379_839829468;
r0 = HEX5BHEX5D_291238_850551059(ri0, i_537364_839829468);
{
Tanalysisresult471003 LOC11;
LOC11 = (Tanalysisresult471003)0;
LOC11 = ispartof_471340_788060399(le0, r0);
if (!!((LOC11 == ((Tanalysisresult471003) 0)))) goto LA12;
result0 = NIM_TRUE;
goto BeforeRet;
}
LA12: ;
res_537379_839829468 += ((NI) 1);
} LA8: ;
}
}
}
LA3: ;
}BeforeRet: ;
return result0;
}
static N_INLINE(NIM_BOOL, hasnoinit_537383_839829468)(Tnode290802* call0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC1 = ((*(*call0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC1)) goto LA2;
LOC1 = (((*(*(*call0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0);
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, resetloc_536350_839829468)(Tcproc527021* p0, Tloc290816* loc0) {
NIM_BOOL containsgcref0;
Ttype290840* typ0;
{ containsgcref0 = containsgarbagecollectedref_318117_3876443242((*loc0).t);
typ0 = skiptypes_294099_850551059((*loc0).t, IL64(211106242013440));
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = isimportedcpptype_531476_839829468(typ0);
if (!LOC3) goto LA4;
goto BeforeRet;
}
LA4: ;
{
NIM_BOOL LOC8;
LOC8 = (NIM_BOOL)0;
LOC8 = iscomplexvaluetype_536317_839829468(typ0);
if (!!(LOC8)) goto LA9;
{
Tloc290816 nilloc0;
if (!containsgcref0) goto LA13;
memset((void*)(&nilloc0), 0, sizeof(nilloc0));
initloc_530273_839829468((&nilloc0), ((Tlockind290808) 1), (*loc0).t, ((Tstorageloc290812) 2));
nilloc0.r = rope_177277_2381377266(((NimStringDesc*) &T839829468_174));
genrefassign_536311_839829468(p0, (*loc0), nilloc0, 8);
}
goto LA11;
LA13: ;
{
TY177507 LOC16;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rdloc_536188_839829468((*loc0));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_494), LOC16, 1);
}
LA11: ;
}
goto LA6;
LA9: ;
{
{
TY177507 LOC22;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 6))&31U)))!=0)) goto LA20;
memset((void*)LOC22, 0, sizeof(LOC22));
LOC22[0] = addrloc_536204_839829468((*loc0));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_495), LOC22, 1);
}
LA20: ;
{
TY530811 LOC27;
if (!!(((*loc0).s == ((Tstorageloc290812) 2)))) goto LA25;
memset((void*)LOC27, 0, sizeof(LOC27));
LOC27[0] = addrloc_536204_839829468((*loc0));
LOC27[1] = gentypeinfo_533941_839829468((*p0).module, (*loc0).t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_496), LOC27, 2);
genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), (*loc0).t, (*loc0), NIM_TRUE);
}
goto LA23;
LA25: ;
{
TY530811 LOC29;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC29, 0, sizeof(LOC29));
LOC29[0] = addrloc_536204_839829468((*loc0));
LOC29[1] = rdloc_536188_839829468((*loc0));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_152), LOC29, 2);
genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 2), (*loc0).t, (*loc0), NIM_TRUE);
}
LA23: ;
}
LA6: ;
}BeforeRet: ;
}
N_NIMCALL(Ropeobj177006*, addcomma_538464_839829468)(Ropeobj177006* r0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
if (!(r0 == NIM_NIL)) goto LA3;
result0 = r0;
}
goto LA1;
LA3: ;
{
TY531289 LOC6;
Ropeobj177006* LOC7;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC7 = (Ropeobj177006*)0;
LOC7 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC6, 0);
result0 = HEX26_177418_2381377266(r0, LOC7);
}
LA1: ;
return result0;
}
N_NIMCALL(void, genclosurecall_538452_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) {
Tloc290816 op0;
Ropeobj177006* pl0;
Ttype290840* typ0;
NI length0;
Ropeobj177006* rawproc0;
NimStringDesc* callpattern0;
memset((void*)(&op0), 0, sizeof(op0));
initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0));
pl0 = (Ropeobj177006*)0;
typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
length0 = sonslen_293351_850551059(ri0);
{
NI i_538613_839829468;
NI HEX3Atmp_539214_839829468;
NI res_539217_839829468;
i_538613_839829468 = (NI)0;
HEX3Atmp_539214_839829468 = (NI)0;
HEX3Atmp_539214_839829468 = (NI)(length0 - ((NI) 1));
res_539217_839829468 = ((NI) 1);
{
while (1) {
if (!(res_539217_839829468 <= HEX3Atmp_539214_839829468)) goto LA3;
i_538613_839829468 = res_539217_839829468;
{
NI LOC6;
Tnode290802* paramtype0;
LOC6 = (NI)0;
LOC6 = sonslen_293327_850551059(typ0);
if (!(i_538613_839829468 < LOC6)) goto LA7;
paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_538613_839829468];
{
NIM_BOOL LOC11;
Ropeobj177006* LOC20;
LOC11 = (NIM_BOOL)0;
LOC11 = iscompiletimeonly_326706_3876443242((*paramtype0).typ);
if (!!(LOC11)) goto LA12;
{
TY531289 LOC18;
Ropeobj177006* LOC19;
if (!!((pl0 == NIM_NIL))) goto LA16;
memset((void*)LOC18, 0, sizeof(LOC18));
LOC19 = (Ropeobj177006*)0;
LOC19 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0);
add_177482_2381377266(&pl0, LOC19);
}
LA16: ;
LOC20 = (Ropeobj177006*)0;
LOC20 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[i_538613_839829468], (*paramtype0).kindU.S4.sym, ri0);
add_177482_2381377266(&pl0, LOC20);
}
LA12: ;
}
goto LA4;
LA7: ;
{
Ropeobj177006* LOC28;
{
TY531289 LOC26;
Ropeobj177006* LOC27;
if (!!((pl0 == NIM_NIL))) goto LA24;
memset((void*)LOC26, 0, sizeof(LOC26));
LOC27 = (Ropeobj177006*)0;
LOC27 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0);
add_177482_2381377266(&pl0, LOC27);
}
LA24: ;
LOC28 = (Ropeobj177006*)0;
LOC28 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i_538613_839829468]);
add_177482_2381377266(&pl0, LOC28);
}
LA4: ;
res_539217_839829468 += ((NI) 1);
} LA3: ;
}
}
rawproc0 = getrawproctype_538459_839829468(p0, typ0);
{
if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 14))&31U)))!=0)) goto LA31;
callpattern0 = copyString(((NimStringDesc*) &T839829468_492));
}
goto LA29;
LA31: ;
{
callpattern0 = copyString(((NimStringDesc*) &T839829468_493));
}
LA29: ;
{
if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA36;
{
NIM_BOOL LOC40;
LOC40 = (NIM_BOOL)0;
LOC40 = isinvalidreturntype_531548_839829468((*typ0).sons->data[((NI) 0)]);
if (!LOC40) goto LA41;
{
NI LOC45;
TY531289 LOC48;
Ropeobj177006* LOC49;
LOC45 = (NI)0;
LOC45 = sonslen_293351_850551059(ri0);
if (!(((NI) 1) < LOC45)) goto LA46;
memset((void*)LOC48, 0, sizeof(LOC48));
LOC49 = (Ropeobj177006*)0;
LOC49 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC48, 0);
add_177482_2381377266(&pl0, LOC49);
}
LA46: ;
{
NIM_BOOL LOC52;
NIM_BOOL LOC54;
Ropeobj177006* LOC67;
NimStringDesc* LOC68;
TY533235 LOC69;
LOC52 = (NIM_BOOL)0;
LOC52 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0);
if (LOC52) goto LA53;
LOC54 = (NIM_BOOL)0;
LOC54 = leftappearsonrightside_537329_839829468(le0, ri0);
LOC52 = !(LOC54);
LA53: ;
if (!LOC52) goto LA55;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA59;
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE);
}
goto LA57;
LA59: ;
{
NIM_BOOL LOC62;
NIM_BOOL LOC64;
LOC62 = (NIM_BOOL)0;
LOC62 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0));
if (!(LOC62)) goto LA63;
LOC64 = (NIM_BOOL)0;
LOC64 = hasnoinit_537383_839829468(ri0);
LOC62 = !(LOC64);
LA63: ;
if (!LOC62) goto LA65;
resetloc_536350_839829468(p0, d0);
}
goto LA57;
LA65: ;
LA57: ;
LOC67 = (Ropeobj177006*)0;
LOC67 = addrloc_536204_839829468((*d0));
add_177482_2381377266(&pl0, LOC67);
LOC68 = (NimStringDesc*)0;
LOC68 = rawNewString(callpattern0->Sup.len + 3);
appendString(LOC68, callpattern0);
appendString(LOC68, ((NimStringDesc*) &T839829468_497));
memset((void*)LOC69, 0, sizeof(LOC69));
LOC69[0] = op0.r;
LOC69[1] = pl0;
LOC69[2] = addcomma_538464_839829468(pl0);
LOC69[3] = rawproc0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC68, LOC69, 4);
}
goto LA50;
LA55: ;
{
Tloc290816 tmp0;
Ropeobj177006* LOC71;
NimStringDesc* LOC72;
TY533235 LOC73;
memset((void*)(&tmp0), 0, sizeof(tmp0));
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE);
LOC71 = (Ropeobj177006*)0;
LOC71 = addrloc_536204_839829468(tmp0);
add_177482_2381377266(&pl0, LOC71);
LOC72 = (NimStringDesc*)0;
LOC72 = rawNewString(callpattern0->Sup.len + 3);
appendString(LOC72, callpattern0);
appendString(LOC72, ((NimStringDesc*) &T839829468_497));
memset((void*)LOC73, 0, sizeof(LOC73));
LOC73[0] = op0.r;
LOC73[1] = pl0;
LOC73[2] = addcomma_538464_839829468(pl0);
LOC73[3] = rawproc0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC72, LOC73, 4);
genassignment_537264_839829468(p0, (*d0), tmp0, 0);
}
LA50: ;
}
goto LA38;
LA41: ;
{
Tloc290816 list0;
TY533235 LOC79;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA77;
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE);
}
LA77: ;
memset((void*)(&list0), 0, sizeof(list0));
initloc_530273_839829468((&list0), ((Tlockind290808) 9), (*d0).t, ((Tstorageloc290812) 0));
memset((void*)LOC79, 0, sizeof(LOC79));
LOC79[0] = op0.r;
LOC79[1] = pl0;
LOC79[2] = addcomma_538464_839829468(pl0);
LOC79[3] = rawproc0;
list0.r = HEX25_177905_2381377266(callpattern0, LOC79, 4);
genassignment_537264_839829468(p0, (*d0), list0, 0);
}
LA38: ;
}
goto LA34;
LA36: ;
{
NimStringDesc* LOC81;
TY533235 LOC82;
LOC81 = (NimStringDesc*)0;
LOC81 = rawNewString(callpattern0->Sup.len + 3);
appendString(LOC81, callpattern0);
appendString(LOC81, ((NimStringDesc*) &T839829468_497));
memset((void*)LOC82, 0, sizeof(LOC82));
LOC82[0] = op0.r;
LOC82[1] = pl0;
LOC82[2] = addcomma_538464_839829468(pl0);
LOC82[3] = rawproc0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC81, LOC82, 4);
}
LA34: ;
}
N_NIMCALL(Ropeobj177006*, genotherarg_537277_839829468)(Tcproc527021* p0, Tnode290802* ri0, NI i0, Ttype290840* typ0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NI LOC3;
Tnode290802* paramtype0;
LOC3 = (NI)0;
LOC3 = sonslen_293327_850551059(typ0);
if (!(i0 < LOC3)) goto LA4;
paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i0];
{
NIM_BOOL LOC8;
LOC8 = (NIM_BOOL)0;
LOC8 = iscompiletimeonly_326706_3876443242((*paramtype0).typ);
if (!LOC8) goto LA9;
result0 = NIM_NIL;
}
goto LA6;
LA9: ;
{
NIM_BOOL LOC12;
Tnode290802* LOC16;
LOC12 = (NIM_BOOL)0;
LOC12 = ((*(*typ0).sons->data[i0]).kind == ((Ttypekind290244) 23));
if (!(LOC12)) goto LA13;
LOC12 = ((*(*ri0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 64));
LA13: ;
if (!LOC12) goto LA14;
LOC16 = (Tnode290802*)0;
LOC16 = HEX5BHEX5D_291238_850551059((*ri0).kindU.S6.sons->data[i0], ((NI) 0));
result0 = genargnoparam_537938_839829468(p0, LOC16);
}
goto LA6;
LA14: ;
{
result0 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]);
}
LA6: ;
}
goto LA1;
LA4: ;
{
{
if (!!((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0))) goto LA21;
localerror_194085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_501));
result0 = NIM_NIL;
}
goto LA19;
LA21: ;
{
result0 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]);
}
LA19: ;
}
LA1: ;
return result0;
}
N_NIMCALL(Tnode290802*, skipaddrderef_539433_839829468)(Tnode290802* node0) {
Tnode290802* result0;
Tnode290802* n0;
NIM_BOOL isaddr0;
{ result0 = (Tnode290802*)0;
n0 = node0;
isaddr0 = NIM_FALSE;
switch ((*n0).kind) {
case ((Tnodekind290020) 63):
case ((Tnodekind290020) 64):
{
n0 = (*n0).kindU.S6.sons->data[((NI) 0)];
isaddr0 = NIM_TRUE;
}
break;
case ((Tnodekind290020) 47):
case ((Tnodekind290020) 65):
{
n0 = (*n0).kindU.S6.sons->data[((NI) 0)];
}
break;
default:
{
result0 = n0;
goto BeforeRet;
}
break;
}
{
if (!((*n0).kind == ((Tnodekind290020) 66))) goto LA6;
n0 = (*n0).kindU.S6.sons->data[((NI) 0)];
}
LA6: ;
{
NIM_BOOL LOC10;
LOC10 = (NIM_BOOL)0;
LOC10 = isaddr0;
if (!(LOC10)) goto LA11;
LOC10 = ((*n0).kind == ((Tnodekind290020) 47) || (*n0).kind == ((Tnodekind290020) 65));
LA11: ;
if (!LOC10) goto LA12;
result0 = (*n0).kindU.S6.sons->data[((NI) 0)];
}
goto LA8;
LA12: ;
{
if (!((*n0).kind == ((Tnodekind290020) 63) || (*n0).kind == ((Tnodekind290020) 64))) goto LA15;
result0 = (*n0).kindU.S6.sons->data[((NI) 0)];
}
goto LA8;
LA15: ;
{
result0 = node0;
}
LA8: ;
}BeforeRet: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, genthisarg_539475_839829468)(Tcproc527021* p0, Tnode290802* ri_539478_839829468, NI i0, Ttype290840* typ0) {
Ropeobj177006* result0;
Tnode290802* ri0;
Ttype290840* t0;
result0 = (Ropeobj177006*)0;
{
NI LOC3;
NimStringDesc* LOC6;
LOC3 = (NI)0;
LOC3 = sonslen_293327_850551059(typ0);
if (!!((i0 < LOC3))) goto LA4;
LOC6 = (NimStringDesc*)0;
LOC6 = HEX24_194185_1689653243(T839829468_503);
internalerror_194113_155036129(LOC6);
}
LA4: ;
ri0 = HEX5BHEX5D_291238_850551059(ri_539478_839829468, i0);
{
while (1) {
if (!((*ri0).kind == ((Tnodekind290020) 66))) goto LA8;
ri0 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0));
} LA8: ;
}
t0 = skiptypes_294099_850551059((*typ0).sons->data[i0], 2048);
{
Tnode290802* x0;
if (!((*t0).kind == ((Ttypekind290244) 23))) goto LA11;
{
if (!((*ri0).kind == ((Tnodekind290020) 64))) goto LA15;
x0 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0));
}
goto LA13;
LA15: ;
{
x0 = ri0;
}
LA13: ;
{
if (!((*(*x0).typ).kind == ((Ttypekind290244) 21))) goto LA20;
result0 = genargnoparam_537938_839829468(p0, x0);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_504));
}
goto LA18;
LA20: ;
{
NIM_BOOL LOC23;
Tnode290802* LOC25;
Tnode290802* LOC28;
LOC23 = (NIM_BOOL)0;
LOC23 = ((*x0).kind == ((Tnodekind290020) 65) || (*x0).kind == ((Tnodekind290020) 47));
if (!(LOC23)) goto LA24;
LOC25 = (Tnode290802*)0;
LOC25 = HEX5BHEX5D_291238_850551059(x0, ((NI) 0));
LOC23 = ((*(*LOC25).typ).kind == ((Ttypekind290244) 21));
LA24: ;
if (!LOC23) goto LA26;
LOC28 = (Tnode290802*)0;
LOC28 = HEX5BHEX5D_291238_850551059(x0, ((NI) 0));
result0 = genargnoparam_537938_839829468(p0, LOC28);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_504));
}
goto LA18;
LA26: ;
{
result0 = genargnoparam_537938_839829468(p0, x0);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_257));
}
LA18: ;
}
goto LA9;
LA11: ;
{
if (!((*t0).kind == ((Ttypekind290244) 21))) goto LA31;
{
Tnode290802* LOC37;
if (!((*ri0).kind == ((Tnodekind290020) 63) || (*ri0).kind == ((Tnodekind290020) 64))) goto LA35;
LOC37 = (Tnode290802*)0;
LOC37 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0));
result0 = genargnoparam_537938_839829468(p0, LOC37);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_257));
}
goto LA33;
LA35: ;
{
result0 = genargnoparam_537938_839829468(p0, ri0);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_504));
}
LA33: ;
}
goto LA9;
LA31: ;
{
ri0 = skipaddrderef_539433_839829468(ri0);
{
if (!((*ri0).kind == ((Tnodekind290020) 63) || (*ri0).kind == ((Tnodekind290020) 64))) goto LA42;
ri0 = HEX5BHEX5D_291238_850551059(ri0, ((NI) 0));
}
LA42: ;
result0 = genargnoparam_537938_839829468(p0, ri0);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_257));
}
LA9: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, genpatterncall_539699_839829468)(Tcproc527021* p0, Tnode290802* ri_539702_839829468, NimStringDesc* pat0, Ttype290840* typ_539704_839829468) {
Ropeobj177006* result0;
NI i0;
NI j0;
result0 = (Ropeobj177006*)0;
i0 = ((NI) 0);
j0 = ((NI) 1);
{
while (1) {
if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA2;
switch (((NU8)(pat0->data[i0]))) {
case 64:
{
{
NI LOC6;
Ropeobj177006* LOC9;
LOC6 = (NI)0;
LOC6 = len_291081_850551059(ri_539702_839829468);
if (!(j0 < LOC6)) goto LA7;
LOC9 = (Ropeobj177006*)0;
LOC9 = genotherarg_537277_839829468(p0, ri_539702_839829468, j0, typ_539704_839829468);
add_177482_2381377266(&result0, LOC9);
{
NI k_539728_839829468;
NI HEX3Atmp_539904_839829468;
NI HEX3Atmp_539905_839829468;
NI LOC11;
NI res_539908_839829468;
k_539728_839829468 = (NI)0;
HEX3Atmp_539904_839829468 = (NI)0;
HEX3Atmp_539905_839829468 = (NI)0;
HEX3Atmp_539904_839829468 = (NI)(j0 + ((NI) 1));
LOC11 = (NI)0;
LOC11 = len_291081_850551059(ri_539702_839829468);
HEX3Atmp_539905_839829468 = (LOC11 - 1);
res_539908_839829468 = HEX3Atmp_539904_839829468;
{
while (1) {
TY531289 LOC14;
Ropeobj177006* LOC15;
Ropeobj177006* LOC16;
if (!(res_539908_839829468 <= HEX3Atmp_539905_839829468)) goto LA13;
k_539728_839829468 = res_539908_839829468;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC15 = (Ropeobj177006*)0;
LOC15 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC14, 0);
add_177482_2381377266(&result0, LOC15);
LOC16 = (Ropeobj177006*)0;
LOC16 = genotherarg_537277_839829468(p0, ri_539702_839829468, k_539728_839829468, typ_539704_839829468);
add_177482_2381377266(&result0, LOC16);
res_539908_839829468 += ((NI) 1);
} LA13: ;
}
}
}
LA7: ;
i0 += ((NI) 1);
}
break;
case 35:
{
{
Tnode290802* ri0;
if (!(((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(43)) || ((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(64)))) goto LA20;
ri0 = HEX5BHEX5D_291238_850551059(ri_539702_839829468, j0);
{
Ttype290840* typ0;
TY531289 LOC31;
Ropeobj177006* LOC32;
TY531289 LOC46;
Ropeobj177006* LOC47;
if (!((*ri0).kind == ((Tnodekind290020) 27) || (*ri0).kind == ((Tnodekind290020) 29) || (*ri0).kind == ((Tnodekind290020) 30) || (*ri0).kind == ((Tnodekind290020) 31) || (*ri0).kind == ((Tnodekind290020) 26) || (*ri0).kind == ((Tnodekind290020) 28) || (*ri0).kind == ((Tnodekind290020) 32))) goto LA24;
typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
{
Ropeobj177006* LOC30;
if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(43))) goto LA28;
LOC30 = (Ropeobj177006*)0;
LOC30 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)]);
add_177482_2381377266(&result0, LOC30);
}
LA28: ;
memset((void*)LOC31, 0, sizeof(LOC31));
LOC32 = (Ropeobj177006*)0;
LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_118), LOC31, 0);
add_177482_2381377266(&result0, LOC32);
{
NI LOC35;
Ropeobj177006* LOC38;
LOC35 = (NI)0;
LOC35 = len_291081_850551059(ri0);
if (!(((NI) 1) < LOC35)) goto LA36;
LOC38 = (Ropeobj177006*)0;
LOC38 = genotherarg_537277_839829468(p0, ri0, ((NI) 1), typ0);
add_177482_2381377266(&result0, LOC38);
}
LA36: ;
{
NI k_539793_839829468;
NI HEX3Atmp_539915_839829468;
NI HEX3Atmp_539916_839829468;
NI LOC40;
NI res_539919_839829468;
k_539793_839829468 = (NI)0;
HEX3Atmp_539915_839829468 = (NI)0;
HEX3Atmp_539916_839829468 = (NI)0;
HEX3Atmp_539915_839829468 = (NI)(j0 + ((NI) 1));
LOC40 = (NI)0;
LOC40 = len_291081_850551059(ri0);
HEX3Atmp_539916_839829468 = (LOC40 - 1);
res_539919_839829468 = HEX3Atmp_539915_839829468;
{
while (1) {
TY531289 LOC43;
Ropeobj177006* LOC44;
Ropeobj177006* LOC45;
if (!(res_539919_839829468 <= HEX3Atmp_539916_839829468)) goto LA42;
k_539793_839829468 = res_539919_839829468;
memset((void*)LOC43, 0, sizeof(LOC43));
LOC44 = (Ropeobj177006*)0;
LOC44 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC43, 0);
add_177482_2381377266(&result0, LOC44);
LOC45 = (Ropeobj177006*)0;
LOC45 = genotherarg_537277_839829468(p0, ri0, k_539793_839829468, typ0);
add_177482_2381377266(&result0, LOC45);
res_539919_839829468 += ((NI) 1);
} LA42: ;
}
}
memset((void*)LOC46, 0, sizeof(LOC46));
LOC47 = (Ropeobj177006*)0;
LOC47 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_117), LOC46, 0);
add_177482_2381377266(&result0, LOC47);
}
goto LA22;
LA24: ;
{
localerror_194085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_502));
}
LA22: ;
i0 += ((NI) 1);
}
goto LA18;
LA20: ;
{
Ropeobj177006* LOC52;
if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(46))) goto LA50;
LOC52 = (Ropeobj177006*)0;
LOC52 = genthisarg_539475_839829468(p0, ri_539702_839829468, j0, typ_539704_839829468);
add_177482_2381377266(&result0, LOC52);
i0 += ((NI) 1);
}
goto LA18;
LA50: ;
{
Tnode290802* arg0;
Ropeobj177006* LOC58;
if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(91))) goto LA54;
arg0 = skipaddrderef_539433_839829468((*ri_539702_839829468).kindU.S6.sons->data[j0]);
{
while (1) {
if (!((*arg0).kind == ((Tnodekind290020) 63) || (*arg0).kind == ((Tnodekind290020) 64) || (*arg0).kind == ((Tnodekind290020) 66))) goto LA57;
arg0 = HEX5BHEX5D_291238_850551059(arg0, ((NI) 0));
} LA57: ;
}
LOC58 = (Ropeobj177006*)0;
LOC58 = genargnoparam_537938_839829468(p0, arg0);
add_177482_2381377266(&result0, LOC58);
}
goto LA18;
LA54: ;
{
Ropeobj177006* LOC60;
LOC60 = (Ropeobj177006*)0;
LOC60 = genotherarg_537277_839829468(p0, ri_539702_839829468, j0, typ_539704_839829468);
add_177482_2381377266(&result0, LOC60);
}
LA18: ;
j0 += ((NI) 1);
i0 += ((NI) 1);
}
break;
case 39:
{
NI idx0;
NI stars0;
idx0 = (NI)0;
stars0 = (NI)0;
{
NIM_BOOL LOC64;
Ttype290840* t0;
LOC64 = (NIM_BOOL)0;
LOC64 = scancppgenericslot_532827_839829468(pat0, (&i0), (&idx0), (&stars0));
if (!LOC64) goto LA65;
t0 = resolvestarsincpptype_532891_839829468(typ_539704_839829468, idx0, stars0);
{
TY531289 LOC71;
Ropeobj177006* LOC72;
if (!(t0 == NIM_NIL)) goto LA69;
memset((void*)LOC71, 0, sizeof(LOC71));
LOC72 = (Ropeobj177006*)0;
LOC72 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_26), LOC71, 0);
add_177482_2381377266(&result0, LOC72);
}
goto LA67;
LA69: ;
{
Ropeobj177006* LOC74;
LOC74 = (Ropeobj177006*)0;
LOC74 = gettypedesc_533671_839829468((*p0).module, t0);
add_177482_2381377266(&result0, LOC74);
}
LA67: ;
}
LA65: ;
}
break;
default:
{
NI start0;
start0 = i0;
{
while (1) {
if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA77;
{
if (!!((((NU8)(pat0->data[i0])) == ((NU8)(64)) || ((NU8)(pat0->data[i0])) == ((NU8)(35)) || ((NU8)(pat0->data[i0])) == ((NU8)(39))))) goto LA80;
i0 += ((NI) 1);
}
goto LA78;
LA80: ;
{
goto LA76;
}
LA78: ;
} LA77: ;
} LA76: ;
{
NimStringDesc* LOC87;
if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA85;
LOC87 = (NimStringDesc*)0;
LOC87 = copyStrLast(pat0, start0, (NI)(i0 - ((NI) 1)));
add_177487_2381377266(&result0, LOC87);
}
LA85: ;
}
break;
}
} LA2: ;
}
return result0;
}
N_NIMCALL(void, fixupcall_537410_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0, Ropeobj177006* callee0, Ropeobj177006* params0) {
Ropeobj177006* pl0;
TY531289 LOC1;
Ropeobj177006* LOC2;
Ropeobj177006* LOC3;
Ttype290840* typ0;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC2 = (Ropeobj177006*)0;
LOC2 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_118), LOC1, 0);
LOC3 = (Ropeobj177006*)0;
LOC3 = HEX26_177418_2381377266(callee0, LOC2);
pl0 = HEX26_177418_2381377266(LOC3, params0);
typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
{
if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA6;
{
NIM_BOOL LOC10;
LOC10 = (NIM_BOOL)0;
LOC10 = isinvalidreturntype_531548_839829468((*typ0).sons->data[((NI) 0)]);
if (!LOC10) goto LA11;
{
TY531289 LOC17;
Ropeobj177006* LOC18;
if (!!((params0 == NIM_NIL))) goto LA15;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC18 = (Ropeobj177006*)0;
LOC18 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC17, 0);
add_177482_2381377266(&pl0, LOC18);
}
LA15: ;
{
NIM_BOOL LOC21;
NIM_BOOL LOC23;
Ropeobj177006* LOC36;
TY531289 LOC37;
Ropeobj177006* LOC38;
LOC21 = (NIM_BOOL)0;
LOC21 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0);
if (LOC21) goto LA22;
LOC23 = (NIM_BOOL)0;
LOC23 = leftappearsonrightside_537329_839829468(le0, ri0);
LOC21 = !(LOC23);
LA22: ;
if (!LOC21) goto LA24;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA28;
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE);
}
goto LA26;
LA28: ;
{
NIM_BOOL LOC31;
NIM_BOOL LOC33;
LOC31 = (NIM_BOOL)0;
LOC31 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0));
if (!(LOC31)) goto LA32;
LOC33 = (NIM_BOOL)0;
LOC33 = hasnoinit_537383_839829468(ri0);
LOC31 = !(LOC33);
LA32: ;
if (!LOC31) goto LA34;
resetloc_536350_839829468(p0, d0);
}
goto LA26;
LA34: ;
LA26: ;
LOC36 = (Ropeobj177006*)0;
LOC36 = addrloc_536204_839829468((*d0));
add_177482_2381377266(&pl0, LOC36);
memset((void*)LOC37, 0, sizeof(LOC37));
LOC38 = (Ropeobj177006*)0;
LOC38 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_505), LOC37, 0);
add_177482_2381377266(&pl0, LOC38);
line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0);
}
goto LA19;
LA24: ;
{
Tloc290816 tmp0;
Ropeobj177006* LOC40;
TY531289 LOC41;
Ropeobj177006* LOC42;
memset((void*)(&tmp0), 0, sizeof(tmp0));
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE);
LOC40 = (Ropeobj177006*)0;
LOC40 = addrloc_536204_839829468(tmp0);
add_177482_2381377266(&pl0, LOC40);
memset((void*)LOC41, 0, sizeof(LOC41));
LOC42 = (Ropeobj177006*)0;
LOC42 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_505), LOC41, 0);
add_177482_2381377266(&pl0, LOC42);
line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0);
genassignment_537264_839829468(p0, (*d0), tmp0, 0);
}
LA19: ;
}
goto LA8;
LA11: ;
{
TY531289 LOC44;
Ropeobj177006* LOC45;
memset((void*)LOC44, 0, sizeof(LOC44));
LOC45 = (Ropeobj177006*)0;
LOC45 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_117), LOC44, 0);
add_177482_2381377266(&pl0, LOC45);
{
NIM_BOOL LOC48;
NIM_BOOL LOC49;
LOC48 = (NIM_BOOL)0;
LOC49 = (NIM_BOOL)0;
LOC49 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC49) goto LA50;
LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA50: ;
LOC48 = LOC49;
if (!(LOC48)) goto LA51;
LOC48 = (((*d0).flags &(1U<<((NU)(((Tlocflag290810) 8))&15U)))!=0);
LA51: ;
if (!LOC48) goto LA52;
(*d0).k = ((Tlockind290808) 9);
unsureAsgnRef((void**) (&(*d0).r), pl0);
(*d0).flags &= ~(((NU16)1) << ((((Tlocflag290810) 8)) % (sizeof(NU16)*8)));
}
goto LA46;
LA52: ;
{
Tloc290816 list0;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA57;
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE);
}
LA57: ;
memset((void*)(&list0), 0, sizeof(list0));
initloc_530273_839829468((&list0), ((Tlockind290808) 9), (*d0).t, ((Tstorageloc290812) 0));
list0.r = pl0;
genassignment_537264_839829468(p0, (*d0), list0, 0);
}
LA46: ;
}
LA8: ;
}
goto LA4;
LA6: ;
{
TY531289 LOC60;
Ropeobj177006* LOC61;
memset((void*)LOC60, 0, sizeof(LOC60));
LOC61 = (Ropeobj177006*)0;
LOC61 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_505), LOC60, 0);
add_177482_2381377266(&pl0, LOC61);
line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0);
}
LA4: ;
}
N_NIMCALL(void, geninfixcall_539929_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) {
Tloc290816 op0;
Ttype290840* typ_539940_839829468;
NI length0;
NimStringDesc* pat0;
memset((void*)(&op0), 0, sizeof(op0));
initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0));
typ_539940_839829468 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
length0 = sonslen_293351_850551059(ri0);
pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data;
{
NimStringDesc* LOC5;
if (!!(!((pat0 == NIM_NIL)))) goto LA3;
LOC5 = (NimStringDesc*)0;
LOC5 = HEX24_194185_1689653243(T839829468_498);
internalerror_194113_155036129(LOC5);
}
LA3: ;
{
NIM_BOOL LOC8;
Ropeobj177006* pl0;
Ttype290840* typ0;
LOC8 = (NIM_BOOL)0;
LOC8 = contains_109056_4286263276(pat0, T839829468_500);
if (!LOC8) goto LA9;
pl0 = genpatterncall_539699_839829468(p0, ri0, pat0, typ_539940_839829468);
typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
{
if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA13;
{
NIM_BOOL LOC17;
NIM_BOOL LOC18;
LOC17 = (NIM_BOOL)0;
LOC18 = (NIM_BOOL)0;
LOC18 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC18) goto LA19;
LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA19: ;
LOC17 = LOC18;
if (!(LOC17)) goto LA20;
LOC17 = (((*d0).flags &(1U<<((NU)(((Tlocflag290810) 8))&15U)))!=0);
LA20: ;
if (!LOC17) goto LA21;
(*d0).k = ((Tlockind290808) 9);
unsureAsgnRef((void**) (&(*d0).r), pl0);
(*d0).flags &= ~(((NU16)1) << ((((Tlocflag290810) 8)) % (sizeof(NU16)*8)));
}
goto LA15;
LA21: ;
{
Tloc290816 list0;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA26;
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE);
}
LA26: ;
memset((void*)(&list0), 0, sizeof(list0));
initloc_530273_839829468((&list0), ((Tlockind290808) 9), (*d0).t, ((Tstorageloc290812) 0));
list0.r = pl0;
genassignment_537264_839829468(p0, (*d0), list0, 0);
}
LA15: ;
}
goto LA11;
LA13: ;
{
TY531289 LOC29;
Ropeobj177006* LOC30;
memset((void*)LOC29, 0, sizeof(LOC29));
LOC30 = (Ropeobj177006*)0;
LOC30 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_497), LOC29, 0);
add_177482_2381377266(&pl0, LOC30);
line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0);
}
LA11: ;
}
goto LA6;
LA9: ;
{
Ropeobj177006* pl0;
Ropeobj177006* params0;
pl0 = NIM_NIL;
{
NI LOC34;
Ropeobj177006* LOC37;
LOC34 = (NI)0;
LOC34 = len_291081_850551059(ri0);
if (!(((NI) 1) < LOC34)) goto LA35;
LOC37 = (Ropeobj177006*)0;
LOC37 = genthisarg_539475_839829468(p0, ri0, ((NI) 1), typ_539940_839829468);
add_177482_2381377266(&pl0, LOC37);
}
LA35: ;
add_177482_2381377266(&pl0, op0.r);
params0 = (Ropeobj177006*)0;
{
NI i_540425_839829468;
NI HEX3Atmp_540609_839829468;
NI res_540612_839829468;
i_540425_839829468 = (NI)0;
HEX3Atmp_540609_839829468 = (NI)0;
HEX3Atmp_540609_839829468 = (NI)(length0 - ((NI) 1));
res_540612_839829468 = ((NI) 2);
{
while (1) {
Ropeobj177006* LOC47;
if (!(res_540612_839829468 <= HEX3Atmp_540609_839829468)) goto LA40;
i_540425_839829468 = res_540612_839829468;
{
TY531289 LOC45;
Ropeobj177006* LOC46;
if (!!((params0 == NIM_NIL))) goto LA43;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC46 = (Ropeobj177006*)0;
LOC46 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC45, 0);
add_177482_2381377266(¶ms0, LOC46);
}
LA43: ;
LOC47 = (Ropeobj177006*)0;
LOC47 = genotherarg_537277_839829468(p0, ri0, i_540425_839829468, typ_539940_839829468);
add_177482_2381377266(¶ms0, LOC47);
res_540612_839829468 += ((NI) 1);
} LA40: ;
}
}
fixupcall_537410_839829468(p0, le0, ri0, d0, pl0, params0);
}
LA6: ;
}
N_NIMCALL(void, gennamedparamcall_540616_839829468)(Tcproc527021* p0, Tnode290802* ri0, Tloc290816* d0) {
Tloc290816 op0;
Ropeobj177006* pl0;
TY531289 LOC1;
Ttype290840* typ0;
NI length0;
NimStringDesc* pat0;
NI start0;
memset((void*)(&op0), 0, sizeof(op0));
initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0));
memset((void*)LOC1, 0, sizeof(LOC1));
pl0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_506), LOC1, 0);
typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
length0 = sonslen_293351_850551059(ri0);
pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data;
{
NimStringDesc* LOC6;
if (!!(!((pat0 == NIM_NIL)))) goto LA4;
LOC6 = (NimStringDesc*)0;
LOC6 = HEX24_194185_1689653243(T839829468_507);
internalerror_194113_155036129(LOC6);
}
LA4: ;
start0 = ((NI) 3);
{
NIM_BOOL LOC9;
LOC9 = (NIM_BOOL)0;
LOC9 = contains_109046_4286263276(pat0, 32);
if (!LOC9) goto LA10;
start0 = ((NI) 1);
add_177482_2381377266(&pl0, op0.r);
{
TY531289 LOC16;
Ropeobj177006* LOC17;
Ropeobj177006* LOC18;
if (!(((NI) 1) < length0)) goto LA14;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC17 = (Ropeobj177006*)0;
LOC17 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_244), LOC16, 0);
add_177482_2381377266(&pl0, LOC17);
LOC18 = (Ropeobj177006*)0;
LOC18 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0);
add_177482_2381377266(&pl0, LOC18);
start0 = ((NI) 2);
}
LA14: ;
}
goto LA7;
LA10: ;
{
{
Ropeobj177006* LOC24;
TY531289 LOC25;
Ropeobj177006* LOC26;
if (!(((NI) 1) < length0)) goto LA22;
LOC24 = (Ropeobj177006*)0;
LOC24 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0);
add_177482_2381377266(&pl0, LOC24);
memset((void*)LOC25, 0, sizeof(LOC25));
LOC26 = (Ropeobj177006*)0;
LOC26 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC25, 0);
add_177482_2381377266(&pl0, LOC26);
}
LA22: ;
add_177482_2381377266(&pl0, op0.r);
{
TY531289 LOC31;
Ropeobj177006* LOC32;
Ropeobj177006* LOC33;
if (!(((NI) 2) < length0)) goto LA29;
memset((void*)LOC31, 0, sizeof(LOC31));
LOC32 = (Ropeobj177006*)0;
LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_244), LOC31, 0);
add_177482_2381377266(&pl0, LOC32);
LOC33 = (Ropeobj177006*)0;
LOC33 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 2)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 2)]).kindU.S4.sym, ri0);
add_177482_2381377266(&pl0, LOC33);
}
LA29: ;
}
LA7: ;
{
NI i_541051_839829468;
NI HEX3Atmp_541617_839829468;
NI res_541620_839829468;
i_541051_839829468 = (NI)0;
HEX3Atmp_541617_839829468 = (NI)0;
HEX3Atmp_541617_839829468 = (NI)(length0 - ((NI) 1));
res_541620_839829468 = start0;
{
while (1) {
Tsym290834* param0;
TY531289 LOC42;
Ropeobj177006* LOC43;
TY531289 LOC44;
Ropeobj177006* LOC45;
Ropeobj177006* LOC46;
if (!(res_541620_839829468 <= HEX3Atmp_541617_839829468)) goto LA36;
i_541051_839829468 = res_541620_839829468;
{
NI LOC39;
LOC39 = (NI)0;
LOC39 = sonslen_293327_850551059(typ0);
if (!(LOC39 <= i_541051_839829468)) goto LA40;
internalerror_194100_155036129((*ri0).info, ((NimStringDesc*) &T839829468_508));
}
LA40: ;
param0 = (*(*(*typ0).n).kindU.S6.sons->data[i_541051_839829468]).kindU.S4.sym;
memset((void*)LOC42, 0, sizeof(LOC42));
LOC43 = (Ropeobj177006*)0;
LOC43 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC42, 0);
add_177482_2381377266(&pl0, LOC43);
add_177487_2381377266(&pl0, (*(*param0).name).s);
memset((void*)LOC44, 0, sizeof(LOC44));
LOC45 = (Ropeobj177006*)0;
LOC45 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_244), LOC44, 0);
add_177482_2381377266(&pl0, LOC45);
LOC46 = (Ropeobj177006*)0;
LOC46 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[i_541051_839829468], param0, ri0);
add_177482_2381377266(&pl0, LOC46);
res_541620_839829468 += ((NI) 1);
} LA36: ;
}
}
{
if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA49;
{
NIM_BOOL LOC53;
LOC53 = (NIM_BOOL)0;
LOC53 = isinvalidreturntype_531548_839829468((*typ0).sons->data[((NI) 0)]);
if (!LOC53) goto LA54;
{
NI LOC58;
TY531289 LOC61;
Ropeobj177006* LOC62;
LOC58 = (NI)0;
LOC58 = sonslen_293351_850551059(ri0);
if (!(((NI) 1) < LOC58)) goto LA59;
memset((void*)LOC61, 0, sizeof(LOC61));
LOC62 = (Ropeobj177006*)0;
LOC62 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_111), LOC61, 0);
add_177482_2381377266(&pl0, LOC62);
}
LA59: ;
{
TY531289 LOC71;
Ropeobj177006* LOC72;
Ropeobj177006* LOC73;
TY531289 LOC74;
Ropeobj177006* LOC75;
if (!((3 &(1U<<((NU)((*d0).k)&15U)))!=0)) goto LA65;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA69;
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE);
}
LA69: ;
memset((void*)LOC71, 0, sizeof(LOC71));
LOC72 = (Ropeobj177006*)0;
LOC72 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_509), LOC71, 0);
add_177482_2381377266(&pl0, LOC72);
LOC73 = (Ropeobj177006*)0;
LOC73 = addrloc_536204_839829468((*d0));
add_177482_2381377266(&pl0, LOC73);
memset((void*)LOC74, 0, sizeof(LOC74));
LOC75 = (Ropeobj177006*)0;
LOC75 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_510), LOC74, 0);
add_177482_2381377266(&pl0, LOC75);
line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0);
}
goto LA63;
LA65: ;
{
Tloc290816 tmp0;
Ropeobj177006* LOC77;
TY531289 LOC78;
Ropeobj177006* LOC79;
memset((void*)(&tmp0), 0, sizeof(tmp0));
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE);
LOC77 = (Ropeobj177006*)0;
LOC77 = addrloc_536204_839829468(tmp0);
add_177482_2381377266(&pl0, LOC77);
memset((void*)LOC78, 0, sizeof(LOC78));
LOC79 = (Ropeobj177006*)0;
LOC79 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_510), LOC78, 0);
add_177482_2381377266(&pl0, LOC79);
line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0);
genassignment_537264_839829468(p0, (*d0), tmp0, 0);
}
LA63: ;
}
goto LA51;
LA54: ;
{
TY531289 LOC81;
Ropeobj177006* LOC82;
Tloc290816 list0;
memset((void*)LOC81, 0, sizeof(LOC81));
LOC82 = (Ropeobj177006*)0;
LOC82 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_511), LOC81, 0);
add_177482_2381377266(&pl0, LOC82);
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA85;
gettemp_535032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE);
}
LA85: ;
memset((void*)(&list0), 0, sizeof(list0));
initloc_530273_839829468((&list0), ((Tlockind290808) 9), NIM_NIL, ((Tstorageloc290812) 0));
list0.r = pl0;
genassignment_537264_839829468(p0, (*d0), list0, 0);
}
LA51: ;
}
goto LA47;
LA49: ;
{
TY531289 LOC88;
Ropeobj177006* LOC89;
memset((void*)LOC88, 0, sizeof(LOC88));
LOC89 = (Ropeobj177006*)0;
LOC89 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_510), LOC88, 0);
add_177482_2381377266(&pl0, LOC89);
line_530690_839829468(p0, ((Tcprocsection527011) 2), pl0);
}
LA47: ;
}
N_NIMCALL(void, genprefixcall_537960_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) {
Tloc290816 op0;
Ropeobj177006* params0;
Ttype290840* typ0;
NI length0;
memset((void*)(&op0), 0, sizeof(op0));
initlocexpr_537283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0));
params0 = (Ropeobj177006*)0;
typ0 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
length0 = sonslen_293351_850551059(ri0);
{
NI i_538213_839829468;
NI HEX3Atmp_538445_839829468;
NI res_538448_839829468;
i_538213_839829468 = (NI)0;
HEX3Atmp_538445_839829468 = (NI)0;
HEX3Atmp_538445_839829468 = (NI)(length0 - ((NI) 1));
res_538448_839829468 = ((NI) 1);
{
while (1) {
if (!(res_538448_839829468 <= HEX3Atmp_538445_839829468)) goto LA3;
i_538213_839829468 = res_538448_839829468;
{
NI LOC6;
Tnode290802* paramtype0;
LOC6 = (NI)0;
LOC6 = sonslen_293327_850551059(typ0);
if (!(i_538213_839829468 < LOC6)) goto LA7;
paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_538213_839829468];
{
NIM_BOOL LOC11;
Ropeobj177006* LOC20;
LOC11 = (NIM_BOOL)0;
LOC11 = iscompiletimeonly_326706_3876443242((*paramtype0).typ);
if (!!(LOC11)) goto LA12;
{
TY531289 LOC18;
Ropeobj177006* LOC19;
if (!!((params0 == NIM_NIL))) goto LA16;
memset((void*)LOC18, 0, sizeof(LOC18));
LOC19 = (Ropeobj177006*)0;
LOC19 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0);
add_177482_2381377266(¶ms0, LOC19);
}
LA16: ;
LOC20 = (Ropeobj177006*)0;
LOC20 = genarg_537787_839829468(p0, (*ri0).kindU.S6.sons->data[i_538213_839829468], (*paramtype0).kindU.S4.sym, ri0);
add_177482_2381377266(¶ms0, LOC20);
}
LA12: ;
}
goto LA4;
LA7: ;
{
Ropeobj177006* LOC28;
{
TY531289 LOC26;
Ropeobj177006* LOC27;
if (!!((params0 == NIM_NIL))) goto LA24;
memset((void*)LOC26, 0, sizeof(LOC26));
LOC27 = (Ropeobj177006*)0;
LOC27 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0);
add_177482_2381377266(¶ms0, LOC27);
}
LA24: ;
LOC28 = (Ropeobj177006*)0;
LOC28 = genargnoparam_537938_839829468(p0, (*ri0).kindU.S6.sons->data[i_538213_839829468]);
add_177482_2381377266(¶ms0, LOC28);
}
LA4: ;
res_538448_839829468 += ((NI) 1);
} LA3: ;
}
}
fixupcall_537410_839829468(p0, le0, ri0, d0, op0.r, params0);
}
static N_INLINE(void, poststmtactions_530942_839829468)(Tcproc527021* p0) {
Ropeobj177006** LOC1;
LOC1 = (Ropeobj177006**)0;
LOC1 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177482_2381377266(LOC1, (*(*p0).module).injectstmt);
}
N_NIMCALL(void, gencall_541632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
{
Ttype290840* LOC3;
LOC3 = (Ttype290840*)0;
LOC3 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, 2048);
if (!((*LOC3).callconv == ((Tcallingconvention290002) 8))) goto LA4;
genclosurecall_538452_839829468(p0, NIM_NIL, e0, d0);
}
goto LA1;
LA4: ;
{
NIM_BOOL LOC7;
LOC7 = (NIM_BOOL)0;
LOC7 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC7)) goto LA8;
LOC7 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA8: ;
if (!LOC7) goto LA9;
geninfixcall_539929_839829468(p0, NIM_NIL, e0, d0);
}
goto LA1;
LA9: ;
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC12)) goto LA13;
LOC12 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 28))&31U)))!=0);
LA13: ;
if (!LOC12) goto LA14;
gennamedparamcall_540616_839829468(p0, e0, d0);
}
goto LA1;
LA14: ;
{
genprefixcall_537960_839829468(p0, NIM_NIL, e0, d0);
}
LA1: ;
poststmtactions_530942_839829468(p0);
}
N_NIMCALL(void, genreset_552731_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Tloc290816 a0;
TY530811 LOC1;
Ttype290840* LOC2;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = addrloc_536204_839829468(a0);
LOC2 = (Ttype290840*)0;
LOC2 = skiptypes_294099_850551059(a0.t, IL64(211106242013440));
LOC1[1] = gentypeinfo_533941_839829468((*p0).module, LOC2);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_496), LOC1, 2);
}
N_NIMCALL(void, genecho_552369_839829468)(Tcproc527021* p0, Tnode290802* n0) {
NIM_BOOL LOC6;
Ropeobj177006* args0;
Tloc290816 a0;
TY530811 LOC18;
NimStringDesc* LOC19;
NI LOC20;
NimStringDesc* LOC21;
TY531289 LOC22;
{
NimStringDesc* LOC5;
if (!!(((*n0).kind == ((Tnodekind290020) 41)))) goto LA3;
LOC5 = (NimStringDesc*)0;
LOC5 = HEX24_194185_1689653243(T839829468_512);
internalerror_194113_155036129(LOC5);
}
LA3: ;
LOC6 = (NIM_BOOL)0;
LOC6 = includestr_147249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_513));
args0 = NIM_NIL;
memset((void*)(&a0), 0, sizeof(a0));
{
NI i_552404_839829468;
NI HEX3Atmp_552431_839829468;
NI LOC8;
NI res_552434_839829468;
i_552404_839829468 = (NI)0;
HEX3Atmp_552431_839829468 = (NI)0;
LOC8 = (NI)0;
LOC8 = len_291081_850551059(n0);
HEX3Atmp_552431_839829468 = (NI)(LOC8 - ((NI) 1));
res_552434_839829468 = ((NI) 0);
{
while (1) {
if (!(res_552434_839829468 <= HEX3Atmp_552431_839829468)) goto LA10;
i_552404_839829468 = res_552434_839829468;
{
Tnode290802* LOC13;
LOC13 = (Tnode290802*)0;
LOC13 = skipconv_326882_3876443242((*n0).kindU.S6.sons->data[i_552404_839829468]);
if (!((*LOC13).kind == ((Tnodekind290020) 23))) goto LA14;
add_177487_2381377266(&args0, ((NimStringDesc*) &T839829468_514));
}
goto LA11;
LA14: ;
{
TY177507 LOC17;
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[i_552404_839829468], (&a0));
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = rdloc_536188_839829468(a0);
addf_178205_2381377266(&args0, ((NimStringDesc*) &T839829468_515), LOC17, 1);
}
LA11: ;
res_552434_839829468 += ((NI) 1);
} LA10: ;
}
}
memset((void*)LOC18, 0, sizeof(LOC18));
LOC19 = (NimStringDesc*)0;
LOC20 = (NI)0;
LOC20 = len_291081_850551059(n0);
LOC21 = (NimStringDesc*)0;
LOC21 = nsuRepeatStr(((NimStringDesc*) &T839829468_517), ((NI) (LOC20)));
LOC19 = rawNewString(LOC21->Sup.len + tnl_175644_4151366050->Sup.len + 0);
appendString(LOC19, LOC21);
appendString(LOC19, tnl_175644_4151366050);
LOC18[0] = makecstring_189638_155036129(LOC19);
LOC18[1] = args0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_516), LOC18, 2);
memset((void*)LOC22, 0, sizeof(LOC22));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_518), LOC22, 0);
}
N_NIMCALL(void, genseqconstr_553004_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) {
Tloc290816 arr0;
NI LOC5;
Ropeobj177006* LOC6;
memset((void*)(&arr0), 0, sizeof(arr0));
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA3;
gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE);
}
LA3: ;
LOC5 = (NI)0;
LOC5 = sonslen_293351_850551059(t0);
LOC6 = (Ropeobj177006*)0;
LOC6 = intliteral_537270_839829468(((NI64) (LOC5)));
gennewseqaux_552795_839829468(p0, (*d0), LOC6);
{
NI i_553031_839829468;
NI HEX3Atmp_553039_839829468;
NI LOC8;
NI res_553042_839829468;
i_553031_839829468 = (NI)0;
HEX3Atmp_553039_839829468 = (NI)0;
LOC8 = (NI)0;
LOC8 = sonslen_293351_850551059(t0);
HEX3Atmp_553039_839829468 = (NI)(LOC8 - ((NI) 1));
res_553042_839829468 = ((NI) 0);
{
while (1) {
Ttype290840* LOC11;
Ttype290840* LOC12;
TY530811 LOC13;
if (!(res_553042_839829468 <= HEX3Atmp_553039_839829468)) goto LA10;
i_553031_839829468 = res_553042_839829468;
LOC11 = (Ttype290840*)0;
LOC11 = skiptypes_294099_850551059((*t0).typ, IL64(211106232576256));
LOC12 = (Ttype290840*)0;
LOC12 = elemtype_318394_3876443242(LOC11);
initloc_530273_839829468((&arr0), ((Tlockind290808) 6), LOC12, ((Tstorageloc290812) 3));
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = rdloc_536188_839829468((*d0));
LOC13[1] = intliteral_537270_839829468(((NI64) (i_553031_839829468)));
arr0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC13, 2);
arr0.s = ((Tstorageloc290812) 3);
expr_537248_839829468(p0, (*t0).kindU.S6.sons->data[i_553031_839829468], (&arr0));
res_553042_839829468 += ((NI) 1);
} LA10: ;
}
}
gcusage_552439_839829468(t0);
}
N_NIMCALL(void, genarrtoseq_553046_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) {
Tloc290816 elem0;
Tloc290816 a0;
Tloc290816 arr0;
NI L0;
NI64 LOC9;
Ropeobj177006* LOC10;
{ memset((void*)(&elem0), 0, sizeof(elem0));
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&arr0), 0, sizeof(arr0));
{
if (!((*t0).kind == ((Tnodekind290020) 41))) goto LA3;
asgnRefNoCycle((void**) (&(*(*t0).kindU.S6.sons->data[((NI) 1)]).typ), (*t0).typ);
genseqconstr_553004_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], d0);
goto BeforeRet;
}
LA3: ;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA7;
gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE);
}
LA7: ;
LOC9 = (NI64)0;
LOC9 = lengthord_318007_3876443242((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ);
L0 = ((NI) (LOC9));
LOC10 = (Ropeobj177006*)0;
LOC10 = intliteral_537270_839829468(((NI64) (L0)));
gennewseqaux_552795_839829468(p0, (*d0), LOC10);
initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], (&a0));
{
NI i_553090_839829468;
NI HEX3Atmp_553103_839829468;
NI res_553106_839829468;
i_553090_839829468 = (NI)0;
HEX3Atmp_553103_839829468 = (NI)0;
HEX3Atmp_553103_839829468 = (NI)(L0 - ((NI) 1));
res_553106_839829468 = ((NI) 0);
{
while (1) {
Ttype290840* LOC14;
Ttype290840* LOC15;
TY530811 LOC16;
Ttype290840* LOC17;
Ttype290840* LOC18;
TY530811 LOC19;
if (!(res_553106_839829468 <= HEX3Atmp_553103_839829468)) goto LA13;
i_553090_839829468 = res_553106_839829468;
LOC14 = (Ttype290840*)0;
LOC14 = skiptypes_294099_850551059((*t0).typ, IL64(211106232576256));
LOC15 = (Ttype290840*)0;
LOC15 = elemtype_318394_3876443242(LOC14);
initloc_530273_839829468((&elem0), ((Tlockind290808) 6), LOC15, ((Tstorageloc290812) 3));
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rdloc_536188_839829468((*d0));
LOC16[1] = intliteral_537270_839829468(((NI64) (i_553090_839829468)));
elem0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC16, 2);
elem0.s = ((Tstorageloc290812) 3);
LOC17 = (Ttype290840*)0;
LOC17 = skiptypes_294099_850551059((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106232576256));
LOC18 = (Ttype290840*)0;
LOC18 = elemtype_318394_3876443242(LOC17);
initloc_530273_839829468((&arr0), ((Tlockind290808) 6), LOC18, a0.s);
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = rdloc_536188_839829468(a0);
LOC19[1] = intliteral_537270_839829468(((NI64) (i_553090_839829468)));
arr0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC19, 2);
genassignment_537264_839829468(p0, elem0, arr0, 3);
res_553106_839829468 += ((NI) 1);
} LA13: ;
}
}
}BeforeRet: ;
}
N_NIMCALL(void, gendeepcopy_548374_839829468)(Tcproc527021* p0, Tloc290816 dest0, Tloc290816 src0) {
Ttype290840* ty0;
ty0 = skiptypes_294099_850551059(dest0.t, IL64(211106242013440));
switch ((*ty0).kind) {
case ((Ttypekind290244) 21):
case ((Ttypekind290244) 22):
case ((Ttypekind290244) 25):
case ((Ttypekind290244) 18):
case ((Ttypekind290244) 17):
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
TY533238 LOC2;
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = addrloc_536204_839829468(dest0);
LOC2[1] = addrloc_536204_839829468(src0);
LOC2[2] = gentypeinfo_533941_839829468((*p0).module, dest0.t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_519), LOC2, 3);
}
break;
case ((Ttypekind290244) 24):
case ((Ttypekind290244) 28):
{
TY533238 LOC4;
memset((void*)LOC4, 0, sizeof(LOC4));
LOC4[0] = addrloc_536204_839829468(dest0);
LOC4[1] = rdloc_536188_839829468(src0);
LOC4[2] = gentypeinfo_533941_839829468((*p0).module, dest0.t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_520), LOC4, 3);
}
break;
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
TY533238 LOC6;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = addrloc_536204_839829468(dest0);
LOC6[1] = addrloc_536204_839829468(src0);
LOC6[2] = gentypeinfo_533941_839829468((*p0).module, dest0.t);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_521), LOC6, 3);
}
break;
case ((Ttypekind290244) 19):
{
{
Tctypekind527007 LOC10;
TY533238 LOC13;
NI64 LOC14;
LOC10 = (Tctypekind527007)0;
LOC10 = maptype_531393_839829468(ty0);
if (!(LOC10 == ((Tctypekind527007) 17))) goto LA11;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = rdloc_536188_839829468(dest0);
LOC13[1] = rdloc_536188_839829468(src0);
LOC14 = (NI64)0;
LOC14 = getsize_318135_3876443242(dest0.t);
LOC13[2] = rope_177401_2381377266(LOC14);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_268), LOC13, 3);
}
goto LA8;
LA11: ;
{
TY530811 LOC16;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rdloc_536188_839829468(dest0);
LOC16[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC16, 2);
}
LA8: ;
}
break;
case ((Ttypekind290244) 26):
case ((Ttypekind290244) 2):
case ((Ttypekind290244) 1):
case ((Ttypekind290244) 14):
case ((Ttypekind290244) 29):
case ((Ttypekind290244) 31) ... ((Ttypekind290244) 44):
case ((Ttypekind290244) 20):
case ((Ttypekind290244) 23):
{
TY530811 LOC18;
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = rdloc_536188_839829468(dest0);
LOC18[1] = rdloc_536188_839829468(src0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_123), LOC18, 2);
}
break;
default:
{
NimStringDesc* LOC20;
LOC20 = (NimStringDesc*)0;
LOC20 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI290244))->Sup.len + 13);
appendString(LOC20, ((NimStringDesc*) &T839829468_522));
appendString(LOC20, reprEnum((NI)(*ty0).kind, (&NTI290244)));
internalerror_194113_155036129(LOC20);
}
break;
}
}
N_NIMCALL(void, genmagicexpr_555033_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tmagic290524 op0) {
switch (op0) {
case ((Tmagic290524) 127):
case ((Tmagic290524) 126):
{
genandor_552311_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 99) ... ((Tmagic290524) 117):
{
unaryarith_550646_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 96) ... ((Tmagic290524) 98):
{
unaryarithoverflow_549633_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 52) ... ((Tmagic290524) 55):
{
binaryfloatarith_554728_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 56) ... ((Tmagic290524) 93):
{
binaryarith_549819_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 95):
{
geneqproc_550214_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 45) ... ((Tmagic290524) 51):
{
binaryarithoverflow_549262_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 149):
{
genrepr_553339_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 259):
{
gengettypeinfo_553383_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 156):
{
genswap_553638_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 25):
{
{
if (!!((((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0))) goto LA14;
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_385));
}
goto LA12;
LA14: ;
{
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_386));
}
LA12: ;
}
break;
case ((Tmagic290524) 26):
case ((Tmagic290524) 27):
{
Ttype290840* underlying0;
underlying0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 9439232);
{
NIM_BOOL LOC20;
LOC20 = (NIM_BOOL)0;
LOC20 = !((((*p0).options &(1U<<((NU)(((Toption168009) 5))&31U)))!=0));
if (LOC20) goto LA21;
LOC20 = ((*underlying0).kind >= ((Ttypekind290244) 40) && (*underlying0).kind <= ((Ttypekind290244) 44));
LA21: ;
if (!LOC20) goto LA22;
binarystmt_548501_839829468(p0, e0, d0, opr_555050_839829468[(op0)- 26]);
}
goto LA18;
LA22: ;
{
Tloc290816 a0;
Tloc290816 b0;
Ttype290840* ranged0;
Ropeobj177006* res0;
NimStringDesc* LOC25;
TY530811 LOC31;
Ropeobj177006* LOC32;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
ranged0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 8390656);
LOC25 = (NimStringDesc*)0;
{
if (!((*underlying0).kind == ((Ttypekind290244) 35))) goto LA28;
LOC25 = copyString(fun64_555055_839829468[(op0)- 26]);
}
goto LA26;
LA28: ;
{
LOC25 = copyString(fun_555060_839829468[(op0)- 26]);
}
LA26: ;
res0 = binaryarithoverflowraw_549235_839829468(p0, ranged0, a0, b0, LOC25);
memset((void*)LOC31, 0, sizeof(LOC31));
LOC31[0] = gettypedesc_533671_839829468((*p0).module, ranged0);
LOC31[1] = res0;
LOC32 = (Ropeobj177006*)0;
LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_370), LOC31, 2);
putintodest_548468_839829468(p0, (&a0), ranged0, LOC32, ((Tstorageloc290812) 0));
}
LA18: ;
}
break;
case ((Tmagic290524) 138):
{
genstrconcat_552452_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 144):
{
binarystmt_548501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_394));
}
break;
case ((Tmagic290524) 145):
{
genstrappend_552554_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 146):
{
genseqelemappend_552683_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 128):
{
genstrequals_554666_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 129):
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_402));
}
break;
case ((Tmagic290524) 130):
{
binaryexpr_548549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_403));
}
break;
case ((Tmagic290524) 157):
{
genisnil_550620_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 120):
{
gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_406));
}
break;
case ((Tmagic290524) 121):
{
gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_407));
}
break;
case ((Tmagic290524) 119):
{
gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_408));
}
break;
case ((Tmagic290524) 118):
{
gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_409));
}
break;
case ((Tmagic290524) 122):
{
gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_410));
}
break;
case ((Tmagic290524) 123):
{
gendollar_553391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_411));
}
break;
case ((Tmagic290524) 124):
{
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0);
}
break;
case ((Tmagic290524) 125):
{
genrepr_553339_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 12):
{
genof_553331_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 29):
{
gennew_552782_839829468(p0, e0);
}
break;
case ((Tmagic290524) 30):
{
gennewfinalize_553110_839829468(p0, e0);
}
break;
case ((Tmagic290524) 31):
{
gennewseq_552824_839829468(p0, e0);
}
break;
case ((Tmagic290524) 32):
{
gennewseqofcap_552836_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 9):
{
Ttype290840* t0;
TY177507 LOC55;
Ropeobj177006* LOC56;
t0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 256);
memset((void*)LOC55, 0, sizeof(LOC55));
LOC55[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC56 = (Ropeobj177006*)0;
LOC56 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_428), LOC55, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC56, ((Tstorageloc290812) 0));
}
break;
case ((Tmagic290524) 42):
{
gensomecast_554480_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 28):
{
genord_554474_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 35):
case ((Tmagic290524) 8):
case ((Tmagic290524) 34):
case ((Tmagic290524) 36):
case ((Tmagic290524) 33):
{
genarraylen_553415_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 37):
case ((Tmagic290524) 38):
{
{
NIM_BOOL LOC63;
LOC63 = (NIM_BOOL)0;
LOC63 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC63) goto LA64;
LOC63 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA64: ;
if (!!(LOC63)) goto LA65;
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_440));
}
goto LA61;
LA65: ;
{
unaryexpr_549209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_441));
}
LA61: ;
}
break;
case ((Tmagic290524) 43):
{
unarystmt_548527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_443));
}
break;
case ((Tmagic290524) 44):
{
unarystmt_548527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_444));
}
break;
case ((Tmagic290524) 151):
{
gensetlengthstr_553632_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 152):
{
gensetlengthseq_553500_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 39):
case ((Tmagic290524) 40):
case ((Tmagic290524) 41):
case ((Tmagic290524) 133):
case ((Tmagic290524) 132):
case ((Tmagic290524) 131):
case ((Tmagic290524) 134):
case ((Tmagic290524) 135):
case ((Tmagic290524) 136):
case ((Tmagic290524) 148):
{
gensetop_554419_839829468(p0, e0, d0, op0);
}
break;
case ((Tmagic290524) 161):
case ((Tmagic290524) 162):
case ((Tmagic290524) 159):
case ((Tmagic290524) 160):
case ((Tmagic290524) 150):
case ((Tmagic290524) 163):
{
Tsym290834* opr0;
opr0 = (*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
{
NimStringDesc* LOC78;
Ropeobj177006* LOC79;
if (!!((((*opr0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0))) goto LA76;
LOC78 = (NimStringDesc*)0;
LOC78 = HEX24_177856_2381377266((*opr0).loc.r);
LOC79 = (Ropeobj177006*)0;
LOC79 = cgsym_530403_839829468((*p0).module, LOC78);
}
LA76: ;
gencall_541632_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 164):
{
genreset_552731_839829468(p0, e0);
}
break;
case ((Tmagic290524) 17):
{
Tnode290802* LOC82;
Tnode290802* LOC83;
LOC82 = (Tnode290802*)0;
LOC82 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1));
LOC83 = (Tnode290802*)0;
LOC83 = skipconv_326882_3876443242(LOC82);
genecho_552369_839829468(p0, LOC83);
}
break;
case ((Tmagic290524) 158):
{
genarrtoseq_553046_839829468(p0, e0, d0);
}
break;
case ((Tmagic290524) 223) ... ((Tmagic290524) 257):
case ((Tmagic290524) 19) ... ((Tmagic290524) 24):
{
localerror_194080_155036129((*e0).info, ((Tmsgkind189002) 229), (*(*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s);
}
break;
case ((Tmagic290524) 208):
{
Tnode290802* n0;
n0 = wrapprocforspawn_433501_2218250499((*(*p0).module).module, e0, (*e0).typ, NIM_NIL, NIM_NIL);
expr_537248_839829468(p0, n0, d0);
}
break;
case ((Tmagic290524) 155):
{
Tnode290802* n0;
n0 = liftparallel_476822_1773027539((*(*p0).module).module, e0);
expr_537248_839829468(p0, n0, d0);
}
break;
case ((Tmagic290524) 209):
{
Tloc290816 a0;
Tloc290816 b0;
Tnode290802* x0;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
{
Tnode290802* LOC91;
Tnode290802* LOC94;
LOC91 = (Tnode290802*)0;
LOC91 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1));
if (!((*LOC91).kind == ((Tnodekind290020) 63) || (*LOC91).kind == ((Tnodekind290020) 64))) goto LA92;
LOC94 = (Tnode290802*)0;
LOC94 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1));
x0 = HEX5BHEX5D_291238_850551059(LOC94, ((NI) 0));
}
goto LA89;
LA92: ;
{
x0 = HEX5BHEX5D_291238_850551059(e0, ((NI) 1));
}
LA89: ;
initlocexpr_537283_839829468(p0, x0, (&a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0));
gendeepcopy_548374_839829468(p0, a0, b0);
}
break;
case ((Tmagic290524) 140):
case ((Tmagic290524) 94):
{
gencall_541632_839829468(p0, e0, d0);
}
break;
default:
{
NimStringDesc* LOC98;
LOC98 = (NimStringDesc*)0;
LOC98 = rawNewString(reprEnum((NI)op0, (&NTI290524))->Sup.len + 14);
appendString(LOC98, ((NimStringDesc*) &T839829468_523));
appendString(LOC98, reprEnum((NI)op0, (&NTI290524)));
internalerror_194100_155036129((*e0).info, LOC98);
}
break;
}
}
N_NIMCALL(Ropeobj177006*, gensetnode_547664_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Ropeobj177006* result0;
Tbitset337004* cs0;
NI size0;
NI64 LOC1;
result0 = (Ropeobj177006*)0;
cs0 = (Tbitset337004*)0;
LOC1 = (NI64)0;
LOC1 = getsize_318135_3876443242((*n0).typ);
size0 = ((NI) (LOC1));
tobitset_338001_452470228(n0, (&cs0));
{
NI id0;
Ropeobj177006* LOC6;
if (!(((NI) 8) < size0)) goto LA4;
id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels)));
LOC6 = (Ropeobj177006*)0;
LOC6 = rope_177401_2381377266(((NI64) (id0)));
result0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC6);
{
TY533238 LOC11;
if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA9;
(*(*p0).module).labels += ((NI) 1);
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = gettypedesc_533671_839829468((*p0).module, (*n0).typ);
LOC11[1] = result0;
LOC11[2] = genrawsetdata_547629_839829468(cs0, size0);
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC11, 3);
}
LA9: ;
}
goto LA2;
LA4: ;
{
result0 = genrawsetdata_547629_839829468(cs0, size0);
}
LA2: ;
return result0;
}
N_NIMCALL(void, gensetconstr_555496_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Tloc290816 idx0;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
memset((void*)(&idx0), 0, sizeof(idx0));
{
Ropeobj177006* LOC5;
if (!(((*e0).flags &(1U<<((NU)(((Tnodeflag290427) 4))&15U)))!=0)) goto LA3;
LOC5 = (Ropeobj177006*)0;
LOC5 = gensetnode_547664_839829468(p0, e0);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC5, ((Tstorageloc290812) 0));
}
goto LA1;
LA3: ;
{
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA9;
gettemp_535032_839829468(p0, (*e0).typ, d0, NIM_FALSE);
}
LA9: ;
{
NI64 LOC13;
TY177507 LOC16;
LOC13 = (NI64)0;
LOC13 = getsize_318135_3876443242((*e0).typ);
if (!(IL64(8) < LOC13)) goto LA14;
usestringh_530345_839829468((*p0).module);
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rdloc_536188_839829468((*d0));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_525), LOC16, 1);
{
NI i_555537_839829468;
NI HEX3Atmp_555603_839829468;
NI LOC18;
NI res_555606_839829468;
i_555537_839829468 = (NI)0;
HEX3Atmp_555603_839829468 = (NI)0;
LOC18 = (NI)0;
LOC18 = sonslen_293351_850551059(e0);
HEX3Atmp_555603_839829468 = (NI)(LOC18 - ((NI) 1));
res_555606_839829468 = ((NI) 0);
{
while (1) {
if (!(res_555606_839829468 <= HEX3Atmp_555603_839829468)) goto LA20;
i_555537_839829468 = res_555606_839829468;
{
Ttype290840* LOC25;
TY533235 LOC26;
if (!((*(*e0).kindU.S6.sons->data[i_555537_839829468]).kind == ((Tnodekind290020) 44))) goto LA23;
LOC25 = (Ttype290840*)0;
LOC25 = getsystype_336150_3937434831(((Ttypekind290244) 31));
gettemp_535032_839829468(p0, LOC25, (&idx0), NIM_FALSE);
initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555537_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0));
initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555537_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0));
memset((void*)LOC26, 0, sizeof(LOC26));
LOC26[0] = rdloc_536188_839829468(idx0);
LOC26[1] = rdloc_536188_839829468((*d0));
LOC26[2] = rdsetelemloc_553662_839829468(a0, (*e0).typ);
LOC26[3] = rdsetelemloc_553662_839829468(b0, (*e0).typ);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_526), LOC26, 4);
}
goto LA21;
LA23: ;
{
TY530811 LOC28;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[i_555537_839829468], (&a0));
memset((void*)LOC28, 0, sizeof(LOC28));
LOC28[0] = rdloc_536188_839829468((*d0));
LOC28[1] = rdsetelemloc_553662_839829468(a0, (*e0).typ);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_527), LOC28, 2);
}
LA21: ;
res_555606_839829468 += ((NI) 1);
} LA20: ;
}
}
}
goto LA11;
LA14: ;
{
NimStringDesc* ts0;
NimStringDesc* LOC30;
NI64 LOC31;
NimStringDesc* LOC32;
TY177507 LOC33;
LOC30 = (NimStringDesc*)0;
LOC31 = (NI64)0;
LOC31 = getsize_318135_3876443242((*e0).typ);
LOC32 = (NimStringDesc*)0;
LOC32 = nimInt64ToStr((NI64)(LOC31 * IL64(8)));
LOC30 = rawNewString(LOC32->Sup.len + 2);
appendString(LOC30, ((NimStringDesc*) &T839829468_45));
appendString(LOC30, LOC32);
ts0 = LOC30;
memset((void*)LOC33, 0, sizeof(LOC33));
LOC33[0] = rdloc_536188_839829468((*d0));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_494), LOC33, 1);
{
NI i_555575_839829468;
NI HEX3Atmp_555611_839829468;
NI LOC35;
NI res_555614_839829468;
i_555575_839829468 = (NI)0;
HEX3Atmp_555611_839829468 = (NI)0;
LOC35 = (NI)0;
LOC35 = sonslen_293351_850551059(e0);
HEX3Atmp_555611_839829468 = (NI)(LOC35 - ((NI) 1));
res_555614_839829468 = ((NI) 0);
{
while (1) {
if (!(res_555614_839829468 <= HEX3Atmp_555611_839829468)) goto LA37;
i_555575_839829468 = res_555614_839829468;
{
Ttype290840* LOC42;
NimStringDesc* LOC43;
TY533235 LOC44;
if (!((*(*e0).kindU.S6.sons->data[i_555575_839829468]).kind == ((Tnodekind290020) 44))) goto LA40;
LOC42 = (Ttype290840*)0;
LOC42 = getsystype_336150_3937434831(((Ttypekind290244) 31));
gettemp_535032_839829468(p0, LOC42, (&idx0), NIM_FALSE);
initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555575_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0));
initlocexpr_537283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_555575_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0));
LOC43 = (NimStringDesc*)0;
LOC43 = rawNewString(ts0->Sup.len + ts0->Sup.len + 68);
appendString(LOC43, ((NimStringDesc*) &T839829468_528));
appendString(LOC43, ts0);
appendString(LOC43, ((NimStringDesc*) &T839829468_529));
appendString(LOC43, ts0);
appendString(LOC43, ((NimStringDesc*) &T839829468_454));
memset((void*)LOC44, 0, sizeof(LOC44));
LOC44[0] = rdloc_536188_839829468(idx0);
LOC44[1] = rdloc_536188_839829468((*d0));
LOC44[2] = rdsetelemloc_553662_839829468(a0, (*e0).typ);
LOC44[3] = rdsetelemloc_553662_839829468(b0, (*e0).typ);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC43, LOC44, 4);
}
goto LA38;
LA40: ;
{
NimStringDesc* LOC46;
TY530811 LOC47;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[i_555575_839829468], (&a0));
LOC46 = (NimStringDesc*)0;
LOC46 = rawNewString(ts0->Sup.len + ts0->Sup.len + 36);
appendString(LOC46, ((NimStringDesc*) &T839829468_530));
appendString(LOC46, ts0);
appendString(LOC46, ((NimStringDesc*) &T839829468_531));
appendString(LOC46, ts0);
appendString(LOC46, ((NimStringDesc*) &T839829468_454));
memset((void*)LOC47, 0, sizeof(LOC47));
LOC47[0] = rdloc_536188_839829468((*d0));
LOC47[1] = rdsetelemloc_553662_839829468(a0, (*e0).typ);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), LOC46, LOC47, 2);
}
LA38: ;
res_555614_839829468 += ((NI) 1);
} LA37: ;
}
}
}
LA11: ;
}
LA1: ;
}
N_NIMCALL(void, exprcomplexconst_556684_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Ttype290840* t0;
Ropeobj177006* LOC1;
NI id0;
Ropeobj177006* tmp0;
Ropeobj177006* LOC2;
t0 = getuniquetype_526640_2036603609((*n0).typ);
LOC1 = (Ropeobj177006*)0;
LOC1 = gettypedesc_533671_839829468((*p0).module, t0);
id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels)));
LOC2 = (Ropeobj177006*)0;
LOC2 = rope_177401_2381377266(((NI64) (id0)));
tmp0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC2);
{
TY533238 LOC7;
if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA5;
(*(*p0).module).labels += ((NI) 1);
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC7[1] = tmp0;
LOC7[2] = genconstexpr_552849_839829468(p0, n0);
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC7, 3);
}
LA5: ;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA10;
fillloc_530282_839829468(d0, ((Tlockind290808) 8), t0, tmp0, ((Tstorageloc290812) 1));
}
goto LA8;
LA10: ;
{
putdataintodest_548436_839829468(p0, d0, t0, tmp0);
{
if (!!(((*t0).kind == ((Ttypekind290244) 24) || (*t0).kind == ((Ttypekind290244) 28)))) goto LA15;
(*d0).s = ((Tstorageloc290812) 1);
}
LA15: ;
}
LA8: ;
}
N_NIMCALL(NIM_BOOL, handleconstexpr_552853_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
{
NIM_BOOL LOC3;
NIM_BOOL LOC4;
NI LOC6;
Ttype290840* t0;
Ropeobj177006* LOC10;
NI id0;
Ropeobj177006* LOC11;
Ropeobj177006* LOC12;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = ((*d0).k == ((Tlockind290808) 0));
if (!(LOC4)) goto LA5;
LOC6 = (NI)0;
LOC6 = len_291081_850551059(n0);
LOC4 = (((NI) (((*n0).kind == ((Tnodekind290020) 38)))) < LOC6);
LA5: ;
LOC3 = LOC4;
if (!(LOC3)) goto LA7;
LOC3 = isdeepconstexpr_316566_2616423590(n0);
LA7: ;
if (!LOC3) goto LA8;
t0 = getuniquetype_526640_2036603609((*n0).typ);
LOC10 = (Ropeobj177006*)0;
LOC10 = gettypedesc_533671_839829468((*p0).module, t0);
id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels)));
LOC11 = (Ropeobj177006*)0;
LOC11 = rope_177401_2381377266(((NI64) (id0)));
LOC12 = (Ropeobj177006*)0;
LOC12 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC11);
fillloc_530282_839829468(d0, ((Tlockind290808) 8), t0, LOC12, ((Tstorageloc290812) 1));
{
TY533238 LOC17;
if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA15;
(*(*p0).module).labels += ((NI) 1);
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = gettypedesc_533671_839829468((*p0).module, t0);
LOC17[1] = (*d0).r;
LOC17[2] = genconstexpr_552849_839829468(p0, n0);
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3);
}
LA15: ;
result0 = NIM_TRUE;
}
goto LA1;
LA8: ;
{
result0 = NIM_FALSE;
}
LA1: ;
return result0;
}
N_NIMCALL(void, genarrayconstr_556207_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Tloc290816 arr0;
memset((void*)(&arr0), 0, sizeof(arr0));
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = handleconstexpr_552853_839829468(p0, n0, d0);
if (!!(LOC3)) goto LA4;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA8;
gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE);
}
LA8: ;
{
NI i_556234_839829468;
NI HEX3Atmp_556242_839829468;
NI LOC11;
NI res_556245_839829468;
i_556234_839829468 = (NI)0;
HEX3Atmp_556242_839829468 = (NI)0;
LOC11 = (NI)0;
LOC11 = sonslen_293351_850551059(n0);
HEX3Atmp_556242_839829468 = (NI)(LOC11 - ((NI) 1));
res_556245_839829468 = ((NI) 0);
{
while (1) {
Ttype290840* LOC14;
Ttype290840* LOC15;
TY530811 LOC16;
if (!(res_556245_839829468 <= HEX3Atmp_556242_839829468)) goto LA13;
i_556234_839829468 = res_556245_839829468;
LOC14 = (Ttype290840*)0;
LOC14 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256));
LOC15 = (Ttype290840*)0;
LOC15 = elemtype_318394_3876443242(LOC14);
initloc_530273_839829468((&arr0), ((Tlockind290808) 6), LOC15, (*d0).s);
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rdloc_536188_839829468((*d0));
LOC16[1] = intliteral_537270_839829468(((NI64) (i_556234_839829468)));
arr0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_138), LOC16, 2);
expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[i_556234_839829468], (&arr0));
res_556245_839829468 += ((NI) 1);
} LA13: ;
}
}
}
LA4: ;
}
N_NIMCALL(void, gentupleconstr_555618_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Tloc290816 rec0;
memset((void*)(&rec0), 0, sizeof(rec0));
{
NIM_BOOL LOC3;
Ttype290840* t0;
Ropeobj177006* LOC6;
LOC3 = (NIM_BOOL)0;
LOC3 = handleconstexpr_552853_839829468(p0, n0, d0);
if (!!(LOC3)) goto LA4;
t0 = getuniquetype_526640_2036603609((*n0).typ);
LOC6 = (Ropeobj177006*)0;
LOC6 = gettypedesc_533671_839829468((*p0).module, t0);
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA9;
gettemp_535032_839829468(p0, t0, d0, NIM_FALSE);
}
LA9: ;
{
NI i_555646_839829468;
NI HEX3Atmp_555803_839829468;
NI LOC12;
NI res_555806_839829468;
i_555646_839829468 = (NI)0;
HEX3Atmp_555803_839829468 = (NI)0;
LOC12 = (NI)0;
LOC12 = sonslen_293351_850551059(n0);
HEX3Atmp_555803_839829468 = (NI)(LOC12 - ((NI) 1));
res_555806_839829468 = ((NI) 0);
{
while (1) {
Tnode290802* it0;
TY530811 LOC19;
if (!(res_555806_839829468 <= HEX3Atmp_555803_839829468)) goto LA14;
i_555646_839829468 = res_555806_839829468;
it0 = (*n0).kindU.S6.sons->data[i_555646_839829468];
{
if (!((*it0).kind == ((Tnodekind290020) 34))) goto LA17;
it0 = (*it0).kindU.S6.sons->data[((NI) 1)];
}
LA17: ;
initloc_530273_839829468((&rec0), ((Tlockind290808) 6), (*it0).typ, (*d0).s);
memset((void*)LOC19, 0, sizeof(LOC19));
LOC19[0] = rdloc_536188_839829468((*d0));
LOC19[1] = rope_177401_2381377266(((NI64) (i_555646_839829468)));
rec0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_185), LOC19, 2);
expr_537248_839829468(p0, it0, (&rec0));
res_555806_839829468 += ((NI) 1);
} LA14: ;
}
}
}
LA4: ;
}
N_NIMCALL(Tsym290834*, lookupfieldagain_551153_839829468)(Tcproc527021* p0, Ttype290840* ty_551156_839829468, Tsym290834* field0, Ropeobj177006** r0) {
Tsym290834* result0;
Ttype290840* ty0;
result0 = (Tsym290834*)0;
ty0 = ty_551156_839829468;
{
while (1) {
if (!!((ty0 == NIM_NIL))) goto LA2;
ty0 = skiptypes_294099_850551059(ty0, IL64(211106247215360));
result0 = lookupinrecord_297119_2984716966((*ty0).n, (*field0).name);
{
if (!!((result0 == NIM_NIL))) goto LA5;
goto LA1;
}
LA5: ;
{
NIM_BOOL LOC9;
LOC9 = (NIM_BOOL)0;
LOC9 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC9) goto LA10;
LOC9 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA10: ;
if (!!(LOC9)) goto LA11;
add_177487_2381377266(r0, ((NimStringDesc*) &T839829468_153));
}
LA11: ;
ty0 = getuniquetype_526640_2036603609((*ty0).sons->data[((NI) 0)]);
} LA2: ;
} LA1: ;
{
if (!(result0 == NIM_NIL)) goto LA15;
internalerror_194100_155036129((*field0).info, ((NimStringDesc*) &T839829468_532));
}
LA15: ;
return result0;
}
N_NIMCALL(void, genfieldcheck_551504_839829468)(Tcproc527021* p0, Tnode290802* e0, Ropeobj177006* obj0, Tsym290834* field0, Ttype290840* origty0) {
Tloc290816 test0;
Tloc290816 u0;
Tloc290816 v0;
memset((void*)(&test0), 0, sizeof(test0));
memset((void*)(&u0), 0, sizeof(u0));
memset((void*)(&v0), 0, sizeof(v0));
{
NI i_551525_839829468;
NI HEX3Atmp_552039_839829468;
NI LOC2;
NI res_552042_839829468;
i_551525_839829468 = (NI)0;
HEX3Atmp_552039_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(e0);
HEX3Atmp_552039_839829468 = (NI)(LOC2 - ((NI) 1));
res_552042_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* it0;
Tsym290834* op0;
Tnode290802* disc0;
Ropeobj177006* o0;
Tsym290834* d0;
NI id0;
Tnode290802* LOC9;
Ropeobj177006* strlit0;
if (!(res_552042_839829468 <= HEX3Atmp_552039_839829468)) goto LA4;
i_551525_839829468 = res_552042_839829468;
it0 = (*e0).kindU.S6.sons->data[i_551525_839829468];
op0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
{
if (!((*op0).magic == ((Tmagic290524) 99))) goto LA7;
it0 = (*it0).kindU.S6.sons->data[((NI) 1)];
}
LA7: ;
disc0 = skipconv_326882_3876443242((*it0).kindU.S6.sons->data[((NI) 2)]);
initloc_530273_839829468((&test0), ((Tlockind290808) 0), (*it0).typ, ((Tstorageloc290812) 2));
initlocexpr_537283_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&u0));
o0 = obj0;
d0 = lookupfieldagain_551153_839829468(p0, origty0, (*disc0).kindU.S4.sym, &o0);
initloc_530273_839829468((&v0), ((Tlockind290808) 6), (*d0).typ, ((Tstorageloc290812) 0));
v0.r = o0;
add_177487_2381377266(&v0.r, ((NimStringDesc*) &T839829468_257));
add_177482_2381377266(&v0.r, (*d0).loc.r);
geninexpraux_551496_839829468(p0, it0, (&u0), (&v0), (&test0));
LOC9 = (Tnode290802*)0;
LOC9 = newstrnode_291678_850551059(((Tnodekind290020) 20), (*(*field0).name).s);
id0 = nodetabletestorset_340682_1142335848((&(*(*p0).module).datacache), LOC9, ((NI) ((*(*p0).module).labels)));
{
if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA12;
strlit0 = getstrlit_547468_839829468((*p0).module, (*(*field0).name).s);
}
goto LA10;
LA12: ;
{
Ropeobj177006* LOC15;
LOC15 = (Ropeobj177006*)0;
LOC15 = rope_177401_2381377266(((NI64) (id0)));
strlit0 = HEX26_177418_2381377266((*(*p0).module).tmpbase, LOC15);
}
LA10: ;
{
TY530811 LOC20;
if (!((*op0).magic == ((Tmagic290524) 99))) goto LA18;
memset((void*)LOC20, 0, sizeof(LOC20));
LOC20[0] = rdloc_536188_839829468(test0);
LOC20[1] = strlit0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_534), LOC20, 2);
}
goto LA16;
LA18: ;
{
TY530811 LOC22;
memset((void*)LOC22, 0, sizeof(LOC22));
LOC22[0] = rdloc_536188_839829468(test0);
LOC22[1] = strlit0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_535), LOC22, 2);
}
LA16: ;
res_552042_839829468 += ((NI) 1);
} LA4: ;
}
}
}
N_NIMCALL(void, genobjconstr_552903_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 tmp0;
Ttype290840* t0;
NIM_BOOL isref0;
Ropeobj177006* r0;
Ropeobj177006* LOC13;
Ttype290840* ty0;
{ {
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = handleconstexpr_552853_839829468(p0, e0, d0);
if (!LOC3) goto LA4;
goto BeforeRet;
}
LA4: ;
memset((void*)(&tmp0), 0, sizeof(tmp0));
t0 = skiptypes_294099_850551059((*e0).typ, IL64(211106232576256));
gettemp_535032_839829468(p0, t0, (&tmp0), NIM_FALSE);
isref0 = ((*t0).kind == ((Ttypekind290244) 22));
r0 = rdloc_536188_839829468(tmp0);
{
Ttype290840* LOC10;
TY177507 LOC11;
if (!isref0) goto LA8;
rawgennew_552741_839829468(p0, tmp0, NIM_NIL);
LOC10 = (Ttype290840*)0;
LOC10 = lastson_293377_850551059(t0);
t0 = skiptypes_294099_850551059(LOC10, IL64(211106232576256));
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = r0;
r0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC11, 1);
gcusage_552439_839829468(e0);
}
goto LA6;
LA8: ;
{
constructloc_536388_839829468(p0, tmp0, NIM_FALSE);
}
LA6: ;
LOC13 = (Ropeobj177006*)0;
LOC13 = gettypedesc_533671_839829468((*p0).module, t0);
ty0 = getuniquetype_526640_2036603609(t0);
{
NI i_552944_839829468;
NI HEX3Atmp_552997_839829468;
NI LOC15;
NI res_553000_839829468;
i_552944_839829468 = (NI)0;
HEX3Atmp_552997_839829468 = (NI)0;
LOC15 = (NI)0;
LOC15 = len_291081_850551059(e0);
HEX3Atmp_552997_839829468 = (LOC15 - 1);
res_553000_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* it0;
Tloc290816 tmp20;
Tsym290834* field0;
if (!(res_553000_839829468 <= HEX3Atmp_552997_839829468)) goto LA17;
i_552944_839829468 = res_553000_839829468;
it0 = (*e0).kindU.S6.sons->data[i_552944_839829468];
memset((void*)(&tmp20), 0, sizeof(tmp20));
tmp20.r = r0;
field0 = lookupfieldagain_551153_839829468(p0, ty0, (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym, &tmp20.r);
{
if (!((*field0).loc.r == NIM_NIL)) goto LA20;
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_533));
}
LA20: ;
{
NIM_BOOL LOC24;
NI LOC25;
LOC24 = (NIM_BOOL)0;
LOC25 = (NI)0;
LOC25 = len_291081_850551059(it0);
LOC24 = (LOC25 == ((NI) 3));
if (!(LOC24)) goto LA26;
LOC24 = (((*p0).options &(1U<<((NU)(((Toption168009) 2))&31U)))!=0);
LA26: ;
if (!LOC24) goto LA27;
genfieldcheck_551504_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 2)], r0, field0, ty0);
}
LA27: ;
add_177487_2381377266(&tmp20.r, ((NimStringDesc*) &T839829468_257));
add_177482_2381377266(&tmp20.r, (*field0).loc.r);
tmp20.k = ((Tlockind290808) 1);
tmp20.t = (*field0).loc.t;
{
if (!isref0) goto LA31;
tmp20.s = ((Tstorageloc290812) 3);
}
goto LA29;
LA31: ;
{
tmp20.s = ((Tstorageloc290812) 2);
}
LA29: ;
expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&tmp20));
res_553000_839829468 += ((NI) 1);
} LA17: ;
}
}
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA36;
genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI290816));
}
goto LA34;
LA36: ;
{
genassignment_537264_839829468(p0, (*d0), tmp0, 0);
}
LA34: ;
}BeforeRet: ;
}
N_NIMCALL(void, gencast_554537_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Ttype290840* destt0;
Ttype290840* srct0;
destt0 = skiptypes_294099_850551059((*e0).typ, IL64(211106233624832));
srct0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832));
{
NIM_BOOL LOC3;
Ropeobj177006* lbl0;
Tloc290816 tmp0;
TY177507 LOC7;
TY533238 LOC8;
TY177507 LOC9;
Ropeobj177006* LOC10;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*destt0).kind >= ((Ttypekind290244) 36) && (*destt0).kind <= ((Ttypekind290244) 39) || (*destt0).kind == ((Ttypekind290244) 18) || (*destt0).kind == ((Ttypekind290244) 17) || (*destt0).kind == ((Ttypekind290244) 16) || (*destt0).kind == ((Ttypekind290244) 4));
if (LOC3) goto LA4;
LOC3 = ((*srct0).kind >= ((Ttypekind290244) 36) && (*srct0).kind <= ((Ttypekind290244) 39) || (*srct0).kind == ((Ttypekind290244) 18) || (*srct0).kind == ((Ttypekind290244) 17) || (*srct0).kind == ((Ttypekind290244) 16) || (*srct0).kind == ((Ttypekind290244) 4));
LA4: ;
if (!LOC3) goto LA5;
(*p0).labels += ((NI) 1);
lbl0 = rope_177401_2381377266(((NI64) ((*p0).labels)));
memset((void*)(&tmp0), 0, sizeof(tmp0));
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = lbl0;
tmp0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_536), LOC7, 1);
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = gettypedesc_533671_839829468((*p0).module, srct0);
LOC8[1] = gettypedesc_533671_839829468((*p0).module, destt0);
LOC8[2] = lbl0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_537), LOC8, 3);
tmp0.k = ((Tlockind290808) 6);
tmp0.t = srct0;
tmp0.s = ((Tstorageloc290812) 2);
tmp0.flags = 0;
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0));
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = lbl0;
LOC10 = (Ropeobj177006*)0;
LOC10 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_538), LOC9, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC10, tmp0.s);
}
goto LA1;
LA5: ;
{
gensomecast_554480_839829468(p0, e0, d0);
}
LA1: ;
}
N_NIMCALL(void, genconv_554632_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Ttype290840* desttype0;
desttype0 = skiptypes_294099_850551059((*e0).typ, 8390656);
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = comparetypes_324214_3876443242(desttype0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, ((Tdistinctcompare322427) 1), 0);
if (!LOC3) goto LA4;
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0);
}
goto LA1;
LA4: ;
{
gensomecast_554480_839829468(p0, e0, d0);
}
LA1: ;
}
static N_INLINE(NIM_BOOL, iscppref_550807_839829468)(Tcproc527021* p0, Ttype290840* typ0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
NIM_BOOL LOC2;
NIM_BOOL LOC3;
Ttype290840* LOC6;
Ttype290840* LOC8;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC2 = (NIM_BOOL)0;
LOC3 = (NIM_BOOL)0;
LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC3) goto LA4;
LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA4: ;
LOC2 = LOC3;
if (!(LOC2)) goto LA5;
LOC6 = (Ttype290840*)0;
LOC6 = skiptypes_294099_850551059(typ0, IL64(211106232576256));
LOC2 = ((*LOC6).kind == ((Ttypekind290244) 23));
LA5: ;
LOC1 = LOC2;
if (!(LOC1)) goto LA7;
LOC8 = (Ttype290840*)0;
LOC8 = skiptypes_294099_850551059(typ0, IL64(211106232576256));
LOC1 = !((((*LOC8).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0));
LA7: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, genaddr_551051_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
{
Ttype290840* LOC3;
Tloc290816 a0;
Ropeobj177006* LOC6;
LOC3 = (Ttype290840*)0;
LOC3 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
if (!((*LOC3).kind == ((Ttypekind290244) 22) || (*LOC3).kind == ((Ttypekind290244) 21))) goto LA4;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0));
LOC6 = (Ropeobj177006*)0;
LOC6 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_52), a0.r);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC6, a0.s);
}
goto LA1;
LA4: ;
{
NIM_BOOL LOC8;
Tctypekind527007 LOC9;
LOC8 = (NIM_BOOL)0;
LOC9 = (Tctypekind527007)0;
LOC9 = maptype_531393_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ);
LOC8 = (LOC9 == ((Tctypekind527007) 17));
if (LOC8) goto LA10;
LOC8 = iscppref_550807_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 0)]).typ);
LA10: ;
if (!LOC8) goto LA11;
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0);
}
goto LA1;
LA11: ;
{
Tloc290816 a0;
Ropeobj177006* LOC14;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0));
LOC14 = (Ropeobj177006*)0;
LOC14 = addrloc_536204_839829468(a0);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC14, a0.s);
}
LA1: ;
}
N_NIMCALL(void, genarrayelem_552093_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Ttype290840* ty0;
Ttype290840* LOC1;
Ropeobj177006* first0;
NI64 LOC2;
Ttype290840* LOC47;
Ttype290840* LOC48;
TY533238 LOC49;
Ropeobj177006* LOC50;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, x0, (&a0));
initlocexpr_537283_839829468(p0, y0, (&b0));
LOC1 = (Ttype290840*)0;
LOC1 = skiptypes_294099_850551059(a0.t, IL64(211106242013440));
ty0 = skiptypes_294099_850551059(LOC1, IL64(211106247256320));
LOC2 = (NI64)0;
LOC2 = firstord_318001_3876443242(ty0);
first0 = intliteral_537270_839829468(LOC2);
{
NIM_BOOL LOC5;
LOC5 = (NIM_BOOL)0;
LOC5 = (((*p0).options &(1U<<((NU)(((Toption168009) 4))&31U)))!=0);
if (!(LOC5)) goto LA6;
LOC5 = !((((*ty0).flags &(1U<<((NU)(((Ttypeflag290431) 0))&31U)))!=0));
LA6: ;
if (!LOC5) goto LA7;
{
NIM_BOOL LOC11;
LOC11 = (NIM_BOOL)0;
LOC11 = isconstexpr_316510_2616423590(y0);
if (!!(LOC11)) goto LA12;
{
NI64 LOC16;
LOC16 = (NI64)0;
LOC16 = firstord_318001_3876443242(ty0);
if (!(LOC16 == IL64(0))) goto LA17;
{
NIM_BOOL LOC21;
NI64 LOC22;
NI64 LOC23;
NI64 LOC25;
NI64 LOC26;
TY530811 LOC29;
NI64 LOC30;
LOC21 = (NIM_BOOL)0;
LOC22 = (NI64)0;
LOC22 = firstord_318001_3876443242(b0.t);
LOC23 = (NI64)0;
LOC23 = firstord_318001_3876443242(ty0);
LOC21 = (LOC22 < LOC23);
if (LOC21) goto LA24;
LOC25 = (NI64)0;
LOC25 = lastord_318004_3876443242(ty0);
LOC26 = (NI64)0;
LOC26 = lastord_318004_3876443242(b0.t);
LOC21 = (LOC25 < LOC26);
LA24: ;
if (!LOC21) goto LA27;
memset((void*)LOC29, 0, sizeof(LOC29));
LOC29[0] = rdcharloc_536227_839829468(b0);
LOC30 = (NI64)0;
LOC30 = lastord_318004_3876443242(ty0);
LOC29[1] = intliteral_537270_839829468(LOC30);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_539), LOC29, 2);
}
LA27: ;
}
goto LA14;
LA17: ;
{
TY533238 LOC32;
NI64 LOC33;
memset((void*)LOC32, 0, sizeof(LOC32));
LOC32[0] = rdcharloc_536227_839829468(b0);
LOC32[1] = first0;
LOC33 = (NI64)0;
LOC33 = lastord_318004_3876443242(ty0);
LOC32[2] = intliteral_537270_839829468(LOC33);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_540), LOC32, 3);
}
LA14: ;
}
goto LA9;
LA12: ;
{
NI64 idx0;
idx0 = getordvalue_318129_3876443242(y0);
{
NIM_BOOL LOC37;
NI64 LOC38;
NI64 LOC40;
LOC37 = (NIM_BOOL)0;
LOC38 = (NI64)0;
LOC38 = firstord_318001_3876443242(ty0);
LOC37 = (idx0 < LOC38);
if (LOC37) goto LA39;
LOC40 = (NI64)0;
LOC40 = lastord_318004_3876443242(ty0);
LOC37 = (LOC40 < idx0);
LA39: ;
if (!LOC37) goto LA41;
localerror_194080_155036129((*x0).info, ((Tmsgkind189002) 86), ((NimStringDesc*) &T839829468_490));
}
LA41: ;
}
LA9: ;
}
LA7: ;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA45;
(*d0).s = a0.s;
}
LA45: ;
LOC47 = (Ttype290840*)0;
LOC47 = skiptypes_294099_850551059(ty0, IL64(211106240964864));
LOC48 = (Ttype290840*)0;
LOC48 = elemtype_318394_3876443242(LOC47);
memset((void*)LOC49, 0, sizeof(LOC49));
LOC49[0] = rdloc_536188_839829468(a0);
LOC49[1] = rdcharloc_536227_839829468(b0);
LOC49[2] = first0;
LOC50 = (Ropeobj177006*)0;
LOC50 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_541), LOC49, 3);
putintodest_548468_839829468(p0, d0, LOC48, LOC50, a0.s);
}
N_NIMCALL(void, genopenarrayelem_552169_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Ttype290840* LOC10;
Ttype290840* LOC11;
TY530811 LOC12;
Ropeobj177006* LOC13;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, x0, (&a0));
initlocexpr_537283_839829468(p0, y0, (&b0));
{
TY530811 LOC5;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 4))&31U)))!=0)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(b0);
LOC5[1] = rdloc_536188_839829468(a0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_542), LOC5, 2);
}
LA3: ;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA8;
(*d0).s = a0.s;
}
LA8: ;
LOC10 = (Ttype290840*)0;
LOC10 = skiptypes_294099_850551059(a0.t, IL64(211106240964864));
LOC11 = (Ttype290840*)0;
LOC11 = elemtype_318394_3876443242(LOC10);
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = rdloc_536188_839829468(a0);
LOC12[1] = rdcharloc_536227_839829468(b0);
LOC13 = (Ropeobj177006*)0;
LOC13 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC12, 2);
putintodest_548468_839829468(p0, d0, LOC11, LOC13, a0.s);
}
N_NIMCALL(void, genseqelem_552205_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Ttype290840* ty0;
Ttype290840* LOC27;
Ttype290840* LOC28;
TY530811 LOC29;
Ropeobj177006* LOC30;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, x0, (&a0));
initlocexpr_537283_839829468(p0, y0, (&b0));
ty0 = skiptypes_294099_850551059(a0.t, IL64(211106242013440));
{
Ttype290840* LOC5;
if (!((*ty0).kind == ((Ttypekind290244) 22) || (*ty0).kind == ((Ttypekind290244) 21))) goto LA3;
LOC5 = (Ttype290840*)0;
LOC5 = lastson_293377_850551059(ty0);
ty0 = skiptypes_294099_850551059(LOC5, IL64(211106242013440));
}
LA3: ;
{
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 4))&31U)))!=0)) goto LA8;
{
TY533238 LOC14;
if (!((*ty0).kind == ((Ttypekind290244) 28))) goto LA12;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = rdloc_536188_839829468(b0);
LOC14[1] = rdloc_536188_839829468(a0);
LOC14[2] = lenfield_537305_839829468(p0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_543), LOC14, 3);
}
goto LA10;
LA12: ;
{
TY533238 LOC16;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rdloc_536188_839829468(b0);
LOC16[1] = rdloc_536188_839829468(a0);
LOC16[2] = lenfield_537305_839829468(p0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_544), LOC16, 3);
}
LA10: ;
}
LA8: ;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA19;
(*d0).s = ((Tstorageloc290812) 3);
}
LA19: ;
{
Ttype290840* LOC23;
TY177507 LOC26;
LOC23 = (Ttype290840*)0;
LOC23 = skiptypes_294099_850551059(a0.t, IL64(211106240964864));
if (!((*LOC23).kind == ((Ttypekind290244) 22) || (*LOC23).kind == ((Ttypekind290244) 21))) goto LA24;
memset((void*)LOC26, 0, sizeof(LOC26));
LOC26[0] = a0.r;
a0.r = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC26, 1);
}
LA24: ;
LOC27 = (Ttype290840*)0;
LOC27 = skiptypes_294099_850551059(a0.t, IL64(211106240964864));
LOC28 = (Ttype290840*)0;
LOC28 = elemtype_318394_3876443242(LOC27);
memset((void*)LOC29, 0, sizeof(LOC29));
LOC29[0] = rdloc_536188_839829468(a0);
LOC29[1] = rdcharloc_536227_839829468(b0);
LOC30 = (Ropeobj177006*)0;
LOC30 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC29, 2);
putintodest_548468_839829468(p0, d0, LOC28, LOC30, a0.s);
}
N_NIMCALL(void, gencstringelem_552144_839829468)(Tcproc527021* p0, Tnode290802* x0, Tnode290802* y0, Tloc290816* d0) {
Tloc290816 a0;
Tloc290816 b0;
Ttype290840* ty0;
Ttype290840* LOC5;
Ttype290840* LOC6;
TY530811 LOC7;
Ropeobj177006* LOC8;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, x0, (&a0));
initlocexpr_537283_839829468(p0, y0, (&b0));
ty0 = skiptypes_294099_850551059(a0.t, IL64(211106242013440));
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA3;
(*d0).s = a0.s;
}
LA3: ;
LOC5 = (Ttype290840*)0;
LOC5 = skiptypes_294099_850551059(ty0, IL64(211106240964864));
LOC6 = (Ttype290840*)0;
LOC6 = elemtype_318394_3876443242(LOC5);
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = rdloc_536188_839829468(a0);
LOC7[1] = rdcharloc_536227_839829468(b0);
LOC8 = (Ropeobj177006*)0;
LOC8 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC7, 2);
putintodest_548468_839829468(p0, d0, LOC6, LOC8, a0.s);
}
N_NIMCALL(void, gentupleelem_551124_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
NI i0;
Ropeobj177006* LOC5;
Ttype290840* ty0;
Ropeobj177006* r0;
TY177507 LOC8;
memset((void*)(&a0), 0, sizeof(a0));
i0 = (NI)0;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0));
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA3;
(*d0).s = a0.s;
}
LA3: ;
LOC5 = (Ropeobj177006*)0;
LOC5 = gettypedesc_533671_839829468((*p0).module, a0.t);
ty0 = getuniquetype_526640_2036603609(a0.t);
r0 = rdloc_536188_839829468(a0);
switch ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind) {
case ((Tnodekind290020) 6) ... ((Tnodekind290020) 15):
{
i0 = ((NI) ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval));
}
break;
default:
{
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_545));
}
break;
}
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rope_177401_2381377266(((NI64) (i0)));
addf_178205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC8, 1);
putintodest_548468_839829468(p0, d0, (*ty0).sons->data[i0], r0, a0.s);
}
N_NIMCALL(void, genbracketexpr_552277_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Ttype290840* ty0;
ty0 = skiptypes_294099_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440));
{
Ttype290840* LOC5;
if (!((*ty0).kind == ((Ttypekind290244) 22) || (*ty0).kind == ((Ttypekind290244) 21))) goto LA3;
LOC5 = (Ttype290840*)0;
LOC5 = lastson_293377_850551059(ty0);
ty0 = skiptypes_294099_850551059(LOC5, IL64(211106242013440));
}
LA3: ;
switch ((*ty0).kind) {
case ((Ttypekind290244) 16):
case ((Ttypekind290244) 4):
{
genarrayelem_552093_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0);
}
break;
case ((Ttypekind290244) 27):
case ((Ttypekind290244) 48):
{
genopenarrayelem_552169_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0);
}
break;
case ((Ttypekind290244) 24):
case ((Ttypekind290244) 28):
{
genseqelem_552205_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0);
}
break;
case ((Ttypekind290244) 29):
{
gencstringelem_552144_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0);
}
break;
case ((Ttypekind290244) 18):
{
gentupleelem_551124_839829468(p0, n0, d0);
}
break;
default:
{
NimStringDesc* LOC12;
LOC12 = (NimStringDesc*)0;
LOC12 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI290244))->Sup.len + 21);
appendString(LOC12, ((NimStringDesc*) &T839829468_547));
appendString(LOC12, reprEnum((NI)(*ty0).kind, (&NTI290244)));
appendChar(LOC12, 41);
internalerror_194100_155036129((*n0).info, LOC12);
}
break;
}
}
N_NIMCALL(void, genderef_541921_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, NIM_BOOL enforcederef0) {
Tctypekind527007 mt0;
{ mt0 = maptype_531393_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ);
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = ((393216 &(1U<<((NU)(mt0)&31U)))!=0);
if (!(LOC3)) goto LA4;
LOC3 = !(enforcederef0);
LA4: ;
if (!LOC3) goto LA5;
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0);
{
Ttype290840* LOC9;
LOC9 = (Ttype290840*)0;
LOC9 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
if (!((*LOC9).kind == ((Ttypekind290244) 22))) goto LA10;
(*d0).s = ((Tstorageloc290812) 3);
}
LA10: ;
}
goto LA1;
LA5: ;
{
Tloc290816 a0;
Ttype290840* typ0;
memset((void*)(&a0), 0, sizeof(a0));
typ0 = skiptypes_294099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
{
NIM_BOOL LOC15;
NIM_BOOL LOC16;
NIM_BOOL LOC17;
NIM_BOOL LOC20;
Tnode290802* LOC25;
Tnode290802* LOC26;
LOC15 = (NIM_BOOL)0;
LOC16 = (NIM_BOOL)0;
LOC17 = (NIM_BOOL)0;
LOC17 = ((*typ0).kind == ((Ttypekind290244) 23));
if (!(LOC17)) goto LA18;
LOC17 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0));
LA18: ;
LOC16 = LOC17;
if (!(LOC16)) goto LA19;
LOC20 = (NIM_BOOL)0;
LOC20 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC20) goto LA21;
LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA21: ;
LOC16 = LOC20;
LA19: ;
LOC15 = LOC16;
if (!(LOC15)) goto LA22;
LOC15 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 64));
LA22: ;
if (!LOC15) goto LA23;
LOC25 = (Tnode290802*)0;
LOC25 = HEX5BHEX5D_291238_850551059(e0, ((NI) 0));
LOC26 = (Tnode290802*)0;
LOC26 = HEX5BHEX5D_291238_850551059(LOC25, ((NI) 0));
initlocexprsingleuse_537289_839829468(p0, LOC26, d0);
goto BeforeRet;
}
goto LA13;
LA23: ;
{
initlocexprsingleuse_537289_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0));
}
LA13: ;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA30;
switch ((*typ0).kind) {
case ((Ttypekind290244) 22):
{
(*d0).s = ((Tstorageloc290812) 3);
}
break;
case ((Ttypekind290244) 23):
{
(*d0).s = ((Tstorageloc290812) 0);
{
NIM_BOOL LOC36;
NIM_BOOL LOC37;
NIM_BOOL LOC39;
Ropeobj177006* LOC44;
LOC36 = (NIM_BOOL)0;
LOC37 = (NIM_BOOL)0;
LOC37 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0));
if (!(LOC37)) goto LA38;
LOC39 = (NIM_BOOL)0;
LOC39 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC39) goto LA40;
LOC39 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA40: ;
LOC37 = LOC39;
LA38: ;
LOC36 = LOC37;
if (!(LOC36)) goto LA41;
LOC36 = ((*e0).kind == ((Tnodekind290020) 65));
LA41: ;
if (!LOC36) goto LA42;
LOC44 = (Ropeobj177006*)0;
LOC44 = rdloc_536188_839829468(a0);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC44, a0.s);
goto BeforeRet;
}
LA42: ;
}
break;
case ((Ttypekind290244) 21):
{
(*d0).s = ((Tstorageloc290812) 0);
}
break;
default:
{
NimStringDesc* LOC47;
LOC47 = (NimStringDesc*)0;
LOC47 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI290244))->Sup.len + 9);
appendString(LOC47, ((NimStringDesc*) &T839829468_548));
appendString(LOC47, reprEnum((NI)(*typ0).kind, (&NTI290244)));
internalerror_194100_155036129((*e0).info, LOC47);
}
break;
}
}
goto LA28;
LA30: ;
{
NIM_BOOL LOC49;
LOC49 = (NIM_BOOL)0;
LOC49 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC49) goto LA50;
LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA50: ;
if (!LOC49) goto LA51;
{
NIM_BOOL LOC55;
NIM_BOOL LOC56;
Ropeobj177006* LOC61;
LOC55 = (NIM_BOOL)0;
LOC56 = (NIM_BOOL)0;
LOC56 = ((*typ0).kind == ((Ttypekind290244) 23));
if (!(LOC56)) goto LA57;
LOC56 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag290431) 18))&31U)))!=0));
LA57: ;
LOC55 = LOC56;
if (!(LOC55)) goto LA58;
LOC55 = ((*e0).kind == ((Tnodekind290020) 65));
LA58: ;
if (!LOC55) goto LA59;
LOC61 = (Ropeobj177006*)0;
LOC61 = rdloc_536188_839829468(a0);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC61, a0.s);
goto BeforeRet;
}
LA59: ;
}
goto LA28;
LA51: ;
LA28: ;
{
NIM_BOOL LOC64;
Ropeobj177006* LOC68;
LOC64 = (NIM_BOOL)0;
LOC64 = enforcederef0;
if (!(LOC64)) goto LA65;
LOC64 = (mt0 == ((Tctypekind527007) 18));
LA65: ;
if (!LOC64) goto LA66;
LOC68 = (Ropeobj177006*)0;
LOC68 = rdloc_536188_839829468(a0);
putintodest_548468_839829468(p0, d0, (*a0.t).sons->data[((NI) 0)], LOC68, a0.s);
}
goto LA62;
LA66: ;
{
TY177507 LOC70;
Ropeobj177006* LOC71;
memset((void*)LOC70, 0, sizeof(LOC70));
LOC70[0] = rdloc_536188_839829468(a0);
LOC71 = (Ropeobj177006*)0;
LOC71 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC70, 1);
putintodest_548468_839829468(p0, d0, (*e0).typ, LOC71, a0.s);
}
LA62: ;
}
LA1: ;
}BeforeRet: ;
}
N_NIMCALL(Ttype290840*, genrecordfieldaux_551096_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0, Tloc290816* a0) {
Ttype290840* result0;
Ropeobj177006* LOC9;
result0 = (Ttype290840*)0;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], a0);
{
if (!!(((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind290020) 3)))) goto LA3;
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_549));
}
LA3: ;
{
if (!((*d0).k == ((Tlockind290808) 0))) goto LA7;
(*d0).s = (*a0).s;
}
LA7: ;
LOC9 = (Ropeobj177006*)0;
LOC9 = gettypedesc_533671_839829468((*p0).module, (*a0).t);
result0 = getuniquetype_526640_2036603609((*a0).t);
return result0;
}
N_NIMCALL(void, genrecordfield_551448_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
Tloc290816 a0;
Ttype290840* ty0;
Ropeobj177006* r0;
Tsym290834* f0;
memset((void*)(&a0), 0, sizeof(a0));
ty0 = genrecordfieldaux_551096_839829468(p0, e0, d0, (&a0));
r0 = rdloc_536188_839829468(a0);
f0 = (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym;
{
TY177507 LOC5;
if (!((*ty0).kind == ((Ttypekind290244) 18))) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rope_177401_2381377266(((NI64) ((*f0).position)));
addf_178205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC5, 1);
putintodest_548468_839829468(p0, d0, (*f0).typ, r0, a0.s);
}
goto LA1;
LA3: ;
{
Tsym290834* field0;
TY177507 LOC11;
field0 = lookupfieldagain_551153_839829468(p0, ty0, f0, &r0);
{
if (!((*field0).loc.r == NIM_NIL)) goto LA9;
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_550));
}
LA9: ;
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = (*field0).loc.r;
addf_178205_2381377266(&r0, ((NimStringDesc*) &T839829468_551), LOC11, 1);
putintodest_548468_839829468(p0, d0, (*field0).typ, r0, a0.s);
}
LA1: ;
}
N_NIMCALL(void, gencheckedrecordfield_552046_839829468)(Tcproc527021* p0, Tnode290802* e0, Tloc290816* d0) {
{
Tloc290816 a0;
Ttype290840* ty0;
Ropeobj177006* r0;
Tsym290834* f0;
Tsym290834* field0;
TY177507 LOC9;
Ropeobj177006* LOC10;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 2))&31U)))!=0)) goto LA3;
memset((void*)(&a0), 0, sizeof(a0));
ty0 = genrecordfieldaux_551096_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0, (&a0));
r0 = rdloc_536188_839829468(a0);
f0 = (*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym;
field0 = lookupfieldagain_551153_839829468(p0, ty0, f0, &r0);
{
if (!((*field0).loc.r == NIM_NIL)) goto LA7;
internalerror_194100_155036129((*e0).info, ((NimStringDesc*) &T839829468_532));
}
LA7: ;
genfieldcheck_551504_839829468(p0, e0, r0, field0, ty0);
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = (*field0).loc.r;
LOC10 = (Ropeobj177006*)0;
LOC10 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_551), LOC9, 1);
add_177482_2381377266(&r0, LOC10);
putintodest_548468_839829468(p0, d0, (*field0).typ, r0, a0.s);
}
goto LA1;
LA3: ;
{
genrecordfield_551448_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0);
}
LA1: ;
}
N_NIMCALL(NI, startblock_541978_839829468)(Tcproc527021* p0, NimStringDesc* start0, Ropeobj177006** args0, NI args0Len0) {
NI result0;
result0 = (NI)0;
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), start0, args0, args0Len0);
(*p0).labels += ((NI) 1);
result0 = ((*p0).blocks ? (*p0).blocks->Sup.len : 0);
(*p0).blocks = (TY527095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock527019), ((NI) ((NI)(result0 + ((NI) 1)))));
(*p0).blocks->data[result0].id = ((NI) ((*p0).labels));
(*p0).blocks->data[result0].nestedtrystmts = ((NI16) (((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0)));
(*p0).blocks->data[result0].nestedexceptstmts = ((NI16) ((*p0).inexceptblock));
return result0;
}
N_NIMCALL(Ropeobj177006*, blockbody_542025_839829468)(Tblock527019* b0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = (*b0).sections[(((Tcprocsection527011) 0))- 0];
{
TY177507 LOC5;
if (!(((NI16) 0) < (*b0).framelen)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rope_177401_2381377266(((NI64) ((*b0).framelen)));
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_554), LOC5, 1);
}
LA3: ;
add_177482_2381377266(&result0, (*b0).sections[(((Tcprocsection527011) 1))- 0]);
add_177482_2381377266(&result0, (*b0).sections[(((Tcprocsection527011) 2))- 0]);
return result0;
}
N_NIMCALL(void, endblock_542035_839829468)(Tcproc527021* p0, Ropeobj177006* blockend0) {
NI topblock0;
Ropeobj177006* LOC1;
topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1));
LOC1 = (Ropeobj177006*)0;
LOC1 = blockbody_542025_839829468((&(*p0).blocks->data[topblock0]));
add_177482_2381377266(&(*p0).blocks->data[(NI)(topblock0 - ((NI) 1))].sections[(((Tcprocsection527011) 2))- 0], LOC1);
(*p0).blocks = (TY527095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock527019), ((NI) (topblock0)));
line_530690_839829468(p0, ((Tcprocsection527011) 2), blockend0);
}
N_NIMCALL(void, endblock_542060_839829468)(Tcproc527021* p0) {
NI topblock0;
Ropeobj177006* blockend0;
NI16 framelen0;
topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1));
{
TY177507 LOC5;
if (!!(((*p0).blocks->data[topblock0].label == NIM_NIL))) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = (*p0).blocks->data[topblock0].label;
blockend0 = ropecg_530407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_552), LOC5, 1);
}
goto LA1;
LA3: ;
{
TY531289 LOC7;
memset((void*)LOC7, 0, sizeof(LOC7));
blockend0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_160), LOC7, 0);
}
LA1: ;
framelen0 = (*p0).blocks->data[topblock0].framelen;
{
TY177507 LOC12;
if (!(((NI16) 0) < framelen0)) goto LA10;
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = rope_177401_2381377266(((NI64) (framelen0)));
addf_178205_2381377266(&blockend0, ((NimStringDesc*) &T839829468_553), LOC12, 1);
}
LA10: ;
endblock_542035_839829468(p0, blockend0);
}
N_NIMCALL(void, genblock_544083_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
NI oldbreakidx_544099_839829468;
TY531289 LOC8;
{
NIM_BOOL LOC3;
NIM_BOOL LOC4;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = isemptytype_295440_850551059((*n0).typ);
LOC3 = !(LOC4);
if (!(LOC3)) goto LA5;
LOC3 = ((*d0).k == ((Tlockind290808) 0));
LA5: ;
if (!LOC3) goto LA6;
gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE);
}
LA6: ;
oldbreakidx_544099_839829468 = (*p0).breakidx;
memset((void*)LOC8, 0, sizeof(LOC8));
(*p0).breakidx = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC8, 0);
{
Tsym290834* sym0;
if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA11;
sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
(*sym0).loc.k = ((Tlockind290808) 10);
(*sym0).position = (NI)((*p0).breakidx + ((NI) 1));
}
LA11: ;
expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], d0);
endblock_542060_839829468(p0);
(*p0).breakidx = oldbreakidx_544099_839829468;
}
N_NIMCALL(void, genstmtlistexpr_556402_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
NI length0;
length0 = sonslen_293351_850551059(n0);
{
NI i_556420_839829468;
NI HEX3Atmp_556424_839829468;
NI res_556427_839829468;
i_556420_839829468 = (NI)0;
HEX3Atmp_556424_839829468 = (NI)0;
HEX3Atmp_556424_839829468 = (NI)(length0 - ((NI) 2));
res_556427_839829468 = ((NI) 0);
{
while (1) {
if (!(res_556427_839829468 <= HEX3Atmp_556424_839829468)) goto LA3;
i_556420_839829468 = res_556427_839829468;
genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[i_556420_839829468]);
res_556427_839829468 += ((NI) 1);
} LA3: ;
}
}
{
if (!(((NI) 0) < length0)) goto LA6;
expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0);
}
LA6: ;
}
N_NIMCALL(void, genif_542982_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Tloc290816 a0;
Ropeobj177006* lelse0;
Ropeobj177006* lend0;
memset((void*)(&a0), 0, sizeof(a0));
lelse0 = (Ropeobj177006*)0;
{
NIM_BOOL LOC3;
NIM_BOOL LOC4;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = isemptytype_295440_850551059((*n0).typ);
LOC3 = !(LOC4);
if (!(LOC3)) goto LA5;
LOC3 = ((*d0).k == ((Tlockind290808) 0));
LA5: ;
if (!LOC3) goto LA6;
gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE);
}
LA6: ;
genlinedir_530823_839829468(p0, n0);
lend0 = getlabel_537217_839829468(p0);
{
NI i_543011_839829468;
NI HEX3Atmp_543435_839829468;
NI LOC9;
NI res_543438_839829468;
i_543011_839829468 = (NI)0;
HEX3Atmp_543435_839829468 = (NI)0;
LOC9 = (NI)0;
LOC9 = sonslen_293351_850551059(n0);
HEX3Atmp_543435_839829468 = (NI)(LOC9 - ((NI) 1));
res_543438_839829468 = ((NI) 0);
{
while (1) {
Tnode290802* it0;
if (!(res_543438_839829468 <= HEX3Atmp_543435_839829468)) goto LA11;
i_543011_839829468 = res_543438_839829468;
{
NIM_BOOL LOC14;
LOC14 = (NIM_BOOL)0;
LOC14 = ((*d0).k == ((Tlockind290808) 1));
if (!(LOC14)) goto LA15;
LOC14 = isemptytype_295440_850551059((*n0).typ);
LA15: ;
if (!LOC14) goto LA16;
(*d0).k = ((Tlockind290808) 0);
}
LA16: ;
it0 = (*n0).kindU.S6.sons->data[i_543011_839829468];
{
NI LOC20;
TY531289 LOC23;
NI LOC24;
TY530811 LOC25;
LOC20 = (NI)0;
LOC20 = len_291081_850551059(it0);
if (!(LOC20 == ((NI) 2))) goto LA21;
memset((void*)LOC23, 0, sizeof(LOC23));
LOC24 = (NI)0;
LOC24 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC23, 0);
initlocexprsingleuse_537289_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], (&a0));
lelse0 = getlabel_537217_839829468(p0);
(*p0).labels += ((NI) 1);
memset((void*)LOC25, 0, sizeof(LOC25));
LOC25[0] = rdloc_536188_839829468(a0);
LOC25[1] = lelse0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_555), LOC25, 2);
{
NIM_BOOL LOC28;
Ropeobj177006** LOC32;
Ropeobj177006** LOC33;
LOC28 = (NIM_BOOL)0;
LOC28 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC28) goto LA29;
LOC28 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA29: ;
if (!LOC28) goto LA30;
LOC32 = (Ropeobj177006**)0;
LOC32 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177487_2381377266(LOC32, ((NimStringDesc*) &T839829468_223));
expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0);
LOC33 = (Ropeobj177006**)0;
LOC33 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177487_2381377266(LOC33, ((NimStringDesc*) &T839829468_280));
}
goto LA26;
LA30: ;
{
expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0);
}
LA26: ;
endblock_542060_839829468(p0);
{
NI LOC37;
TY177507 LOC40;
LOC37 = (NI)0;
LOC37 = sonslen_293351_850551059(n0);
if (!(((NI) 1) < LOC37)) goto LA38;
memset((void*)LOC40, 0, sizeof(LOC40));
LOC40[0] = lend0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_556), LOC40, 1);
}
LA38: ;
fixlabel_537230_839829468(p0, lelse0);
}
goto LA18;
LA21: ;
{
NI LOC42;
TY531289 LOC45;
NI LOC46;
LOC42 = (NI)0;
LOC42 = len_291081_850551059(it0);
if (!(LOC42 == ((NI) 1))) goto LA43;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC46 = (NI)0;
LOC46 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0);
expr_537248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], d0);
endblock_542060_839829468(p0);
}
goto LA18;
LA43: ;
{
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_557));
}
LA18: ;
res_543438_839829468 += ((NI) 1);
} LA11: ;
}
}
{
NI LOC50;
LOC50 = (NI)0;
LOC50 = sonslen_293351_850551059(n0);
if (!(((NI) 1) < LOC50)) goto LA51;
fixlabel_537230_839829468(p0, lend0);
}
LA51: ;
}
N_NIMCALL(void, downconv_556581_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC3) goto LA4;
LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA4: ;
if (!LOC3) goto LA5;
expr_537248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], d0);
}
goto LA1;
LA5: ;
{
Ttype290840* dest0;
Tnode290802* arg0;
Ttype290840* src0;
Tloc290816 a0;
Ropeobj177006* r0;
NIM_BOOL isref0;
Ttype290840* LOC10;
dest0 = skiptypes_294099_850551059((*n0).typ, IL64(211106247256320));
arg0 = (*n0).kindU.S6.sons->data[((NI) 0)];
{
while (1) {
if (!((*arg0).kind == ((Tnodekind290020) 66))) goto LA9;
arg0 = (*arg0).kindU.S6.sons->data[((NI) 0)];
} LA9: ;
}
src0 = skiptypes_294099_850551059((*arg0).typ, IL64(211106247256320));
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, arg0, (&a0));
r0 = rdloc_536188_839829468(a0);
LOC10 = (Ttype290840*)0;
LOC10 = skiptypes_294099_850551059((*arg0).typ, IL64(211106232576256));
isref0 = ((*LOC10).kind == ((Ttypekind290244) 22) || (*LOC10).kind == ((Ttypekind290244) 21) || (*LOC10).kind == ((Ttypekind290244) 23));
{
if (!isref0) goto LA13;
add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_558));
}
goto LA11;
LA13: ;
{
add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153));
}
LA11: ;
{
NI i_556650_839829468;
NI HEX3Atmp_556677_839829468;
NI LOC17;
NI res_556680_839829468;
i_556650_839829468 = (NI)0;
HEX3Atmp_556677_839829468 = (NI)0;
LOC17 = (NI)0;
LOC17 = inheritancediff_324252_3876443242(dest0, src0);
HEX3Atmp_556677_839829468 = (LOC17 > 0? (LOC17) : -(LOC17));
res_556680_839829468 = ((NI) 2);
{
while (1) {
if (!(res_556680_839829468 <= HEX3Atmp_556677_839829468)) goto LA19;
i_556650_839829468 = res_556680_839829468;
add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153));
res_556680_839829468 += ((NI) 1);
} LA19: ;
}
}
{
if (!isref0) goto LA22;
{
NIM_BOOL LOC26;
Ttype290840* LOC28;
TY530811 LOC31;
LOC26 = (NIM_BOOL)0;
LOC26 = ((*d0).k == ((Tlockind290808) 0));
if (!(LOC26)) goto LA27;
LOC28 = (Ttype290840*)0;
LOC28 = skiptypes_294099_850551059((*n0).typ, IL64(211106232576256));
LOC26 = ((*LOC28).kind == ((Ttypekind290244) 22) || (*LOC28).kind == ((Ttypekind290244) 21) || (*LOC28).kind == ((Ttypekind290244) 23));
LA27: ;
if (!LOC26) goto LA29;
gettemp_535032_839829468(p0, (*n0).typ, d0, NIM_FALSE);
memset((void*)LOC31, 0, sizeof(LOC31));
LOC31[0] = rdloc_536188_839829468((*d0));
LOC31[1] = r0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_559), LOC31, 2);
}
goto LA24;
LA29: ;
{
r0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_52), r0);
putintodest_548468_839829468(p0, d0, (*n0).typ, r0, a0.s);
}
LA24: ;
}
goto LA20;
LA22: ;
{
putintodest_548468_839829468(p0, d0, (*n0).typ, r0, a0.s);
}
LA20: ;
}
LA1: ;
}
N_NIMCALL(void, upconv_556431_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Tloc290816 a0;
Ttype290840* dest0;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
dest0 = skiptypes_294099_850551059((*n0).typ, IL64(211106247256320));
{
NIM_BOOL LOC3;
NIM_BOOL LOC5;
Ropeobj177006* r0;
Ropeobj177006* nilcheck0;
Ttype290840* t0;
LOC3 = (NIM_BOOL)0;
LOC3 = (((*p0).options &(1U<<((NU)(((Toption168009) 1))&31U)))!=0);
if (!(LOC3)) goto LA4;
LOC5 = (NIM_BOOL)0;
LOC5 = isobjlackingtypefield_531513_839829468(dest0);
LOC3 = !(LOC5);
LA4: ;
if (!LOC3) goto LA6;
r0 = rdloc_536188_839829468(a0);
nilcheck0 = NIM_NIL;
t0 = skiptypes_294099_850551059(a0.t, IL64(211106232576256));
{
while (1) {
Ttype290840* LOC23;
if (!((*t0).kind == ((Ttypekind290244) 23) || (*t0).kind == ((Ttypekind290244) 21) || (*t0).kind == ((Ttypekind290244) 22))) goto LA9;
{
if (!!(((*t0).kind == ((Ttypekind290244) 23)))) goto LA12;
nilcheck0 = r0;
}
LA12: ;
{
NIM_BOOL LOC16;
NIM_BOOL LOC18;
TY177507 LOC22;
LOC16 = (NIM_BOOL)0;
LOC16 = !(((*t0).kind == ((Ttypekind290244) 23)));
if (LOC16) goto LA17;
LOC18 = (NIM_BOOL)0;
LOC18 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC18) goto LA19;
LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA19: ;
LOC16 = !(LOC18);
LA17: ;
if (!LOC16) goto LA20;
memset((void*)LOC22, 0, sizeof(LOC22));
LOC22[0] = r0;
r0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_124), LOC22, 1);
}
LA20: ;
LOC23 = (Ttype290840*)0;
LOC23 = lastson_293377_850551059(t0);
t0 = skiptypes_294099_850551059(LOC23, IL64(211106232576256));
} LA9: ;
}
{
NIM_BOOL LOC26;
LOC26 = (NIM_BOOL)0;
LOC26 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC26) goto LA27;
LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA27: ;
if (!!(LOC26)) goto LA28;
{
while (1) {
NIM_BOOL LOC32;
LOC32 = (NIM_BOOL)0;
LOC32 = ((*t0).kind == ((Ttypekind290244) 17));
if (!(LOC32)) goto LA33;
LOC32 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL));
LA33: ;
if (!LOC32) goto LA31;
add_177487_2381377266(&r0, ((NimStringDesc*) &T839829468_153));
t0 = skiptypes_294099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360));
} LA31: ;
}
}
LA28: ;
{
TY533238 LOC38;
if (!!((nilcheck0 == NIM_NIL))) goto LA36;
memset((void*)LOC38, 0, sizeof(LOC38));
LOC38[0] = nilcheck0;
LOC38[1] = r0;
LOC38[2] = gentypeinfo_533941_839829468((*p0).module, dest0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_560), LOC38, 3);
}
goto LA34;
LA36: ;
{
TY530811 LOC40;
memset((void*)LOC40, 0, sizeof(LOC40));
LOC40[0] = r0;
LOC40[1] = gentypeinfo_533941_839829468((*p0).module, dest0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_561), LOC40, 2);
}
LA34: ;
}
LA6: ;
{
TY530811 LOC45;
Ropeobj177006* LOC46;
if (!!(((*(*(*n0).kindU.S6.sons->data[((NI) 0)]).typ).kind == ((Ttypekind290244) 17)))) goto LA43;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC45[0] = gettypedesc_533671_839829468((*p0).module, (*n0).typ);
LOC45[1] = rdloc_536188_839829468(a0);
LOC46 = (Ropeobj177006*)0;
LOC46 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC45, 2);
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC46, a0.s);
}
goto LA41;
LA43: ;
{
TY530811 LOC48;
Ropeobj177006* LOC49;
memset((void*)LOC48, 0, sizeof(LOC48));
LOC48[0] = gettypedesc_533671_839829468((*p0).module, dest0);
LOC48[1] = addrloc_536204_839829468(a0);
LOC49 = (Ropeobj177006*)0;
LOC49 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_429), LOC48, 2);
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC49, a0.s);
}
LA41: ;
}
N_NIMCALL(void, genrangechck_554590_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0, NimStringDesc* magic0) {
Tloc290816 a0;
Ttype290840* dest0;
memset((void*)(&a0), 0, sizeof(a0));
dest0 = skiptypes_294099_850551059((*n0).typ, IL64(211106240964864));
{
NIM_BOOL LOC3;
Ttype290840* LOC5;
TY530811 LOC8;
Ropeobj177006* LOC9;
LOC3 = (NIM_BOOL)0;
LOC3 = !((((*p0).options &(1U<<((NU)(((Toption168009) 3))&31U)))!=0));
if (LOC3) goto LA4;
LOC5 = (Ttype290840*)0;
LOC5 = skiptypes_294099_850551059(dest0, 1048576);
LOC3 = ((*LOC5).kind >= ((Ttypekind290244) 40) && (*LOC5).kind <= ((Ttypekind290244) 44));
LA4: ;
if (!LOC3) goto LA6;
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = gettypedesc_533671_839829468((*p0).module, dest0);
LOC8[1] = rdcharloc_536227_839829468(a0);
LOC9 = (Ropeobj177006*)0;
LOC9 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_430), LOC8, 2);
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC9, a0.s);
}
goto LA1;
LA6: ;
{
TY534475 LOC11;
Ropeobj177006* LOC12;
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = gettypedesc_533671_839829468((*p0).module, dest0);
LOC11[1] = rdcharloc_536227_839829468(a0);
LOC11[2] = genliteral_547476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], dest0);
LOC11[3] = genliteral_547476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 2)], dest0);
LOC11[4] = rope_177277_2381377266(magic0);
LOC12 = (Ropeobj177006*)0;
LOC12 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_562), LOC11, 5);
putintodest_548468_839829468(p0, d0, dest0, LOC12, a0.s);
}
LA1: ;
}
N_NIMCALL(void, convstrtocstr_554642_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Tloc290816 a0;
Ttype290840* LOC1;
TY177507 LOC2;
Ropeobj177006* LOC3;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
LOC1 = (Ttype290840*)0;
LOC1 = skiptypes_294099_850551059((*n0).typ, IL64(211106240964864));
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = rdloc_536188_839829468(a0);
LOC3 = (Ropeobj177006*)0;
LOC3 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_485), LOC2, 1);
putintodest_548468_839829468(p0, d0, LOC1, LOC3, a0.s);
}
N_NIMCALL(void, convcstrtostr_554654_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
Tloc290816 a0;
Ttype290840* LOC1;
TY177507 LOC2;
Ropeobj177006* LOC3;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
LOC1 = (Ttype290840*)0;
LOC1 = skiptypes_294099_850551059((*n0).typ, IL64(211106240964864));
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = rdloc_536188_839829468(a0);
LOC3 = (Ropeobj177006*)0;
LOC3 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_411), LOC2, 1);
putintodest_548468_839829468(p0, d0, LOC1, LOC3, a0.s);
gcusage_552439_839829468(n0);
}
static N_INLINE(NIM_BOOL, isroutine_295323_850551059)(Tsym290834* s0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
result0 = ((258048 &(1U<<((NU)((*s0).kind)&31U)))!=0);
return result0;
}
static N_INLINE(NIM_BOOL, isconstclosure_555810_839829468)(Tnode290802* n0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
NIM_BOOL LOC2;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC2 = (NIM_BOOL)0;
LOC2 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC2)) goto LA3;
LOC2 = isroutine_295323_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym);
LA3: ;
LOC1 = LOC2;
if (!(LOC1)) goto LA4;
LOC1 = ((*(*n0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind290020) 23));
LA4: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, genclosure_555836_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
{
NIM_BOOL LOC3;
Ropeobj177006* tmp0;
Ropeobj177006* LOC6;
TY533238 LOC7;
LOC3 = (NIM_BOOL)0;
LOC3 = isconstclosure_555810_839829468(n0);
if (!LOC3) goto LA4;
(*(*p0).module).labels += ((NI) 1);
LOC6 = (Ropeobj177006*)0;
LOC6 = rope_177401_2381377266(((NI64) ((*(*p0).module).labels)));
tmp0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_566), LOC6);
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = gettypedesc_533671_839829468((*p0).module, (*n0).typ);
LOC7[1] = tmp0;
LOC7[2] = genconstexpr_552849_839829468(p0, n0);
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC7, 3);
putintodest_548468_839829468(p0, d0, (*n0).typ, tmp0, ((Tstorageloc290812) 1));
}
goto LA1;
LA4: ;
{
Tloc290816 tmp0;
Tloc290816 a0;
Tloc290816 b0;
TY533238 LOC14;
memset((void*)(&tmp0), 0, sizeof(tmp0));
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&b0), 0, sizeof(b0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&b0));
{
Tnode290802* LOC11;
LOC11 = (Tnode290802*)0;
LOC11 = skipconv_326882_3876443242((*n0).kindU.S6.sons->data[((NI) 0)]);
if (!((*LOC11).kind == ((Tnodekind290020) 155))) goto LA12;
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_567));
}
LA12: ;
gettemp_535032_839829468(p0, (*n0).typ, (&tmp0), NIM_FALSE);
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = rdloc_536188_839829468(tmp0);
LOC14[1] = rdloc_536188_839829468(a0);
LOC14[2] = rdloc_536188_839829468(b0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_568), LOC14, 3);
putlocintodest_537258_839829468(p0, d0, tmp0);
}
LA1: ;
}
static N_INLINE(Ropeobj177006*, assignlabel_542020_839829468)(Tblock527019* b0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
result0 = (Ropeobj177006*)0;
LOC1 = (Ropeobj177006*)0;
LOC1 = rope_177401_2381377266(((NI64) ((*b0).id)));
unsureAsgnRef((void**) (&(*b0).label), HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC1));
result0 = (*b0).label;
return result0;
}
N_NIMCALL(void, gencomputedgoto_543744_839829468)(Tcproc527021* p0, Tnode290802* n0) {
NI casepos0;
NI arraysize0;
NI id0;
Ropeobj177006* tmp0;
TY177507 LOC27;
Ropeobj177006* gotoarray0;
TY530811 LOC28;
TY177507 LOC33;
NI topblock0;
Ropeobj177006* oldbody0;
Ropeobj177006* tailb0;
Ropeobj177006* taila0;
Tnode290802* casestmt0;
Tloc290816 a_543871_839829468;
TY530811 LOC41;
{ casepos0 = ((NI) -1);
arraysize0 = (NI)0;
{
NI i_543768_839829468;
NI HEX3Atmp_543933_839829468;
NI LOC2;
NI res_543936_839829468;
i_543768_839829468 = (NI)0;
HEX3Atmp_543933_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = len_291081_850551059(n0);
HEX3Atmp_543933_839829468 = (LOC2 - 1);
res_543936_839829468 = ((NI) 0);
{
while (1) {
Tnode290802* it0;
if (!(res_543936_839829468 <= HEX3Atmp_543933_839829468)) goto LA4;
i_543768_839829468 = res_543936_839829468;
it0 = (*n0).kindU.S6.sons->data[i_543768_839829468];
{
NI64 asize0;
if (!((*it0).kind == ((Tnodekind290020) 97))) goto LA7;
{
Tnode290802* LOC11;
LOC11 = (Tnode290802*)0;
LOC11 = lastson_293364_850551059(it0);
if (!!(((*LOC11).kind == ((Tnodekind290020) 85)))) goto LA12;
localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_570));
goto BeforeRet;
}
LA12: ;
casepos0 = i_543768_839829468;
asize0 = lengthord_318007_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ);
{
if (!(IL64(10000) < asize0)) goto LA16;
localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_571));
goto BeforeRet;
}
LA16: ;
arraysize0 = ((NI) (asize0));
{
NI64 LOC20;
LOC20 = (NI64)0;
LOC20 = firstord_318001_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ);
if (!!((LOC20 == IL64(0)))) goto LA21;
localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_572));
goto BeforeRet;
}
LA21: ;
}
LA7: ;
res_543936_839829468 += ((NI) 1);
} LA4: ;
}
}
{
if (!(casepos0 < ((NI) 0))) goto LA25;
localerror_194085_155036129((*n0).info, ((NimStringDesc*) &T839829468_573));
goto BeforeRet;
}
LA25: ;
id0 = (NI)(((NI) ((*p0).labels)) + ((NI) 1));
(*p0).labels += (NI)(arraysize0 + ((NI) 1));
memset((void*)LOC27, 0, sizeof(LOC27));
LOC27[0] = rope_177401_2381377266(((NI64) (id0)));
tmp0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_574), LOC27, 1);
memset((void*)LOC28, 0, sizeof(LOC28));
LOC28[0] = tmp0;
LOC28[1] = rope_177401_2381377266(((NI64) (arraysize0)));
gotoarray0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_575), LOC28, 2);
{
NI i_543819_839829468;
NI HEX3Atmp_543941_839829468;
NI res_543944_839829468;
i_543819_839829468 = (NI)0;
HEX3Atmp_543941_839829468 = (NI)0;
HEX3Atmp_543941_839829468 = (NI)(arraysize0 - ((NI) 1));
res_543944_839829468 = ((NI) 1);
{
while (1) {
TY177507 LOC32;
if (!(res_543944_839829468 <= HEX3Atmp_543941_839829468)) goto LA31;
i_543819_839829468 = res_543944_839829468;
memset((void*)LOC32, 0, sizeof(LOC32));
LOC32[0] = rope_177401_2381377266(((NI64) ((NI)(((NI) (id0)) + i_543819_839829468))));
addf_178205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_576), LOC32, 1);
res_543944_839829468 += ((NI) 1);
} LA31: ;
}
}
memset((void*)LOC33, 0, sizeof(LOC33));
LOC33[0] = rope_177401_2381377266(((NI64) ((NI)(((NI) (id0)) + arraysize0))));
addf_178205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_577), LOC33, 1);
line_530690_839829468(p0, ((Tcprocsection527011) 0), gotoarray0);
topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1));
oldbody0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0];
asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]), NIM_NIL);
{
NI j_543854_839829468;
NI HEX3Atmp_543949_839829468;
NI HEX3Atmp_543950_839829468;
NI LOC35;
NI res_543953_839829468;
j_543854_839829468 = (NI)0;
HEX3Atmp_543949_839829468 = (NI)0;
HEX3Atmp_543950_839829468 = (NI)0;
HEX3Atmp_543949_839829468 = (NI)(casepos0 + ((NI) 1));
LOC35 = (NI)0;
LOC35 = len_291081_850551059(n0);
HEX3Atmp_543950_839829468 = (LOC35 - 1);
res_543953_839829468 = HEX3Atmp_543949_839829468;
{
while (1) {
if (!(res_543953_839829468 <= HEX3Atmp_543950_839829468)) goto LA37;
j_543854_839829468 = res_543953_839829468;
genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[j_543854_839829468]);
res_543953_839829468 += ((NI) 1);
} LA37: ;
}
}
tailb0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0];
asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]), NIM_NIL);
{
NI j_543866_839829468;
NI HEX3Atmp_543958_839829468;
NI res_543961_839829468;
j_543866_839829468 = (NI)0;
HEX3Atmp_543958_839829468 = (NI)0;
HEX3Atmp_543958_839829468 = (NI)(casepos0 - ((NI) 1));
res_543961_839829468 = ((NI) 0);
{
while (1) {
if (!(res_543961_839829468 <= HEX3Atmp_543958_839829468)) goto LA40;
j_543866_839829468 = res_543961_839829468;
genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[j_543866_839829468]);
res_543961_839829468 += ((NI) 1);
} LA40: ;
}
}
taila0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0];
asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection527011) 2))- 0]), HEX26_177418_2381377266(oldbody0, taila0));
casestmt0 = (*n0).kindU.S6.sons->data[casepos0];
memset((void*)(&a_543871_839829468), 0, sizeof(a_543871_839829468));
initlocexpr_537283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a_543871_839829468));
memset((void*)LOC41, 0, sizeof(LOC41));
LOC41[0] = tmp0;
LOC41[1] = rdloc_536188_839829468(a_543871_839829468);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_578), LOC41, 2);
{
NI i_543894_839829468;
NI HEX3Atmp_543977_839829468;
NI LOC43;
NI res_543980_839829468;
i_543894_839829468 = (NI)0;
HEX3Atmp_543977_839829468 = (NI)0;
LOC43 = (NI)0;
LOC43 = len_291081_850551059(casestmt0);
HEX3Atmp_543977_839829468 = (LOC43 - 1);
res_543980_839829468 = ((NI) 1);
{
while (1) {
TY531289 LOC46;
NI LOC47;
Tnode290802* it0;
Tnode290802* LOC57;
Ropeobj177006** LOC58;
Ropeobj177006** LOC59;
Tloc290816 a0;
TY530811 LOC60;
if (!(res_543980_839829468 <= HEX3Atmp_543977_839829468)) goto LA45;
i_543894_839829468 = res_543980_839829468;
memset((void*)LOC46, 0, sizeof(LOC46));
LOC47 = (NI)0;
LOC47 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC46, 0);
it0 = (*casestmt0).kindU.S6.sons->data[i_543894_839829468];
{
NI j_543910_839829468;
NI HEX3Atmp_543969_839829468;
NI LOC49;
NI res_543972_839829468;
j_543910_839829468 = (NI)0;
HEX3Atmp_543969_839829468 = (NI)0;
LOC49 = (NI)0;
LOC49 = len_291081_850551059(it0);
HEX3Atmp_543969_839829468 = (NI)(LOC49 - ((NI) 2));
res_543972_839829468 = ((NI) 0);
{
while (1) {
NI64 val0;
TY177507 LOC56;
if (!(res_543972_839829468 <= HEX3Atmp_543969_839829468)) goto LA51;
j_543910_839829468 = res_543972_839829468;
{
if (!((*(*it0).kindU.S6.sons->data[j_543910_839829468]).kind == ((Tnodekind290020) 44))) goto LA54;
localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579));
goto BeforeRet;
}
LA54: ;
val0 = getordvalue_318129_3876443242((*it0).kindU.S6.sons->data[j_543910_839829468]);
memset((void*)LOC56, 0, sizeof(LOC56));
LOC56[0] = intliteral_537270_839829468((NI64)((NI64)(val0 + ((NI64) (id0))) + IL64(1)));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_580), LOC56, 1);
res_543972_839829468 += ((NI) 1);
} LA51: ;
}
}
LOC57 = (Tnode290802*)0;
LOC57 = lastson_293364_850551059(it0);
genstmts_537244_839829468(p0, LOC57);
LOC58 = (Ropeobj177006**)0;
LOC58 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177482_2381377266(LOC58, tailb0);
LOC59 = (Ropeobj177006**)0;
LOC59 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
add_177482_2381377266(LOC59, taila0);
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a0));
memset((void*)LOC60, 0, sizeof(LOC60));
LOC60[0] = tmp0;
LOC60[1] = rdloc_536188_839829468(a0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_578), LOC60, 2);
endblock_542060_839829468(p0);
res_543980_839829468 += ((NI) 1);
} LA45: ;
}
}
}BeforeRet: ;
}
N_NIMCALL(void, genwhilestmt_543984_839829468)(Tcproc527021* p0, Tnode290802* t0) {
Tloc290816 a0;
NI oldbreakidx_544011_839829468;
TY531289 LOC1;
Tnode290802* loopbody0;
memset((void*)(&a0), 0, sizeof(a0));
(*p0).withinloop += ((NI) 1);
genlinedir_530823_839829468(p0, t0);
oldbreakidx_544011_839829468 = (*p0).breakidx;
memset((void*)LOC1, 0, sizeof(LOC1));
(*p0).breakidx = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_569), LOC1, 0);
(*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE;
initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0));
{
NIM_BOOL LOC4;
Ropeobj177006* label0;
TY530811 LOC8;
LOC4 = (NIM_BOOL)0;
LOC4 = !(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 6)));
if (LOC4) goto LA5;
LOC4 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval == IL64(0));
LA5: ;
if (!LOC4) goto LA6;
label0 = assignlabel_542020_839829468((&(*p0).blocks->data[(*p0).breakidx]));
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rdloc_536188_839829468(a0);
LOC8[1] = label0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_555), LOC8, 2);
}
LA6: ;
loopbody0 = (*t0).kindU.S6.sons->data[((NI) 1)];
{
NIM_BOOL LOC11;
LOC11 = (NIM_BOOL)0;
LOC11 = stmtscontainpragma_526083_2036603609(loopbody0, ((Tspecialword273003) 182));
if (!(LOC11)) goto LA12;
LOC11 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 1))&7U)))!=0);
LA12: ;
if (!LOC11) goto LA13;
{
NIM_BOOL LOC17;
NI LOC18;
LOC17 = (NIM_BOOL)0;
LOC18 = (NI)0;
LOC18 = len_291081_850551059(loopbody0);
LOC17 = (LOC18 == ((NI) 2));
if (!(LOC17)) goto LA19;
LOC17 = ((*(*loopbody0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1));
LA19: ;
if (!LOC17) goto LA20;
loopbody0 = (*loopbody0).kindU.S6.sons->data[((NI) 1)];
}
LA20: ;
gencomputedgoto_543744_839829468(p0, loopbody0);
}
goto LA9;
LA13: ;
{
genstmts_537244_839829468(p0, loopbody0);
}
LA9: ;
{
TY531289 LOC27;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 19))&31U)))!=0)) goto LA25;
memset((void*)LOC27, 0, sizeof(LOC27));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_581), LOC27, 0);
}
LA25: ;
endblock_542060_839829468(p0);
(*p0).breakidx = oldbreakidx_544011_839829468;
(*p0).withinloop -= ((NI) 1);
}
N_NIMCALL(void, gengotovar_542258_839829468)(Tcproc527021* p0, Tnode290802* value0) {
{
if (!!(((*value0).kind >= ((Tnodekind290020) 5) && (*value0).kind <= ((Tnodekind290020) 15)))) goto LA3;
localerror_194085_155036129((*value0).info, ((NimStringDesc*) &T839829468_582));
}
goto LA1;
LA3: ;
{
TY177507 LOC6;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = rope_177401_2381377266((*value0).kindU.S1.intval);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_583), LOC6, 1);
}
LA1: ;
}
N_NIMCALL(void, varindynamiclib_536812_839829468)(Tcgen527027* m0, Tsym290834* sym0) {
Tlib290820* lib0;
Ropeobj177006* extname0;
Ropeobj177006* tmp0;
TY533235 LOC1;
NimStringDesc* LOC2;
TY530811 LOC3;
lib0 = (*sym0).annex;
extname0 = (*sym0).loc.r;
loaddynamiclib_557480_839829468(m0, lib0);
(*sym0).loc.flags |= ((NU16)1)<<((((Tlocflag290810) 0))%(sizeof(NU16)*8));
tmp0 = mangledynlibproc_536816_839829468(sym0);
asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0);
(*m0).labels += ((NI) 2);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = tmp0;
LOC1[1] = gettypedesc_533671_839829468(m0, (*sym0).typ);
LOC1[2] = (*lib0).name;
LOC2 = (NimStringDesc*)0;
LOC2 = HEX24_177856_2381377266(extname0);
LOC1[3] = makecstring_189638_155036129(LOC2);
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 16))- 0], ((NimStringDesc*) &T839829468_584), LOC1, 4);
memset((void*)LOC3, 0, sizeof(LOC3));
LOC3[0] = (*sym0).loc.r;
LOC3[1] = gettypedesc_533671_839829468(m0, (*sym0).loc.t);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 9))- 0], ((NimStringDesc*) &T839829468_585), LOC3, 2);
}
N_NIMCALL(void, assignglobalvar_536819_839829468)(Tcproc527021* p0, Tsym290834* s0) {
{ {
Ropeobj177006* LOC5;
if (!((*s0).loc.k == ((Tlockind290808) 0))) goto LA3;
LOC5 = (Ropeobj177006*)0;
LOC5 = manglename_531205_839829468(s0);
fillloc_530282_839829468((&(*s0).loc), ((Tlockind290808) 3), (*s0).typ, LOC5, ((Tstorageloc290812) 3));
}
LA3: ;
{
Tcgen527027* q0;
if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0)) goto LA8;
q0 = findpendingmodule_530241_839829468((*p0).module, s0);
{
NIM_BOOL LOC12;
NIM_BOOL LOC14;
LOC12 = (NIM_BOOL)0;
LOC12 = !((q0 == NIM_NIL));
if (!(LOC12)) goto LA13;
LOC14 = (NIM_BOOL)0;
LOC14 = containsorincl_266862_2627731572((&(*q0).declaredthings), (*s0).Sup.id);
LOC12 = !(LOC14);
LA13: ;
if (!LOC12) goto LA15;
varindynamiclib_536812_839829468(q0, s0);
}
goto LA10;
LA15: ;
{
asgnRefNoCycle((void**) (&(*s0).loc.r), mangledynlibproc_536816_839829468(s0));
}
LA10: ;
goto BeforeRet;
}
LA8: ;
useheader_530369_839829468((*p0).module, s0);
{
if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0)) goto LA20;
goto BeforeRet;
}
LA20: ;
{
if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0)) goto LA24;
declarethreadvar_536676_839829468((*p0).module, s0, (((*s0).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0));
}
goto LA22;
LA24: ;
{
Ropeobj177006* decl0;
Ropeobj177006* td0;
decl0 = NIM_NIL;
td0 = gettypedesc_533671_839829468((*p0).module, (*s0).loc.t);
{
TY177507 LOC43;
if (!(*s0).constraint == 0) goto LA29;
{
if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 5))&31U)))!=0)) goto LA33;
add_177487_2381377266(&decl0, ((NimStringDesc*) &T839829468_240));
}
LA33: ;
add_177482_2381377266(&decl0, td0);
{
if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 8))&31U)))!=0)) goto LA37;
add_177487_2381377266(&decl0, ((NimStringDesc*) &T839829468_121));
}
LA37: ;
{
if (!(((*s0).flags &(1U<<((NU)(((Tsymflag290184) 7))&31U)))!=0)) goto LA41;
add_177487_2381377266(&decl0, ((NimStringDesc*) &T839829468_122));
}
LA41: ;
memset((void*)LOC43, 0, sizeof(LOC43));
LOC43[0] = (*s0).loc.r;
addf_178205_2381377266(&decl0, ((NimStringDesc*) &T839829468_242), LOC43, 1);
}
goto LA27;
LA29: ;
{
NimStringDesc* LOC45;
TY530811 LOC46;
LOC45 = (NimStringDesc*)0;
LOC45 = rawNewString((*(*s0).constraint).kindU.S3.strval->Sup.len + 3);
appendString(LOC45, (*(*s0).constraint).kindU.S3.strval);
appendString(LOC45, ((NimStringDesc*) &T839829468_497));
memset((void*)LOC46, 0, sizeof(LOC46));
LOC46[0] = td0;
LOC46[1] = (*s0).loc.r;
decl0 = HEX25_177905_2381377266(LOC45, LOC46, 2);
}
LA27: ;
add_177482_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 9))- 0], decl0);
}
LA22: ;
{
if (!(((NI) 0) < (*p0).withinloop)) goto LA49;
resetloc_536350_839829468(p0, (&(*s0).loc));
}
LA49: ;
{
TY533238 LOC55;
NimStringDesc* LOC56;
NimStringDesc* LOC57;
if (!(((*(*(*p0).module).module).options & 163840) == 163840)) goto LA53;
memset((void*)LOC55, 0, sizeof(LOC55));
LOC56 = (NimStringDesc*)0;
LOC56 = rawNewString((*(*(*s0).owner).name).s->Sup.len + (*(*s0).name).s->Sup.len + 1);
appendString(LOC56, (*(*(*s0).owner).name).s);
appendChar(LOC56, 46);
appendString(LOC56, (*(*s0).name).s);
LOC57 = (NimStringDesc*)0;
LOC57 = nsuNormalize(LOC56);
LOC55[0] = makecstring_189638_155036129(LOC57);
LOC55[1] = (*s0).loc.r;
LOC55[2] = gentypeinfo_533941_839829468((*p0).module, (*s0).typ);
appcg_530632_839829468((*p0).module, &(*(*p0).module).s[(((Tcfilesection527005) 15))- 0], ((NimStringDesc*) &T839829468_586), LOC55, 3);
}
LA53: ;
}BeforeRet: ;
}
N_NIMCALL(Ropeobj177006*, gentraverseprocforglobal_536032_839829468)(Tcgen527027* m0, Tsym290834* s0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
Ttraversalclosure535019 c0;
Tcproc527021* p0;
Ropeobj177006* sloc0;
Ropeobj177006* header0;
TY177507 LOC8;
Ropeobj177006* generatedproc0;
TY533235 LOC9;
Ropeobj177006** LOC10;
Ropeobj177006** LOC11;
Ropeobj177006** LOC12;
TY177507 LOC13;
result0 = (Ropeobj177006*)0;
LOC1 = (Ropeobj177006*)0;
LOC1 = gentypeinfo_533941_839829468(m0, (*s0).loc.t);
memset((void*)(&c0), 0, sizeof(c0));
p0 = newproc_527206_3723162438(NIM_NIL, m0);
sloc0 = (*s0).loc.r;
result0 = gettempname_531596_839829468(m0);
{
NIM_BOOL LOC4;
LOC4 = (NIM_BOOL)0;
LOC4 = (((*s0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0);
if (!(LOC4)) goto LA5;
LOC4 = emulatedthreadvars_530949_839829468();
LA5: ;
if (!LOC4) goto LA6;
accessthreadlocalvar_530945_839829468(p0, s0);
sloc0 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_288), sloc0);
}
LA6: ;
c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_587));
c0.p = p0;
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = result0;
header0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_588), LOC8, 1);
gentraverseproc_535022_839829468((&c0), sloc0, (*s0).loc.t);
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = header0;
LOC10 = (Ropeobj177006**)0;
LOC10 = s_527179_3723162438(p0, ((Tcprocsection527011) 0));
LOC9[1] = (*LOC10);
LOC11 = (Ropeobj177006**)0;
LOC11 = s_527179_3723162438(p0, ((Tcprocsection527011) 1));
LOC9[2] = (*LOC11);
LOC12 = (Ropeobj177006**)0;
LOC12 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
LOC9[3] = (*LOC12);
generatedproc0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_190), LOC9, 4);
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = header0;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC13, 1);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], generatedproc0);
return result0;
}
N_NIMCALL(void, registergcroot_541762_839829468)(Tcproc527021* p0, Tsym290834* v0) {
{
NIM_BOOL LOC3;
Ropeobj177006* prc0;
Ropeobj177006** LOC7;
TY177507 LOC8;
LOC3 = (NIM_BOOL)0;
LOC3 = ((240 &(1U<<((NU)(gselectedgc_168133_2607990831)&7U)))!=0);
if (!(LOC3)) goto LA4;
LOC3 = containsgarbagecollectedref_318117_3876443242((*v0).loc.t);
LA4: ;
if (!LOC3) goto LA5;
prc0 = gentraverseprocforglobal_536032_839829468((*p0).module, v0);
LOC7 = (Ropeobj177006**)0;
LOC7 = procsec_527194_3723162438((*(*p0).module).initproc, ((Tcprocsection527011) 1));
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = prc0;
appcg_530632_839829468((*p0).module, LOC7, ((NimStringDesc*) &T839829468_589), LOC8, 1);
}
LA5: ;
}
static N_INLINE(NIM_BOOL, isassignedimmediately_541781_839829468)(Tnode290802* n0) {
NIM_BOOL result0;
{ result0 = (NIM_BOOL)0;
{
if (!((*n0).kind == ((Tnodekind290020) 1))) goto LA3;
result0 = NIM_FALSE;
goto BeforeRet;
}
LA3: ;
{
NIM_BOOL LOC7;
LOC7 = (NIM_BOOL)0;
LOC7 = isinvalidreturntype_531548_839829468((*n0).typ);
if (!LOC7) goto LA8;
result0 = NIM_FALSE;
goto BeforeRet;
}
LA8: ;
result0 = NIM_TRUE;
}BeforeRet: ;
return result0;
}
N_NIMCALL(void, genasgncall_541695_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* d0) {
{
Ttype290840* LOC3;
LOC3 = (Ttype290840*)0;
LOC3 = skiptypes_294099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, 2048);
if (!((*LOC3).callconv == ((Tcallingconvention290002) 8))) goto LA4;
genclosurecall_538452_839829468(p0, le0, ri0, d0);
}
goto LA1;
LA4: ;
{
NIM_BOOL LOC7;
LOC7 = (NIM_BOOL)0;
LOC7 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC7)) goto LA8;
LOC7 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA8: ;
if (!LOC7) goto LA9;
geninfixcall_539929_839829468(p0, le0, ri0, d0);
}
goto LA1;
LA9: ;
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC12)) goto LA13;
LOC12 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 28))&31U)))!=0);
LA13: ;
if (!LOC12) goto LA14;
gennamedparamcall_540616_839829468(p0, ri0, d0);
}
goto LA1;
LA14: ;
{
genprefixcall_537960_839829468(p0, le0, ri0, d0);
}
LA1: ;
poststmtactions_530942_839829468(p0);
}
static N_INLINE(void, loadinto_541928_839829468)(Tcproc527021* p0, Tnode290802* le0, Tnode290802* ri0, Tloc290816* a0) {
{
NIM_BOOL LOC3;
NIM_BOOL LOC5;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*ri0).kind == ((Tnodekind290020) 27) || (*ri0).kind == ((Tnodekind290020) 29) || (*ri0).kind == ((Tnodekind290020) 30) || (*ri0).kind == ((Tnodekind290020) 31) || (*ri0).kind == ((Tnodekind290020) 26) || (*ri0).kind == ((Tnodekind290020) 28) || (*ri0).kind == ((Tnodekind290020) 32));
if (!(LOC3)) goto LA4;
LOC5 = (NIM_BOOL)0;
LOC5 = !(((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3)));
if (LOC5) goto LA6;
LOC5 = ((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).magic == ((Tmagic290524) 0));
LA6: ;
LOC3 = LOC5;
LA4: ;
if (!LOC3) goto LA7;
genasgncall_541695_839829468(p0, le0, ri0, a0);
}
goto LA1;
LA7: ;
{
if (!((*ri0).kind == ((Tnodekind290020) 47) || (*ri0).kind == ((Tnodekind290020) 65))) goto LA10;
genderef_541921_839829468(p0, ri0, a0, NIM_TRUE);
}
goto LA1;
LA10: ;
{
expr_537248_839829468(p0, ri0, a0);
}
LA1: ;
}
N_NIMCALL(void, gensinglevar_542276_839829468)(Tcproc527021* p0, Tnode290802* a0) {
Tsym290834* v0;
Tcproc527021* targetproc0;
{ v0 = (*(*a0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
{
if (!!(((1082130432 & (*v0).flags) == 0))) goto LA3;
{
if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 30))&31U)))!=0)) goto LA7;
gengotovar_542258_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 2)]);
}
LA7: ;
goto BeforeRet;
}
LA3: ;
targetproc0 = p0;
{
if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 3))&31U)))!=0)) goto LA11;
{
NIM_BOOL LOC15;
NIM_BOOL LOC16;
LOC15 = (NIM_BOOL)0;
LOC16 = (NIM_BOOL)0;
LOC16 = (((*v0).flags & 96) == 32);
if (!(LOC16)) goto LA17;
LOC16 = ((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1));
LA17: ;
LOC15 = LOC16;
if (!(LOC15)) goto LA18;
LOC15 = !((((*v0).loc.flags & 72) == 0));
LA18: ;
if (!LOC15) goto LA19;
goto BeforeRet;
}
LA19: ;
{
if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 9))&31U)))!=0)) goto LA23;
targetproc0 = (*(*p0).module).preinitproc;
}
LA23: ;
assignglobalvar_536819_839829468(targetproc0, v0);
genobjectinit_536242_839829468((*(*p0).module).preinitproc, ((Tcprocsection527011) 1), (*v0).typ, (*v0).loc, NIM_TRUE);
{
NIM_BOOL LOC27;
LOC27 = (NIM_BOOL)0;
LOC27 = (((*v0).flags &(1U<<((NU)(((Tsymflag290184) 6))&31U)))!=0);
if (!(LOC27)) goto LA28;
LOC27 = !((generatedheader_530201_839829468 == NIM_NIL));
LA28: ;
if (!LOC27) goto LA29;
genvarprototypeaux_542254_839829468(generatedheader_530201_839829468, v0);
}
LA29: ;
registergcroot_541762_839829468(p0, v0);
}
goto LA9;
LA11: ;
{
Tnode290802* value0;
NIM_BOOL imm0;
value0 = (*a0).kindU.S6.sons->data[((NI) 2)];
imm0 = isassignedimmediately_541781_839829468(value0);
{
NIM_BOOL LOC34;
NIM_BOOL LOC35;
NIM_BOOL LOC36;
NIM_BOOL LOC38;
NIM_BOOL LOC42;
Ropeobj177006* decl0;
Tloc290816 tmp0;
LOC34 = (NIM_BOOL)0;
LOC35 = (NIM_BOOL)0;
LOC36 = (NIM_BOOL)0;
LOC36 = imm0;
if (!(LOC36)) goto LA37;
LOC38 = (NIM_BOOL)0;
LOC38 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC38) goto LA39;
LOC38 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA39: ;
LOC36 = LOC38;
LA37: ;
LOC35 = LOC36;
if (!(LOC35)) goto LA40;
LOC35 = ((*p0).splitdecls == ((NI) 0));
LA40: ;
LOC34 = LOC35;
if (!(LOC34)) goto LA41;
LOC42 = (NIM_BOOL)0;
LOC42 = containshiddenpointer_318120_3876443242((*v0).typ);
LOC34 = !(LOC42);
LA41: ;
if (!LOC34) goto LA43;
genlinedir_530823_839829468(p0, a0);
decl0 = localvardecl_536532_839829468(p0, v0);
memset((void*)(&tmp0), 0, sizeof(tmp0));
{
NIM_BOOL LOC47;
NIM_BOOL LOC48;
Tnode290802* LOC50;
Tnode290802* LOC52;
Ropeobj177006* params0;
Ttype290840* typ0;
TY530811 LOC66;
LOC47 = (NIM_BOOL)0;
LOC48 = (NIM_BOOL)0;
LOC48 = ((*value0).kind == ((Tnodekind290020) 27) || (*value0).kind == ((Tnodekind290020) 29) || (*value0).kind == ((Tnodekind290020) 30) || (*value0).kind == ((Tnodekind290020) 31) || (*value0).kind == ((Tnodekind290020) 26) || (*value0).kind == ((Tnodekind290020) 28) || (*value0).kind == ((Tnodekind290020) 32));
if (!(LOC48)) goto LA49;
LOC50 = (Tnode290802*)0;
LOC50 = HEX5BHEX5D_291238_850551059(value0, ((NI) 0));
LOC48 = ((*LOC50).kind == ((Tnodekind290020) 3));
LA49: ;
LOC47 = LOC48;
if (!(LOC47)) goto LA51;
LOC52 = (Tnode290802*)0;
LOC52 = HEX5BHEX5D_291238_850551059(value0, ((NI) 0));
LOC47 = (((*(*LOC52).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 24))&31U)))!=0);
LA51: ;
if (!LOC47) goto LA53;
params0 = (Ropeobj177006*)0;
typ0 = skiptypes_294099_850551059((*(*value0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256));
{
NI i_542619_839829468;
NI HEX3Atmp_542825_839829468;
NI LOC56;
NI res_542828_839829468;
i_542619_839829468 = (NI)0;
HEX3Atmp_542825_839829468 = (NI)0;
LOC56 = (NI)0;
LOC56 = len_291081_850551059(value0);
HEX3Atmp_542825_839829468 = (LOC56 - 1);
res_542828_839829468 = ((NI) 1);
{
while (1) {
Ropeobj177006* LOC65;
if (!(res_542828_839829468 <= HEX3Atmp_542825_839829468)) goto LA58;
i_542619_839829468 = res_542828_839829468;
{
TY531289 LOC63;
Ropeobj177006* LOC64;
if (!!((params0 == NIM_NIL))) goto LA61;
memset((void*)LOC63, 0, sizeof(LOC63));
LOC64 = (Ropeobj177006*)0;
LOC64 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_110), LOC63, 0);
add_177482_2381377266(¶ms0, LOC64);
}
LA61: ;
LOC65 = (Ropeobj177006*)0;
LOC65 = genotherarg_537277_839829468(p0, value0, i_542619_839829468, typ0);
add_177482_2381377266(¶ms0, LOC65);
res_542828_839829468 += ((NI) 1);
} LA58: ;
}
}
memset((void*)LOC66, 0, sizeof(LOC66));
LOC66[0] = decl0;
LOC66[1] = params0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_590), LOC66, 2);
}
goto LA45;
LA53: ;
{
TY530811 LOC68;
initlocexprsingleuse_537289_839829468(p0, value0, (&tmp0));
memset((void*)LOC68, 0, sizeof(LOC68));
LOC68[0] = decl0;
LOC68[1] = rdloc_536188_839829468(tmp0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_591), LOC68, 2);
}
LA45: ;
goto BeforeRet;
}
LA43: ;
assignlocalvar_536614_839829468(p0, v0);
initlocalvar_536398_839829468(p0, v0, imm0);
}
LA9: ;
{
if (!!(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1)))) goto LA71;
genlinedir_530823_839829468(targetproc0, a0);
loadinto_541928_839829468(targetproc0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&(*v0).loc));
}
LA71: ;
}BeforeRet: ;
}
N_NIMCALL(void, genclosurevar_542832_839829468)(Tcproc527021* p0, Tnode290802* a0) {
NIM_BOOL immediateasgn0;
immediateasgn0 = !(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1)));
{
Tloc290816 v0;
if (!immediateasgn0) goto LA3;
memset((void*)(&v0), 0, sizeof(v0));
initlocexpr_537283_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (&v0));
genlinedir_530823_839829468(p0, a0);
loadinto_541928_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&v0));
}
LA3: ;
}
N_NIMCALL(void, genvartuple_541794_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Tloc290816 tup0;
Tloc290816 field0;
NI L0;
NIM_BOOL uselowering0;
Ttype290840* t0;
{ memset((void*)(&tup0), 0, sizeof(tup0));
memset((void*)(&field0), 0, sizeof(field0));
{
if (!!(((*n0).kind == ((Tnodekind290020) 36)))) goto LA3;
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592));
}
LA3: ;
L0 = sonslen_293351_850551059(n0);
uselowering0 = NIM_FALSE;
{
NI i_541822_839829468;
NI HEX3Atmp_541905_839829468;
NI res_541908_839829468;
i_541822_839829468 = (NI)0;
HEX3Atmp_541905_839829468 = (NI)0;
HEX3Atmp_541905_839829468 = (NI)(L0 - ((NI) 3));
res_541908_839829468 = ((NI) 0);
{
while (1) {
if (!(res_541908_839829468 <= HEX3Atmp_541905_839829468)) goto LA7;
i_541822_839829468 = res_541908_839829468;
{
Tnode290802* LOC10;
LOC10 = (Tnode290802*)0;
LOC10 = HEX5BHEX5D_291238_850551059(n0, i_541822_839829468);
if (!!(((*LOC10).kind == ((Tnodekind290020) 3)))) goto LA11;
uselowering0 = NIM_TRUE;
goto LA5;
}
LA11: ;
res_541908_839829468 += ((NI) 1);
} LA7: ;
}
} LA5: ;
{
Tnode290802* LOC17;
if (!uselowering0) goto LA15;
LOC17 = (Tnode290802*)0;
LOC17 = lowertupleunpacking_431037_2218250499(n0, (*p0).prc);
genstmts_537244_839829468(p0, LOC17);
goto BeforeRet;
}
LA15: ;
genlinedir_530823_839829468(p0, n0);
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(L0 - ((NI) 1))], (&tup0));
t0 = getuniquetype_526640_2036603609(tup0.t);
{
NI i_541846_839829468;
NI HEX3Atmp_541914_839829468;
NI res_541917_839829468;
i_541846_839829468 = (NI)0;
HEX3Atmp_541914_839829468 = (NI)0;
HEX3Atmp_541914_839829468 = (NI)(L0 - ((NI) 3));
res_541917_839829468 = ((NI) 0);
{
while (1) {
if (!(res_541917_839829468 <= HEX3Atmp_541914_839829468)) goto LA20;
i_541846_839829468 = res_541917_839829468;
{
Tsym290834* v0;
v0 = (*(*n0).kindU.S6.sons->data[i_541846_839829468]).kindU.S4.sym;
{
if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 23))&31U)))!=0)) goto LA24;
goto LA21;
}
LA24: ;
{
if (!(((*v0).flags &(1U<<((NU)(((Tsymflag290184) 3))&31U)))!=0)) goto LA28;
assignglobalvar_536819_839829468(p0, v0);
genobjectinit_536242_839829468(p0, ((Tcprocsection527011) 1), (*v0).typ, (*v0).loc, NIM_TRUE);
registergcroot_541762_839829468(p0, v0);
}
goto LA26;
LA28: ;
{
Tnode290802* LOC31;
NIM_BOOL LOC32;
assignlocalvar_536614_839829468(p0, v0);
LOC31 = (Tnode290802*)0;
LOC31 = HEX5BHEX5D_291238_850551059(n0, (NI)(L0 - ((NI) 1)));
LOC32 = (NIM_BOOL)0;
LOC32 = isassignedimmediately_541781_839829468(LOC31);
initlocalvar_536398_839829468(p0, v0, LOC32);
}
LA26: ;
initloc_530273_839829468((&field0), ((Tlockind290808) 6), (*t0).sons->data[i_541846_839829468], tup0.s);
{
TY530811 LOC37;
if (!((*t0).kind == ((Ttypekind290244) 18))) goto LA35;
memset((void*)LOC37, 0, sizeof(LOC37));
LOC37[0] = rdloc_536188_839829468(tup0);
LOC37[1] = rope_177401_2381377266(((NI64) (i_541846_839829468)));
field0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_185), LOC37, 2);
}
goto LA33;
LA35: ;
{
TY530811 LOC43;
{
if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_541846_839829468]).kind == ((Tnodekind290020) 3)))) goto LA41;
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592));
}
LA41: ;
memset((void*)LOC43, 0, sizeof(LOC43));
LOC43[0] = rdloc_536188_839829468(tup0);
LOC43[1] = manglerecfieldname_532361_839829468((*(*(*t0).n).kindU.S6.sons->data[i_541846_839829468]).kindU.S4.sym, t0);
field0.r = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_90), LOC43, 2);
}
LA33: ;
putlocintodest_537258_839829468(p0, (&(*v0).loc), field0);
} LA21: ;
res_541917_839829468 += ((NI) 1);
} LA20: ;
}
}
}BeforeRet: ;
}
N_NIMCALL(void, genvarstmt_542854_839829468)(Tcproc527021* p0, Tnode290802* n0) {
{
NI i_542869_839829468;
NI HEX3Atmp_542902_839829468;
NI LOC2;
NI res_542905_839829468;
i_542869_839829468 = (NI)0;
HEX3Atmp_542902_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(n0);
HEX3Atmp_542902_839829468 = (NI)(LOC2 - ((NI) 1));
res_542905_839829468 = ((NI) 0);
{
while (1) {
if (!(res_542905_839829468 <= HEX3Atmp_542902_839829468)) goto LA4;
i_542869_839829468 = res_542905_839829468;
{
Tnode290802* a0;
a0 = (*n0).kindU.S6.sons->data[i_542869_839829468];
{
if (!((*a0).kind == ((Tnodekind290020) 125))) goto LA8;
goto LA5;
}
LA8: ;
{
if (!((*a0).kind == ((Tnodekind290020) 35))) goto LA12;
{
if (!((*(*a0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3))) goto LA16;
gensinglevar_542276_839829468(p0, a0);
}
goto LA14;
LA16: ;
{
genclosurevar_542832_839829468(p0, a0);
}
LA14: ;
}
goto LA10;
LA12: ;
{
genvartuple_541794_839829468(p0, a0);
}
LA10: ;
} LA5: ;
res_542905_839829468 += ((NI) 1);
} LA4: ;
}
}
}
static N_INLINE(NIM_BOOL, emitlazily_530248_839829468)(Tsym290834* s0) {
NIM_BOOL result0;
NIM_BOOL LOC1;
Tsym290834* LOC3;
result0 = (NIM_BOOL)0;
LOC1 = (NIM_BOOL)0;
LOC1 = ((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 2))&63U)))!=0);
if (LOC1) goto LA2;
LOC3 = (Tsym290834*)0;
LOC3 = getmodule_297123_2984716966(s0);
LOC1 = (((*LOC3).flags &(1U<<((NU)(((Tsymflag290184) 25))&31U)))!=0);
LA2: ;
result0 = LOC1;
return result0;
}
N_NIMCALL(void, genconststmt_542909_839829468)(Tcproc527021* p0, Tnode290802* t0) {
{
NI i_542924_839829468;
NI HEX3Atmp_542975_839829468;
NI LOC2;
NI res_542978_839829468;
i_542924_839829468 = (NI)0;
HEX3Atmp_542975_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(t0);
HEX3Atmp_542975_839829468 = (NI)(LOC2 - ((NI) 1));
res_542978_839829468 = ((NI) 0);
{
while (1) {
if (!(res_542978_839829468 <= HEX3Atmp_542975_839829468)) goto LA4;
i_542924_839829468 = res_542978_839829468;
{
Tnode290802* it0;
Tsym290834* c0;
it0 = (*t0).kindU.S6.sons->data[i_542924_839829468];
{
if (!((*it0).kind == ((Tnodekind290020) 125))) goto LA8;
goto LA5;
}
LA8: ;
{
if (!!(((*it0).kind == ((Tnodekind290020) 102)))) goto LA12;
internalerror_194100_155036129((*t0).info, ((NimStringDesc*) &T839829468_593));
}
LA12: ;
c0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
{
NIM_BOOL LOC16;
LOC16 = (NIM_BOOL)0;
LOC16 = containscompiletimeonly_326721_3876443242((*c0).typ);
if (!LOC16) goto LA17;
goto LA5;
}
goto LA14;
LA17: ;
{
NIM_BOOL LOC20;
NIM_BOOL LOC21;
NI LOC24;
LOC20 = (NIM_BOOL)0;
LOC21 = (NIM_BOOL)0;
LOC21 = ((*(*c0).typ).kind == ((Ttypekind290244) 4) || (*(*c0).typ).kind == ((Ttypekind290244) 16) || (*(*c0).typ).kind == ((Ttypekind290244) 19) || (*(*c0).typ).kind == ((Ttypekind290244) 18) || (*(*c0).typ).kind == ((Ttypekind290244) 24));
if (!(LOC21)) goto LA22;
LOC21 = !((((*c0).loc.flags &(1U<<((NU)(((Tlocflag290810) 3))&15U)))!=0));
LA22: ;
LOC20 = LOC21;
if (!(LOC20)) goto LA23;
LOC24 = (NI)0;
LOC24 = len_291081_850551059((*c0).ast);
LOC20 = !((LOC24 == ((NI) 0)));
LA23: ;
if (!LOC20) goto LA25;
{
NIM_BOOL LOC29;
LOC29 = (NIM_BOOL)0;
LOC29 = emitlazily_530248_839829468(c0);
if (!!(LOC29)) goto LA30;
requestconstimpl_537240_839829468(p0, c0);
}
LA30: ;
}
goto LA14;
LA25: ;
LA14: ;
} LA5: ;
res_542978_839829468 += ((NI) 1);
} LA4: ;
}
}
}
N_NIMCALL(void, gencasestringbranch_545100_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816 e0, Ropeobj177006* labl0, Ropeobj177006** branches0, NI branches0Len0) {
Tloc290816 x0;
NI length0;
memset((void*)(&x0), 0, sizeof(x0));
length0 = sonslen_293351_850551059(b0);
{
NI i_545122_839829468;
NI HEX3Atmp_545409_839829468;
NI res_545412_839829468;
i_545122_839829468 = (NI)0;
HEX3Atmp_545409_839829468 = (NI)0;
HEX3Atmp_545409_839829468 = (NI)(length0 - ((NI) 2));
res_545412_839829468 = ((NI) 0);
{
while (1) {
NI j0;
NI64 LOC4;
TY533238 LOC5;
if (!(res_545412_839829468 <= HEX3Atmp_545409_839829468)) goto LA3;
i_545122_839829468 = res_545412_839829468;
initlocexpr_537283_839829468(p0, (*b0).kindU.S6.sons->data[i_545122_839829468], (&x0));
LOC4 = (NI64)0;
LOC4 = hashstring_526100_2036603609((*(*b0).kindU.S6.sons->data[i_545122_839829468]).kindU.S3.strval);
j0 = ((NI) ((NI64)(LOC4 & ((NI64) ((branches0Len0-1))))));
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(e0);
LOC5[1] = rdloc_536188_839829468(x0);
LOC5[2] = labl0;
appcg_530632_839829468((*p0).module, &branches0[j0], ((NimStringDesc*) &T839829468_595), LOC5, 3);
res_545412_839829468 += ((NI) 1);
} LA3: ;
}
}
}
N_NIMCALL(void, exprblock_542103_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
TY531289 LOC1;
NI LOC2;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC2 = (NI)0;
LOC2 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0);
expr_537248_839829468(p0, n0, d0);
endblock_542060_839829468(p0);
}
N_NIMCALL(Ropeobj177006*, gencasesecondpass_544965_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NI labid0, NI until0) {
Ropeobj177006* result0;
Ropeobj177006* lend0;
result0 = (Ropeobj177006*)0;
lend0 = getlabel_537217_839829468(p0);
{
NI i_544984_839829468;
NI res_545017_839829468;
i_544984_839829468 = (NI)0;
res_545017_839829468 = ((NI) 1);
{
while (1) {
TY177507 LOC10;
if (!(res_545017_839829468 <= until0)) goto LA3;
i_544984_839829468 = res_545017_839829468;
{
NIM_BOOL LOC6;
LOC6 = (NIM_BOOL)0;
LOC6 = ((*d0).k == ((Tlockind290808) 1));
if (!(LOC6)) goto LA7;
LOC6 = isemptytype_295440_850551059((*t0).typ);
LA7: ;
if (!LOC6) goto LA8;
(*d0).k = ((Tlockind290808) 0);
}
LA8: ;
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = rope_177401_2381377266(((NI64) ((NI)(labid0 + i_544984_839829468))));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_599), LOC10, 1);
{
NI length0;
TY177507 LOC15;
if (!((*(*t0).kindU.S6.sons->data[i_544984_839829468]).kind == ((Tnodekind290020) 85))) goto LA13;
length0 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i_544984_839829468]);
exprblock_542103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_544984_839829468]).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0);
memset((void*)LOC15, 0, sizeof(LOC15));
LOC15[0] = lend0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_556), LOC15, 1);
}
goto LA11;
LA13: ;
{
exprblock_542103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_544984_839829468]).kindU.S6.sons->data[((NI) 0)], d0);
}
LA11: ;
res_545017_839829468 += ((NI) 1);
} LA3: ;
}
}
result0 = lend0;
return result0;
}
N_NIMCALL(void, gencasegenericbranch_544910_839829468)(Tcproc527021* p0, Tnode290802* b0, Tloc290816 e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj177006* labl0) {
Tloc290816 x0;
Tloc290816 y0;
NI length0;
memset((void*)(&x0), 0, sizeof(x0));
memset((void*)(&y0), 0, sizeof(y0));
length0 = sonslen_293351_850551059(b0);
{
NI i_544932_839829468;
NI HEX3Atmp_544958_839829468;
NI res_544961_839829468;
i_544932_839829468 = (NI)0;
HEX3Atmp_544958_839829468 = (NI)0;
HEX3Atmp_544958_839829468 = (NI)(length0 - ((NI) 2));
res_544961_839829468 = ((NI) 0);
{
while (1) {
if (!(res_544961_839829468 <= HEX3Atmp_544958_839829468)) goto LA3;
i_544932_839829468 = res_544961_839829468;
{
TY533235 LOC8;
if (!((*(*b0).kindU.S6.sons->data[i_544932_839829468]).kind == ((Tnodekind290020) 44))) goto LA6;
initlocexpr_537283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_544932_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0));
initlocexpr_537283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_544932_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0));
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rdcharloc_536227_839829468(e0);
LOC8[1] = rdcharloc_536227_839829468(x0);
LOC8[2] = rdcharloc_536227_839829468(y0);
LOC8[3] = labl0;
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), rangeformat0, LOC8, 4);
}
goto LA4;
LA6: ;
{
TY533238 LOC10;
initlocexpr_537283_839829468(p0, (*b0).kindU.S6.sons->data[i_544932_839829468], (&x0));
memset((void*)LOC10, 0, sizeof(LOC10));
LOC10[0] = rdcharloc_536227_839829468(e0);
LOC10[1] = rdcharloc_536227_839829468(x0);
LOC10[2] = labl0;
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), eqformat0, LOC10, 3);
}
LA4: ;
res_544961_839829468 += ((NI) 1);
} LA3: ;
}
}
}
N_NIMCALL(Ropeobj177006*, genifforcaseuntil_545021_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc290816 a0) {
Ropeobj177006* result0;
NI labid0;
result0 = (Ropeobj177006*)0;
labid0 = (*p0).labels;
{
NI i_545042_839829468;
NI res_545083_839829468;
i_545042_839829468 = (NI)0;
res_545083_839829468 = ((NI) 1);
{
while (1) {
if (!(res_545083_839829468 <= until0)) goto LA3;
i_545042_839829468 = res_545083_839829468;
(*p0).labels += ((NI) 1);
{
Ropeobj177006* LOC8;
Ropeobj177006* LOC9;
if (!((*(*t0).kindU.S6.sons->data[i_545042_839829468]).kind == ((Tnodekind290020) 85))) goto LA6;
LOC8 = (Ropeobj177006*)0;
LOC8 = rope_177401_2381377266(((NI64) ((*p0).labels)));
LOC9 = (Ropeobj177006*)0;
LOC9 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC8);
gencasegenericbranch_544910_839829468(p0, (*t0).kindU.S6.sons->data[i_545042_839829468], a0, rangeformat0, eqformat0, LOC9);
}
goto LA4;
LA6: ;
{
TY177507 LOC11;
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = rope_177401_2381377266(((NI64) ((*p0).labels)));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_598), LOC11, 1);
}
LA4: ;
res_545083_839829468 += ((NI) 1);
} LA3: ;
}
}
{
NI LOC14;
NI gototarget0;
TY177507 LOC17;
TY177507 LOC18;
LOC14 = (NI)0;
LOC14 = len_291081_850551059(t0);
if (!(until0 < (NI)(LOC14 - ((NI) 1)))) goto LA15;
(*p0).labels += ((NI) 1);
gototarget0 = (*p0).labels;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = rope_177401_2381377266(((NI64) (gototarget0)));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_598), LOC17, 1);
result0 = gencasesecondpass_544965_839829468(p0, t0, d0, ((NI) (labid0)), until0);
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = rope_177401_2381377266(((NI64) (gototarget0)));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_599), LOC18, 1);
}
goto LA12;
LA15: ;
{
result0 = gencasesecondpass_544965_839829468(p0, t0, d0, ((NI) (labid0)), until0);
}
LA12: ;
return result0;
}
N_NIMCALL(void, gencasegeneric_545087_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0) {
Tloc290816 a0;
Ropeobj177006* lend0;
NI LOC1;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0));
LOC1 = (NI)0;
LOC1 = sonslen_293351_850551059(t0);
lend0 = genifforcaseuntil_545021_839829468(p0, t0, d0, rangeformat0, eqformat0, (NI)(LOC1 - ((NI) 1)), a0);
fixlabel_537230_839829468(p0, lend0);
}
N_NIMCALL(void, genstringcase_545416_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) {
NI strings0;
strings0 = ((NI) 0);
{
NI i_545434_839829468;
NI HEX3Atmp_545549_839829468;
NI LOC2;
NI res_545552_839829468;
i_545434_839829468 = (NI)0;
HEX3Atmp_545549_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(t0);
HEX3Atmp_545549_839829468 = (NI)(LOC2 - ((NI) 1));
res_545552_839829468 = ((NI) 1);
{
while (1) {
if (!(res_545552_839829468 <= HEX3Atmp_545549_839829468)) goto LA4;
i_545434_839829468 = res_545552_839829468;
{
NI LOC9;
if (!((*(*t0).kindU.S6.sons->data[i_545434_839829468]).kind == ((Tnodekind290020) 85))) goto LA7;
LOC9 = (NI)0;
LOC9 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i_545434_839829468]);
strings0 += (NI)(LOC9 - ((NI) 1));
}
LA7: ;
res_545552_839829468 += ((NI) 1);
} LA4: ;
}
}
{
NI bitmask0;
NI LOC14;
TY189350* branches0;
Tloc290816 a0;
NI labid0;
TY530811 LOC26;
TY531289 LOC35;
Ropeobj177006* lend0;
NI LOC42;
if (!(((NI) 8) < strings0)) goto LA12;
LOC14 = (NI)0;
LOC14 = nextpoweroftwo_100629_1009420244(strings0);
bitmask0 = (NI)(LOC14 - ((NI) 1));
branches0 = (TY189350*)0;
branches0 = (TY189350*) newSeq((&NTI189350), ((NI) ((NI)(bitmask0 + ((NI) 1)))));
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0));
labid0 = (*p0).labels;
{
NI i_545483_839829468;
NI HEX3Atmp_545559_839829468;
NI LOC16;
NI res_545562_839829468;
i_545483_839829468 = (NI)0;
HEX3Atmp_545559_839829468 = (NI)0;
LOC16 = (NI)0;
LOC16 = sonslen_293351_850551059(t0);
HEX3Atmp_545559_839829468 = (NI)(LOC16 - ((NI) 1));
res_545562_839829468 = ((NI) 1);
{
while (1) {
if (!(res_545562_839829468 <= HEX3Atmp_545559_839829468)) goto LA18;
i_545483_839829468 = res_545562_839829468;
(*p0).labels += ((NI) 1);
{
Ropeobj177006* LOC23;
Ropeobj177006* LOC24;
if (!((*(*t0).kindU.S6.sons->data[i_545483_839829468]).kind == ((Tnodekind290020) 85))) goto LA21;
LOC23 = (Ropeobj177006*)0;
LOC23 = rope_177401_2381377266(((NI64) ((*p0).labels)));
LOC24 = (Ropeobj177006*)0;
LOC24 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_296), LOC23);
gencasestringbranch_545100_839829468(p0, (*t0).kindU.S6.sons->data[i_545483_839829468], a0, LOC24, branches0->data, branches0->Sup.len);
}
goto LA19;
LA21: ;
{
}
LA19: ;
res_545562_839829468 += ((NI) 1);
} LA18: ;
}
}
memset((void*)LOC26, 0, sizeof(LOC26));
LOC26[0] = rdloc_536188_839829468(a0);
LOC26[1] = rope_177401_2381377266(((NI64) (bitmask0)));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_596), LOC26, 2);
{
NI j_545517_839829468;
NI HEX3Atmp_545567_839829468;
NI res_545570_839829468;
j_545517_839829468 = (NI)0;
HEX3Atmp_545567_839829468 = (NI)0;
HEX3Atmp_545567_839829468 = (branches0 ? (branches0->Sup.len-1) : -1);
res_545570_839829468 = ((NI) 0);
{
while (1) {
if (!(res_545570_839829468 <= HEX3Atmp_545567_839829468)) goto LA29;
j_545517_839829468 = res_545570_839829468;
{
TY530811 LOC34;
if (!!((branches0->data[j_545517_839829468] == NIM_NIL))) goto LA32;
memset((void*)LOC34, 0, sizeof(LOC34));
LOC34[0] = intliteral_537270_839829468(((NI64) (j_545517_839829468)));
LOC34[1] = branches0->data[j_545517_839829468];
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_597), LOC34, 2);
}
LA32: ;
res_545570_839829468 += ((NI) 1);
} LA29: ;
}
}
memset((void*)LOC35, 0, sizeof(LOC35));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC35, 0);
{
NI LOC38;
TY177507 LOC41;
LOC38 = (NI)0;
LOC38 = sonslen_293351_850551059(t0);
if (!!(((*(*t0).kindU.S6.sons->data[(NI)(LOC38 - ((NI) 1))]).kind == ((Tnodekind290020) 85)))) goto LA39;
memset((void*)LOC41, 0, sizeof(LOC41));
LOC41[0] = rope_177401_2381377266(((NI64) ((*p0).labels)));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_598), LOC41, 1);
}
LA39: ;
LOC42 = (NI)0;
LOC42 = sonslen_293351_850551059(t0);
lend0 = gencasesecondpass_544965_839829468(p0, t0, d0, ((NI) (labid0)), (NI)(LOC42 - ((NI) 1)));
fixlabel_537230_839829468(p0, lend0);
}
goto LA10;
LA12: ;
{
gencasegeneric_545087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_490), ((NimStringDesc*) &T839829468_595));
}
LA10: ;
}
N_NIMCALL(void, gengotoforcase_543673_839829468)(Tcproc527021* p0, Tnode290802* casestmt0) {
{ {
NI i_543695_839829468;
NI HEX3Atmp_543737_839829468;
NI LOC2;
NI res_543740_839829468;
i_543695_839829468 = (NI)0;
HEX3Atmp_543737_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = len_291081_850551059(casestmt0);
HEX3Atmp_543737_839829468 = (LOC2 - 1);
res_543740_839829468 = ((NI) 1);
{
while (1) {
TY531289 LOC5;
NI LOC6;
Tnode290802* it0;
Tnode290802* LOC16;
if (!(res_543740_839829468 <= HEX3Atmp_543737_839829468)) goto LA4;
i_543695_839829468 = res_543740_839829468;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC6 = (NI)0;
LOC6 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC5, 0);
it0 = (*casestmt0).kindU.S6.sons->data[i_543695_839829468];
{
NI j_543711_839829468;
NI HEX3Atmp_543730_839829468;
NI LOC8;
NI res_543733_839829468;
j_543711_839829468 = (NI)0;
HEX3Atmp_543730_839829468 = (NI)0;
LOC8 = (NI)0;
LOC8 = len_291081_850551059(it0);
HEX3Atmp_543730_839829468 = (NI)(LOC8 - ((NI) 2));
res_543733_839829468 = ((NI) 0);
{
while (1) {
NI64 val0;
TY177507 LOC15;
if (!(res_543733_839829468 <= HEX3Atmp_543730_839829468)) goto LA10;
j_543711_839829468 = res_543733_839829468;
{
if (!((*(*it0).kindU.S6.sons->data[j_543711_839829468]).kind == ((Tnodekind290020) 44))) goto LA13;
localerror_194085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579));
goto BeforeRet;
}
LA13: ;
val0 = getordvalue_318129_3876443242((*it0).kindU.S6.sons->data[j_543711_839829468]);
memset((void*)LOC15, 0, sizeof(LOC15));
LOC15[0] = rope_177401_2381377266(val0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_602), LOC15, 1);
res_543733_839829468 += ((NI) 1);
} LA10: ;
}
}
LOC16 = (Tnode290802*)0;
LOC16 = lastson_293364_850551059(it0);
genstmts_537244_839829468(p0, LOC16);
endblock_542060_839829468(p0);
res_543740_839829468 += ((NI) 1);
} LA4: ;
}
}
}BeforeRet: ;
}
N_NIMCALL(NIM_BOOL, branchhastoobigrange_545575_839829468)(Tnode290802* b0) {
NIM_BOOL result0;
{ result0 = (NIM_BOOL)0;
{
NI i_545590_839829468;
NI HEX3Atmp_545608_839829468;
NI LOC2;
NI res_545611_839829468;
i_545590_839829468 = (NI)0;
HEX3Atmp_545608_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(b0);
HEX3Atmp_545608_839829468 = (NI)(LOC2 - ((NI) 2));
res_545611_839829468 = ((NI) 0);
{
while (1) {
if (!(res_545611_839829468 <= HEX3Atmp_545608_839829468)) goto LA4;
i_545590_839829468 = res_545611_839829468;
{
NIM_BOOL LOC7;
LOC7 = (NIM_BOOL)0;
LOC7 = ((*(*b0).kindU.S6.sons->data[i_545590_839829468]).kind == ((Tnodekind290020) 44));
if (!(LOC7)) goto LA8;
LOC7 = (IL64(256) < (NI64)((*(*(*b0).kindU.S6.sons->data[i_545590_839829468]).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval - (*(*(*b0).kindU.S6.sons->data[i_545590_839829468]).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval));
LA8: ;
if (!LOC7) goto LA9;
result0 = NIM_TRUE;
goto BeforeRet;
}
LA9: ;
res_545611_839829468 += ((NI) 1);
} LA4: ;
}
}
}BeforeRet: ;
return result0;
}
N_NIMCALL(NI, ifswitchsplitpoint_545615_839829468)(Tcproc527021* p0, Tnode290802* n0) {
NI result0;
result0 = (NI)0;
{
NI i_545630_839829468;
NI HEX3Atmp_545654_839829468;
NI LOC2;
NI res_545657_839829468;
i_545630_839829468 = (NI)0;
HEX3Atmp_545654_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = len_291081_850551059(n0);
HEX3Atmp_545654_839829468 = (NI)(LOC2 - ((NI) 1));
res_545657_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* branch0;
Tnode290802* stmtblock0;
if (!(res_545657_839829468 <= HEX3Atmp_545654_839829468)) goto LA4;
i_545630_839829468 = res_545657_839829468;
branch0 = HEX5BHEX5D_291238_850551059(n0, i_545630_839829468);
stmtblock0 = lastson_293364_850551059(branch0);
{
NIM_BOOL LOC7;
LOC7 = (NIM_BOOL)0;
LOC7 = stmtscontainpragma_526083_2036603609(stmtblock0, ((Tspecialword273003) 181));
if (!LOC7) goto LA8;
result0 = i_545630_839829468;
}
goto LA5;
LA8: ;
{
if (!!(((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 0))&7U)))!=0))) goto LA11;
{
NIM_BOOL LOC15;
LOC15 = (NIM_BOOL)0;
LOC15 = ((*branch0).kind == ((Tnodekind290020) 85));
if (!(LOC15)) goto LA16;
LOC15 = branchhastoobigrange_545575_839829468(branch0);
LA16: ;
if (!LOC15) goto LA17;
result0 = i_545630_839829468;
}
LA17: ;
}
goto LA5;
LA11: ;
LA5: ;
res_545657_839829468 += ((NI) 1);
} LA4: ;
}
}
return result0;
}
N_NIMCALL(void, genordinalcase_545724_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
NI splitpoint0;
Tloc290816 a0;
Ropeobj177006* lend0;
splitpoint0 = ifswitchsplitpoint_545615_839829468(p0, n0);
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
{
if (!(((NI) 0) < splitpoint0)) goto LA3;
lend0 = genifforcaseuntil_545021_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601), splitpoint0, a0);
}
goto LA1;
LA3: ;
{
lend0 = NIM_NIL;
}
LA1: ;
{
NI LOC8;
TY177507 LOC11;
NIM_BOOL hasdefault0;
TY531289 LOC37;
LOC8 = (NI)0;
LOC8 = len_291081_850551059(n0);
if (!((NI)(splitpoint0 + ((NI) 1)) < LOC8)) goto LA9;
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = rdcharloc_536227_839829468(a0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_603), LOC11, 1);
hasdefault0 = NIM_FALSE;
{
NI i_545757_839829468;
NI HEX3Atmp_545816_839829468;
NI HEX3Atmp_545817_839829468;
NI LOC13;
NI res_545820_839829468;
i_545757_839829468 = (NI)0;
HEX3Atmp_545816_839829468 = (NI)0;
HEX3Atmp_545817_839829468 = (NI)0;
HEX3Atmp_545816_839829468 = (NI)(splitpoint0 + ((NI) 1));
LOC13 = (NI)0;
LOC13 = len_291081_850551059(n0);
HEX3Atmp_545817_839829468 = (LOC13 - 1);
res_545820_839829468 = HEX3Atmp_545816_839829468;
{
while (1) {
Tnode290802* branch0;
Tnode290802* LOC28;
TY531289 LOC29;
if (!(res_545820_839829468 <= HEX3Atmp_545817_839829468)) goto LA15;
i_545757_839829468 = res_545820_839829468;
{
NIM_BOOL LOC18;
LOC18 = (NIM_BOOL)0;
LOC18 = ((*d0).k == ((Tlockind290808) 1));
if (!(LOC18)) goto LA19;
LOC18 = isemptytype_295440_850551059((*n0).typ);
LA19: ;
if (!LOC18) goto LA20;
(*d0).k = ((Tlockind290808) 0);
}
LA20: ;
branch0 = HEX5BHEX5D_291238_850551059(n0, i_545757_839829468);
{
if (!((*branch0).kind == ((Tnodekind290020) 85))) goto LA24;
gencaserange_535028_839829468(p0, branch0);
}
goto LA22;
LA24: ;
{
TY531289 LOC27;
memset((void*)LOC27, 0, sizeof(LOC27));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_181), LOC27, 0);
hasdefault0 = NIM_TRUE;
}
LA22: ;
LOC28 = (Tnode290802*)0;
LOC28 = lastson_293364_850551059(branch0);
exprblock_542103_839829468(p0, LOC28, d0);
memset((void*)LOC29, 0, sizeof(LOC29));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_182), LOC29, 0);
res_545820_839829468 += ((NI) 1);
} LA15: ;
}
}
{
NIM_BOOL LOC32;
TY531289 LOC36;
LOC32 = (NIM_BOOL)0;
LOC32 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 3))&7U)))!=0);
if (!(LOC32)) goto LA33;
LOC32 = !(hasdefault0);
LA33: ;
if (!LOC32) goto LA34;
memset((void*)LOC36, 0, sizeof(LOC36));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_604), LOC36, 0);
}
LA34: ;
memset((void*)LOC37, 0, sizeof(LOC37));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC37, 0);
}
LA9: ;
{
if (!!((lend0 == NIM_NIL))) goto LA40;
fixlabel_537230_839829468(p0, lend0);
}
LA40: ;
}
N_NIMCALL(void, gencase_545826_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) {
Ttype290840* LOC8;
genlinedir_530823_839829468(p0, t0);
{
NIM_BOOL LOC3;
NIM_BOOL LOC4;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = isemptytype_295440_850551059((*t0).typ);
LOC3 = !(LOC4);
if (!(LOC3)) goto LA5;
LOC3 = ((*d0).k == ((Tlockind290808) 0));
LA5: ;
if (!LOC3) goto LA6;
gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE);
}
LA6: ;
LOC8 = (Ttype290840*)0;
LOC8 = skiptypes_294099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440));
switch ((*LOC8).kind) {
case ((Ttypekind290244) 28):
{
genstringcase_545416_839829468(p0, t0, d0);
}
break;
case ((Ttypekind290244) 36) ... ((Ttypekind290244) 39):
{
gencasegeneric_545087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601));
}
break;
default:
{
{
NIM_BOOL LOC14;
LOC14 = (NIM_BOOL)0;
LOC14 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC14)) goto LA15;
LOC14 = (((*(*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 30))&31U)))!=0);
LA15: ;
if (!LOC14) goto LA16;
gengotoforcase_543673_839829468(p0, t0);
}
goto LA12;
LA16: ;
{
genordinalcase_545724_839829468(p0, t0, d0);
}
LA12: ;
}
break;
}
}
static N_INLINE(Tnode290802*, pop_316246_1689653243)(Tnodeseq290796** s0) {
Tnode290802* result0;
NI L0;
result0 = (Tnode290802*)0;
L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1));
result0 = (*s0)->data[L0];
(*s0) = (Tnodeseq290796*) setLengthSeq(&((*s0))->Sup, sizeof(Tnode290802*), ((NI) (L0)));
return result0;
}
N_NIMCALL(void, blockleaveactions_543442_839829468)(Tcproc527021* p0, NI howmanytrys0, NI howmanyexcepts0) {
Tnodeseq290796* stack0;
NI alreadypoppedcnt0;
stack0 = (Tnodeseq290796*)0;
stack0 = (Tnodeseq290796*) newSeq((&NTI290796), ((NI) 0));
alreadypoppedcnt0 = (*p0).inexceptblock;
{
NI i_543471_839829468;
NI res_543596_839829468;
i_543471_839829468 = (NI)0;
res_543596_839829468 = ((NI) 1);
{
while (1) {
Tnode290802* trystmt0;
Tnode290802* finallystmt0;
if (!(res_543596_839829468 <= howmanytrys0)) goto LA3;
i_543471_839829468 = res_543596_839829468;
{
NIM_BOOL LOC6;
LOC6 = (NIM_BOOL)0;
LOC6 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC6) goto LA7;
LOC6 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA7: ;
if (!!(LOC6)) goto LA8;
{
if (!(((NI) 0) < alreadypoppedcnt0)) goto LA12;
alreadypoppedcnt0 -= ((NI) 1);
}
goto LA10;
LA12: ;
{
TY531289 LOC15;
memset((void*)LOC15, 0, sizeof(LOC15));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_605), LOC15, 0);
}
LA10: ;
}
LA8: ;
trystmt0 = pop_316246_1689653243((&(*p0).nestedtrystmts));
stack0 = (Tnodeseq290796*) incrSeqV2(&(stack0)->Sup, sizeof(Tnode290802*));
asgnRefNoCycle((void**) (&stack0->data[stack0->Sup.len]), trystmt0);
++stack0->Sup.len;
finallystmt0 = lastson_293364_850551059(trystmt0);
{
if (!((*finallystmt0).kind == ((Tnodekind290020) 107))) goto LA18;
genstmts_537244_839829468(p0, (*finallystmt0).kindU.S6.sons->data[((NI) 0)]);
}
LA18: ;
res_543596_839829468 += ((NI) 1);
} LA3: ;
}
}
{
NI i_543546_839829468;
NI HEX3Atmp_543601_839829468;
NI res_543604_839829468;
i_543546_839829468 = (NI)0;
HEX3Atmp_543601_839829468 = (NI)0;
HEX3Atmp_543601_839829468 = (NI)(howmanytrys0 - ((NI) 1));
res_543604_839829468 = HEX3Atmp_543601_839829468;
{
while (1) {
if (!(((NI) 0) <= res_543604_839829468)) goto LA22;
i_543546_839829468 = res_543604_839829468;
(*p0).nestedtrystmts = (Tnodeseq290796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode290802*));
asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), stack0->data[i_543546_839829468]);
++(*p0).nestedtrystmts->Sup.len;
res_543604_839829468 -= ((NI) 1);
} LA22: ;
}
}
{
NIM_BOOL LOC25;
LOC25 = (NIM_BOOL)0;
LOC25 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC25) goto LA26;
LOC25 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA26: ;
if (!!(LOC25)) goto LA27;
{
NI i_543587_839829468;
NI HEX3Atmp_543610_839829468;
NI res_543613_839829468;
i_543587_839829468 = (NI)0;
HEX3Atmp_543610_839829468 = (NI)0;
HEX3Atmp_543610_839829468 = (NI)(howmanyexcepts0 - ((NI) 1));
res_543613_839829468 = HEX3Atmp_543610_839829468;
{
while (1) {
TY531289 LOC32;
if (!(((NI) 0) <= res_543613_839829468)) goto LA31;
i_543587_839829468 = res_543613_839829468;
memset((void*)LOC32, 0, sizeof(LOC32));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC32, 0);
res_543613_839829468 -= ((NI) 1);
} LA31: ;
}
}
}
LA27: ;
}
N_NIMCALL(void, genreturnstmt_543617_839829468)(Tcproc527021* p0, Tnode290802* t0) {
TY531289 LOC14;
{ {
if (!(((*t0).flags &(1U<<((NU)(((Tnodeflag290427) 14))&15U)))!=0)) goto LA3;
goto BeforeRet;
}
LA3: ;
(*p0).beforeretneeded = NIM_TRUE;
genlinedir_530823_839829468(p0, t0);
{
if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA7;
genstmts_537244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)]);
}
LA7: ;
blockleaveactions_543442_839829468(p0, ((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0), (*p0).inexceptblock);
{
Ropeobj177006* safepoint0;
TY177507 LOC13;
if (!(((NI) 0) < ((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0))) goto LA11;
safepoint0 = (*p0).finallysafepoints->data[(NI)(((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0) - ((NI) 1))];
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_607), LOC13, 1);
}
LA11: ;
memset((void*)LOC14, 0, sizeof(LOC14));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_608), LOC14, 0);
}BeforeRet: ;
}
N_NIMCALL(void, genbreakstmt_544444_839829468)(Tcproc527021* p0, Tnode290802* t0) {
NI idx0;
Ropeobj177006* label0;
TY177507 LOC16;
idx0 = (*p0).breakidx;
{
Tsym290834* sym0;
if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA3;
sym0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
idx0 = (NI)((*sym0).position - ((NI) 1));
}
goto LA1;
LA3: ;
{
{
while (1) {
NIM_BOOL LOC8;
LOC8 = (NIM_BOOL)0;
LOC8 = (((NI) 0) <= idx0);
if (!(LOC8)) goto LA9;
LOC8 = !((*p0).blocks->data[idx0].isloop);
LA9: ;
if (!LOC8) goto LA7;
idx0 -= ((NI) 1);
} LA7: ;
}
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = (idx0 < ((NI) 0));
if (LOC12) goto LA13;
LOC12 = !((*p0).blocks->data[idx0].isloop);
LA13: ;
if (!LOC12) goto LA14;
internalerror_194100_155036129((*t0).info, ((NimStringDesc*) &T839829468_609));
}
LA14: ;
}
LA1: ;
label0 = assignlabel_542020_839829468((&(*p0).blocks->data[idx0]));
blockleaveactions_543442_839829468(p0, (NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) ((*p0).blocks->data[idx0].nestedtrystmts))), (NI)((*p0).inexceptblock - ((NI) ((*p0).blocks->data[idx0].nestedexceptstmts))));
genlinedir_530823_839829468(p0, t0);
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = label0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_556), LOC16, 1);
}
N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_547080_839829468)(Tcproc527021* p0, Tnode290802* asgn0) {
NIM_BOOL result0;
result0 = (NIM_BOOL)0;
{
Tnode290802* le0;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 2))&31U)))!=0)) goto LA3;
le0 = (*asgn0).kindU.S6.sons->data[((NI) 0)];
{
Tsym290834* field0;
if (!((*le0).kind == ((Tnodekind290020) 46))) goto LA7;
field0 = (*(*(*le0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym;
result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag290184) 18))&31U)))!=0);
}
goto LA5;
LA7: ;
{
Tsym290834* field0;
if (!((*le0).kind == ((Tnodekind290020) 45))) goto LA10;
field0 = (*(*le0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym;
result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag290184) 18))&31U)))!=0);
}
goto LA5;
LA10: ;
LA5: ;
}
LA3: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, discriminatortabledecl_534094_839829468)(Tcgen527027* m0, Ttype290840* objtype0, Tsym290834* d0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
Ropeobj177006* tmp0;
TY530811 LOC2;
NI64 LOC3;
result0 = (Ropeobj177006*)0;
LOC1 = (Ropeobj177006*)0;
LOC1 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_130));
tmp0 = discriminatortablename_534057_839829468(m0, objtype0, d0);
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = tmp0;
LOC3 = (NI64)0;
LOC3 = lengthord_318007_3876443242((*d0).typ);
LOC2[1] = rope_177401_2381377266((NI64)(LOC3 + IL64(1)));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_203), LOC2, 2);
return result0;
}
N_NIMCALL(void, gendiscriminantcheck_547144_839829468)(Tcproc527021* p0, Tloc290816 a0, Tloc290816 tmp0, Ttype290840* objtype0, Tsym290834* field0) {
Ttype290840* t0;
Ropeobj177006* LOC1;
NI64 L0;
TY533235 LOC8;
t0 = skiptypes_294099_850551059(objtype0, IL64(211106240964864));
LOC1 = (Ropeobj177006*)0;
LOC1 = gentypeinfo_533941_839829468((*p0).module, t0);
L0 = lengthord_318007_3876443242((*field0).typ);
{
NIM_BOOL LOC4;
TY177507 LOC7;
LOC4 = (NIM_BOOL)0;
LOC4 = containsorincl_266862_2627731572((&(*(*p0).module).declaredthings), (*field0).Sup.id);
if (!!(LOC4)) goto LA5;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = discriminatortabledecl_534094_839829468((*p0).module, t0, field0);
appcg_530640_839829468((*p0).module, ((Tcfilesection527005) 9), ((NimStringDesc*) &T839829468_610), LOC7, 1);
}
LA5: ;
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = rdloc_536188_839829468(a0);
LOC8[1] = rdloc_536188_839829468(tmp0);
LOC8[2] = discriminatortablename_534057_839829468((*p0).module, t0, field0);
LOC8[3] = intliteral_537270_839829468((NI64)(L0 + IL64(1)));
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_611), LOC8, 4);
}
N_NIMCALL(void, asgnfielddiscriminant_547209_839829468)(Tcproc527021* p0, Tnode290802* e0) {
Tloc290816 a0;
Tloc290816 tmp0;
Tnode290802* dotexpr0;
memset((void*)(&a0), 0, sizeof(a0));
memset((void*)(&tmp0), 0, sizeof(tmp0));
dotexpr0 = (*e0).kindU.S6.sons->data[((NI) 0)];
{
if (!((*dotexpr0).kind == ((Tnodekind290020) 46))) goto LA3;
dotexpr0 = (*dotexpr0).kindU.S6.sons->data[((NI) 0)];
}
LA3: ;
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0));
gettemp_535032_839829468(p0, a0.t, (&tmp0), NIM_FALSE);
expr_537248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0));
gendiscriminantcheck_547144_839829468(p0, a0, tmp0, (*(*dotexpr0).kindU.S6.sons->data[((NI) 0)]).typ, (*(*dotexpr0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym);
genassignment_537264_839829468(p0, a0, tmp0, 0);
}
N_NIMCALL(void, genasgn_547239_839829468)(Tcproc527021* p0, Tnode290802* e0, NIM_BOOL fastasgn0) {
genlinedir_530823_839829468(p0, e0);
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 3));
if (!(LOC3)) goto LA4;
LOC3 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag290184) 30))&31U)))!=0);
LA4: ;
if (!LOC3) goto LA5;
gengotovar_542258_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)]);
}
goto LA1;
LA5: ;
{
NIM_BOOL LOC8;
Tloc290816 a0;
LOC8 = (NIM_BOOL)0;
LOC8 = fielddiscriminantcheckneeded_547080_839829468(p0, e0);
if (!!(LOC8)) goto LA9;
memset((void*)(&a0), 0, sizeof(a0));
{
Tnode290802* LOC13;
Tnode290802* LOC16;
LOC13 = (Tnode290802*)0;
LOC13 = HEX5BHEX5D_291238_850551059(e0, ((NI) 0));
if (!((*LOC13).kind == ((Tnodekind290020) 47) || (*LOC13).kind == ((Tnodekind290020) 65))) goto LA14;
LOC16 = (Tnode290802*)0;
LOC16 = HEX5BHEX5D_291238_850551059(e0, ((NI) 0));
genderef_541921_839829468(p0, LOC16, (&a0), NIM_TRUE);
}
goto LA11;
LA14: ;
{
initlocexpr_537283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0));
}
LA11: ;
{
if (!fastasgn0) goto LA20;
a0.flags |= ((NU16)1)<<((((Tlocflag290810) 2))%(sizeof(NU16)*8));
}
LA20: ;
loadinto_541928_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (*e0).kindU.S6.sons->data[((NI) 1)], (&a0));
}
goto LA1;
LA9: ;
{
asgnfielddiscriminant_547209_839829468(p0, e0);
}
LA1: ;
}
N_NIMCALL(Ropeobj177006*, genasmoremitstmt_546529_839829468)(Tcproc527021* p0, Tnode290802* t0, NIM_BOOL isasmstmt0) {
Ropeobj177006* result0;
NimStringDesc* res0;
result0 = (Ropeobj177006*)0;
res0 = copyString(((NimStringDesc*) &T839829468_490));
{
NI i_546547_839829468;
NI HEX3Atmp_546644_839829468;
NI LOC2;
NI res_546647_839829468;
i_546547_839829468 = (NI)0;
HEX3Atmp_546644_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(t0);
HEX3Atmp_546644_839829468 = (NI)(LOC2 - ((NI) 1));
res_546647_839829468 = ((NI) 0);
{
while (1) {
if (!(res_546647_839829468 <= HEX3Atmp_546644_839829468)) goto LA4;
i_546547_839829468 = res_546647_839829468;
switch ((*(*t0).kindU.S6.sons->data[i_546547_839829468]).kind) {
case ((Tnodekind290020) 20) ... ((Tnodekind290020) 22):
{
res0 = resizeString(res0, (*(*t0).kindU.S6.sons->data[i_546547_839829468]).kindU.S3.strval->Sup.len + 0);
appendString(res0, (*(*t0).kindU.S6.sons->data[i_546547_839829468]).kindU.S3.strval);
}
break;
case ((Tnodekind290020) 3):
{
Tsym290834* sym0;
sym0 = (*(*t0).kindU.S6.sons->data[i_546547_839829468]).kindU.S4.sym;
{
Tloc290816 a0;
Ropeobj177006* LOC11;
NimStringDesc* LOC12;
if (!((28672 &(1U<<((NU)((*sym0).kind)&31U)))!=0)) goto LA9;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[i_546547_839829468], (&a0));
LOC11 = (Ropeobj177006*)0;
LOC11 = rdloc_536188_839829468(a0);
LOC12 = (NimStringDesc*)0;
LOC12 = HEX24_177856_2381377266(LOC11);
res0 = resizeString(res0, LOC12->Sup.len + 0);
appendString(res0, LOC12);
}
goto LA7;
LA9: ;
{
Ropeobj177006* LOC16;
NimStringDesc* LOC17;
if (!((*sym0).kind == ((Tsymkind290435) 7))) goto LA14;
LOC16 = (Ropeobj177006*)0;
LOC16 = gettypedesc_533671_839829468((*p0).module, (*sym0).typ);
LOC17 = (NimStringDesc*)0;
LOC17 = HEX24_177856_2381377266(LOC16);
res0 = resizeString(res0, LOC17->Sup.len + 0);
appendString(res0, LOC17);
}
goto LA7;
LA14: ;
{
Ropeobj177006* r0;
NimStringDesc* LOC23;
r0 = (*sym0).loc.r;
{
if (!(r0 == NIM_NIL)) goto LA21;
r0 = manglename_531205_839829468(sym0);
asgnRefNoCycle((void**) (&(*sym0).loc.r), r0);
}
LA21: ;
LOC23 = (NimStringDesc*)0;
LOC23 = HEX24_177856_2381377266(r0);
res0 = resizeString(res0, LOC23->Sup.len + 0);
appendString(res0, LOC23);
}
LA7: ;
}
break;
default:
{
internalerror_194100_155036129((*(*t0).kindU.S6.sons->data[i_546547_839829468]).info, ((NimStringDesc*) &T839829468_612));
}
break;
}
res_546647_839829468 += ((NI) 1);
} LA4: ;
}
}
{
NIM_BOOL LOC27;
LOC27 = (NIM_BOOL)0;
LOC27 = isasmstmt0;
if (!(LOC27)) goto LA28;
LOC27 = ((Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop271004) 5))&7U)))!=0);
LA28: ;
if (!LOC27) goto LA29;
{
NimStringDesc* x_546604_839829468;
NI first_546656_839829468;
NI last_546658_839829468;
x_546604_839829468 = (NimStringDesc*)0;
first_546656_839829468 = ((NI) 0);
last_546658_839829468 = ((NI) 0);
{
while (1) {
NI j0;
{
while (1) {
if (!!((((NU8)(res0->data[last_546658_839829468])) == ((NU8)(0)) || ((NU8)(res0->data[last_546658_839829468])) == ((NU8)(13)) || ((NU8)(res0->data[last_546658_839829468])) == ((NU8)(10))))) goto LA35;
last_546658_839829468 += ((NI) 1);
} LA35: ;
}
x_546604_839829468 = copyStrLast(res0, first_546656_839829468, (NI)(last_546658_839829468 - ((NI) 1)));
j0 = ((NI) 0);
{
while (1) {
if (!(((NU8)(x_546604_839829468->data[j0])) == ((NU8)(32)) || ((NU8)(x_546604_839829468->data[j0])) == ((NU8)(9)))) goto LA37;
j0 += ((NI) 1);
} LA37: ;
}
{
if (!(((NU8)(x_546604_839829468->data[j0])) == ((NU8)(34)) || ((NU8)(x_546604_839829468->data[j0])) == ((NU8)(58)))) goto LA40;
add_177487_2381377266(&result0, x_546604_839829468);
add_177487_2381377266(&result0, tnl_175644_4151366050);
}
goto LA38;
LA40: ;
{
if (!!(((NU8)(x_546604_839829468->data[j0]) == (NU8)(0)))) goto LA43;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_613));
add_177487_2381377266(&result0, x_546604_839829468);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_614));
}
goto LA38;
LA43: ;
LA38: ;
{
if (!((NU8)(res0->data[last_546658_839829468]) == (NU8)(10))) goto LA47;
last_546658_839829468 += ((NI) 1);
}
goto LA45;
LA47: ;
{
if (!((NU8)(res0->data[last_546658_839829468]) == (NU8)(13))) goto LA50;
last_546658_839829468 += ((NI) 1);
{
if (!((NU8)(res0->data[last_546658_839829468]) == (NU8)(10))) goto LA54;
last_546658_839829468 += ((NI) 1);
}
LA54: ;
}
goto LA45;
LA50: ;
{
goto LA32;
}
LA45: ;
first_546656_839829468 = last_546658_839829468;
}
} LA32: ;
}
}
goto LA25;
LA29: ;
{
res0 = resizeString(res0, tnl_175644_4151366050->Sup.len + 0);
appendString(res0, tnl_175644_4151366050);
result0 = rope_177277_2381377266(res0);
}
LA25: ;
return result0;
}
N_NIMCALL(void, genasmstmt_546659_839829468)(Tcproc527021* p0, Tnode290802* t0) {
Ropeobj177006* s0;
genlinedir_530823_839829468(p0, t0);
s0 = genasmoremitstmt_546529_839829468(p0, t0, NIM_TRUE);
{
TY177507 LOC5;
if (!((*p0).prc == NIM_NIL)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = s0;
addf_178205_2381377266(&(*(*p0).module).s[(((Tcfilesection527005) 7))- 0], Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field17, LOC5, 1);
}
goto LA1;
LA3: ;
{
TY177507 LOC7;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = s0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field17, LOC7, 1);
}
LA1: ;
}
static N_INLINE(void, gensimpleblock_542095_839829468)(Tcproc527021* p0, Tnode290802* stmts0) {
TY531289 LOC1;
NI LOC2;
memset((void*)LOC1, 0, sizeof(LOC1));
LOC2 = (NI)0;
LOC2 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0);
genstmts_537244_839829468(p0, stmts0);
endblock_542060_839829468(p0);
}
N_NIMCALL(void, gentrycpp_545865_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) {
Ropeobj177006* exc0;
TY531289 LOC16;
NI LOC17;
NI length0;
TY177507 LOC18;
Ropeobj177006* LOC19;
NI i0;
NIM_BOOL catchallpresent0;
TY531289 LOC78;
Tnode290802* LOC79;
{
NIM_BOOL LOC3;
NIM_BOOL LOC4;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = isemptytype_295440_850551059((*t0).typ);
LOC3 = !(LOC4);
if (!(LOC3)) goto LA5;
LOC3 = ((*d0).k == ((Tlockind290808) 0));
LA5: ;
if (!LOC3) goto LA6;
gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE);
}
LA6: ;
genlinedir_530823_839829468(p0, t0);
exc0 = gettempname_531596_839829468((*p0).module);
{
Tsym290834* LOC10;
Ropeobj177006* LOC13;
LOC10 = (Tsym290834*)0;
LOC10 = getcompilerproc_336746_3937434831(((NimStringDesc*) &T839829468_615));
if (!!((LOC10 == NIM_NIL))) goto LA11;
LOC13 = (Ropeobj177006*)0;
LOC13 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615));
}
goto LA8;
LA11: ;
{
Ropeobj177006* LOC15;
LOC15 = (Ropeobj177006*)0;
LOC15 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616));
}
LA8: ;
(*p0).nestedtrystmts = (Tnodeseq290796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode290802*));
asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0);
++(*p0).nestedtrystmts->Sup.len;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC17 = (NI)0;
LOC17 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_617), LOC16, 0);
expr_537248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0);
length0 = sonslen_293351_850551059(t0);
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = exc0;
LOC19 = (Ropeobj177006*)0;
LOC19 = ropecg_530407_839829468((*p0).module, ((NimStringDesc*) &T839829468_618), LOC18, 1);
endblock_542035_839829468(p0, LOC19);
{
TY531289 LOC24;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA22;
memset((void*)LOC24, 0, sizeof(LOC24));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_619), LOC24, 0);
}
LA22: ;
(*p0).inexceptblock += ((NI) 1);
i0 = ((NI) 1);
catchallpresent0 = NIM_FALSE;
{
while (1) {
NIM_BOOL LOC27;
NI blen0;
LOC27 = (NIM_BOOL)0;
LOC27 = (i0 < length0);
if (!(LOC27)) goto LA28;
LOC27 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 87));
LA28: ;
if (!LOC27) goto LA26;
{
NIM_BOOL LOC31;
LOC31 = (NIM_BOOL)0;
LOC31 = ((*d0).k == ((Tlockind290808) 1));
if (!(LOC31)) goto LA32;
LOC31 = isemptytype_295440_850551059((*t0).typ);
LA32: ;
if (!LOC31) goto LA33;
(*d0).k = ((Tlockind290808) 0);
}
LA33: ;
blen0 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i0]);
{
Ropeobj177006** LOC39;
TY531289 LOC40;
if (!(((NI) 1) < i0)) goto LA37;
LOC39 = (Ropeobj177006**)0;
LOC39 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
memset((void*)LOC40, 0, sizeof(LOC40));
addf_178205_2381377266(LOC39, ((NimStringDesc*) &T839829468_620), LOC40, 0);
}
LA37: ;
{
TY531289 LOC45;
NI LOC46;
TY531289 LOC47;
if (!(blen0 == ((NI) 1))) goto LA43;
catchallpresent0 = NIM_TRUE;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC46 = (NI)0;
LOC46 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0);
expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0);
memset((void*)LOC47, 0, sizeof(LOC47));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC47, 0);
endblock_542060_839829468(p0);
}
goto LA41;
LA43: ;
{
Ropeobj177006* orexpr0;
TY177507 LOC57;
TY531289 LOC58;
NI LOC59;
TY531289 LOC60;
orexpr0 = NIM_NIL;
{
NI j_545978_839829468;
NI HEX3Atmp_546101_839829468;
NI res_546104_839829468;
j_545978_839829468 = (NI)0;
HEX3Atmp_546101_839829468 = (NI)0;
HEX3Atmp_546101_839829468 = (NI)(blen0 - ((NI) 2));
res_546104_839829468 = ((NI) 0);
{
while (1) {
TY530811 LOC56;
if (!(res_546104_839829468 <= HEX3Atmp_546101_839829468)) goto LA51;
j_545978_839829468 = res_546104_839829468;
{
if (!!((orexpr0 == NIM_NIL))) goto LA54;
add_177487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229));
}
LA54: ;
memset((void*)LOC56, 0, sizeof(LOC56));
LOC56[0] = exc0;
LOC56[1] = gentypeinfo_533941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_545978_839829468]).typ);
appcg_530632_839829468((*p0).module, &orexpr0, ((NimStringDesc*) &T839829468_621), LOC56, 2);
res_546104_839829468 += ((NI) 1);
} LA51: ;
}
}
memset((void*)LOC57, 0, sizeof(LOC57));
LOC57[0] = orexpr0;
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_622), LOC57, 1);
memset((void*)LOC58, 0, sizeof(LOC58));
LOC59 = (NI)0;
LOC59 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC58, 0);
expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0);
memset((void*)LOC60, 0, sizeof(LOC60));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC60, 0);
endblock_542060_839829468(p0);
}
LA41: ;
i0 += ((NI) 1);
} LA26: ;
}
{
TY531289 LOC70;
NI LOC71;
Tnode290802* finallyblock0;
TY531289 LOC76;
Ropeobj177006* LOC77;
if (!!(catchallpresent0)) goto LA63;
{
TY531289 LOC69;
if (!(((NI) 1) < i0)) goto LA67;
memset((void*)LOC69, 0, sizeof(LOC69));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_620), LOC69, 0);
}
LA67: ;
memset((void*)LOC70, 0, sizeof(LOC70));
LOC71 = (NI)0;
LOC71 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC70, 0);
finallyblock0 = lastson_293364_850551059(t0);
{
if (!((*finallyblock0).kind == ((Tnodekind290020) 107))) goto LA74;
genstmts_537244_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]);
}
LA74: ;
memset((void*)LOC76, 0, sizeof(LOC76));
LOC77 = (Ropeobj177006*)0;
LOC77 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_623), LOC76, 0);
line_530690_839829468(p0, ((Tcprocsection527011) 2), LOC77);
endblock_542060_839829468(p0);
}
LA63: ;
memset((void*)LOC78, 0, sizeof(LOC78));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC78, 0);
(*p0).inexceptblock -= ((NI) 1);
LOC79 = (Tnode290802*)0;
LOC79 = pop_316246_1689653243((&(*p0).nestedtrystmts));
{
NIM_BOOL LOC82;
LOC82 = (NIM_BOOL)0;
LOC82 = (i0 < length0);
if (!(LOC82)) goto LA83;
LOC82 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 107));
LA83: ;
if (!LOC82) goto LA84;
gensimpleblock_542095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]);
}
LA84: ;
}
N_NIMCALL(void, line_530695_839829468)(Tcproc527021* p0, Tcprocsection527011 s0, NimStringDesc* r0) {
Ropeobj177006** LOC1;
Ropeobj177006* LOC2;
Ropeobj177006* LOC3;
LOC1 = (Ropeobj177006**)0;
LOC1 = s_527179_3723162438(p0, s0);
LOC2 = (Ropeobj177006*)0;
LOC2 = rope_177277_2381377266(r0);
LOC3 = (Ropeobj177006*)0;
LOC3 = indentline_530656_839829468(p0, LOC2);
add_177482_2381377266(LOC1, LOC3);
}
static N_INLINE(Ropeobj177006*, pop_177530_1689653243)(TY189350** s0) {
Ropeobj177006* result0;
NI L0;
result0 = (Ropeobj177006*)0;
L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1));
result0 = (*s0)->data[L0];
(*s0) = (TY189350*) setLengthSeq(&((*s0))->Sup, sizeof(Ropeobj177006*), ((NI) (L0)));
return result0;
}
N_NIMCALL(void, gentry_546114_839829468)(Tcproc527021* p0, Tnode290802* t0, Tloc290816* d0) {
NIM_BOOL LOC8;
Ropeobj177006* safepoint0;
TY177507 LOC17;
TY177507 LOC18;
TY177507 LOC37;
NI LOC38;
NI length0;
TY531289 LOC39;
TY531289 LOC40;
NI LOC41;
TY531289 LOC42;
NI i0;
Tnode290802* LOC95;
TY177507 LOC103;
{
NIM_BOOL LOC3;
NIM_BOOL LOC4;
LOC3 = (NIM_BOOL)0;
LOC4 = (NIM_BOOL)0;
LOC4 = isemptytype_295440_850551059((*t0).typ);
LOC3 = !(LOC4);
if (!(LOC3)) goto LA5;
LOC3 = ((*d0).k == ((Tlockind290808) 0));
LA5: ;
if (!LOC3) goto LA6;
gettemp_535032_839829468(p0, (*t0).typ, d0, NIM_FALSE);
}
LA6: ;
LOC8 = (NIM_BOOL)0;
LOC8 = includestr_147249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_624));
genlinedir_530823_839829468(p0, t0);
safepoint0 = gettempname_531596_839829468((*p0).module);
{
Tsym290834* LOC11;
Ropeobj177006* LOC14;
LOC11 = (Tsym290834*)0;
LOC11 = getcompilerproc_336746_3937434831(((NimStringDesc*) &T839829468_615));
if (!!((LOC11 == NIM_NIL))) goto LA12;
LOC14 = (Ropeobj177006*)0;
LOC14 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615));
}
goto LA9;
LA12: ;
{
Ropeobj177006* LOC16;
LOC16 = (Ropeobj177006*)0;
LOC16 = cgsym_530403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616));
}
LA9: ;
memset((void*)LOC17, 0, sizeof(LOC17));
LOC17[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 0), ((NimStringDesc*) &T839829468_625), LOC17, 1);
memset((void*)LOC18, 0, sizeof(LOC18));
LOC18[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_626), LOC18, 1);
{
NIM_BOOL LOC21;
TY177507 LOC24;
LOC21 = (NIM_BOOL)0;
LOC21 = isdefined_198011_1967573533(((NimStringDesc*) &T839829468_627));
if (!LOC21) goto LA22;
memset((void*)LOC24, 0, sizeof(LOC24));
LOC24[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_628), LOC24, 1);
}
goto LA19;
LA22: ;
{
NIM_BOOL LOC26;
TY177507 LOC29;
LOC26 = (NIM_BOOL)0;
LOC26 = isdefined_198011_1967573533(((NimStringDesc*) &T839829468_629));
if (!LOC26) goto LA27;
memset((void*)LOC29, 0, sizeof(LOC29));
LOC29[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_630), LOC29, 1);
}
goto LA19;
LA27: ;
{
NIM_BOOL LOC31;
TY177507 LOC34;
LOC31 = (NIM_BOOL)0;
LOC31 = isdefined_198011_1967573533(((NimStringDesc*) &T839829468_631));
if (!LOC31) goto LA32;
memset((void*)LOC34, 0, sizeof(LOC34));
LOC34[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_632), LOC34, 1);
}
goto LA19;
LA32: ;
{
TY177507 LOC36;
memset((void*)LOC36, 0, sizeof(LOC36));
LOC36[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_628), LOC36, 1);
}
LA19: ;
memset((void*)LOC37, 0, sizeof(LOC37));
LOC37[0] = safepoint0;
LOC38 = (NI)0;
LOC38 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_633), LOC37, 1);
length0 = sonslen_293351_850551059(t0);
(*p0).nestedtrystmts = (Tnodeseq290796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode290802*));
asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0);
++(*p0).nestedtrystmts->Sup.len;
expr_537248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0);
memset((void*)LOC39, 0, sizeof(LOC39));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_605), LOC39, 0);
endblock_542060_839829468(p0);
memset((void*)LOC40, 0, sizeof(LOC40));
LOC41 = (NI)0;
LOC41 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_634), LOC40, 0);
memset((void*)LOC42, 0, sizeof(LOC42));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_605), LOC42, 0);
{
TY531289 LOC47;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0)) goto LA45;
memset((void*)LOC47, 0, sizeof(LOC47));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_619), LOC47, 0);
}
LA45: ;
(*p0).inexceptblock += ((NI) 1);
i0 = ((NI) 1);
{
while (1) {
NIM_BOOL LOC50;
NI blen0;
LOC50 = (NIM_BOOL)0;
LOC50 = (i0 < length0);
if (!(LOC50)) goto LA51;
LOC50 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 87));
LA51: ;
if (!LOC50) goto LA49;
{
NIM_BOOL LOC54;
LOC54 = (NIM_BOOL)0;
LOC54 = ((*d0).k == ((Tlockind290808) 1));
if (!(LOC54)) goto LA55;
LOC54 = isemptytype_295440_850551059((*t0).typ);
LA55: ;
if (!LOC54) goto LA56;
(*d0).k = ((Tlockind290808) 0);
}
LA56: ;
blen0 = sonslen_293351_850551059((*t0).kindU.S6.sons->data[i0]);
{
TY531289 LOC67;
NI LOC68;
TY177507 LOC69;
TY531289 LOC70;
if (!(blen0 == ((NI) 1))) goto LA60;
{
TY531289 LOC66;
if (!(((NI) 1) < i0)) goto LA64;
memset((void*)LOC66, 0, sizeof(LOC66));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_635), LOC66, 0);
}
LA64: ;
memset((void*)LOC67, 0, sizeof(LOC67));
LOC68 = (NI)0;
LOC68 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC67, 0);
memset((void*)LOC69, 0, sizeof(LOC69));
LOC69[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_636), LOC69, 1);
expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0);
memset((void*)LOC70, 0, sizeof(LOC70));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC70, 0);
endblock_542060_839829468(p0);
}
goto LA58;
LA60: ;
{
Ropeobj177006* orexpr0;
TY177507 LOC91;
NI LOC92;
TY177507 LOC93;
TY531289 LOC94;
orexpr0 = NIM_NIL;
{
NI j_546247_839829468;
NI HEX3Atmp_546521_839829468;
NI res_546524_839829468;
j_546247_839829468 = (NI)0;
HEX3Atmp_546521_839829468 = (NI)0;
HEX3Atmp_546521_839829468 = (NI)(blen0 - ((NI) 2));
res_546524_839829468 = ((NI) 0);
{
while (1) {
NimStringDesc* isobjformat0;
TY177507 LOC86;
if (!(res_546524_839829468 <= HEX3Atmp_546521_839829468)) goto LA74;
j_546247_839829468 = res_546524_839829468;
{
if (!!((orexpr0 == NIM_NIL))) goto LA77;
add_177487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229));
}
LA77: ;
{
NIM_BOOL LOC81;
LOC81 = (NIM_BOOL)0;
LOC81 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC81) goto LA82;
LOC81 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA82: ;
if (!!(LOC81)) goto LA83;
isobjformat0 = copyString(((NimStringDesc*) &T839829468_637));
}
goto LA79;
LA83: ;
{
isobjformat0 = copyString(((NimStringDesc*) &T839829468_638));
}
LA79: ;
memset((void*)LOC86, 0, sizeof(LOC86));
LOC86[0] = gentypeinfo_533941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_546247_839829468]).typ);
appcg_530632_839829468((*p0).module, &orexpr0, isobjformat0, LOC86, 1);
res_546524_839829468 += ((NI) 1);
} LA74: ;
}
}
{
if (!(((NI) 1) < i0)) goto LA89;
line_530695_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_620));
}
LA89: ;
memset((void*)LOC91, 0, sizeof(LOC91));
LOC91[0] = orexpr0;
LOC92 = (NI)0;
LOC92 = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_639), LOC91, 1);
memset((void*)LOC93, 0, sizeof(LOC93));
LOC93[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_636), LOC93, 1);
expr_537248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0);
memset((void*)LOC94, 0, sizeof(LOC94));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_606), LOC94, 0);
endblock_542060_839829468(p0);
}
LA58: ;
i0 += ((NI) 1);
} LA49: ;
}
(*p0).inexceptblock -= ((NI) 1);
LOC95 = (Tnode290802*)0;
LOC95 = pop_316246_1689653243((&(*p0).nestedtrystmts));
endblock_542060_839829468(p0);
{
NIM_BOOL LOC98;
Ropeobj177006* LOC102;
LOC98 = (NIM_BOOL)0;
LOC98 = (i0 < length0);
if (!(LOC98)) goto LA99;
LOC98 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind290020) 107));
LA99: ;
if (!LOC98) goto LA100;
(*p0).finallysafepoints = (TY189350*) incrSeqV2(&((*p0).finallysafepoints)->Sup, sizeof(Ropeobj177006*));
asgnRefNoCycle((void**) (&(*p0).finallysafepoints->data[(*p0).finallysafepoints->Sup.len]), safepoint0);
++(*p0).finallysafepoints->Sup.len;
gensimpleblock_542095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]);
LOC102 = (Ropeobj177006*)0;
LOC102 = pop_177530_1689653243((&(*p0).finallysafepoints));
}
LA100: ;
memset((void*)LOC103, 0, sizeof(LOC103));
LOC103[0] = safepoint0;
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_640), LOC103, 1);
}
N_NIMCALL(NimStringDesc*, getraisefrmt_544824_839829468)(Tcproc527021* p0) {
NimStringDesc* result0;
result0 = (NimStringDesc*)0;
result0 = copyString(((NimStringDesc*) &T839829468_641));
return result0;
}
N_NIMCALL(void, genraisestmt_544828_839829468)(Tcproc527021* p0, Tnode290802* t0) {
{
Tnode290802* finallyblock0;
if (!(((NI) 0) < (*p0).inexceptblock)) goto LA3;
finallyblock0 = lastson_293364_850551059((*p0).nestedtrystmts->data[(NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) 1))]);
{
if (!((*finallyblock0).kind == ((Tnodekind290020) 107))) goto LA7;
gensimpleblock_542095_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]);
}
LA7: ;
}
LA3: ;
{
Tloc290816 a0;
Ropeobj177006* e0;
Ttype290840* typ0;
NimStringDesc* LOC13;
TY530811 LOC14;
if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA11;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0));
e0 = rdloc_536188_839829468(a0);
typ0 = skiptypes_294099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106247256320));
genlinedir_530823_839829468(p0, t0);
LOC13 = (NimStringDesc*)0;
LOC13 = getraisefrmt_544824_839829468(p0);
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = e0;
LOC14[1] = makecstring_189638_155036129((*(*(*typ0).sym).name).s);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), LOC13, LOC14, 2);
}
goto LA9;
LA11: ;
{
genlinedir_530823_839829468(p0, t0);
{
NIM_BOOL LOC18;
NIM_BOOL LOC19;
TY531289 LOC24;
Ropeobj177006* LOC25;
LOC18 = (NIM_BOOL)0;
LOC19 = (NIM_BOOL)0;
LOC19 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC19) goto LA20;
LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA20: ;
LOC18 = LOC19;
if (!(LOC18)) goto LA21;
LOC18 = !(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 31))&63U)))!=0));
LA21: ;
if (!LOC18) goto LA22;
memset((void*)LOC24, 0, sizeof(LOC24));
LOC25 = (Ropeobj177006*)0;
LOC25 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_623), LOC24, 0);
line_530690_839829468(p0, ((Tcprocsection527011) 2), LOC25);
}
goto LA16;
LA22: ;
{
TY531289 LOC27;
memset((void*)LOC27, 0, sizeof(LOC27));
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_642), LOC27, 0);
}
LA16: ;
}
LA9: ;
}
N_NIMCALL(void, gentypesection_536184_839829468)(Tcgen527027* m0, Tnode290802* n0) {
}
N_NIMCALL(Tcfilesection527005, determinesection_546819_839829468)(Tnode290802* n0) {
Tcfilesection527005 result0;
result0 = (Tcfilesection527005)0;
result0 = ((Tcfilesection527005) 7);
{
NIM_BOOL LOC3;
NI LOC4;
NimStringDesc* sec0;
LOC3 = (NIM_BOOL)0;
LOC4 = (NI)0;
LOC4 = len_291081_850551059(n0);
LOC3 = (((NI) 1) <= LOC4);
if (!(LOC3)) goto LA5;
LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind >= ((Tnodekind290020) 20) && (*(*n0).kindU.S6.sons->data[((NI) 0)]).kind <= ((Tnodekind290020) 22));
LA5: ;
if (!LOC3) goto LA6;
sec0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S3.strval;
{
NIM_BOOL LOC10;
LOC10 = (NIM_BOOL)0;
LOC10 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_643));
if (!LOC10) goto LA11;
result0 = ((Tcfilesection527005) 3);
}
goto LA8;
LA11: ;
{
NIM_BOOL LOC14;
LOC14 = (NIM_BOOL)0;
LOC14 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_644));
if (!LOC14) goto LA15;
result0 = ((Tcfilesection527005) 9);
}
goto LA8;
LA15: ;
{
NIM_BOOL LOC18;
LOC18 = (NIM_BOOL)0;
LOC18 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_645));
if (!LOC18) goto LA19;
result0 = ((Tcfilesection527005) 1);
}
goto LA8;
LA19: ;
LA8: ;
}
LA6: ;
return result0;
}
N_NIMCALL(void, genemit_546839_839829468)(Tcproc527021* p0, Tnode290802* t0) {
Ropeobj177006* s0;
s0 = genasmoremitstmt_546529_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], NIM_FALSE);
{
Tcfilesection527005 section0;
Tnode290802* LOC5;
if (!((*p0).prc == NIM_NIL)) goto LA3;
LOC5 = (Tnode290802*)0;
LOC5 = HEX5BHEX5D_291238_850551059(t0, ((NI) 1));
section0 = determinesection_546819_839829468(LOC5);
genclinedir_530813_839829468(&(*(*p0).module).s[(section0)- 0], (*t0).info);
add_177482_2381377266(&(*(*p0).module).s[(section0)- 0], s0);
}
goto LA1;
LA3: ;
{
genlinedir_530823_839829468(p0, t0);
line_530690_839829468(p0, ((Tcprocsection527011) 2), s0);
}
LA1: ;
}
N_NIMCALL(void, genbreakpoint_546862_839829468)(Tcproc527021* p0, Tnode290802* t0) {
NimStringDesc* name0;
name0 = (NimStringDesc*)0;
{
TY533238 LOC12;
NI LOC13;
NimStringDesc* LOC14;
if (!(((*p0).options &(1U<<((NU)(((Toption168009) 17))&31U)))!=0)) goto LA3;
{
if (!((*t0).kind == ((Tnodekind290020) 34))) goto LA7;
name0 = nsuNormalize((*(*t0).kindU.S6.sons->data[((NI) 1)]).kindU.S3.strval);
}
goto LA5;
LA7: ;
{
NimStringDesc* LOC10;
NimStringDesc* LOC11;
breakpointid_546860_839829468 += ((NI) 1);
LOC10 = (NimStringDesc*)0;
LOC11 = (NimStringDesc*)0;
LOC11 = nimIntToStr(breakpointid_546860_839829468);
LOC10 = rawNewString(LOC11->Sup.len + 2);
appendString(LOC10, ((NimStringDesc*) &T839829468_646));
appendString(LOC10, LOC11);
name0 = LOC10;
}
LA5: ;
genlinedir_530823_839829468(p0, t0);
memset((void*)LOC12, 0, sizeof(LOC12));
LOC13 = (NI)0;
LOC13 = tolinenumber_190415_155036129((*t0).info);
LOC12[0] = rope_177401_2381377266(((NI64) (LOC13)));
LOC14 = (NimStringDesc*)0;
LOC14 = tofilename_190260_155036129((*t0).info.fileindex);
LOC12[1] = makecstring_189638_155036129(LOC14);
LOC12[2] = makecstring_189638_155036129(name0);
appcg_530632_839829468((*p0).module, &gbreakpoints_546861_839829468, ((NimStringDesc*) &T839829468_647), LOC12, 3);
}
LA3: ;
}
N_NIMCALL(void, genwatchpoint_547016_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Tloc290816 a0;
Ttype290840* typ0;
TY533238 LOC5;
NimStringDesc* LOC6;
{ {
if (!!((((*p0).options &(1U<<((NU)(((Toption168009) 17))&31U)))!=0))) goto LA3;
goto BeforeRet;
}
LA3: ;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0));
typ0 = skiptypes_294099_850551059((*(*n0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440));
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = addrloc_536204_839829468(a0);
LOC6 = (NimStringDesc*)0;
LOC6 = rendertree_309044_382274130((*n0).kindU.S6.sons->data[((NI) 1)], 0);
LOC5[1] = makecstring_189638_155036129(LOC6);
LOC5[2] = gentypeinfo_533941_839829468((*p0).module, typ0);
linecg_530707_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_648), LOC5, 3);
}BeforeRet: ;
}
N_NIMCALL(void, genpragma_547039_839829468)(Tcproc527021* p_547041_839829468, Tnode290802* n0) {
{
NI i_547054_839829468;
NI HEX3Atmp_547073_839829468;
NI LOC2;
NI res_547076_839829468;
i_547054_839829468 = (NI)0;
HEX3Atmp_547073_839829468 = (NI)0;
LOC2 = (NI)0;
LOC2 = sonslen_293351_850551059(n0);
HEX3Atmp_547073_839829468 = (NI)(LOC2 - ((NI) 1));
res_547076_839829468 = ((NI) 0);
{
while (1) {
Tnode290802* it0;
Tspecialword273003 LOC5;
if (!(res_547076_839829468 <= HEX3Atmp_547073_839829468)) goto LA4;
i_547054_839829468 = res_547076_839829468;
it0 = (*n0).kindU.S6.sons->data[i_547054_839829468];
LOC5 = (Tspecialword273003)0;
LOC5 = whichpragma_316911_2616423590(it0);
switch (LOC5) {
case ((Tspecialword273003) 191):
{
genemit_546839_839829468(p_547041_839829468, it0);
}
break;
case ((Tspecialword273003) 131):
{
genbreakpoint_546862_839829468(p_547041_839829468, it0);
}
break;
case ((Tspecialword273003) 176):
{
genwatchpoint_547016_839829468(p_547041_839829468, it0);
}
break;
case ((Tspecialword273003) 183):
{
Tcproc527021* p0;
Ropeobj177006** LOC10;
p0 = newproc_527206_3723162438(NIM_NIL, (*p_547041_839829468).module);
(*p0).options = ((*p0).options & ~ 98304);
genstmts_537244_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)]);
LOC10 = (Ropeobj177006**)0;
LOC10 = s_527179_3723162438(p0, ((Tcprocsection527011) 2));
asgnRefNoCycle((void**) (&(*(*p0).module).injectstmt), (*LOC10));
}
break;
default:
{
}
break;
}
res_547076_839829468 += ((NI) 1);
} LA4: ;
}
}
}
N_NIMCALL(void, genparforstmt_544208_839829468)(Tcproc527021* p0, Tnode290802* t0) {
NI oldbreakidx_544411_839829468;
Tsym290834* forloopvar0;
Tloc290816 rangea0;
Tloc290816 rangeb0;
Tnode290802* call0;
TY533235 LOC1;
NimStringDesc* LOC2;
TY531289 LOC3;
(*p0).withinloop += ((NI) 1);
genlinedir_530823_839829468(p0, t0);
oldbreakidx_544411_839829468 = (*p0).breakidx;
forloopvar0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
memset((void*)(&rangea0), 0, sizeof(rangea0));
memset((void*)(&rangeb0), 0, sizeof(rangeb0));
assignlocalvar_536614_839829468(p0, forloopvar0);
call0 = (*t0).kindU.S6.sons->data[((NI) 1)];
initlocexpr_537283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 1)], (&rangea0));
initlocexpr_537283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 2)], (&rangeb0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468((*forloopvar0).loc);
LOC1[1] = rdloc_536188_839829468(rangea0);
LOC1[2] = rdloc_536188_839829468(rangeb0);
LOC2 = (NimStringDesc*)0;
LOC2 = getstr_295230_850551059((*call0).kindU.S6.sons->data[((NI) 3)]);
LOC1[3] = rope_177277_2381377266(LOC2);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_649), LOC1, 4);
memset((void*)LOC3, 0, sizeof(LOC3));
(*p0).breakidx = startblock_541978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC3, 0);
(*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE;
genstmts_537244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 2)]);
endblock_542060_839829468(p0);
(*p0).breakidx = oldbreakidx_544411_839829468;
(*p0).withinloop -= ((NI) 1);
}
N_NIMCALL(void, genstate_542117_839829468)(Tcproc527021* p0, Tnode290802* n0) {
NI64 idx0;
TY177507 LOC9;
{
NIM_BOOL LOC3;
NI LOC4;
NimStringDesc* LOC8;
LOC3 = (NIM_BOOL)0;
LOC4 = (NI)0;
LOC4 = len_291081_850551059(n0);
LOC3 = (LOC4 == ((NI) 1));
if (!(LOC3)) goto LA5;
LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 6));
LA5: ;
if (!!(LOC3)) goto LA6;
LOC8 = (NimStringDesc*)0;
LOC8 = HEX24_194185_1689653243(T839829468_650);
internalerror_194113_155036129(LOC8);
}
LA6: ;
idx0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval;
memset((void*)LOC9, 0, sizeof(LOC9));
LOC9[0] = rope_177401_2381377266(idx0);
linefmt_530714_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_652), LOC9, 1);
}
N_NIMCALL(void, gengotostate_542144_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Tloc290816 a0;
TY177507 LOC1;
TY531289 LOC2;
TY531289 LOC7;
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = rdloc_536188_839829468(a0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_603), LOC1, 1);
(*p0).beforeretneeded = NIM_TRUE;
memset((void*)LOC2, 0, sizeof(LOC2));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_653), LOC2, 0);
{
NI64 i_542214_839829468;
NI64 HEX3Atmp_542223_839829468;
NI64 res_542226_839829468;
i_542214_839829468 = (NI64)0;
HEX3Atmp_542223_839829468 = (NI64)0;
HEX3Atmp_542223_839829468 = lastord_318004_3876443242((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ);
res_542226_839829468 = IL64(0);
{
while (1) {
TY177507 LOC6;
if (!(res_542226_839829468 <= HEX3Atmp_542223_839829468)) goto LA5;
i_542214_839829468 = res_542226_839829468;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = rope_177401_2381377266(i_542214_839829468);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_654), LOC6, 1);
res_542226_839829468 += ((NI) 1);
} LA5: ;
}
}
memset((void*)LOC7, 0, sizeof(LOC7));
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_160), LOC7, 0);
}
N_NIMCALL(void, genbreakstate_542229_839829468)(Tcproc527021* p0, Tnode290802* n0) {
Tloc290816 a0;
memset((void*)(&a0), 0, sizeof(a0));
{
TY177507 LOC5;
if (!((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 155))) goto LA3;
initlocexpr_537283_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)], (&a0));
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rdloc_536188_839829468(a0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_655), LOC5, 1);
}
goto LA1;
LA3: ;
{
TY177507 LOC7;
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = rdloc_536188_839829468(a0);
linef_530700_839829468(p0, ((Tcprocsection527011) 2), ((NimStringDesc*) &T839829468_656), LOC7, 1);
}
LA1: ;
}
N_NIMCALL(void, expr_537248_839829468)(Tcproc527021* p0, Tnode290802* n0, Tloc290816* d0) {
switch ((*n0).kind) {
case ((Tnodekind290020) 3):
{
Tsym290834* sym0;
sym0 = (*n0).kindU.S4.sym;
switch ((*sym0).kind) {
case ((Tsymkind290435) 13):
{
{
if (!!(((33554448 & (*sym0).flags) == 0))) goto LA5;
fillprocloc_537201_839829468(sym0);
genprocprototype_537254_839829468((*p0).module, sym0);
}
goto LA3;
LA5: ;
{
genproc_530951_839829468((*p0).module, sym0);
}
LA3: ;
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
break;
case ((Tsymkind290435) 12):
case ((Tsymkind290435) 15):
case ((Tsymkind290435) 14):
{
{
NimStringDesc* LOC13;
if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 23))&31U)))!=0)) goto LA11;
LOC13 = (NimStringDesc*)0;
LOC13 = rawNewString((*(*sym0).name).s->Sup.len + 48);
appendString(LOC13, ((NimStringDesc*) &T839829468_270));
appendString(LOC13, (*(*sym0).name).s);
localerror_194085_155036129((*n0).info, LOC13);
}
LA11: ;
genproc_530951_839829468((*p0).module, sym0);
{
NIM_BOOL LOC16;
NimStringDesc* LOC20;
LOC16 = (NIM_BOOL)0;
LOC16 = ((*sym0).loc.r == NIM_NIL);
if (LOC16) goto LA17;
LOC16 = ((*sym0).loc.t == NIM_NIL);
LA17: ;
if (!LOC16) goto LA18;
LOC20 = (NimStringDesc*)0;
LOC20 = rawNewString((*(*sym0).name).s->Sup.len + 20);
appendString(LOC20, ((NimStringDesc*) &T839829468_271));
appendString(LOC20, (*(*sym0).name).s);
internalerror_194100_155036129((*n0).info, LOC20);
}
LA18: ;
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
break;
case ((Tsymkind290435) 10):
{
{
NIM_BOOL LOC24;
Ropeobj177006* LOC27;
LOC24 = (NIM_BOOL)0;
LOC24 = issimpleconst_530311_839829468((*sym0).typ);
if (!LOC24) goto LA25;
LOC27 = (Ropeobj177006*)0;
LOC27 = genliteral_547476_839829468(p0, (*sym0).ast, (*sym0).typ);
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC27, ((Tstorageloc290812) 1));
}
goto LA22;
LA25: ;
{
gencomplexconst_556249_839829468(p0, sym0, d0);
}
LA22: ;
}
break;
case ((Tsymkind290435) 19):
{
Ropeobj177006* LOC30;
LOC30 = (Ropeobj177006*)0;
LOC30 = rope_177401_2381377266(((NI64) ((*sym0).position)));
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC30, ((Tstorageloc290812) 0));
}
break;
case ((Tsymkind290435) 8):
case ((Tsymkind290435) 20):
case ((Tsymkind290435) 11):
case ((Tsymkind290435) 9):
{
{
if (!!(((4194312 & (*sym0).flags) == 0))) goto LA34;
genvarprototype_537236_839829468((*p0).module, sym0);
}
LA34: ;
{
NIM_BOOL LOC38;
NimStringDesc* LOC42;
NimStringDesc* LOC43;
LOC38 = (NIM_BOOL)0;
LOC38 = ((*sym0).loc.r == NIM_NIL);
if (LOC38) goto LA39;
LOC38 = ((*sym0).loc.t == NIM_NIL);
LA39: ;
if (!LOC38) goto LA40;
LOC42 = (NimStringDesc*)0;
LOC43 = (NimStringDesc*)0;
LOC43 = nimIntToStr((*sym0).Sup.id);
LOC42 = rawNewString((*(*sym0).name).s->Sup.len + LOC43->Sup.len + 20);
appendString(LOC42, ((NimStringDesc*) &T839829468_285));
appendString(LOC42, (*(*sym0).name).s);
appendString(LOC42, ((NimStringDesc*) &T839829468_12));
appendString(LOC42, LOC43);
internalerror_194100_155036129((*n0).info, LOC42);
}
LA40: ;
{
if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag290184) 22))&31U)))!=0)) goto LA46;
accessthreadlocalvar_530945_839829468(p0, sym0);
{
NIM_BOOL LOC50;
Ropeobj177006* LOC53;
LOC50 = (NIM_BOOL)0;
LOC50 = emulatedthreadvars_530949_839829468();
if (!LOC50) goto LA51;
LOC53 = (Ropeobj177006*)0;
LOC53 = HEX26_177452_2381377266(((NimStringDesc*) &T839829468_288), (*sym0).loc.r);
putintodest_548468_839829468(p0, d0, (*sym0).loc.t, LOC53, ((Tstorageloc290812) 0));
}
goto LA48;
LA51: ;
{
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
LA48: ;
}
goto LA44;
LA46: ;
{
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
LA44: ;
}
break;
case ((Tsymkind290435) 5):
{
{
NIM_BOOL LOC59;
NimStringDesc* LOC63;
NimStringDesc* LOC64;
LOC59 = (NIM_BOOL)0;
LOC59 = ((*sym0).loc.r == NIM_NIL);
if (LOC59) goto LA60;
LOC59 = ((*sym0).loc.t == NIM_NIL);
LA60: ;
if (!LOC59) goto LA61;
LOC63 = (NimStringDesc*)0;
LOC64 = (NimStringDesc*)0;
LOC64 = nimIntToStr((*sym0).Sup.id);
LOC63 = rawNewString((*(*sym0).name).s->Sup.len + LOC64->Sup.len + 21);
appendString(LOC63, ((NimStringDesc*) &T839829468_289));
appendString(LOC63, (*(*sym0).name).s);
appendString(LOC63, ((NimStringDesc*) &T839829468_12));
appendString(LOC63, LOC64);
internalerror_194100_155036129((*n0).info, LOC63);
}
LA61: ;
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
break;
case ((Tsymkind290435) 3):
{
{
NIM_BOOL LOC68;
NimStringDesc* LOC72;
NimStringDesc* LOC73;
LOC68 = (NIM_BOOL)0;
LOC68 = ((*sym0).loc.r == NIM_NIL);
if (LOC68) goto LA69;
LOC68 = ((*sym0).loc.t == NIM_NIL);
LA69: ;
if (!LOC68) goto LA70;
LOC72 = (NimStringDesc*)0;
LOC73 = (NimStringDesc*)0;
LOC73 = nimIntToStr((*sym0).Sup.id);
LOC72 = rawNewString((*(*sym0).name).s->Sup.len + LOC73->Sup.len + 22);
appendString(LOC72, ((NimStringDesc*) &T839829468_290));
appendString(LOC72, (*(*sym0).name).s);
appendString(LOC72, ((NimStringDesc*) &T839829468_12));
appendString(LOC72, LOC73);
internalerror_194100_155036129((*n0).info, LOC72);
}
LA70: ;
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
break;
default:
{
NimStringDesc* LOC75;
LOC75 = (NimStringDesc*)0;
LOC75 = rawNewString(reprEnum((NI)(*sym0).kind, (&NTI290435))->Sup.len + 22);
appendString(LOC75, ((NimStringDesc*) &T839829468_291));
appendString(LOC75, reprEnum((NI)(*sym0).kind, (&NTI290435)));
appendString(LOC75, ((NimStringDesc*) &T839829468_292));
internalerror_194100_155036129((*n0).info, LOC75);
}
break;
}
}
break;
case ((Tnodekind290020) 23):
{
{
NIM_BOOL LOC79;
Ropeobj177006* LOC82;
LOC79 = (NIM_BOOL)0;
LOC79 = isemptytype_295440_850551059((*n0).typ);
if (!!(LOC79)) goto LA80;
LOC82 = (Ropeobj177006*)0;
LOC82 = genliteral_537273_839829468(p0, n0);
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC82, ((Tstorageloc290812) 0));
}
LA80: ;
}
break;
case ((Tnodekind290020) 20) ... ((Tnodekind290020) 22):
{
Ropeobj177006* LOC84;
LOC84 = (Ropeobj177006*)0;
LOC84 = genliteral_537273_839829468(p0, n0);
putdataintodest_548436_839829468(p0, d0, (*n0).typ, LOC84);
}
break;
case ((Tnodekind290020) 6) ... ((Tnodekind290020) 15):
case ((Tnodekind290020) 16) ... ((Tnodekind290020) 19):
case ((Tnodekind290020) 5):
{
Ropeobj177006* LOC86;
LOC86 = (Ropeobj177006*)0;
LOC86 = genliteral_537273_839829468(p0, n0);
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC86, ((Tstorageloc290812) 0));
}
break;
case ((Tnodekind290020) 27):
case ((Tnodekind290020) 32):
case ((Tnodekind290020) 29):
case ((Tnodekind290020) 30):
case ((Tnodekind290020) 31):
case ((Tnodekind290020) 26):
case ((Tnodekind290020) 28):
{
Tnode290802* op0;
genlinedir_530823_839829468(p0, n0);
op0 = (*n0).kindU.S6.sons->data[((NI) 0)];
{
Tloc290816 a0;
if (!(*n0).typ == 0) goto LA90;
memset((void*)(&a0), 0, sizeof(a0));
{
NIM_BOOL LOC94;
LOC94 = (NIM_BOOL)0;
LOC94 = ((*op0).kind == ((Tnodekind290020) 3));
if (!(LOC94)) goto LA95;
LOC94 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic290524) 0)));
LA95: ;
if (!LOC94) goto LA96;
genmagicexpr_555033_839829468(p0, n0, (&a0), (*(*op0).kindU.S4.sym).magic);
}
goto LA92;
LA96: ;
{
gencall_541632_839829468(p0, n0, (&a0));
}
LA92: ;
}
goto LA88;
LA90: ;
{
{
NIM_BOOL LOC102;
LOC102 = (NIM_BOOL)0;
LOC102 = ((*op0).kind == ((Tnodekind290020) 3));
if (!(LOC102)) goto LA103;
LOC102 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic290524) 0)));
LA103: ;
if (!LOC102) goto LA104;
genmagicexpr_555033_839829468(p0, n0, d0, (*(*op0).kindU.S4.sym).magic);
}
goto LA100;
LA104: ;
{
gencall_541632_839829468(p0, n0, d0);
}
LA100: ;
}
LA88: ;
}
break;
case ((Tnodekind290020) 39):
{
{
NIM_BOOL LOC110;
NI LOC112;
Ropeobj177006* LOC115;
LOC110 = (NIM_BOOL)0;
LOC110 = isdeepconstexpr_316566_2616423590(n0);
if (!(LOC110)) goto LA111;
LOC112 = (NI)0;
LOC112 = len_291081_850551059(n0);
LOC110 = !((LOC112 == ((NI) 0)));
LA111: ;
if (!LOC110) goto LA113;
LOC115 = (Ropeobj177006*)0;
LOC115 = gensetnode_547664_839829468(p0, n0);
putintodest_548468_839829468(p0, d0, (*n0).typ, LOC115, ((Tstorageloc290812) 0));
}
goto LA108;
LA113: ;
{
gensetconstr_555496_839829468(p0, n0, d0);
}
LA108: ;
}
break;
case ((Tnodekind290020) 41):
{
{
NIM_BOOL LOC120;
NI LOC122;
LOC120 = (NIM_BOOL)0;
LOC120 = isdeepconstexpr_316566_2616423590(n0);
if (!(LOC120)) goto LA121;
LOC122 = (NI)0;
LOC122 = len_291081_850551059(n0);
LOC120 = !((LOC122 == ((NI) 0)));
LA121: ;
if (!LOC120) goto LA123;
exprcomplexconst_556684_839829468(p0, n0, d0);
}
goto LA118;
LA123: ;
{
Ttype290840* LOC126;
LOC126 = (Ttype290840*)0;
LOC126 = skiptypes_294099_850551059((*n0).typ, IL64(211106242013440));
if (!((*LOC126).kind == ((Ttypekind290244) 24))) goto LA127;
genseqconstr_553004_839829468(p0, n0, d0);
}
goto LA118;
LA127: ;
{
genarrayconstr_556207_839829468(p0, n0, d0);
}
LA118: ;
}
break;
case ((Tnodekind290020) 37):
{
{
NIM_BOOL LOC133;
NI LOC135;
LOC133 = (NIM_BOOL)0;
LOC133 = isdeepconstexpr_316566_2616423590(n0);
if (!(LOC133)) goto LA134;
LOC135 = (NI)0;
LOC135 = len_291081_850551059(n0);
LOC133 = !((LOC135 == ((NI) 0)));
LA134: ;
if (!LOC133) goto LA136;
exprcomplexconst_556684_839829468(p0, n0, d0);
}
goto LA131;
LA136: ;
{
gentupleconstr_555618_839829468(p0, n0, d0);
}
LA131: ;
}
break;
case ((Tnodekind290020) 38):
{
genobjconstr_552903_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 61):
{
gencast_554537_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 58):
case ((Tnodekind290020) 59):
case ((Tnodekind290020) 60):
{
genconv_554632_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 64):
case ((Tnodekind290020) 63):
{
genaddr_551051_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 42):
{
genbracketexpr_552277_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 47):
case ((Tnodekind290020) 65):
{
genderef_541921_839829468(p0, n0, d0, NIM_FALSE);
}
break;
case ((Tnodekind290020) 45):
{
genrecordfield_551448_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 46):
{
gencheckedrecordfield_552046_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 127):
case ((Tnodekind290020) 112):
{
genblock_544083_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 126):
{
genstmtlistexpr_556402_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 115):
{
{
NI i_557023_839829468;
NI HEX3Atmp_557276_839829468;
NI LOC151;
NI res_557279_839829468;
i_557023_839829468 = (NI)0;
HEX3Atmp_557276_839829468 = (NI)0;
LOC151 = (NI)0;
LOC151 = sonslen_293351_850551059(n0);
HEX3Atmp_557276_839829468 = (NI)(LOC151 - ((NI) 1));
res_557279_839829468 = ((NI) 0);
{
while (1) {
if (!(res_557279_839829468 <= HEX3Atmp_557276_839829468)) goto LA153;
i_557023_839829468 = res_557279_839829468;
genstmts_537244_839829468(p0, (*n0).kindU.S6.sons->data[i_557023_839829468]);
res_557279_839829468 += ((NI) 1);
} LA153: ;
}
}
}
break;
case ((Tnodekind290020) 48):
case ((Tnodekind290020) 92):
{
genif_542982_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 93):
{
expr_537248_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[((NI) 0)], d0);
}
break;
case ((Tnodekind290020) 66):
{
downconv_556581_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 67):
{
upconv_556431_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 68):
{
genrangechck_554590_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_563));
}
break;
case ((Tnodekind290020) 69):
{
genrangechck_554590_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_564));
}
break;
case ((Tnodekind290020) 70):
{
genrangechck_554590_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_565));
}
break;
case ((Tnodekind290020) 71):
{
convstrtocstr_554642_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 72):
{
convcstrtostr_554654_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 51):
case ((Tnodekind290020) 52):
{
Tsym290834* sym0;
sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
genproc_530951_839829468((*p0).module, sym0);
{
NIM_BOOL LOC166;
NimStringDesc* LOC170;
LOC166 = (NIM_BOOL)0;
LOC166 = ((*sym0).loc.r == NIM_NIL);
if (LOC166) goto LA167;
LOC166 = ((*sym0).loc.t == NIM_NIL);
LA167: ;
if (!LOC166) goto LA168;
LOC170 = (NimStringDesc*)0;
LOC170 = rawNewString((*(*sym0).name).s->Sup.len + 20);
appendString(LOC170, ((NimStringDesc*) &T839829468_271));
appendString(LOC170, (*(*sym0).name).s);
internalerror_194100_155036129((*n0).info, LOC170);
}
LA168: ;
putlocintodest_537258_839829468(p0, d0, (*sym0).loc);
}
break;
case ((Tnodekind290020) 155):
{
genclosure_555836_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 1):
{
}
break;
case ((Tnodekind290020) 96):
{
genwhilestmt_543984_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 99):
case ((Tnodekind290020) 100):
{
genvarstmt_542854_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 101):
{
genconststmt_542909_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 94):
{
internalerror_194100_155036129((*n0).info, ((NimStringDesc*) &T839829468_594));
}
break;
case ((Tnodekind290020) 97):
{
gencase_545826_839829468(p0, n0, d0);
}
break;
case ((Tnodekind290020) 109):
{
genreturnstmt_543617_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 110):
{
genbreakstmt_544444_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 73):
{
{
if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag290427) 14))&15U)))!=0))) goto LA183;
genasgn_547239_839829468(p0, n0, NIM_FALSE);
}
LA183: ;
}
break;
case ((Tnodekind290020) 74):
{
{
if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag290427) 14))&15U)))!=0))) goto LA188;
genasgn_547239_839829468(p0, n0, !(((*p0).prc == NIM_NIL)));
}
LA188: ;
}
break;
case ((Tnodekind290020) 114):
{
{
Tloc290816 a0;
if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind290020) 1)))) goto LA193;
genlinedir_530823_839829468(p0, n0);
memset((void*)(&a0), 0, sizeof(a0));
initlocexpr_537283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0));
}
LA193: ;
}
break;
case ((Tnodekind290020) 89):
{
genasmstmt_546659_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 106):
{
{
NIM_BOOL LOC199;
NIM_BOOL LOC200;
LOC199 = (NIM_BOOL)0;
LOC200 = (NIM_BOOL)0;
LOC200 = (gcmd_168132_2607990831 == ((Tcommands168076) 2));
if (LOC200) goto LA201;
LOC200 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA201: ;
LOC199 = LOC200;
if (!(LOC199)) goto LA202;
LOC199 = !(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 31))&63U)))!=0));
LA202: ;
if (!LOC199) goto LA203;
gentrycpp_545865_839829468(p0, n0, d0);
}
goto LA197;
LA203: ;
{
gentry_546114_839829468(p0, n0, d0);
}
LA197: ;
}
break;
case ((Tnodekind290020) 108):
{
genraisestmt_544828_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 98):
{
gentypesection_536184_839829468((*p0).module, n0);
}
break;
case ((Tnodekind290020) 125):
case ((Tnodekind290020) 84):
case ((Tnodekind290020) 121):
case ((Tnodekind290020) 116):
case ((Tnodekind290020) 117):
case ((Tnodekind290020) 118):
case ((Tnodekind290020) 119):
case ((Tnodekind290020) 120):
case ((Tnodekind290020) 83):
case ((Tnodekind290020) 82):
{
}
break;
case ((Tnodekind290020) 90):
{
genpragma_547039_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 91):
{
Tnode290802* LOC211;
LOC211 = (Tnode290802*)0;
LOC211 = lastson_293364_850551059(n0);
expr_537248_839829468(p0, LOC211, d0);
}
break;
case ((Tnodekind290020) 79):
case ((Tnodekind290020) 80):
case ((Tnodekind290020) 81):
{
{
Tsym290834* prc0;
if (!((*(*n0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind290020) 1))) goto LA215;
prc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym;
{
NIM_BOOL LOC219;
Tsym290834* LOC220;
LOC219 = (NIM_BOOL)0;
LOC220 = (Tsym290834*)0;
LOC220 = skipgenericowner_295279_850551059(prc0);
LOC219 = ((*LOC220).kind == ((Tsymkind290435) 6));
if (!(LOC219)) goto LA221;
LOC219 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 23))&31U)))!=0));
LA221: ;
if (!LOC219) goto LA222;
{
NIM_BOOL LOC226;
NIM_BOOL LOC227;
NIM_BOOL LOC228;
NIM_BOOL LOC229;
Tsym290834* LOC231;
NIM_BOOL LOC234;
LOC226 = (NIM_BOOL)0;
LOC227 = (NIM_BOOL)0;
LOC228 = (NIM_BOOL)0;
LOC229 = (NIM_BOOL)0;
LOC229 = !(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 2))&63U)))!=0));
if (!(LOC229)) goto LA230;
LOC231 = (Tsym290834*)0;
LOC231 = getmodule_297123_2984716966(prc0);
LOC229 = !((((*LOC231).flags &(1U<<((NU)(((Tsymflag290184) 25))&31U)))!=0));
LA230: ;
LOC228 = LOC229;
if (LOC228) goto LA232;
LOC228 = ((65600 & (*prc0).flags) == 64);
LA232: ;
LOC227 = LOC228;
if (LOC227) goto LA233;
LOC234 = (NIM_BOOL)0;
LOC234 = (((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 6))&31U)))!=0);
if (!(LOC234)) goto LA235;
LOC234 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 5))&15U)))!=0);
LA235: ;
LOC227 = LOC234;
LA233: ;
LOC226 = LOC227;
if (LOC226) goto LA236;
LOC226 = ((*prc0).kind == ((Tsymkind290435) 13));
LA236: ;
if (!LOC226) goto LA237;
{
NIM_BOOL LOC241;
Tnode290802* LOC242;
LOC241 = (NIM_BOOL)0;
LOC242 = (Tnode290802*)0;
LOC242 = getbody_333227_1724185294(prc0);
LOC241 = !(((*LOC242).kind == ((Tnodekind290020) 1)));
if (LOC241) goto LA243;
LOC241 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag290810) 4))&15U)))!=0);
LA243: ;
if (!LOC241) goto LA244;
genproc_530951_839829468((*p0).module, prc0);
}
LA244: ;
}
LA237: ;
}
LA222: ;
}
LA215: ;
}
break;
case ((Tnodekind290020) 95):
{
genparforstmt_544208_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 157):
{
genstate_542117_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 156):
{
gengotostate_542144_839829468(p0, n0);
}
break;
case ((Tnodekind290020) 158):
{
genbreakstate_542229_839829468(p0, n0);
}
break;
default:
{
NimStringDesc* LOC251;
LOC251 = (NimStringDesc*)0;
LOC251 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI290020))->Sup.len + 25);
appendString(LOC251, ((NimStringDesc*) &T839829468_291));
appendString(LOC251, reprEnum((NI)(*n0).kind, (&NTI290020)));
appendString(LOC251, ((NimStringDesc*) &T839829468_657));
internalerror_194100_155036129((*n0).info, LOC251);
}
break;
}
}
N_NIMCALL(void, genstmts_537244_839829468)(Tcproc527021* p0, Tnode290802* t0) {
Tloc290816 a0;
memset((void*)(&a0), 0, sizeof(a0));
expr_537248_839829468(p0, t0, (&a0));
{
NimStringDesc* LOC5;
if (!!(((7 &(1U<<((NU)(a0.k)&15U)))!=0))) goto LA3;
LOC5 = (NimStringDesc*)0;
LOC5 = HEX24_194185_1689653243(T839829468_658);
internalerror_194113_155036129(LOC5);
}
LA3: ;
}
N_NIMCALL(Tnode290802*, myprocess_561402_839829468)(Tpasscontext339002* b0, Tnode290802* n0) {
Tnode290802* result0;
Tcgen527027* m0;
{ result0 = (Tnode290802*)0;
result0 = n0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (b0 == NIM_NIL);
if (LOC3) goto LA4;
LOC3 = skipcodegen_339085_2355241294(n0);
LA4: ;
if (!LOC3) goto LA5;
goto BeforeRet;
}
LA5: ;
m0 = ((Tcgen527027*) (b0));
(*(*m0).initproc).options = initprocoptions_560635_839829468(m0);
genstmts_537244_839829468((*m0).initproc, n0);
}BeforeRet: ;
return result0;
}
N_NIMCALL(Ropeobj177006*, getsomeinitname_559904_839829468)(Tsym290834* m0, NimStringDesc* suffix0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
NimStringDesc* LOC5;
if (!((12288 & (*m0).flags) == 0)) goto LA3;
LOC5 = (NimStringDesc*)0;
LOC5 = mangle_526847_2036603609((*(*(*m0).owner).name).s);
result0 = rope_177277_2381377266(LOC5);
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_12));
}
LA3: ;
add_177487_2381377266(&result0, (*(*m0).name).s);
add_177487_2381377266(&result0, suffix0);
return result0;
}
N_NIMCALL(Ropeobj177006*, getinitname_560235_839829468)(Tsym290834* m0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = getsomeinitname_559904_839829468(m0, ((NimStringDesc*) &T839829468_659));
return result0;
}
N_NIMCALL(Ropeobj177006*, getdatinitname_560239_839829468)(Tsym290834* m0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = getsomeinitname_559904_839829468(m0, ((NimStringDesc*) &T839829468_660));
return result0;
}
N_NIMCALL(void, registermoduletomain_560243_839829468)(Tsym290834* m0) {
Ropeobj177006* init0;
Ropeobj177006* datinit0;
TY177507 LOC1;
TY177507 LOC2;
init0 = getinitname_560235_839829468(m0);
datinit0 = getdatinitname_560239_839829468(m0);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = init0;
addf_178205_2381377266(&mainmodprocs_527148_3723162438, ((NimStringDesc*) &T839829468_661), LOC1, 1);
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = datinit0;
addf_178205_2381377266(&mainmodprocs_527148_3723162438, ((NimStringDesc*) &T839829468_661), LOC2, 1);
{
TY177507 LOC7;
Ropeobj177006* initcall0;
TY177507 LOC8;
if (!!((((*m0).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0))) goto LA5;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = datinit0;
addf_178205_2381377266(&maindatinit_527151_3723162438, ((NimStringDesc*) &T839829468_662), LOC7, 1);
memset((void*)LOC8, 0, sizeof(LOC8));
LOC8[0] = init0;
initcall0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_662), LOC8, 1);
{
if (!(((*m0).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA11;
add_177482_2381377266(&mainmodinit_527149_3723162438, initcall0);
}
goto LA9;
LA11: ;
{
add_177482_2381377266(&othermodsinit_527150_3723162438, initcall0);
}
LA9: ;
}
LA5: ;
}
N_NIMCALL(Ropeobj177006*, genfilenames_559688_839829468)(Tcgen527027* m0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
result0 = (Ropeobj177006*)0;
LOC1 = (Ropeobj177006*)0;
LOC1 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_673));
result0 = NIM_NIL;
{
NI i_559717_839829468;
NI HEX3Atmp_559722_839829468;
NI res_559725_839829468;
i_559717_839829468 = (NI)0;
HEX3Atmp_559722_839829468 = (NI)0;
HEX3Atmp_559722_839829468 = ((fileinfos_189629_155036129 ? fileinfos_189629_155036129->Sup.len : 0) - 1);
res_559725_839829468 = ((NI) 0);
{
while (1) {
TY177507 LOC5;
if (!(res_559725_839829468 <= HEX3Atmp_559722_839829468)) goto LA4;
i_559717_839829468 = res_559725_839829468;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = makecstring_189638_155036129(fileinfos_189629_155036129->data[i_559717_839829468].projpath);
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_674), LOC5, 1);
res_559725_839829468 += ((NI) 1);
} LA4: ;
}
}
return result0;
}
N_NIMCALL(void, genmainproc_559729_839829468)(Tcgen527027* m0) {
NimStringDesc* nimmain0;
NimStringDesc* othermain0;
Ropeobj177006* initstackbottomcall0;
TY534475 LOC38;
TY533238 LOC47;
nimmain0 = (NimStringDesc*)0;
othermain0 = (NimStringDesc*)0;
{
NIM_BOOL LOC3;
NIM_BOOL LOC12;
LOC3 = (NIM_BOOL)0;
LOC3 = (targetos_175629_4151366050 == ((Tsystemos175004) 2));
if (!(LOC3)) goto LA4;
LOC3 = !(((gglobaloptions_168130_2607990831 & 1280) == 0));
LA4: ;
if (!LOC3) goto LA5;
{
if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 10))&63U)))!=0)) goto LA9;
nimmain0 = copyString(((NimStringDesc*) &T839829468_663));
othermain0 = copyString(((NimStringDesc*) &T839829468_664));
}
goto LA7;
LA9: ;
{
nimmain0 = copyString(((NimStringDesc*) &T839829468_665));
othermain0 = copyString(((NimStringDesc*) &T839829468_666));
}
LA7: ;
LOC12 = (NIM_BOOL)0;
LOC12 = includestr_147249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_667));
}
goto LA1;
LA5: ;
{
if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 8))&63U)))!=0)) goto LA14;
nimmain0 = copyString(((NimStringDesc*) &T839829468_665));
othermain0 = copyString(((NimStringDesc*) &T839829468_668));
}
goto LA1;
LA14: ;
{
if (!(targetos_175629_4151366050 == ((Tsystemos175004) 24))) goto LA17;
nimmain0 = copyString(((NimStringDesc*) &T839829468_669));
othermain0 = copyString(((NimStringDesc*) &T839829468_670));
}
goto LA1;
LA17: ;
{
nimmain0 = copyString(((NimStringDesc*) &T839829468_669));
othermain0 = copyString(((NimStringDesc*) &T839829468_671));
}
LA1: ;
{
Ropeobj177006* LOC24;
if (!!((gbreakpoints_546861_839829468 == NIM_NIL))) goto LA22;
LOC24 = (Ropeobj177006*)0;
LOC24 = cgsym_530403_839829468(m0, ((NimStringDesc*) &T839829468_672));
}
LA22: ;
{
Ropeobj177006* LOC29;
if (!((goptions_168128_2607990831 &(1U<<((NU)(((Toption168009) 17))&31U)))!=0)) goto LA27;
LOC29 = (Ropeobj177006*)0;
LOC29 = genfilenames_559688_839829468(m0);
add_177482_2381377266(&gbreakpoints_546861_839829468, LOC29);
}
LA27: ;
{
NIM_BOOL LOC32;
LOC32 = (NIM_BOOL)0;
LOC32 = (targetos_175629_4151366050 == ((Tsystemos175004) 24));
if (LOC32) goto LA33;
LOC32 = (gselectedgc_168133_2607990831 == ((Tgcmode168080) 0));
LA33: ;
if (!LOC32) goto LA34;
initstackbottomcall0 = rope_177277_2381377266(((NimStringDesc*) &T839829468_490));
}
goto LA30;
LA34: ;
{
TY531289 LOC37;
memset((void*)LOC37, 0, sizeof(LOC37));
initstackbottomcall0 = ropecg_530407_839829468(m0, ((NimStringDesc*) &T839829468_675), LOC37, 0);
}
LA30: ;
(*m0).labels += ((NI) 1);
memset((void*)LOC38, 0, sizeof(LOC38));
LOC38[0] = maindatinit_527151_3723162438;
LOC38[1] = gbreakpoints_546861_839829468;
LOC38[2] = othermodsinit_527150_3723162438;
{
NIM_BOOL LOC41;
TY531289 LOC45;
LOC41 = (NIM_BOOL)0;
LOC41 = emulatedthreadvars_530949_839829468();
if (!(LOC41)) goto LA42;
LOC41 = !((targetos_175629_4151366050 == ((Tsystemos175004) 24)));
LA42: ;
if (!LOC41) goto LA43;
memset((void*)LOC45, 0, sizeof(LOC45));
LOC38[3] = ropecg_530407_839829468(m0, ((NimStringDesc*) &T839829468_677), LOC45, 0);
}
goto LA39;
LA43: ;
{
LOC38[3] = rope_177277_2381377266(((NimStringDesc*) &T839829468_490));
}
LA39: ;
LOC38[4] = initstackbottomcall0;
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 10))- 0], ((NimStringDesc*) &T839829468_676), LOC38, 5);
memset((void*)LOC47, 0, sizeof(LOC47));
LOC47[0] = mainmodinit_527149_3723162438;
LOC47[1] = initstackbottomcall0;
LOC47[2] = rope_177401_2381377266(((NI64) ((*m0).labels)));
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 10))- 0], nimmain0, LOC47, 3);
{
TY531289 LOC52;
if (!!(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 20))&63U)))!=0))) goto LA50;
memset((void*)LOC52, 0, sizeof(LOC52));
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 10))- 0], othermain0, LOC52, 0);
}
LA50: ;
}
N_NIMCALL(Tnode290802*, myclose_561830_839829468)(Tpasscontext339002* b0, Tnode290802* n0) {
Tnode290802* result0;
Tcgen527027* m0;
{ result0 = (Tnode290802*)0;
result0 = n0;
{
NIM_BOOL LOC3;
LOC3 = (NIM_BOOL)0;
LOC3 = (b0 == NIM_NIL);
if (LOC3) goto LA4;
LOC3 = skipcodegen_339085_2355241294(n0);
LA4: ;
if (!LOC3) goto LA5;
goto BeforeRet;
}
LA5: ;
m0 = ((Tcgen527027*) (b0));
{
if (!!((n0 == NIM_NIL))) goto LA9;
(*(*m0).initproc).options = initprocoptions_560635_839829468(m0);
genstmts_537244_839829468((*m0).initproc, n0);
}
LA9: ;
registermoduletomain_560243_839829468((*m0).module);
{
Tnode290802* disp0;
if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA13;
(*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 5))%(sizeof(NU8)*8));
disp0 = generatemethoddispatchers_430151_3853300031();
{
NI i_561891_839829468;
NI HEX3Atmp_561895_839829468;
NI LOC16;
NI res_561898_839829468;
i_561891_839829468 = (NI)0;
HEX3Atmp_561895_839829468 = (NI)0;
LOC16 = (NI)0;
LOC16 = sonslen_293351_850551059(disp0);
HEX3Atmp_561895_839829468 = (NI)(LOC16 - ((NI) 1));
res_561898_839829468 = ((NI) 0);
{
while (1) {
if (!(res_561898_839829468 <= HEX3Atmp_561895_839829468)) goto LA18;
i_561891_839829468 = res_561898_839829468;
genprocaux_558284_839829468(m0, (*(*disp0).kindU.S6.sons->data[i_561891_839829468]).kindU.S4.sym);
res_561898_839829468 += ((NI) 1);
} LA18: ;
}
}
genmainproc_559729_839829468(m0);
}
LA13: ;
}BeforeRet: ;
return result0;
}
N_NIMCALL(void, finishmodule_561420_839829468)(Tcgen527027* m0) {
NI i0;
i0 = ((NI) 0);
{
while (1) {
Tsym290834* prc0;
if (!(i0 <= ((*m0).forwardedprocs ? ((*m0).forwardedprocs->Sup.len-1) : -1))) goto LA2;
prc0 = (*m0).forwardedprocs->data[i0];
{
NimStringDesc* LOC7;
if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag290184) 4))&31U)))!=0)) goto LA5;
LOC7 = (NimStringDesc*)0;
LOC7 = rawNewString((*(*prc0).name).s->Sup.len + 17);
appendString(LOC7, ((NimStringDesc*) &T839829468_678));
appendString(LOC7, (*(*prc0).name).s);
internalerror_194100_155036129((*prc0).info, LOC7);
}
LA5: ;
genprocnoforward_558906_839829468(m0, prc0);
i0 += ((NI) 1);
} LA2: ;
}
gforwardedprocscounter_527171_3723162438 -= i0;
(*m0).forwardedprocs = (Tsymseq290804*) setLengthSeq(&((*m0).forwardedprocs)->Sup, sizeof(Tsym290834*), ((NI) 0));
}
N_NIMCALL(void, geninitcode_560286_839829468)(Tcgen527027* m0) {
Ropeobj177006* initname0;
Ropeobj177006* prc0;
TY177507 LOC1;
Ropeobj177006* LOC12;
Ropeobj177006* LOC13;
Ropeobj177006** LOC14;
Ropeobj177006** LOC15;
Ropeobj177006** LOC16;
Ropeobj177006* LOC17;
Ropeobj177006* LOC33;
Ropeobj177006** LOC34;
Ropeobj177006** LOC35;
Ropeobj177006** LOC36;
Ropeobj177006* LOC37;
Ropeobj177006* LOC38;
Ropeobj177006** LOC39;
Ropeobj177006** LOC40;
Ropeobj177006** LOC41;
Ropeobj177006* LOC42;
Ropeobj177006* LOC50;
TY531289 LOC51;
TY177507 LOC52;
TY531289 LOC58;
initname0 = getinitname_560235_839829468((*m0).module);
memset((void*)LOC1, 0, sizeof(LOC1));
LOC1[0] = initname0;
prc0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_679), LOC1, 1);
{
TY530811 LOC6;
if (!(((NI) 0) < (*m0).typenodes)) goto LA4;
memset((void*)LOC6, 0, sizeof(LOC6));
LOC6[0] = (*m0).typenodesname;
LOC6[1] = rope_177401_2381377266(((NI64) ((*m0).typenodes)));
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_680), LOC6, 2);
}
LA4: ;
{
TY530811 LOC11;
if (!(((NI) 0) < (*m0).nimtypes)) goto LA9;
memset((void*)LOC11, 0, sizeof(LOC11));
LOC11[0] = (*m0).nimtypesname;
LOC11[1] = rope_177401_2381377266(((NI64) ((*m0).nimtypes)));
appcg_530632_839829468(m0, &(*m0).s[(((Tcfilesection527005) 12))- 0], ((NimStringDesc*) &T839829468_681), LOC11, 2);
}
LA9: ;
LOC12 = (Ropeobj177006*)0;
LOC12 = initgcframe_536435_839829468((*m0).initproc);
add_177482_2381377266(&prc0, LOC12);
LOC13 = (Ropeobj177006*)0;
LOC13 = gensectionstart_528081_2760143328(((Tcprocsection527011) 0));
add_177482_2381377266(&prc0, LOC13);
LOC14 = (Ropeobj177006**)0;
LOC14 = s_527179_3723162438((*m0).preinitproc, ((Tcprocsection527011) 0));
add_177482_2381377266(&prc0, (*LOC14));
LOC15 = (Ropeobj177006**)0;
LOC15 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 0));
add_177482_2381377266(&prc0, (*LOC15));
LOC16 = (Ropeobj177006**)0;
LOC16 = s_527179_3723162438((*m0).postinitproc, ((Tcprocsection527011) 0));
add_177482_2381377266(&prc0, (*LOC16));
LOC17 = (Ropeobj177006*)0;
LOC17 = gensectionend_528116_2760143328(((Tcprocsection527011) 0));
add_177482_2381377266(&prc0, LOC17);
{
NIM_BOOL LOC20;
LOC20 = (NIM_BOOL)0;
LOC20 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0);
if (!(LOC20)) goto LA21;
LOC20 = !((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 2))&7U)))!=0));
LA21: ;
if (!LOC20) goto LA22;
(*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 2))%(sizeof(NU8)*8));
{
Ropeobj177006* procname0;
Ropeobj177006* LOC28;
Ropeobj177006* LOC29;
if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 0))&7U)))!=0))) goto LA26;
procname0 = makecstring_189638_155036129((*(*(*m0).module).name).s);
LOC28 = (Ropeobj177006*)0;
LOC28 = quotedfilename_194818_155036129((*(*m0).module).info);
LOC29 = (Ropeobj177006*)0;
LOC29 = initframe_558140_839829468((*m0).initproc, procname0, LOC28);
add_177482_2381377266(&prc0, LOC29);
}
goto LA24;
LA26: ;
{
TY531289 LOC31;
Ropeobj177006* LOC32;
memset((void*)LOC31, 0, sizeof(LOC31));
LOC32 = (Ropeobj177006*)0;
LOC32 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_682), LOC31, 0);
add_177482_2381377266(&prc0, LOC32);
}
LA24: ;
}
LA22: ;
LOC33 = (Ropeobj177006*)0;
LOC33 = gensectionstart_528081_2760143328(((Tcprocsection527011) 1));
add_177482_2381377266(&prc0, LOC33);
LOC34 = (Ropeobj177006**)0;
LOC34 = s_527179_3723162438((*m0).preinitproc, ((Tcprocsection527011) 1));
add_177482_2381377266(&prc0, (*LOC34));
LOC35 = (Ropeobj177006**)0;
LOC35 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 1));
add_177482_2381377266(&prc0, (*LOC35));
LOC36 = (Ropeobj177006**)0;
LOC36 = s_527179_3723162438((*m0).postinitproc, ((Tcprocsection527011) 1));
add_177482_2381377266(&prc0, (*LOC36));
LOC37 = (Ropeobj177006*)0;
LOC37 = gensectionend_528116_2760143328(((Tcprocsection527011) 1));
add_177482_2381377266(&prc0, LOC37);
LOC38 = (Ropeobj177006*)0;
LOC38 = gensectionstart_528081_2760143328(((Tcprocsection527011) 2));
add_177482_2381377266(&prc0, LOC38);
LOC39 = (Ropeobj177006**)0;
LOC39 = s_527179_3723162438((*m0).preinitproc, ((Tcprocsection527011) 2));
add_177482_2381377266(&prc0, (*LOC39));
LOC40 = (Ropeobj177006**)0;
LOC40 = s_527179_3723162438((*m0).initproc, ((Tcprocsection527011) 2));
add_177482_2381377266(&prc0, (*LOC40));
LOC41 = (Ropeobj177006**)0;
LOC41 = s_527179_3723162438((*m0).postinitproc, ((Tcprocsection527011) 2));
add_177482_2381377266(&prc0, (*LOC41));
LOC42 = (Ropeobj177006*)0;
LOC42 = gensectionend_528116_2760143328(((Tcprocsection527011) 2));
add_177482_2381377266(&prc0, LOC42);
{
NIM_BOOL LOC45;
Ropeobj177006* LOC49;
LOC45 = (NIM_BOOL)0;
LOC45 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption168009) 15))&31U)))!=0);
if (!(LOC45)) goto LA46;
LOC45 = !((((*m0).flags &(1U<<((NU)(((Codegenflag527025) 0))&7U)))!=0));
LA46: ;
if (!LOC45) goto LA47;
LOC49 = (Ropeobj177006*)0;
LOC49 = deinitframe_558150_839829468((*m0).initproc);
add_177482_2381377266(&prc0, LOC49);
}
LA47: ;
LOC50 = (Ropeobj177006*)0;
LOC50 = deinitgcframe_536441_839829468((*m0).initproc);
add_177482_2381377266(&prc0, LOC50);
memset((void*)LOC51, 0, sizeof(LOC51));
addf_178205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC51, 0);
memset((void*)LOC52, 0, sizeof(LOC52));
LOC52[0] = getdatinitname_560239_839829468((*m0).module);
addf_178205_2381377266(&prc0, ((NimStringDesc*) &T839829468_679), LOC52, 1);
{
Tcfilesection527005 i_560401_839829468;
NI res_560482_839829468;
i_560401_839829468 = (Tcfilesection527005)0;
res_560482_839829468 = ((NI) 12);
{
while (1) {
Ropeobj177006* LOC56;
Ropeobj177006* LOC57;
if (!(res_560482_839829468 <= ((NI) 16))) goto LA55;
i_560401_839829468 = ((Tcfilesection527005) (res_560482_839829468));
LOC56 = (Ropeobj177006*)0;
LOC56 = gensectionstart_528015_2760143328(i_560401_839829468);
add_177482_2381377266(&prc0, LOC56);
add_177482_2381377266(&prc0, (*m0).s[(i_560401_839829468)- 0]);
LOC57 = (Ropeobj177006*)0;
LOC57 = gensectionend_528050_2760143328(i_560401_839829468);
add_177482_2381377266(&prc0, LOC57);
res_560482_839829468 += ((NI) 1);
} LA55: ;
}
}
memset((void*)LOC58, 0, sizeof(LOC58));
addf_178205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC58, 0);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 11))- 0], prc0);
{
NIM_CHAR i_560442_839829468;
Ropeobj177006* el_560443_839829468;
TY527136 HEX3Atmp_560487_839829468;
NIM_CHAR i_560490_839829468;
i_560442_839829468 = (NIM_CHAR)0;
el_560443_839829468 = (Ropeobj177006*)0;
memset((void*)HEX3Atmp_560487_839829468, 0, sizeof(HEX3Atmp_560487_839829468));
memcpy((void*)HEX3Atmp_560487_839829468, (NIM_CONST void*)(*m0).extensionloaders, sizeof(HEX3Atmp_560487_839829468));
i_560490_839829468 = 48;
{
if (!((NU8)(((NIM_CHAR) (((NU8)(i_560490_839829468))))) <= (NU8)(57))) goto LA62;
{
while (1) {
i_560442_839829468 = i_560490_839829468;
el_560443_839829468 = HEX3Atmp_560487_839829468[(((NU8)(i_560490_839829468)))- 48];
{
Ropeobj177006* ex0;
TY530811 LOC70;
if (!!((el_560443_839829468 == NIM_NIL))) goto LA68;
memset((void*)LOC70, 0, sizeof(LOC70));
LOC70[0] = rope_177401_2381377266(((NI64) ((NI)(((NI) (((NU8)(i_560442_839829468)))) - ((NI) 48)))));
LOC70[1] = el_560443_839829468;
ex0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_684), LOC70, 2);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 11))- 0], ex0);
}
LA68: ;
{
if (!((NU8)(57) <= (NU8)(((NIM_CHAR) (((NU8)(i_560490_839829468))))))) goto LA73;
goto LA64;
}
LA73: ;
i_560490_839829468 += ((NI) 1);
}
} LA64: ;
}
LA62: ;
}
}
N_NIMCALL(void, finishtypedescriptions_533842_839829468)(Tcgen527027* m0) {
NI i0;
i0 = ((NI) 0);
{
while (1) {
Ropeobj177006* LOC3;
if (!(i0 < ((*m0).typestack ? (*m0).typestack->Sup.len : 0))) goto LA2;
LOC3 = (Ropeobj177006*)0;
LOC3 = gettypedesc_533671_839829468(m0, (*m0).typestack->data[i0]);
i0 += ((NI) 1);
} LA2: ;
}
}
N_NIMCALL(Ropeobj177006*, getcopyright_559665_839829468)(NimStringDesc* cfile0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
{
TY177507 LOC5;
if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 4))&63U)))!=0)) goto LA3;
memset((void*)LOC5, 0, sizeof(LOC5));
LOC5[0] = rope_177277_2381377266(((NimStringDesc*) &T839829468_686));
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_685), LOC5, 1);
}
goto LA1;
LA3: ;
{
TY534475 LOC7;
NimStringDesc* LOC8;
memset((void*)LOC7, 0, sizeof(LOC7));
LOC7[0] = rope_177277_2381377266(((NimStringDesc*) &T839829468_686));
LOC7[1] = rope_177277_2381377266(Os_175068_4151366050[(targetos_175629_4151366050)- 1].Field0);
LOC7[2] = rope_177277_2381377266(Cpu_175496_4151366050[(targetcpu_175627_4151366050)- 1].Field0);
LOC7[3] = rope_177277_2381377266(Cc_271413_2528170400[(ccompiler_271431_2528170400)- 1].Field0);
LOC8 = (NimStringDesc*)0;
LOC8 = getcompilecfilecmd_272284_2528170400(cfile0, NIM_FALSE);
LOC7[4] = rope_177277_2381377266(LOC8);
result0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_687), LOC7, 5);
}
LA1: ;
return result0;
}
static N_INLINE(void, addinttypes_559659_839829468)(Ropeobj177006** result0) {
NimStringDesc* LOC1;
TY177507 LOC2;
LOC1 = (NimStringDesc*)0;
LOC1 = rawNewString(tnl_175644_4151366050->Sup.len + 22);
appendString(LOC1, ((NimStringDesc*) &T839829468_688));
appendString(LOC1, tnl_175644_4151366050);
memset((void*)LOC2, 0, sizeof(LOC2));
LOC2[0] = rope_177401_2381377266(((NI64) (Cpu_175496_4151366050[(targetcpu_175627_4151366050)- 1].Field1)));
addf_178205_2381377266(result0, LOC1, LOC2, 1);
}
N_NIMCALL(Ropeobj177006*, getfileheader_559683_839829468)(NimStringDesc* cfile0) {
Ropeobj177006* result0;
result0 = (Ropeobj177006*)0;
result0 = getcopyright_559665_839829468(cfile0);
addinttypes_559659_839829468(&result0);
return result0;
}
N_NIMCALL(void, generatethreadlocalstorage_536717_839829468)(Tcgen527027* m0) {
{
NIM_BOOL LOC3;
NIM_BOOL LOC5;
TY177507 LOC13;
LOC3 = (NIM_BOOL)0;
LOC3 = !((nimtv_536656_839829468 == NIM_NIL));
if (!(LOC3)) goto LA4;
LOC5 = (NIM_BOOL)0;
LOC5 = (((*m0).flags &(1U<<((NU)(((Codegenflag527025) 1))&7U)))!=0);
if (LOC5) goto LA6;
LOC5 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0);
LA6: ;
LOC3 = LOC5;
LA4: ;
if (!LOC3) goto LA7;
{
Ttype290840* t_536761_839829468;
NI i_536768_839829468;
NI L_536770_839829468;
t_536761_839829468 = (Ttype290840*)0;
i_536768_839829468 = ((NI) 0);
L_536770_839829468 = (nimtvdeps_536674_839829468 ? nimtvdeps_536674_839829468->Sup.len : 0);
{
while (1) {
Ropeobj177006* LOC12;
if (!(i_536768_839829468 < L_536770_839829468)) goto LA11;
t_536761_839829468 = nimtvdeps_536674_839829468->data[i_536768_839829468];
LOC12 = (Ropeobj177006*)0;
LOC12 = gettypedesc_533671_839829468(m0, t_536761_839829468);
i_536768_839829468 += ((NI) 1);
} LA11: ;
}
}
memset((void*)LOC13, 0, sizeof(LOC13));
LOC13[0] = nimtv_536656_839829468;
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 4))- 0], ((NimStringDesc*) &T839829468_689), LOC13, 1);
}
LA7: ;
}
N_NIMCALL(void, generateheaders_558104_839829468)(Tcgen527027* m0) {
NimStringDesc* LOC1;
Tstrentry147009* it0;
LOC1 = (NimStringDesc*)0;
LOC1 = rawNewString(tnl_175644_4151366050->Sup.len + tnl_175644_4151366050->Sup.len + 20);
appendString(LOC1, tnl_175644_4151366050);
appendString(LOC1, ((NimStringDesc*) &T839829468_690));
appendString(LOC1, tnl_175644_4151366050);
add_177487_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], LOC1);
it0 = ((Tstrentry147009*) ((*m0).headerfiles.head));
{
while (1) {
if (!!((it0 == NIM_NIL))) goto LA3;
{
NimStringDesc* LOC8;
NimStringDesc* LOC9;
Ropeobj177006* LOC10;
if (!((NU8)((*it0).data->data[((NI) 0)]) == (NU8)(35))) goto LA6;
LOC8 = (NimStringDesc*)0;
LOC9 = (NimStringDesc*)0;
LOC9 = nsuReplaceChar((*it0).data, 96, 34);
LOC8 = rawNewString(LOC9->Sup.len + tnl_175644_4151366050->Sup.len + 0);
appendString(LOC8, LOC9);
appendString(LOC8, tnl_175644_4151366050);
LOC10 = (Ropeobj177006*)0;
LOC10 = rope_177277_2381377266(LOC8);
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], LOC10);
}
goto LA4;
LA6: ;
{
TY177507 LOC14;
if (!!((((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(34)) || ((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(60))))) goto LA12;
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = rope_177277_2381377266((*it0).data);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], ((NimStringDesc*) &T839829468_691), LOC14, 1);
}
goto LA4;
LA12: ;
{
TY177507 LOC16;
memset((void*)LOC16, 0, sizeof(LOC16));
LOC16[0] = rope_177277_2381377266((*it0).data);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 1))- 0], ((NimStringDesc*) &T839829468_692), LOC16, 1);
}
LA4: ;
it0 = ((Tstrentry147009*) ((*it0).Sup.next));
} LA3: ;
}
}
N_NIMCALL(Ropeobj177006*, genmodule_560491_839829468)(Tcgen527027* m0, NimStringDesc* cfile0) {
Ropeobj177006* result0;
Ropeobj177006* LOC1;
result0 = (Ropeobj177006*)0;
result0 = getfileheader_559683_839829468(cfile0);
LOC1 = (Ropeobj177006*)0;
LOC1 = genmergeinfo_528203_2760143328(m0);
add_177482_2381377266(&result0, LOC1);
generatethreadlocalstorage_536717_839829468(m0);
generateheaders_558104_839829468(m0);
{
Tcfilesection527005 i_560614_839829468;
NI res_560622_839829468;
i_560614_839829468 = (Tcfilesection527005)0;
res_560622_839829468 = ((NI) 1);
{
while (1) {
Ropeobj177006* LOC5;
Ropeobj177006* LOC6;
if (!(res_560622_839829468 <= ((NI) 10))) goto LA4;
i_560614_839829468 = ((Tcfilesection527005) (res_560622_839829468));
LOC5 = (Ropeobj177006*)0;
LOC5 = gensectionstart_528015_2760143328(i_560614_839829468);
add_177482_2381377266(&result0, LOC5);
add_177482_2381377266(&result0, (*m0).s[(i_560614_839829468)- 0]);
LOC6 = (Ropeobj177006*)0;
LOC6 = gensectionend_528050_2760143328(i_560614_839829468);
add_177482_2381377266(&result0, LOC6);
res_560622_839829468 += ((NI) 1);
} LA4: ;
}
}
add_177482_2381377266(&result0, (*m0).s[(((Tcfilesection527005) 11))- 0]);
return result0;
}
N_NIMCALL(void, updatecachedmodule_561813_839829468)(Tcgen527027* m0) {
NimStringDesc* cfile0;
NimStringDesc* cfilenoext0;
cfile0 = getcfile_561204_839829468(m0);
cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490));
{
NIM_BOOL LOC3;
Ropeobj177006* code0;
LOC3 = (NIM_BOOL)0;
LOC3 = mergerequired_528832_2760143328(m0);
if (!(LOC3)) goto LA4;
LOC3 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0));
LA4: ;
if (!LOC3) goto LA5;
mergefiles_529241_2760143328(cfile0, m0);
geninitcode_560286_839829468(m0);
finishtypedescriptions_533842_839829468(m0);
code0 = genmodule_560491_839829468(m0, cfile0);
writerope_177836_2381377266(code0, cfile0, NIM_FALSE);
addfiletocompile_271863_2528170400(cfile0);
}
LA5: ;
addfiletolink_271872_2528170400(cfilenoext0);
}
N_NIMCALL(void, generatethreadvarssize_536771_839829468)(Tcgen527027* m0) {
{
NimStringDesc* externc0;
TY177507 LOC12;
if (!!((nimtv_536656_839829468 == NIM_NIL))) goto LA3;
{
NIM_BOOL LOC7;
LOC7 = (NIM_BOOL)0;
LOC7 = !((gcmd_168132_2607990831 == ((Tcommands168076) 2)));
if (!(LOC7)) goto LA8;
LOC7 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 27))&31U)))!=0);
LA8: ;
if (!LOC7) goto LA9;
externc0 = copyString(((NimStringDesc*) &T839829468_693));
}
goto LA5;
LA9: ;
{
externc0 = copyString(((NimStringDesc*) &T839829468_490));
}
LA5: ;
memset((void*)LOC12, 0, sizeof(LOC12));
LOC12[0] = rope_177277_2381377266(externc0);
addf_178205_2381377266(&(*m0).s[(((Tcfilesection527005) 10))- 0], ((NimStringDesc*) &T839829468_694), LOC12, 1);
}
LA3: ;
}
N_NIMCALL(NIM_BOOL, shouldrecompile_561621_839829468)(Ropeobj177006* code0, NimStringDesc* cfile0) {
NIM_BOOL result0;
{ result0 = (NIM_BOOL)0;
result0 = NIM_TRUE;
{
NimStringDesc* objfile0;
if (!!(((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 1))&63U)))!=0))) goto LA3;
objfile0 = toobjfile_271859_2528170400(cfile0);
{
NIM_BOOL LOC7;
LOC7 = (NIM_BOOL)0;
LOC7 = writeropeifnotequal_178511_2381377266(code0, cfile0);
if (!LOC7) goto LA8;
goto BeforeRet;
}
LA8: ;
{
NIM_BOOL LOC12;
LOC12 = (NIM_BOOL)0;
LOC12 = nosexistsFile(objfile0);
if (!(LOC12)) goto LA13;
LOC12 = nosfileNewer(objfile0, cfile0);
LA13: ;
if (!LOC12) goto LA14;
result0 = NIM_FALSE;
}
LA14: ;
}
goto LA1;
LA3: ;
{
writerope_177836_2381377266(code0, cfile0, NIM_FALSE);
}
LA1: ;
}BeforeRet: ;
return result0;
}
N_NIMCALL(void, writemodule_561637_839829468)(Tcgen527027* m0, NIM_BOOL pending0) {
NimStringDesc* cfile0;
NimStringDesc* cfilenoext0;
cfile0 = getcfile_561204_839829468(m0);
cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490));
{
NIM_BOOL LOC3;
Ropeobj177006* code0;
LOC3 = (NIM_BOOL)0;
LOC3 = !((*m0).Sup.fromcache);
if (LOC3) goto LA4;
LOC3 = ((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 1))&63U)))!=0);
LA4: ;
if (!LOC3) goto LA5;
geninitcode_560286_839829468(m0);
finishtypedescriptions_533842_839829468(m0);
{
if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0)) goto LA9;
add_177482_2381377266(&(*m0).s[(((Tcfilesection527005) 7))- 0], mainmodprocs_527148_3723162438);
generatethreadvarssize_536771_839829468(m0);
}
LA9: ;
code0 = genmodule_560491_839829468(m0, cfile0);
{
NIM_BOOL LOC13;
LOC13 = (NIM_BOOL)0;
LOC13 = shouldrecompile_561621_839829468(code0, cfile0);
if (!LOC13) goto LA14;
addfiletocompile_271863_2528170400(cfile0);
}
LA14: ;
}
goto LA1;
LA5: ;
{
NIM_BOOL LOC17;
NIM_BOOL LOC18;
Ropeobj177006* code0;
LOC17 = (NIM_BOOL)0;
LOC18 = (NIM_BOOL)0;
LOC18 = pending0;
if (!(LOC18)) goto LA19;
LOC18 = mergerequired_528832_2760143328(m0);
LA19: ;
LOC17 = LOC18;
if (!(LOC17)) goto LA20;
LOC17 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 12))&31U)))!=0));
LA20: ;
if (!LOC17) goto LA21;
mergefiles_529241_2760143328(cfile0, m0);
geninitcode_560286_839829468(m0);
finishtypedescriptions_533842_839829468(m0);
code0 = genmodule_560491_839829468(m0, cfile0);
writerope_177836_2381377266(code0, cfile0, NIM_FALSE);
addfiletocompile_271863_2528170400(cfile0);
}
goto LA1;
LA21: ;
{
NimStringDesc* LOC24;
NIM_BOOL LOC25;
LOC24 = (NimStringDesc*)0;
LOC24 = toobjfile_271859_2528170400(cfilenoext0);
LOC25 = (NIM_BOOL)0;
LOC25 = nosexistsFile(LOC24);
if (!!(LOC25)) goto LA26;
addfiletocompile_271863_2528170400(cfile0);
}
goto LA1;
LA26: ;
LA1: ;
addfiletolink_271872_2528170400(cfilenoext0);
}
N_NIMCALL(void, writeheader_561152_839829468)(Tcgen527027* m0) {
Ropeobj177006* result0;
Ropeobj177006* guard0;
TY177507 LOC1;
TY124315 LOC2;
TY177507 LOC3;
TY531289 LOC13;
TY177507 LOC14;
result0 = getcopyright_559665_839829468((*m0).filename);
memset((void*)LOC1, 0, sizeof(LOC1));
memset((void*)(&LOC2), 0, sizeof(LOC2));
nossplitFile((*m0).filename, (&LOC2));
LOC1[0] = rope_177277_2381377266(LOC2.Field1);
guard0 = HEX25_177905_2381377266(((NimStringDesc*) &T839829468_695), LOC1, 1);
memset((void*)LOC3, 0, sizeof(LOC3));
LOC3[0] = guard0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_696), LOC3, 1);
addinttypes_559659_839829468(&result0);
generateheaders_558104_839829468(m0);
generatethreadlocalstorage_536717_839829468(m0);
{
Tcfilesection527005 i_561174_839829468;
NI res_561200_839829468;
i_561174_839829468 = (Tcfilesection527005)0;
res_561200_839829468 = ((NI) 1);
{
while (1) {
Ropeobj177006* LOC7;
Ropeobj177006* LOC8;
if (!(res_561200_839829468 <= ((NI) 10))) goto LA6;
i_561174_839829468 = ((Tcfilesection527005) (res_561200_839829468));
LOC7 = (Ropeobj177006*)0;
LOC7 = gensectionstart_528015_2760143328(i_561174_839829468);
add_177482_2381377266(&result0, LOC7);
add_177482_2381377266(&result0, (*m0).s[(i_561174_839829468)- 0]);
LOC8 = (Ropeobj177006*)0;
LOC8 = gensectionend_528050_2760143328(i_561174_839829468);
add_177482_2381377266(&result0, LOC8);
res_561200_839829468 += ((NI) 1);
} LA6: ;
}
}
add_177482_2381377266(&result0, (*m0).s[(((Tcfilesection527005) 11))- 0]);
{
if (!((gglobaloptions_168130_2607990831 &((NU64)1<<((NU)(((Tglobaloption168013) 8))&63U)))!=0)) goto LA11;
add_177487_2381377266(&result0, ((NimStringDesc*) &T839829468_22));
}
LA11: ;
memset((void*)LOC13, 0, sizeof(LOC13));
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_697), LOC13, 0);
memset((void*)LOC14, 0, sizeof(LOC14));
LOC14[0] = guard0;
addf_178205_2381377266(&result0, ((NimStringDesc*) &T839829468_698), LOC14, 1);
writerope_177836_2381377266(result0, (*m0).filename, NIM_FALSE);
}
N_NIMCALL(void, cgenwritemodules_561902_839829468)(void) {
{
if (!!((generatedheader_530201_839829468 == NIM_NIL))) goto LA3;
finishmodule_561420_839829468(generatedheader_530201_839829468);
}
LA3: ;
{
while (1) {
if (!(((NI) 0) < gforwardedprocscounter_527171_3723162438)) goto LA6;
{
Tcgen527027* m_561916_839829468;
m_561916_839829468 = (Tcgen527027*)0;
{
NI i_561935_839829468;
NI HEX3Atmp_561937_839829468;
NI res_561939_839829468;
i_561935_839829468 = (NI)0;
HEX3Atmp_561937_839829468 = (NI)0;
HEX3Atmp_561937_839829468 = (gmodules_527170_3723162438 ? (gmodules_527170_3723162438->Sup.len-1) : -1);
res_561939_839829468 = ((NI) 0);
{
while (1) {
if (!(res_561939_839829468 <= HEX3Atmp_561937_839829468)) goto LA10;
i_561935_839829468 = res_561939_839829468;
{
if (!!((gmodules_527170_3723162438->data[i_561935_839829468] == NIM_NIL))) goto LA13;
m_561916_839829468 = gmodules_527170_3723162438->data[i_561935_839829468];
{
if (!!((*m_561916_839829468).Sup.fromcache)) goto LA17;
finishmodule_561420_839829468(m_561916_839829468);
}
LA17: ;
}
LA13: ;
res_561939_839829468 += ((NI) 1);
} LA10: ;
}
}
}
} LA6: ;
}
{
Tcgen527027* m_561917_839829468;
m_561917_839829468 = (Tcgen527027*)0;
{
NI i_561946_839829468;
NI HEX3Atmp_561948_839829468;
NI res_561950_839829468;
i_561946_839829468 = (NI)0;
HEX3Atmp_561948_839829468 = (NI)0;
HEX3Atmp_561948_839829468 = (gmodules_527170_3723162438 ? (gmodules_527170_3723162438->Sup.len-1) : -1);
res_561950_839829468 = ((NI) 0);
{
while (1) {
if (!(res_561950_839829468 <= HEX3Atmp_561948_839829468)) goto LA22;
i_561946_839829468 = res_561950_839829468;
{
if (!!((gmodules_527170_3723162438->data[i_561946_839829468] == NIM_NIL))) goto LA25;
m_561917_839829468 = gmodules_527170_3723162438->data[i_561946_839829468];
{
if (!(*m_561917_839829468).Sup.fromcache) goto LA29;
updatecachedmodule_561813_839829468(m_561917_839829468);
}
goto LA27;
LA29: ;
{
writemodule_561637_839829468(m_561917_839829468, NIM_TRUE);
}
LA27: ;
}
LA25: ;
res_561950_839829468 += ((NI) 1);
} LA22: ;
}
}
}
writemapping_272789_2528170400(gmapping_527152_3723162438);
{
if (!!((generatedheader_530201_839829468 == NIM_NIL))) goto LA34;
writeheader_561152_839829468(generatedheader_530201_839829468);
}
LA34: ;
}
N_NIMCALL(void, nullify_560833_839829468)(Ropeobj177006** arr0) {
{
Tcfilesection527005 i_560848_839829468;
NI res_560853_839829468;
i_560848_839829468 = (Tcfilesection527005)0;
res_560853_839829468 = ((NI) 0);
{
while (1) {
if (!(res_560853_839829468 <= ((NI) 17))) goto LA3;
i_560848_839829468 = ((Tcfilesection527005) (res_560853_839829468));
unsureAsgnRef((void**) (&arr0[(i_560848_839829468)- 0]), NIM_NIL);
res_560853_839829468 += ((NI) 1);
} LA3: ;
}
}
}
N_NIMCALL(void, nullify_560858_839829468)(Ropeobj177006** arr0) {
{
NIM_CHAR i_561014_839829468;
NI res_561019_839829468;
i_561014_839829468 = (NIM_CHAR)0;
res_561019_839829468 = ((NI) 48);
{
while (1) {
if (!(res_561019_839829468 <= ((NI) 57))) goto LA3;
i_561014_839829468 = ((NIM_CHAR) (res_561019_839829468));
unsureAsgnRef((void**) (&arr0[(((NU8)(i_561014_839829468)))- 48]), NIM_NIL);
res_561019_839829468 += ((NI) 1);
} LA3: ;
}
}
}
N_NIMCALL(void, resetmodule_560763_839829468)(Tcgen527027* m0) {
initlinkedlist_147031_3771138726((&(*m0).headerfiles));
initintset_266885_2627731572((&(*m0).declaredprotos));
initidtable_294019_850551059((&(*m0).forwtypecache));
asgnRef((void**) (&(*m0).initproc), newproc_527206_3723162438(NIM_NIL, m0));
(*(*m0).initproc).options = initprocoptions_560635_839829468(m0);
asgnRef((void**) (&(*m0).preinitproc), newpreinitproc_560625_839829468(m0));
asgnRef((void**) (&(*m0).postinitproc), newpostinitproc_560630_839829468(m0));
initnodetable_294085_850551059((&(*m0).datacache));
if ((*m0).typestack) nimGCunrefNoCycle((*m0).typestack);
(*m0).typestack = (Ttypeseq290836*) newSeqRC1((&NTI290836), 0);
if ((*m0).forwardedprocs) nimGCunrefNoCycle((*m0).forwardedprocs);
(*m0).forwardedprocs = (Tsymseq290804*) newSeqRC1((&NTI290804), 0);
asgnRefNoCycle((void**) (&(*m0).typenodesname), gettempname_531596_839829468(m0));
asgnRefNoCycle((void**) (&(*m0).nimtypesname), gettempname_531596_839829468(m0));
{
if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag290184) 13))&31U)))!=0)) goto LA3;
(*m0).flags |= ((NU8)1)<<((((Codegenflag527025) 0))%(sizeof(NU8)*8));
}
goto LA1;
LA3: ;
{
(*m0).flags &= ~(((NU8)1) << ((((Codegenflag527025) 0)) % (sizeof(NU8)*8)));
}
LA1: ;
nullify_560833_839829468((*m0).s);
(*m0).typenodes = ((NI) 0);
(*m0).nimtypes = ((NI) 0);
nullify_560858_839829468((*m0).extensionloaders);
(*m0).Sup.fromcache = NIM_TRUE;
}
N_NIMCALL(void, resetcgenmodules_561024_839829468)(void) {
{
Tcgen527027* m_561026_839829468;
m_561026_839829468 = (Tcgen527027*)0;
{
NI i_561031_839829468;
NI HEX3Atmp_561033_839829468;
NI res_561035_839829468;
i_561031_839829468 = (NI)0;
HEX3Atmp_561033_839829468 = (NI)0;
HEX3Atmp_561033_839829468 = (gmodules_527170_3723162438 ? (gmodules_527170_3723162438->Sup.len-1) : -1);
res_561035_839829468 = ((NI) 0);
{
while (1) {
if (!(res_561035_839829468 <= HEX3Atmp_561033_839829468)) goto LA4;
i_561031_839829468 = res_561035_839829468;
{
if (!!((gmodules_527170_3723162438->data[i_561031_839829468] == NIM_NIL))) goto LA7;
m_561026_839829468 = gmodules_527170_3723162438->data[i_561031_839829468];
resetmodule_560763_839829468(m_561026_839829468);
}
LA7: ;
res_561035_839829468 += ((NI) 1);
} LA4: ;
}
}
}
}
NIM_EXTERNC N_NOINLINE(void, compiler_cgenInit000)(void) {
nimRegisterGlobalMarker(T839829468_2);
nimRegisterGlobalMarker(T839829468_3);
nimRegisterGlobalMarker(T839829468_5);
nimRegisterGlobalMarker(T839829468_6);
nimRegisterGlobalMarker(T839829468_7);
nimRegisterGlobalMarker(T839829468_8);
asgnRefNoCycle((void**) (&indent_530655_839829468), rope_177277_2381377266(((NimStringDesc*) &T839829468_4)));
if (nimtvdeps_536674_839829468) nimGCunrefNoCycle(nimtvdeps_536674_839829468);
nimtvdeps_536674_839829468 = (Ttypeseq290836*) newSeqRC1((&NTI290836), 0);
chckNil((void*)(&nimtvdeclared_536675_839829468));
genericReset((void*)(&nimtvdeclared_536675_839829468), (&NTI266030));
initintset_266885_2627731572((&nimtvdeclared_536675_839829468));
breakpointid_546860_839829468 = ((NI) 0);
}
NIM_EXTERNC N_NOINLINE(void, compiler_cgenDatInit000)(void) {
}
|
CombinedOtherStartIndexNNeighboursWorklet.h
|
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
// Copyright (c) 2018, The Regents of the University of California, through
// Lawrence Berkeley National Laboratory (subject to receipt of any required approvals
// from the U.S. Dept. of Energy). 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.
//
// (3) Neither the name of the University of California, Lawrence Berkeley National
// Laboratory, U.S. Dept. of Energy 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.
//
//=============================================================================
//
// This code is an extension of the algorithm presented in the paper:
// Parallel Peak Pruning for Scalable SMP Contour Tree Computation.
// Hamish Carr, Gunther Weber, Christopher Sewell, and James Ahrens.
// Proceedings of the IEEE Symposium on Large Data Analysis and Visualization
// (LDAV), October 2016, Baltimore, Maryland.
//
// The PPP2 algorithm and software were jointly developed by
// Hamish Carr (University of Leeds), Gunther H. Weber (LBNL), and
// Oliver Ruebel (LBNL)
//==============================================================================
#ifndef vtkm_worklet_contourtree_augmented_contourtree_mesh_inc_combined_other_start_index_nneighbours_worklet_worklet_h
#define vtkm_worklet_contourtree_augmented_contourtree_mesh_inc_combined_other_start_index_nneighbours_worklet_worklet_h
#include <vtkm/worklet/WorkletMapField.h>
#include <vtkm/worklet/contourtree_augmented/Types.h>
namespace vtkm
{
namespace worklet
{
namespace contourtree_augmented
{
namespace mesh_dem_contourtree_mesh_inc
{
class CombinedOtherStartIndexNNeighboursWorklet : public vtkm::worklet::WorkletMapField
{
public:
typedef void ControlSignature(
FieldIn nNeighbours, // (input) nNeighbours
FieldIn otherToCombinedSortOrder, // (input) otherToCombinedSortOrder
WholeArrayInOut combinedNNeighbours, // (input/output) combinedNNeighbours
WholeArrayInOut combinedOtherStartIndex // (input/output) combinedOthertStartIndex
);
typedef void ExecutionSignature(_1, _2, _3, _4);
typedef _1 InputDomain;
// Default Constructor
VTKM_EXEC_CONT
CombinedOtherStartIndexNNeighboursWorklet() {}
template <typename InOutPortalType>
VTKM_EXEC void operator()(const vtkm::Id& nneighboursVal,
const vtkm::Id& otherToCombinedSortOrderVal,
const InOutPortalType combinedNNeighboursPortal,
const InOutPortalType combinedOtherStartIndexPortal) const
{
combinedOtherStartIndexPortal.Set(otherToCombinedSortOrderVal,
combinedNNeighboursPortal.Get(otherToCombinedSortOrderVal));
combinedNNeighboursPortal.Set(otherToCombinedSortOrderVal,
combinedNNeighboursPortal.Get(otherToCombinedSortOrderVal) +
nneighboursVal);
// Implements in reference code
// #pragma omp parallel for
// The following is save since each global index is only written by one entry
// for (indexVector::size_type vtx = 0; vtx < nNeighbours.size(); ++vtx)
// {
// combinedOtherStartIndex[otherToCombinedSortOrder[vtx]] = combinedNNeighbours[otherToCombinedSortOrder[vtx]];
// combinedNNeighbours[otherToCombinedSortOrder[vtx]] += nNeighbours[vtx];
// }
}
}; // CombinedOtherStartIndexNNeighboursWorklet
} // namespace mesh_dem_contourtree_mesh_inc
} // namespace contourtree_augmented
} // namespace worklet
} // namespace vtkm
#endif
|
SplineC2RAdoptor.h
|
//////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Jeremy McMinnis, [email protected], University of Illinois at Urbana-Champaign
// Jeongnim Kim, [email protected], University of Illinois at Urbana-Champaign
// Ye Luo, [email protected], Argonne National Laboratory
// Anouar Benali, [email protected], Argonne National Laboratory
// Mark A. Berrill, [email protected], Oak Ridge National Laboratory
//
// File created by: Jeongnim Kim, [email protected], University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////
/** @file
*
* Adoptor classes to handle complex-to-(real,complex) with arbitrary precision
*/
#ifndef QMCPLUSPLUS_EINSPLINE_C2R_ADOPTOR_H
#define QMCPLUSPLUS_EINSPLINE_C2R_ADOPTOR_H
#include <memory>
#include <OhmmsSoA/Container.h>
#include <spline2/MultiBspline.hpp>
#include <spline2/MultiBsplineEval.hpp>
#include "QMCWaveFunctions/BsplineFactory/SplineAdoptorBase.h"
#include "QMCWaveFunctions/BsplineFactory/contraction_helper.hpp"
#include "Utilities/FairDivide.h"
namespace qmcplusplus
{
/** adoptor class to match std::complex<ST> spline with TT real SPOs
* @tparam ST precision of spline
* @tparam TT precision of SPOs
* @tparam D dimension
*
* Requires temporage storage and multiplication of phase vectors
* Internal storage use double sized arrays of ST type, aligned and padded.
*/
template<typename ST, typename TT>
struct SplineC2RSoA : public SplineAdoptorBase<ST, 3>
{
static const int D = 3;
using Base = SplineAdoptorBase<ST, 3>;
using SplineType = typename bspline_traits<ST, 3>::SplineType;
using BCType = typename bspline_traits<ST, 3>::BCType;
using DataType = ST;
using PointType = typename Base::PointType;
using SingleSplineType = typename Base::SingleSplineType;
using vContainer_type = Vector<ST, aligned_allocator<ST>>;
using gContainer_type = VectorSoaContainer<ST, 3>;
using hContainer_type = VectorSoaContainer<ST, 6>;
using ghContainer_type = VectorSoaContainer<ST, 10>;
using Base::first_spo;
using Base::GGt;
using Base::kPoints;
using Base::last_spo;
using Base::MakeTwoCopies;
using Base::offset;
using Base::PrimLattice;
///number of complex bands
int nComplexBands;
///multi bspline set
std::shared_ptr<MultiBspline<ST>> SplineInst;
vContainer_type mKK;
VectorSoaContainer<ST, 3> myKcart;
vContainer_type myV;
vContainer_type myL;
gContainer_type myG;
hContainer_type myH;
ghContainer_type mygH;
///thread private ratios for reduction when using nested threading, numVP x numThread
Matrix<TT> ratios_private;
SplineC2RSoA() : Base(), nComplexBands(0)
{
this->is_complex = true;
this->is_soa_ready = true;
this->AdoptorName = "SplineC2RSoAAdoptor";
this->KeyWord = "SplineC2RSoA";
}
inline void resizeStorage(size_t n, size_t nvals)
{
Base::init_base(n);
size_t npad = getAlignedSize<ST>(2 * n);
myV.resize(npad);
myG.resize(npad);
myL.resize(npad);
myH.resize(npad);
mygH.resize(npad);
}
void bcast_tables(Communicate* comm) { chunked_bcast(comm, SplineInst->getSplinePtr()); }
void gather_tables(Communicate* comm)
{
if (comm->size() == 1)
return;
const int Nbands = kPoints.size();
const int Nbandgroups = comm->size();
offset.resize(Nbandgroups + 1, 0);
FairDivideLow(Nbands, Nbandgroups, offset);
for (size_t ib = 0; ib < offset.size(); ib++)
offset[ib] = offset[ib] * 2;
gatherv(comm, SplineInst->getSplinePtr(), SplineInst->getSplinePtr()->z_stride, offset);
}
template<typename GT, typename BCT>
void create_spline(GT& xyz_g, BCT& xyz_bc)
{
resize_kpoints();
SplineInst = std::make_shared<MultiBspline<ST>>();
SplineInst->create(xyz_g, xyz_bc, myV.size());
app_log() << "MEMORY " << SplineInst->sizeInByte() / (1 << 20) << " MB allocated "
<< "for the coefficients in 3D spline orbital representation" << std::endl;
}
inline void flush_zero() { SplineInst->flush_zero(); }
/** remap kPoints to pack the double copy */
inline void resize_kpoints()
{
#ifndef QMC_CUDA
// GPU CUDA code doesn't allow a change of the ordering
nComplexBands = this->remap_kpoints();
#endif
int nk = kPoints.size();
mKK.resize(nk);
myKcart.resize(nk);
for (size_t i = 0; i < nk; ++i)
{
mKK[i] = -dot(kPoints[i], kPoints[i]);
myKcart(i) = kPoints[i];
}
}
inline void set_spline(SingleSplineType* spline_r, SingleSplineType* spline_i, int twist, int ispline, int level)
{
SplineInst->copy_spline(spline_r, 2 * ispline);
SplineInst->copy_spline(spline_i, 2 * ispline + 1);
}
bool read_splines(hdf_archive& h5f)
{
std::ostringstream o;
o << "spline_" << SplineAdoptorBase<ST, D>::MyIndex;
einspline_engine<SplineType> bigtable(SplineInst->getSplinePtr());
return h5f.readEntry(bigtable, o.str().c_str()); //"spline_0");
}
bool write_splines(hdf_archive& h5f)
{
std::ostringstream o;
o << "spline_" << SplineAdoptorBase<ST, D>::MyIndex;
einspline_engine<SplineType> bigtable(SplineInst->getSplinePtr());
return h5f.writeEntry(bigtable, o.str().c_str()); //"spline_0");
}
template<typename VV>
inline void assign_v(const PointType& r, const vContainer_type& myV, VV& psi, int first, int last) const
{
// protect last
last = last > kPoints.size() ? kPoints.size() : last;
const ST x = r[0], y = r[1], z = r[2];
const ST* restrict kx = myKcart.data(0);
const ST* restrict ky = myKcart.data(1);
const ST* restrict kz = myKcart.data(2);
TT* restrict psi_s = psi.data() + first_spo;
#pragma omp simd
for (size_t j = first; j < std::min(nComplexBands, last); j++)
{
ST s, c;
const size_t jr = j << 1;
const size_t ji = jr + 1;
const ST val_r = myV[jr];
const ST val_i = myV[ji];
sincos(-(x * kx[j] + y * ky[j] + z * kz[j]), &s, &c);
psi_s[jr] = val_r * c - val_i * s;
psi_s[ji] = val_i * c + val_r * s;
}
psi_s += nComplexBands;
#pragma omp simd
for (size_t j = std::max(nComplexBands, first); j < last; j++)
{
ST s, c;
const ST val_r = myV[2 * j];
const ST val_i = myV[2 * j + 1];
sincos(-(x * kx[j] + y * ky[j] + z * kz[j]), &s, &c);
psi_s[j] = val_r * c - val_i * s;
}
}
template<typename VV>
inline void evaluate_v(const ParticleSet& P, const int iat, VV& psi)
{
const PointType& r = P.activeR(iat);
PointType ru(PrimLattice.toUnit_floor(r));
#pragma omp parallel
{
int first, last;
FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last);
spline2::evaluate3d(SplineInst->getSplinePtr(), ru, myV, first, last);
assign_v(r, myV, psi, first / 2, last / 2);
}
}
template<typename VV, typename RT>
inline void evaluateDetRatios(const VirtualParticleSet& VP, VV& psi, const VV& psiinv, std::vector<RT>& ratios)
{
const bool need_resize = ratios_private.rows() < VP.getTotalNum();
#pragma omp parallel
{
int tid = omp_get_thread_num();
// initialize thread private ratios
if (need_resize)
{
if (tid == 0) // just like #pragma omp master, but one fewer call to the runtime
ratios_private.resize(VP.getTotalNum(), omp_get_num_threads());
#pragma omp barrier
}
int first, last;
FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), tid, first, last);
const int first_cplx = first / 2;
const int last_cplx = kPoints.size() < last / 2 ? kPoints.size() : last / 2;
for (int iat = 0; iat < VP.getTotalNum(); ++iat)
{
const PointType& r = VP.activeR(iat);
PointType ru(PrimLattice.toUnit_floor(r));
spline2::evaluate3d(SplineInst->getSplinePtr(), ru, myV, first, last);
assign_v(r, myV, psi, first_cplx, last_cplx);
const int first_real = first_cplx + std::min(nComplexBands, first_cplx);
const int last_real = last_cplx + std::min(nComplexBands, last_cplx);
ratios_private[iat][tid] =
simd::dot(psi.data() + first_real, psiinv.data() + first_real, last_real - first_real);
}
}
// do the reduction manually
for (int iat = 0; iat < VP.getTotalNum(); ++iat)
{
ratios[iat] = TT(0);
for (int tid = 0; tid < ratios_private.cols(); tid++)
ratios[iat] += ratios_private[iat][tid];
}
}
/** assign_vgl
*/
template<typename VV, typename GV>
inline void assign_vgl(const PointType& r, VV& psi, GV& dpsi, VV& d2psi, int first, int last) const
{
// protect last
last = last > kPoints.size() ? kPoints.size() : last;
constexpr ST two(2);
const ST g00 = PrimLattice.G(0), g01 = PrimLattice.G(1), g02 = PrimLattice.G(2), g10 = PrimLattice.G(3),
g11 = PrimLattice.G(4), g12 = PrimLattice.G(5), g20 = PrimLattice.G(6), g21 = PrimLattice.G(7),
g22 = PrimLattice.G(8);
const ST x = r[0], y = r[1], z = r[2];
const ST symGG[6] = {GGt[0], GGt[1] + GGt[3], GGt[2] + GGt[6], GGt[4], GGt[5] + GGt[7], GGt[8]};
const ST* restrict k0 = myKcart.data(0);
ASSUME_ALIGNED(k0);
const ST* restrict k1 = myKcart.data(1);
ASSUME_ALIGNED(k1);
const ST* restrict k2 = myKcart.data(2);
ASSUME_ALIGNED(k2);
const ST* restrict g0 = myG.data(0);
ASSUME_ALIGNED(g0);
const ST* restrict g1 = myG.data(1);
ASSUME_ALIGNED(g1);
const ST* restrict g2 = myG.data(2);
ASSUME_ALIGNED(g2);
const ST* restrict h00 = myH.data(0);
ASSUME_ALIGNED(h00);
const ST* restrict h01 = myH.data(1);
ASSUME_ALIGNED(h01);
const ST* restrict h02 = myH.data(2);
ASSUME_ALIGNED(h02);
const ST* restrict h11 = myH.data(3);
ASSUME_ALIGNED(h11);
const ST* restrict h12 = myH.data(4);
ASSUME_ALIGNED(h12);
const ST* restrict h22 = myH.data(5);
ASSUME_ALIGNED(h22);
#pragma omp simd
for (size_t j = first; j < std::min(nComplexBands, last); j++)
{
const size_t jr = j << 1;
const size_t ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr];
const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr];
const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr];
const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji];
const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji];
const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const ST lcart_r = SymTrace(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], symGG);
const ST lcart_i = SymTrace(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], symGG);
const ST lap_r = lcart_r + mKK[j] * val_r + two * (kX * dX_i + kY * dY_i + kZ * dZ_i);
const ST lap_i = lcart_i + mKK[j] * val_i - two * (kX * dX_r + kY * dY_r + kZ * dZ_r);
const size_t psiIndex = first_spo + jr;
//this will be fixed later
psi[psiIndex] = c * val_r - s * val_i;
psi[psiIndex + 1] = c * val_i + s * val_r;
d2psi[psiIndex] = c * lap_r - s * lap_i;
d2psi[psiIndex + 1] = c * lap_i + s * lap_r;
//this will go way with Determinant
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
dpsi[psiIndex + 1][0] = c * gX_i + s * gX_r;
dpsi[psiIndex + 1][1] = c * gY_i + s * gY_r;
dpsi[psiIndex + 1][2] = c * gZ_i + s * gZ_r;
}
#pragma omp simd
for (size_t j = std::max(nComplexBands, first); j < last; j++)
{
const size_t jr = j << 1;
const size_t ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr];
const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr];
const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr];
const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji];
const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji];
const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const size_t psiIndex = first_spo + nComplexBands + j;
psi[psiIndex] = c * val_r - s * val_i;
//this will be fixed later
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
const ST lcart_r = SymTrace(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], symGG);
const ST lcart_i = SymTrace(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], symGG);
const ST lap_r = lcart_r + mKK[j] * val_r + two * (kX * dX_i + kY * dY_i + kZ * dZ_i);
const ST lap_i = lcart_i + mKK[j] * val_i - two * (kX * dX_r + kY * dY_r + kZ * dZ_r);
d2psi[psiIndex] = c * lap_r - s * lap_i;
}
}
/** assign_vgl_from_l can be used when myL is precomputed and myV,myG,myL in cartesian
*/
template<typename VV, typename GV>
inline void assign_vgl_from_l(const PointType& r, VV& psi, GV& dpsi, VV& d2psi)
{
constexpr ST two(2);
const ST x = r[0], y = r[1], z = r[2];
const ST* restrict k0 = myKcart.data(0);
ASSUME_ALIGNED(k0);
const ST* restrict k1 = myKcart.data(1);
ASSUME_ALIGNED(k1);
const ST* restrict k2 = myKcart.data(2);
ASSUME_ALIGNED(k2);
const ST* restrict g0 = myG.data(0);
ASSUME_ALIGNED(g0);
const ST* restrict g1 = myG.data(1);
ASSUME_ALIGNED(g1);
const ST* restrict g2 = myG.data(2);
ASSUME_ALIGNED(g2);
const size_t N = kPoints.size();
#pragma omp simd
for (size_t j = 0; j < nComplexBands; j++)
{
const size_t jr = j << 1;
const size_t ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g0[jr];
const ST dY_r = g1[jr];
const ST dZ_r = g2[jr];
const ST dX_i = g0[ji];
const ST dY_i = g1[ji];
const ST dZ_i = g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const ST lap_r = myL[jr] + mKK[j] * val_r + two * (kX * dX_i + kY * dY_i + kZ * dZ_i);
const ST lap_i = myL[ji] + mKK[j] * val_i - two * (kX * dX_r + kY * dY_r + kZ * dZ_r);
//this will be fixed later
const size_t psiIndex = first_spo + jr;
psi[psiIndex] = c * val_r - s * val_i;
psi[psiIndex + 1] = c * val_i + s * val_r;
d2psi[psiIndex] = c * lap_r - s * lap_i;
d2psi[psiIndex + 1] = c * lap_i + s * lap_r;
//this will go way with Determinant
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
dpsi[psiIndex + 1][0] = c * gX_i + s * gX_r;
dpsi[psiIndex + 1][1] = c * gY_i + s * gY_r;
dpsi[psiIndex + 1][2] = c * gZ_i + s * gZ_r;
}
#pragma omp simd
for (size_t j = nComplexBands; j < N; j++)
{
const size_t jr = j << 1;
const size_t ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g0[jr];
const ST dY_r = g1[jr];
const ST dZ_r = g2[jr];
const ST dX_i = g0[ji];
const ST dY_i = g1[ji];
const ST dZ_i = g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const size_t psiIndex = first_spo + nComplexBands + j;
psi[psiIndex] = c * val_r - s * val_i;
//this will be fixed later
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
const ST lap_r = myL[jr] + mKK[j] * val_r + two * (kX * dX_i + kY * dY_i + kZ * dZ_i);
const ST lap_i = myL[ji] + mKK[j] * val_i - two * (kX * dX_r + kY * dY_r + kZ * dZ_r);
d2psi[psiIndex] = c * lap_r - s * lap_i;
}
}
template<typename VV, typename GV>
inline void evaluate_vgl(const ParticleSet& P, const int iat, VV& psi, GV& dpsi, VV& d2psi)
{
const PointType& r = P.activeR(iat);
PointType ru(PrimLattice.toUnit_floor(r));
#pragma omp parallel
{
int first, last;
FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last);
spline2::evaluate3d_vgh(SplineInst->getSplinePtr(), ru, myV, myG, myH, first, last);
assign_vgl(r, psi, dpsi, d2psi, first / 2, last / 2);
}
}
template<typename VV, typename GV>
inline void mw_evaluate_vgl(const std::vector<SplineC2RSoA*>& sa_list,
const std::vector<ParticleSet*>& P_list,
int iat,
const std::vector<VV*>& psi_v_list,
const std::vector<GV*>& dpsi_v_list,
const std::vector<VV*>& d2psi_v_list)
{
#pragma omp parallel for
for (int iw = 0; iw < sa_list.size(); iw++)
sa_list[iw]->evaluate_vgl(*P_list[iw], iat, *psi_v_list[iw], *dpsi_v_list[iw], *d2psi_v_list[iw]);
}
template<typename VV, typename GV, typename GGV>
void assign_vgh(const PointType& r, VV& psi, GV& dpsi, GGV& grad_grad_psi, int first, int last) const
{
// protect last
last = last > kPoints.size() ? kPoints.size() : last;
const ST g00 = PrimLattice.G(0), g01 = PrimLattice.G(1), g02 = PrimLattice.G(2), g10 = PrimLattice.G(3),
g11 = PrimLattice.G(4), g12 = PrimLattice.G(5), g20 = PrimLattice.G(6), g21 = PrimLattice.G(7),
g22 = PrimLattice.G(8);
const ST x = r[0], y = r[1], z = r[2];
const ST* restrict k0 = myKcart.data(0);
const ST* restrict k1 = myKcart.data(1);
const ST* restrict k2 = myKcart.data(2);
const ST* restrict g0 = myG.data(0);
const ST* restrict g1 = myG.data(1);
const ST* restrict g2 = myG.data(2);
const ST* restrict h00 = myH.data(0);
const ST* restrict h01 = myH.data(1);
const ST* restrict h02 = myH.data(2);
const ST* restrict h11 = myH.data(3);
const ST* restrict h12 = myH.data(4);
const ST* restrict h22 = myH.data(5);
#pragma omp simd
for (size_t j = first; j < std::min(nComplexBands, last); j++)
{
int jr = j << 1;
int ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr];
const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr];
const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr];
const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji];
const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji];
const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const size_t psiIndex = first_spo + jr;
psi[psiIndex] = c * val_r - s * val_i;
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
psi[psiIndex + 1] = c * val_i + s * val_r;
dpsi[psiIndex + 1][0] = c * gX_i + s * gX_r;
dpsi[psiIndex + 1][1] = c * gY_i + s * gY_r;
dpsi[psiIndex + 1][2] = c * gZ_i + s * gZ_r;
const ST h_xx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g00, g01, g02) +
kX * (gX_i + dX_i);
const ST h_xy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g10, g11, g12) +
kX * (gY_i + dY_i);
const ST h_xz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g20, g21, g22) +
kX * (gZ_i + dZ_i);
const ST h_yx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g00, g01, g02) +
kY * (gX_i + dX_i);
const ST h_yy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g10, g11, g12) +
kY * (gY_i + dY_i);
const ST h_yz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g20, g21, g22) +
kY * (gZ_i + dZ_i);
const ST h_zx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g00, g01, g02) +
kZ * (gX_i + dX_i);
const ST h_zy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g10, g11, g12) +
kZ * (gY_i + dY_i);
const ST h_zz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g20, g21, g22) +
kZ * (gZ_i + dZ_i);
const ST h_xx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g00, g01, g02) -
kX * (gX_r + dX_r);
const ST h_xy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g10, g11, g12) -
kX * (gY_r + dY_r);
const ST h_xz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g20, g21, g22) -
kX * (gZ_r + dZ_r);
const ST h_yx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g00, g01, g02) -
kY * (gX_r + dX_r);
const ST h_yy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g10, g11, g12) -
kY * (gY_r + dY_r);
const ST h_yz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g20, g21, g22) -
kY * (gZ_r + dZ_r);
const ST h_zx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g00, g01, g02) -
kZ * (gX_r + dX_r);
const ST h_zy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g10, g11, g12) -
kZ * (gY_r + dY_r);
const ST h_zz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g20, g21, g22) -
kZ * (gZ_r + dZ_r);
grad_grad_psi[psiIndex][0] = c * h_xx_r - s * h_xx_i;
grad_grad_psi[psiIndex][1] = c * h_xy_r - s * h_xy_i;
grad_grad_psi[psiIndex][2] = c * h_xz_r - s * h_xz_i;
grad_grad_psi[psiIndex][3] = c * h_yx_r - s * h_yx_i;
grad_grad_psi[psiIndex][4] = c * h_yy_r - s * h_yy_i;
grad_grad_psi[psiIndex][5] = c * h_yz_r - s * h_yz_i;
grad_grad_psi[psiIndex][6] = c * h_zx_r - s * h_zx_i;
grad_grad_psi[psiIndex][7] = c * h_zy_r - s * h_zy_i;
grad_grad_psi[psiIndex][8] = c * h_zz_r - s * h_zz_i;
grad_grad_psi[psiIndex + 1][0] = c * h_xx_i + s * h_xx_r;
grad_grad_psi[psiIndex + 1][1] = c * h_xy_i + s * h_xy_r;
grad_grad_psi[psiIndex + 1][2] = c * h_xz_i + s * h_xz_r;
grad_grad_psi[psiIndex + 1][3] = c * h_yx_i + s * h_yx_r;
grad_grad_psi[psiIndex + 1][4] = c * h_yy_i + s * h_yy_r;
grad_grad_psi[psiIndex + 1][5] = c * h_yz_i + s * h_yz_r;
grad_grad_psi[psiIndex + 1][6] = c * h_zx_i + s * h_zx_r;
grad_grad_psi[psiIndex + 1][7] = c * h_zy_i + s * h_zy_r;
grad_grad_psi[psiIndex + 1][8] = c * h_zz_i + s * h_zz_r;
}
#pragma omp simd
for (size_t j = std::max(nComplexBands, first); j < last; j++)
{
int jr = j << 1;
int ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr];
const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr];
const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr];
const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji];
const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji];
const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const size_t psiIndex = first_spo + nComplexBands + j;
psi[psiIndex] = c * val_r - s * val_i;
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
const ST h_xx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g00, g01, g02) +
kX * (gX_i + dX_i);
const ST h_xy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g10, g11, g12) +
kX * (gY_i + dY_i);
const ST h_xz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g20, g21, g22) +
kX * (gZ_i + dZ_i);
const ST h_yx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g00, g01, g02) +
kY * (gX_i + dX_i);
const ST h_yy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g10, g11, g12) +
kY * (gY_i + dY_i);
const ST h_yz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g20, g21, g22) +
kY * (gZ_i + dZ_i);
const ST h_zx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g00, g01, g02) +
kZ * (gX_i + dX_i);
const ST h_zy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g10, g11, g12) +
kZ * (gY_i + dY_i);
const ST h_zz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g20, g21, g22) +
kZ * (gZ_i + dZ_i);
const ST h_xx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g00, g01, g02) -
kX * (gX_r + dX_r);
const ST h_xy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g10, g11, g12) -
kX * (gY_r + dY_r);
const ST h_xz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g20, g21, g22) -
kX * (gZ_r + dZ_r);
const ST h_yx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g00, g01, g02) -
kY * (gX_r + dX_r);
const ST h_yy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g10, g11, g12) -
kY * (gY_r + dY_r);
const ST h_yz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g20, g21, g22) -
kY * (gZ_r + dZ_r);
const ST h_zx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g00, g01, g02) -
kZ * (gX_r + dX_r);
const ST h_zy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g10, g11, g12) -
kZ * (gY_r + dY_r);
const ST h_zz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g20, g21, g22) -
kZ * (gZ_r + dZ_r);
grad_grad_psi[psiIndex][0] = c * h_xx_r - s * h_xx_i;
grad_grad_psi[psiIndex][1] = c * h_xy_r - s * h_xy_i;
grad_grad_psi[psiIndex][2] = c * h_xz_r - s * h_xz_i;
grad_grad_psi[psiIndex][3] = c * h_yx_r - s * h_yx_i;
grad_grad_psi[psiIndex][4] = c * h_yy_r - s * h_yy_i;
grad_grad_psi[psiIndex][5] = c * h_yz_r - s * h_yz_i;
grad_grad_psi[psiIndex][6] = c * h_zx_r - s * h_zx_i;
grad_grad_psi[psiIndex][7] = c * h_zy_r - s * h_zy_i;
grad_grad_psi[psiIndex][8] = c * h_zz_r - s * h_zz_i;
}
}
template<typename VV, typename GV, typename GGV>
void evaluate_vgh(const ParticleSet& P, const int iat, VV& psi, GV& dpsi, GGV& grad_grad_psi)
{
const PointType& r = P.activeR(iat);
PointType ru(PrimLattice.toUnit_floor(r));
#pragma omp parallel
{
int first, last;
FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last);
spline2::evaluate3d_vgh(SplineInst->getSplinePtr(), ru, myV, myG, myH, first, last);
assign_vgh(r, psi, dpsi, grad_grad_psi, first / 2, last / 2);
}
}
template<typename VV, typename GV, typename GGV, typename GGGV>
void assign_vghgh(const PointType& r,
VV& psi,
GV& dpsi,
GGV& grad_grad_psi,
GGGV& grad_grad_grad_psi,
int first = 0,
int last = -1) const
{
// protect last
last = last < 0 ? kPoints.size() : (last > kPoints.size() ? kPoints.size() : last);
const ST g00 = PrimLattice.G(0), g01 = PrimLattice.G(1), g02 = PrimLattice.G(2), g10 = PrimLattice.G(3),
g11 = PrimLattice.G(4), g12 = PrimLattice.G(5), g20 = PrimLattice.G(6), g21 = PrimLattice.G(7),
g22 = PrimLattice.G(8);
const ST x = r[0], y = r[1], z = r[2];
const ST* restrict k0 = myKcart.data(0);
const ST* restrict k1 = myKcart.data(1);
const ST* restrict k2 = myKcart.data(2);
const ST* restrict g0 = myG.data(0);
const ST* restrict g1 = myG.data(1);
const ST* restrict g2 = myG.data(2);
const ST* restrict h00 = myH.data(0);
const ST* restrict h01 = myH.data(1);
const ST* restrict h02 = myH.data(2);
const ST* restrict h11 = myH.data(3);
const ST* restrict h12 = myH.data(4);
const ST* restrict h22 = myH.data(5);
const ST* restrict gh000 = mygH.data(0);
const ST* restrict gh001 = mygH.data(1);
const ST* restrict gh002 = mygH.data(2);
const ST* restrict gh011 = mygH.data(3);
const ST* restrict gh012 = mygH.data(4);
const ST* restrict gh022 = mygH.data(5);
const ST* restrict gh111 = mygH.data(6);
const ST* restrict gh112 = mygH.data(7);
const ST* restrict gh122 = mygH.data(8);
const ST* restrict gh222 = mygH.data(9);
//SIMD doesn't work quite right yet. Comment out until further debugging.
#pragma omp simd
for (size_t j = first; j < std::min(nComplexBands, last); j++)
{
int jr = j << 1;
int ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr];
const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr];
const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr];
const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji];
const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji];
const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const size_t psiIndex = first_spo + jr;
psi[psiIndex] = c * val_r - s * val_i;
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
psi[psiIndex + 1] = c * val_i + s * val_r;
dpsi[psiIndex + 1][0] = c * gX_i + s * gX_r;
dpsi[psiIndex + 1][1] = c * gY_i + s * gY_r;
dpsi[psiIndex + 1][2] = c * gZ_i + s * gZ_r;
//intermediates for computation of hessian. \partial_i \partial_j phi in cartesian coordinates.
const ST f_xx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g00, g01, g02);
const ST f_xy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g10, g11, g12);
const ST f_xz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g20, g21, g22);
const ST f_yy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g10, g11, g12);
const ST f_yz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g20, g21, g22);
const ST f_zz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g20, g21, g22);
const ST f_xx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g00, g01, g02);
const ST f_xy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g10, g11, g12);
const ST f_xz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g20, g21, g22);
const ST f_yy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g10, g11, g12);
const ST f_yz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g20, g21, g22);
const ST f_zz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g20, g21, g22);
const ST h_xx_r = f_xx_r + 2 * kX * dX_i - kX * kX * val_r;
const ST h_xy_r = f_xy_r + (kX * dY_i + kY * dX_i) - kX * kY * val_r;
const ST h_xz_r = f_xz_r + (kX * dZ_i + kZ * dX_i) - kX * kZ * val_r;
const ST h_yy_r = f_yy_r + 2 * kY * dY_i - kY * kY * val_r;
const ST h_yz_r = f_yz_r + (kY * dZ_i + kZ * dY_i) - kY * kZ * val_r;
const ST h_zz_r = f_zz_r + 2 * kZ * dZ_i - kZ * kZ * val_r;
const ST h_xx_i = f_xx_i - 2 * kX * dX_r - kX * kX * val_i;
const ST h_xy_i = f_xy_i - (kX * dY_r + kY * dX_r) - kX * kY * val_i;
const ST h_xz_i = f_xz_i - (kX * dZ_r + kZ * dX_r) - kX * kZ * val_i;
const ST h_yy_i = f_yy_i - 2 * kY * dY_r - kY * kY * val_i;
const ST h_yz_i = f_yz_i - (kZ * dY_r + kY * dZ_r) - kZ * kY * val_i;
const ST h_zz_i = f_zz_i - 2 * kZ * dZ_r - kZ * kZ * val_i;
grad_grad_psi[psiIndex][0] = c * h_xx_r - s * h_xx_i;
grad_grad_psi[psiIndex][1] = c * h_xy_r - s * h_xy_i;
grad_grad_psi[psiIndex][2] = c * h_xz_r - s * h_xz_i;
grad_grad_psi[psiIndex][3] = c * h_xy_r - s * h_xy_i;
grad_grad_psi[psiIndex][4] = c * h_yy_r - s * h_yy_i;
grad_grad_psi[psiIndex][5] = c * h_yz_r - s * h_yz_i;
grad_grad_psi[psiIndex][6] = c * h_xz_r - s * h_xz_i;
grad_grad_psi[psiIndex][7] = c * h_yz_r - s * h_yz_i;
grad_grad_psi[psiIndex][8] = c * h_zz_r - s * h_zz_i;
grad_grad_psi[psiIndex + 1][0] = c * h_xx_i + s * h_xx_r;
grad_grad_psi[psiIndex + 1][1] = c * h_xy_i + s * h_xy_r;
grad_grad_psi[psiIndex + 1][2] = c * h_xz_i + s * h_xz_r;
grad_grad_psi[psiIndex + 1][3] = c * h_xy_i + s * h_xy_r;
grad_grad_psi[psiIndex + 1][4] = c * h_yy_i + s * h_yy_r;
grad_grad_psi[psiIndex + 1][5] = c * h_yz_i + s * h_yz_r;
grad_grad_psi[psiIndex + 1][6] = c * h_xz_i + s * h_xz_r;
grad_grad_psi[psiIndex + 1][7] = c * h_yz_i + s * h_yz_r;
grad_grad_psi[psiIndex + 1][8] = c * h_zz_i + s * h_zz_r;
//These are the real and imaginary components of the third SPO derivative. _xxx denotes
// third derivative w.r.t. x, _xyz, a derivative with resepect to x,y, and z, and so on.
const ST f3_xxx_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g00, g01, g02);
const ST f3_xxy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g10, g11, g12);
const ST f3_xxz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g20, g21, g22);
const ST f3_xyy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g10, g11, g12, g10, g11, g12);
const ST f3_xyz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g10, g11, g12, g20, g21, g22);
const ST f3_xzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g20, g21, g22, g20, g21, g22);
const ST f3_yyy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g10, g11, g12, g10, g11, g12);
const ST f3_yyz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g10, g11, g12, g20, g21, g22);
const ST f3_yzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g20, g21, g22, g20, g21, g22);
const ST f3_zzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g20, g21, g22, g20, g21, g22, g20, g21, g22);
const ST f3_xxx_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g00, g01, g02);
const ST f3_xxy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g10, g11, g12);
const ST f3_xxz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g20, g21, g22);
const ST f3_xyy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g10, g11, g12, g10, g11, g12);
const ST f3_xyz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g10, g11, g12, g20, g21, g22);
const ST f3_xzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g20, g21, g22, g20, g21, g22);
const ST f3_yyy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g10, g11, g12, g10, g11, g12);
const ST f3_yyz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g10, g11, g12, g20, g21, g22);
const ST f3_yzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g20, g21, g22, g20, g21, g22);
const ST f3_zzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g20, g21, g22, g20, g21, g22, g20, g21, g22);
//Here is where we build up the components of the physical hessian gradient, namely, d^3/dx^3(e^{-ik*r}\phi(r)
const ST gh_xxx_r = f3_xxx_r + 3 * kX * f_xx_i - 3 * kX * kX * dX_r - kX * kX * kX * val_i;
const ST gh_xxx_i = f3_xxx_i - 3 * kX * f_xx_r - 3 * kX * kX * dX_i + kX * kX * kX * val_r;
const ST gh_xxy_r =
f3_xxy_r + (kY * f_xx_i + 2 * kX * f_xy_i) - (kX * kX * dY_r + 2 * kX * kY * dX_r) - kX * kX * kY * val_i;
const ST gh_xxy_i =
f3_xxy_i - (kY * f_xx_r + 2 * kX * f_xy_r) - (kX * kX * dY_i + 2 * kX * kY * dX_i) + kX * kX * kY * val_r;
const ST gh_xxz_r =
f3_xxz_r + (kZ * f_xx_i + 2 * kX * f_xz_i) - (kX * kX * dZ_r + 2 * kX * kZ * dX_r) - kX * kX * kZ * val_i;
const ST gh_xxz_i =
f3_xxz_i - (kZ * f_xx_r + 2 * kX * f_xz_r) - (kX * kX * dZ_i + 2 * kX * kZ * dX_i) + kX * kX * kZ * val_r;
const ST gh_xyy_r =
f3_xyy_r + (2 * kY * f_xy_i + kX * f_yy_i) - (2 * kX * kY * dY_r + kY * kY * dX_r) - kX * kY * kY * val_i;
const ST gh_xyy_i =
f3_xyy_i - (2 * kY * f_xy_r + kX * f_yy_r) - (2 * kX * kY * dY_i + kY * kY * dX_i) + kX * kY * kY * val_r;
const ST gh_xyz_r = f3_xyz_r + (kX * f_yz_i + kY * f_xz_i + kZ * f_xy_i) -
(kX * kY * dZ_r + kY * kZ * dX_r + kZ * kX * dY_r) - kX * kY * kZ * val_i;
const ST gh_xyz_i = f3_xyz_i - (kX * f_yz_r + kY * f_xz_r + kZ * f_xy_r) -
(kX * kY * dZ_i + kY * kZ * dX_i + kZ * kX * dY_i) + kX * kY * kZ * val_r;
const ST gh_xzz_r =
f3_xzz_r + (2 * kZ * f_xz_i + kX * f_zz_i) - (2 * kX * kZ * dZ_r + kZ * kZ * dX_r) - kX * kZ * kZ * val_i;
const ST gh_xzz_i =
f3_xzz_i - (2 * kZ * f_xz_r + kX * f_zz_r) - (2 * kX * kZ * dZ_i + kZ * kZ * dX_i) + kX * kZ * kZ * val_r;
const ST gh_yyy_r = f3_yyy_r + 3 * kY * f_yy_i - 3 * kY * kY * dY_r - kY * kY * kY * val_i;
const ST gh_yyy_i = f3_yyy_i - 3 * kY * f_yy_r - 3 * kY * kY * dY_i + kY * kY * kY * val_r;
const ST gh_yyz_r =
f3_yyz_r + (kZ * f_yy_i + 2 * kY * f_yz_i) - (kY * kY * dZ_r + 2 * kY * kZ * dY_r) - kY * kY * kZ * val_i;
const ST gh_yyz_i =
f3_yyz_i - (kZ * f_yy_r + 2 * kY * f_yz_r) - (kY * kY * dZ_i + 2 * kY * kZ * dY_i) + kY * kY * kZ * val_r;
const ST gh_yzz_r =
f3_yzz_r + (2 * kZ * f_yz_i + kY * f_zz_i) - (2 * kY * kZ * dZ_r + kZ * kZ * dY_r) - kY * kZ * kZ * val_i;
const ST gh_yzz_i =
f3_yzz_i - (2 * kZ * f_yz_r + kY * f_zz_r) - (2 * kY * kZ * dZ_i + kZ * kZ * dY_i) + kY * kZ * kZ * val_r;
const ST gh_zzz_r = f3_zzz_r + 3 * kZ * f_zz_i - 3 * kZ * kZ * dZ_r - kZ * kZ * kZ * val_i;
const ST gh_zzz_i = f3_zzz_i - 3 * kZ * f_zz_r - 3 * kZ * kZ * dZ_i + kZ * kZ * kZ * val_r;
grad_grad_grad_psi[psiIndex][0][0] = c * gh_xxx_r - s * gh_xxx_i;
grad_grad_grad_psi[psiIndex][0][1] = c * gh_xxy_r - s * gh_xxy_i;
grad_grad_grad_psi[psiIndex][0][2] = c * gh_xxz_r - s * gh_xxz_i;
grad_grad_grad_psi[psiIndex][0][3] = c * gh_xxy_r - s * gh_xxy_i;
grad_grad_grad_psi[psiIndex][0][4] = c * gh_xyy_r - s * gh_xyy_i;
grad_grad_grad_psi[psiIndex][0][5] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][0][6] = c * gh_xxz_r - s * gh_xxz_i;
grad_grad_grad_psi[psiIndex][0][7] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][0][8] = c * gh_xzz_r - s * gh_xzz_i;
grad_grad_grad_psi[psiIndex][1][0] = c * gh_xxy_r - s * gh_xxy_i;
grad_grad_grad_psi[psiIndex][1][1] = c * gh_xyy_r - s * gh_xyy_i;
grad_grad_grad_psi[psiIndex][1][2] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][1][3] = c * gh_xyy_r - s * gh_xyy_i;
grad_grad_grad_psi[psiIndex][1][4] = c * gh_yyy_r - s * gh_yyy_i;
grad_grad_grad_psi[psiIndex][1][5] = c * gh_yyz_r - s * gh_yyz_i;
grad_grad_grad_psi[psiIndex][1][6] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][1][7] = c * gh_yyz_r - s * gh_yyz_i;
grad_grad_grad_psi[psiIndex][1][8] = c * gh_yzz_r - s * gh_yzz_i;
grad_grad_grad_psi[psiIndex][2][0] = c * gh_xxz_r - s * gh_xxz_i;
grad_grad_grad_psi[psiIndex][2][1] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][2][2] = c * gh_xzz_r - s * gh_xzz_i;
grad_grad_grad_psi[psiIndex][2][3] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][2][4] = c * gh_yyz_r - s * gh_yyz_i;
grad_grad_grad_psi[psiIndex][2][5] = c * gh_yzz_r - s * gh_yzz_i;
grad_grad_grad_psi[psiIndex][2][6] = c * gh_xzz_r - s * gh_xzz_i;
grad_grad_grad_psi[psiIndex][2][7] = c * gh_yzz_r - s * gh_yzz_i;
grad_grad_grad_psi[psiIndex][2][8] = c * gh_zzz_r - s * gh_zzz_i;
grad_grad_grad_psi[psiIndex + 1][0][0] = c * gh_xxx_i + s * gh_xxx_r;
grad_grad_grad_psi[psiIndex + 1][0][1] = c * gh_xxy_i + s * gh_xxy_r;
grad_grad_grad_psi[psiIndex + 1][0][2] = c * gh_xxz_i + s * gh_xxz_r;
grad_grad_grad_psi[psiIndex + 1][0][3] = c * gh_xxy_i + s * gh_xxy_r;
grad_grad_grad_psi[psiIndex + 1][0][4] = c * gh_xyy_i + s * gh_xyy_r;
grad_grad_grad_psi[psiIndex + 1][0][5] = c * gh_xyz_i + s * gh_xyz_r;
grad_grad_grad_psi[psiIndex + 1][0][6] = c * gh_xxz_i + s * gh_xxz_r;
grad_grad_grad_psi[psiIndex + 1][0][7] = c * gh_xyz_i + s * gh_xyz_r;
grad_grad_grad_psi[psiIndex + 1][0][8] = c * gh_xzz_i + s * gh_xzz_r;
grad_grad_grad_psi[psiIndex + 1][1][0] = c * gh_xxy_i + s * gh_xxy_r;
grad_grad_grad_psi[psiIndex + 1][1][1] = c * gh_xyy_i + s * gh_xyy_r;
grad_grad_grad_psi[psiIndex + 1][1][2] = c * gh_xyz_i + s * gh_xyz_r;
grad_grad_grad_psi[psiIndex + 1][1][3] = c * gh_xyy_i + s * gh_xyy_r;
grad_grad_grad_psi[psiIndex + 1][1][4] = c * gh_yyy_i + s * gh_yyy_r;
grad_grad_grad_psi[psiIndex + 1][1][5] = c * gh_yyz_i + s * gh_yyz_r;
grad_grad_grad_psi[psiIndex + 1][1][6] = c * gh_xyz_i + s * gh_xyz_r;
grad_grad_grad_psi[psiIndex + 1][1][7] = c * gh_yyz_i + s * gh_yyz_r;
grad_grad_grad_psi[psiIndex + 1][1][8] = c * gh_yzz_i + s * gh_yzz_r;
grad_grad_grad_psi[psiIndex + 1][2][0] = c * gh_xxz_i + s * gh_xxz_r;
grad_grad_grad_psi[psiIndex + 1][2][1] = c * gh_xyz_i + s * gh_xyz_r;
grad_grad_grad_psi[psiIndex + 1][2][2] = c * gh_xzz_i + s * gh_xzz_r;
grad_grad_grad_psi[psiIndex + 1][2][3] = c * gh_xyz_i + s * gh_xyz_r;
grad_grad_grad_psi[psiIndex + 1][2][4] = c * gh_yyz_i + s * gh_yyz_r;
grad_grad_grad_psi[psiIndex + 1][2][5] = c * gh_yzz_i + s * gh_yzz_r;
grad_grad_grad_psi[psiIndex + 1][2][6] = c * gh_xzz_i + s * gh_xzz_r;
grad_grad_grad_psi[psiIndex + 1][2][7] = c * gh_yzz_i + s * gh_yzz_r;
grad_grad_grad_psi[psiIndex + 1][2][8] = c * gh_zzz_i + s * gh_zzz_r;
}
#pragma omp simd
for (size_t j = std::max(nComplexBands, first); j < last; j++)
{
int jr = j << 1;
int ji = jr + 1;
const ST kX = k0[j];
const ST kY = k1[j];
const ST kZ = k2[j];
const ST val_r = myV[jr];
const ST val_i = myV[ji];
//phase
ST s, c;
sincos(-(x * kX + y * kY + z * kZ), &s, &c);
//dot(PrimLattice.G,myG[j])
const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr];
const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr];
const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr];
const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji];
const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji];
const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji];
// \f$\nabla \psi_r + {\bf k}\psi_i\f$
const ST gX_r = dX_r + val_i * kX;
const ST gY_r = dY_r + val_i * kY;
const ST gZ_r = dZ_r + val_i * kZ;
const ST gX_i = dX_i - val_r * kX;
const ST gY_i = dY_i - val_r * kY;
const ST gZ_i = dZ_i - val_r * kZ;
const size_t psiIndex = first_spo + nComplexBands + j;
psi[psiIndex] = c * val_r - s * val_i;
dpsi[psiIndex][0] = c * gX_r - s * gX_i;
dpsi[psiIndex][1] = c * gY_r - s * gY_i;
dpsi[psiIndex][2] = c * gZ_r - s * gZ_i;
//intermediates for computation of hessian. \partial_i \partial_j phi in cartesian coordinates.
const ST f_xx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g00, g01, g02);
const ST f_xy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g10, g11, g12);
const ST f_xz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g20, g21, g22);
const ST f_yy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g10, g11, g12);
const ST f_yz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g20, g21, g22);
const ST f_zz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g20, g21, g22);
const ST f_xx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g00, g01, g02);
const ST f_xy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g10, g11, g12);
const ST f_xz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g20, g21, g22);
const ST f_yy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g10, g11, g12);
const ST f_yz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g20, g21, g22);
const ST f_zz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g20, g21, g22);
const ST h_xx_r = f_xx_r + 2 * kX * dX_i - kX * kX * val_r;
const ST h_xy_r = f_xy_r + (kX * dY_i + kY * dX_i) - kX * kY * val_r;
const ST h_xz_r = f_xz_r + (kX * dZ_i + kZ * dX_i) - kX * kZ * val_r;
const ST h_yy_r = f_yy_r + 2 * kY * dY_i - kY * kY * val_r;
const ST h_yz_r = f_yz_r + (kY * dZ_i + kZ * dY_i) - kY * kZ * val_r;
const ST h_zz_r = f_zz_r + 2 * kZ * dZ_i - kZ * kZ * val_r;
const ST h_xx_i = f_xx_i - 2 * kX * dX_r - kX * kX * val_i;
const ST h_xy_i = f_xy_i - (kX * dY_r + kY * dX_r) - kX * kY * val_i;
const ST h_xz_i = f_xz_i - (kX * dZ_r + kZ * dX_r) - kX * kZ * val_i;
const ST h_yy_i = f_yy_i - 2 * kY * dY_r - kY * kY * val_i;
const ST h_yz_i = f_yz_i - (kZ * dY_r + kY * dZ_r) - kZ * kY * val_i;
const ST h_zz_i = f_zz_i - 2 * kZ * dZ_r - kZ * kZ * val_i;
grad_grad_psi[psiIndex][0] = c * h_xx_r - s * h_xx_i;
grad_grad_psi[psiIndex][1] = c * h_xy_r - s * h_xy_i;
grad_grad_psi[psiIndex][2] = c * h_xz_r - s * h_xz_i;
grad_grad_psi[psiIndex][3] = c * h_xy_r - s * h_xy_i;
grad_grad_psi[psiIndex][4] = c * h_yy_r - s * h_yy_i;
grad_grad_psi[psiIndex][5] = c * h_yz_r - s * h_yz_i;
grad_grad_psi[psiIndex][6] = c * h_xz_r - s * h_xz_i;
grad_grad_psi[psiIndex][7] = c * h_yz_r - s * h_yz_i;
grad_grad_psi[psiIndex][8] = c * h_zz_r - s * h_zz_i;
//These are the real and imaginary components of the third SPO derivative. _xxx denotes
// third derivative w.r.t. x, _xyz, a derivative with resepect to x,y, and z, and so on.
const ST f3_xxx_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g00, g01, g02);
const ST f3_xxy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g10, g11, g12);
const ST f3_xxz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g20, g21, g22);
const ST f3_xyy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g10, g11, g12, g10, g11, g12);
const ST f3_xyz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g10, g11, g12, g20, g21, g22);
const ST f3_xzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g20, g21, g22, g20, g21, g22);
const ST f3_yyy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g10, g11, g12, g10, g11, g12);
const ST f3_yyz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g10, g11, g12, g20, g21, g22);
const ST f3_yzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g20, g21, g22, g20, g21, g22);
const ST f3_zzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr],
gh112[jr], gh122[jr], gh222[jr], g20, g21, g22, g20, g21, g22, g20, g21, g22);
const ST f3_xxx_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g00, g01, g02);
const ST f3_xxy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g10, g11, g12);
const ST f3_xxz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g20, g21, g22);
const ST f3_xyy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g10, g11, g12, g10, g11, g12);
const ST f3_xyz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g10, g11, g12, g20, g21, g22);
const ST f3_xzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g20, g21, g22, g20, g21, g22);
const ST f3_yyy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g10, g11, g12, g10, g11, g12);
const ST f3_yyz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g10, g11, g12, g20, g21, g22);
const ST f3_yzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g20, g21, g22, g20, g21, g22);
const ST f3_zzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji],
gh112[ji], gh122[ji], gh222[ji], g20, g21, g22, g20, g21, g22, g20, g21, g22);
//Here is where we build up the components of the physical hessian gradient, namely, d^3/dx^3(e^{-ik*r}\phi(r)
const ST gh_xxx_r = f3_xxx_r + 3 * kX * f_xx_i - 3 * kX * kX * dX_r - kX * kX * kX * val_i;
const ST gh_xxx_i = f3_xxx_i - 3 * kX * f_xx_r - 3 * kX * kX * dX_i + kX * kX * kX * val_r;
const ST gh_xxy_r =
f3_xxy_r + (kY * f_xx_i + 2 * kX * f_xy_i) - (kX * kX * dY_r + 2 * kX * kY * dX_r) - kX * kX * kY * val_i;
const ST gh_xxy_i =
f3_xxy_i - (kY * f_xx_r + 2 * kX * f_xy_r) - (kX * kX * dY_i + 2 * kX * kY * dX_i) + kX * kX * kY * val_r;
const ST gh_xxz_r =
f3_xxz_r + (kZ * f_xx_i + 2 * kX * f_xz_i) - (kX * kX * dZ_r + 2 * kX * kZ * dX_r) - kX * kX * kZ * val_i;
const ST gh_xxz_i =
f3_xxz_i - (kZ * f_xx_r + 2 * kX * f_xz_r) - (kX * kX * dZ_i + 2 * kX * kZ * dX_i) + kX * kX * kZ * val_r;
const ST gh_xyy_r =
f3_xyy_r + (2 * kY * f_xy_i + kX * f_yy_i) - (2 * kX * kY * dY_r + kY * kY * dX_r) - kX * kY * kY * val_i;
const ST gh_xyy_i =
f3_xyy_i - (2 * kY * f_xy_r + kX * f_yy_r) - (2 * kX * kY * dY_i + kY * kY * dX_i) + kX * kY * kY * val_r;
const ST gh_xyz_r = f3_xyz_r + (kX * f_yz_i + kY * f_xz_i + kZ * f_xy_i) -
(kX * kY * dZ_r + kY * kZ * dX_r + kZ * kX * dY_r) - kX * kY * kZ * val_i;
const ST gh_xyz_i = f3_xyz_i - (kX * f_yz_r + kY * f_xz_r + kZ * f_xy_r) -
(kX * kY * dZ_i + kY * kZ * dX_i + kZ * kX * dY_i) + kX * kY * kZ * val_r;
const ST gh_xzz_r =
f3_xzz_r + (2 * kZ * f_xz_i + kX * f_zz_i) - (2 * kX * kZ * dZ_r + kZ * kZ * dX_r) - kX * kZ * kZ * val_i;
const ST gh_xzz_i =
f3_xzz_i - (2 * kZ * f_xz_r + kX * f_zz_r) - (2 * kX * kZ * dZ_i + kZ * kZ * dX_i) + kX * kZ * kZ * val_r;
const ST gh_yyy_r = f3_yyy_r + 3 * kY * f_yy_i - 3 * kY * kY * dY_r - kY * kY * kY * val_i;
const ST gh_yyy_i = f3_yyy_i - 3 * kY * f_yy_r - 3 * kY * kY * dY_i + kY * kY * kY * val_r;
const ST gh_yyz_r =
f3_yyz_r + (kZ * f_yy_i + 2 * kY * f_yz_i) - (kY * kY * dZ_r + 2 * kY * kZ * dY_r) - kY * kY * kZ * val_i;
const ST gh_yyz_i =
f3_yyz_i - (kZ * f_yy_r + 2 * kY * f_yz_r) - (kY * kY * dZ_i + 2 * kY * kZ * dY_i) + kY * kY * kZ * val_r;
const ST gh_yzz_r =
f3_yzz_r + (2 * kZ * f_yz_i + kY * f_zz_i) - (2 * kY * kZ * dZ_r + kZ * kZ * dY_r) - kY * kZ * kZ * val_i;
const ST gh_yzz_i =
f3_yzz_i - (2 * kZ * f_yz_r + kY * f_zz_r) - (2 * kY * kZ * dZ_i + kZ * kZ * dY_i) + kY * kZ * kZ * val_r;
const ST gh_zzz_r = f3_zzz_r + 3 * kZ * f_zz_i - 3 * kZ * kZ * dZ_r - kZ * kZ * kZ * val_i;
const ST gh_zzz_i = f3_zzz_i - 3 * kZ * f_zz_r - 3 * kZ * kZ * dZ_i + kZ * kZ * kZ * val_r;
//[x][xx] //These are the unique entries
grad_grad_grad_psi[psiIndex][0][0] = c * gh_xxx_r - s * gh_xxx_i;
grad_grad_grad_psi[psiIndex][0][1] = c * gh_xxy_r - s * gh_xxy_i;
grad_grad_grad_psi[psiIndex][0][2] = c * gh_xxz_r - s * gh_xxz_i;
grad_grad_grad_psi[psiIndex][0][3] = c * gh_xxy_r - s * gh_xxy_i;
grad_grad_grad_psi[psiIndex][0][4] = c * gh_xyy_r - s * gh_xyy_i;
grad_grad_grad_psi[psiIndex][0][5] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][0][6] = c * gh_xxz_r - s * gh_xxz_i;
grad_grad_grad_psi[psiIndex][0][7] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][0][8] = c * gh_xzz_r - s * gh_xzz_i;
grad_grad_grad_psi[psiIndex][1][0] = c * gh_xxy_r - s * gh_xxy_i;
grad_grad_grad_psi[psiIndex][1][1] = c * gh_xyy_r - s * gh_xyy_i;
grad_grad_grad_psi[psiIndex][1][2] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][1][3] = c * gh_xyy_r - s * gh_xyy_i;
grad_grad_grad_psi[psiIndex][1][4] = c * gh_yyy_r - s * gh_yyy_i;
grad_grad_grad_psi[psiIndex][1][5] = c * gh_yyz_r - s * gh_yyz_i;
grad_grad_grad_psi[psiIndex][1][6] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][1][7] = c * gh_yyz_r - s * gh_yyz_i;
grad_grad_grad_psi[psiIndex][1][8] = c * gh_yzz_r - s * gh_yzz_i;
grad_grad_grad_psi[psiIndex][2][0] = c * gh_xxz_r - s * gh_xxz_i;
grad_grad_grad_psi[psiIndex][2][1] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][2][2] = c * gh_xzz_r - s * gh_xzz_i;
grad_grad_grad_psi[psiIndex][2][3] = c * gh_xyz_r - s * gh_xyz_i;
grad_grad_grad_psi[psiIndex][2][4] = c * gh_yyz_r - s * gh_yyz_i;
grad_grad_grad_psi[psiIndex][2][5] = c * gh_yzz_r - s * gh_yzz_i;
grad_grad_grad_psi[psiIndex][2][6] = c * gh_xzz_r - s * gh_xzz_i;
grad_grad_grad_psi[psiIndex][2][7] = c * gh_yzz_r - s * gh_yzz_i;
grad_grad_grad_psi[psiIndex][2][8] = c * gh_zzz_r - s * gh_zzz_i;
}
}
template<typename VV, typename GV, typename GGV, typename GGGV>
void evaluate_vghgh(const ParticleSet& P,
const int iat,
VV& psi,
GV& dpsi,
GGV& grad_grad_psi,
GGGV& grad_grad_grad_psi)
{
const PointType& r = P.activeR(iat);
PointType ru(PrimLattice.toUnit_floor(r));
#pragma omp parallel
{
int first, last;
FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last);
spline2::evaluate3d_vghgh(SplineInst->getSplinePtr(), ru, myV, myG, myH, mygH, first, last);
assign_vghgh(r, psi, dpsi, grad_grad_psi, grad_grad_grad_psi, first / 2, last / 2);
}
}
};
} // namespace qmcplusplus
#endif
|
image.h
|
// Copyright (c) 2017 Marek Dvoroznak
// Licensed under the MIT License.
// Define IMAGE_READ_WRITE for writing and reading methods to be included.
// Define IMAGE_READ_WRITE_NO_COMPRESSION for not including miniz.
// Define IMAGE_SCALE for up-/down- scaling (using stb_image_resize)
#ifndef IMAGE_H
#define IMAGE_H
#include <iostream>
#include <stdexcept>
#include <cmath>
#include <cassert>
#include <vector>
#include <cstring>
#include <string>
#include <fstream>
#include <utility>
#include <map>
#include <algorithm>
#ifndef DEBUG_CMD_IMG
#ifdef ENABLE_DEBUG_CMD_IMG
#define DEBUG_CMD_IMG(x) {x}
#else
#define DEBUG_CMD_IMG(x) ;
#endif
#endif
#ifndef fora
#define fora(a,s,e) for (int a=s; a<e; a++)
#endif
#ifndef forlist
#define forlist(a,s) for (size_t a=0; a<(s).size(); a++)
#endif
template<typename T>
class Color
{
public:
int ch;
T *data = nullptr;
bool sharedData;
Color();
virtual ~Color();
// Color(Color &&c) = default;
Color(int ch);
Color(int ch, const T &defaultValue);
Color(const Color &c);
Color(int ch, T *data);
Color(std::initializer_list<T> init_list);
template<typename U> Color<T>& initColor(const Color<U> &from, bool sharedData = false);
inline const Color& operator=(const Color &c);
inline const T& operator()(int ch) const;
inline T& operator()(int ch);
Color head(int n);
template<typename U> Color<U> cast();
bool isNull() const;
inline Color& operator/=(const Color<T> &rhs);
inline Color<T>& operator/=(const T &c);
inline Color& operator+=(const Color<T> &rhs);
inline Color<T>& operator+=(const T &c);
};
template<typename T>
class Img
{
public:
T *data = nullptr;
int w;
int h;
int ch; // number of channels
int alphaChannel;
bool sharedData;
int valuesPerChannel = -1;
enum BoundaryHandling { clip, reflect, none };
enum Sampling { nearest, bilinear };
// If the input image has shared data, the result is an image also with shared data.
// The same holds for new data.
Img(const Img &img);
Img();
Img(int w, int h, int channels, int alphaChannel = -1);
Img(T *data, int w, int h, int channels);
Img(T *data, int w, int h, int channels, int alphaChannel);
Img(const Img &img, int nChannelsFactor, int alphaChannel = -1);
virtual ~Img();
static const Img nullImage();
bool isNull() const;
Img<T>& setNull();
Img& clear();
Img& fill(const Color<T> &c);
Img& fill(const T &value);
// Returns a deep copy of this image (of type T) which has its data casted to type U.
template<typename U> Img<U> cast() const;
Img<T> cast() const;
// The data of the image on the left will be rewritten by the data of the image on the right (deep copy)
// and type conversion will be performed.
// If the image on the left is NULL image, then it is initialized according to the image on the right.
template<typename U> Img& cast(const Img<U> &img);
Img& cast(const Img<T> &img);
// Returns a deep copy of this image (of type T) which has its data casted to type U
// and also all values scaled according to the new type.
template<typename U> Img<U> castAndConvert() const;
Img<T> castAndConvert() const;
// The data of the image on the left will be rewritten by the data of the image on the right (deep copy)
// and type conversion will be performed and all values scaled according to the type T.
// If the image on the left is NULL image, then it is initialized according to the image on the right.
template<typename U> Img& castAndConvert(const Img<U> &img);
Img& castAndConvert(const Img<T> &img);
// If the type of the image on the left differs from the type of the image on the right,
// deep copy with conversion (castAndConvert() method) is performed.
// Otherwise it returns a shallow copy.
template<typename U> Img<U> shallowCopyCastAndConvert() const;
// If the type of the image on the left differs from the type of the image on the right,
// deep copy with conversion (castAndConvert() method) is performed.
// Otherwise it returns a shallow copy.
Img<T> shallowCopyCastAndConvert() const;
template<typename U> Img& shallowCopyCastAndConvert(const Img<U> &img);
Img& shallowCopyCastAndConvert(const Img<T> &img);
// No matter if the image has or has not shared data, the result is an image with new data.
Img deepCopy() const;
// No matter if the image on the left has or has not shared data, the same for the image on the right,
// the data of the image on the left will be rewritten by the data of the image on the right (deep copy).
// If the image on the left is NULL image, then it is initialized according to the image on the right.
Img& deepCopy(const Img &img);
// No matter if the image has or has not shared data, the result is an image with shared data.
Img shallowCopy() const;
const Img<const T>& constShallowCopy() const;
// No matter if the image on the left has or has not shared data, the same for the image on the right,
// the image on the left will become image with shared data, i.e. the pointer to data of the image on the left
// will point to the data of the image on the right (shallow copy).
// If the image on the left is NULL image, then it is initialized according to the image on the right.
// If the image on the left has not shared data then the data will be freed.
Img& shallowCopy(const Img &img);
// If the image on the left has shared data, it will still have shared data after the assignment.
// The same holds for new data.
const Img& operator=(const Img &img);
// Img& operator=(Img &&img);
// check out of range
const T& at(int x, int y, int channel) const;
// check out of range
T& at(int x, int y, int channel);
// check out of range
T sampleBilinearAt(double x, double y, int channel) const;
// do not check out of range
T sampleBilinear(double x, double y, int channel) const;
T sampleBilinear(double x, double y, int channel, BoundaryHandling bndHandling) const;
// do not check out of range
T sampleNearest(double x, double y, int channel) const;
T sampleNearest(double x, double y, int channel, BoundaryHandling bndHandling) const;
// do not check out of range
T sample(double x, double y, int channel, BoundaryHandling bndHandling, Sampling sampling) const;
// do not check out of range
Color<T> samplePixel(double x, double y, BoundaryHandling bndHandling, Sampling sampling) const;
// Access image data by x, y coordinates and channel.
// do not check out of range
inline const T& operator()(int x, int y, int channel) const;
// Access image data by x, y coordinates and channel.
// do not check out of range
inline T& operator()(int x, int y, int channel);
inline const T& operator()(int x, int y, int channel, BoundaryHandling bndHandling) const;
inline T& operator()(int x, int y, int channel, BoundaryHandling bndHandling);
// Access image data by index and channel.
// do not check out of range
inline const T& operator()(int index, int channel) const;
// Access image data by index and channel.
// do not check out of range
inline T& operator()(int index, int channel);
// Access alpha channel by x, y coordinates.
// do not check out of range
inline const T& alpha(int x, int y) const;
// Access alpha channel by x, y coordinates.
// do not check out of range
inline T& alpha(int x, int y);
inline Img& operator+=(const T &t);
template<typename U> inline Img& operator-=(const U &t);
inline Img& operator*=(const T &t);
inline Img& operator/=(const T &t);
inline Img& operator+=(const Img &rhs);
inline Img& operator-=(const Img &rhs);
inline Img& operator*=(const Img &rhs);
inline Img& operator/=(const Img &rhs);
// inline const Color<T>& getPixel(int x, int y) const;
// inline Color<T>& getPixel(int x, int y);
inline const Color<T> getPixel(int x, int y) const;
inline Color<T> getPixel(int x, int y);
static int getBytesPerChannel();
static int getMaxValuesPerChannel();
int getValuesPerChannel() const;
void setValuesPerChannel(int val);
int getTotalBytes();
int wh() const;
int whch() const;
template<typename U> Img& initImage(const Img<U> &fromImg, bool sharedData = false);
// convert to premultiplied alpha
Img& multiplyByAlpha();
// convert to postmultiplied alpha
Img& divideByAlpha();
Img getChannel(int channel, int alphaChannel = -1) const;
Img getChannels(std::vector<int> channels, int alphaChannel = -1) const;
Img cloneChannels(int nChannelsFactor, int alphaChannel = -1) const;
Img& replaceChannels(const Img &inImg, std::vector<int> inImgChannels, std::vector<int> thisImgChannels);
Img& swapChannels(int ch1, int ch2);
Img getAlphaChannel() const;
Img& replaceAlpha(const Img &alpha);
void getBoundingBox(int &x1, int &y1, int &x2, int &y2, int channel, int minVal, int maxVal) const;
Img crop(int x1, int y1, int x2, int y2, int &modX1, int &modY1, int &modX2, int &modY2) const;
Img crop(int w, int h, int shiftX = 0, int shiftY = 0) const;
Img resize(int w, int h, int shiftX = 0, int shiftY = 0) const;
Img resize(int w, int h, int shiftX, int shiftY, const Color<T> &c) const;
Img& blendWithInPlace(const Img &topImg);
// Convolution of the image with 1D kernel. Boundary reflection or clipping (default).
Img<float> conv1D(const std::vector<float> &kernel, BoundaryHandling bndHandling = clip);
Img& blur(float sigma);
Img& invert(T maxVal);
Img transpose() const;
Img& clamp(T min, T max);
bool equalData(const Img &img) const;
bool equalDimension(const Img &img) const;
void computeCentroid(double &cx, double &cy, T threshold = 0);
Img warp(const Img<float> &Dx, const Img<float> &Dy, BoundaryHandling bndHandling = clip, Sampling sampling = bilinear);
static Img warp(const Img &img, const Img<float> &Dx, const Img<float> &Dy, BoundaryHandling bndHandling = clip, Sampling sampling = bilinear);
void reduceColors(const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold);
void reduceColors(const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold, int &maxColors);
static void reduceColors(Img &img, const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold);
static void reduceColors(Img &img, const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold, int &maxColors);
void reduceColors(const std::vector<Color<T>> &colors, const std::vector<int> &count, int maxColors);
static void reduceColors(Img &img, const std::vector<Color<T>> &colors, const std::vector<int> &count, int maxColors);
void getColorsUsage(std::vector<Color<T>> &colors, std::vector<int> &count);
static void getColorsUsage(const Img &img, std::vector<Color<T>> &colors, std::vector<int> &count);
void getColorsUsage(std::vector<Color<T>> &colors, std::vector<int> &count, const Img &alphaChannel);
static void getColorsUsage(const Img &img, std::vector<Color<T>> &colors, std::vector<int> &count, const Img &alphaChannel);
static void replaceColors(Img &img, const std::map<const Color<T>,Color<T>> &replacement);
void replaceColors(const std::map<const Color<T>,Color<T>> &replacement);
void minMax(std::vector<T> &min, std::vector<T> &max) const;
Img subsample(int subsampleFactor, Sampling sampling) const;
bool checkBounds(int x, int y, int c = 0) const;
private:
void updateColorData();
static std::string debugPrefix();
static T bilinearInterpolation(T I0, T I1, T I2, T I3, double dx, double dy);
static double alphaBlending(double A, double B, double BAlpha);
static inline float gauss(float x, float sigma);
static std::vector<float> genGaussKernel(float sigma);
#ifdef IMAGE_READ_WRITE
public:
bool saveRaw(const std::string &filename, bool includeHeader = true) const;
#ifndef IMAGE_READ_WRITE_NO_COMPRESSION
bool save(const std::string &filename, bool includeHeader = true) const;
#endif
// Loading of raw data (uncompressed or compressed) without a header.
static Img load(const std::string &filename, int width, int height, int channels, int alphaChannel, int bytesPerChannel, bool compressed);
// Loading of data with a header.
static Img load(const std::string &filename);
// Load from 8 or 16 bit per channel PNG file.
static Img loadPNG(const std::string &filename, int alphaChannel = -1, int desiredNumChannels = 0);
// Load from 8 bit per channel PNG file from memory.
static Img loadPNG(unsigned char *imgData, int length, int alphaChannel = -1, int desiredNumChannels = 0);
// Load image from file. Should work for all image formats supported by stb_image.
static Img loadImage(const std::string &filename, int alphaChannel = -1, int desiredNumChannels = 0);
// Load image from memory. Should work for all image formats supported by stb_image.
static Img loadImage(unsigned char *imgData, int length, int alphaChannel = -1, int desiredNumChannels = 0);
// Save to 8 bit per channel PNG file.
bool savePNG(const std::string &filename) const;
// Save to 8 bit per channel PNG image in memory.
bool savePNG(unsigned char *&pngData, int &length) const;
private:
bool saveToFile(const std::string &filename, const char* data, int length, bool compressed, bool includeHeader = true) const;
static Img loadFileFromStream(std::ifstream &stream, int width, int height, int channels, int alphaChannel, int bytesPerChannel, bool compressed, int length);
#endif
#ifdef IMAGE_SCALE
public:
Img scale(int newW, int newH);
// scale width and keep aspect ratio
Img scaleWidth(int newW);
// scale height and keep aspect ratio
Img scaleHeight(int newH);
#endif
};
// typedefs
typedef Color<unsigned char> Cu;
typedef Color<unsigned char> Cuc;
typedef Color<float> Cf;
typedef Color<double> Cd;
typedef Img<unsigned char> Imguc;
typedef Img<float> Imgf;
typedef Img<double> Imgd;
typedef Img<unsigned char> Image8;
typedef Img<const unsigned char> Imagec8;
typedef Img<unsigned short> Image16;
typedef Img<const unsigned short> Imagec16;
#ifdef IMAGE_READ_WRITE
#include "imageReadWrite.hpp"
#endif
// Implementation
// -----------
// Color
// -----------
template<typename T>
Color<T>::Color() : ch(0), sharedData(false) {
}
template<typename T>
Color<T>::~Color()
{
if (!sharedData && data != nullptr) {
delete[] data;
data = nullptr;
}
}
//template<typename T>
//Color<T>::Color(Color &&c)
//{
// std::cout << "move";
// ch = c.ch;
// data = std::move(c.data);
// sharedData = c.sharedData;
//}
template<typename T>
Color<T>::Color(int ch) : ch(ch), sharedData(false)
{
data = new T[ch];
std::memset(data, 0, ch*sizeof(T));
}
template<typename T>
Color<T>::Color(int ch, const T &defaultValue) : ch(ch), sharedData(false)
{
data = new T[ch];
fora(i, 0, ch) data[i] = defaultValue;
}
// all copies of this color are deep
template<typename T>
Color<T>::Color(const Color &c)
{
initColor(c, false);
*this = c;
}
template<typename T>
Color<T>::Color(int ch, T *data) : ch(ch), data(data), sharedData(true) {}
template<typename T>
Color<T>::Color(std::initializer_list<T> init_list) : sharedData(false)
{
ch = init_list.size();
data = new T[ch];
int j = 0;
for(const T &i : init_list) data[j++] = i;
}
template<typename T>
template<typename U>
Color<T>& Color<T>::initColor(const Color<U> &from, bool sharedData)
{
ch = from.ch;
this->sharedData = sharedData;
if (!sharedData) data = new T[ch];
else data = nullptr;
return *this;
}
// all copies of this color are deep
template<typename T>
inline const Color<T>& Color<T>::operator=(const Color &c)
{
if (ch == 0) initColor(c, false);
assert(ch == c.ch);
fora(i, 0, ch) data[i] = c.data[i];
return *this;
}
template<typename T>
inline const T& Color<T>::operator()(int ch) const
{
return data[ch];
}
template<typename T>
inline T& Color<T>::operator()(int ch)
{
return const_cast<T&>(static_cast<const Color&>(*this)(ch));
}
template<typename T>
Color<T> Color<T>::head(int n)
{
return Color(n, data);
}
template<typename T>
template<typename U>
Color<U> Color<T>::cast()
{
Color<U> c;
c.initColor(*this, false);
fora(i,0,ch) c(i) = (U)operator()(i);
return c;
}
template<typename T>
bool Color<T>::isNull() const
{
return ch == 0;
}
//template<typename T>
//template<typename T2,int CH2>
//Color<T2,CH2> Color<T,CH>::cast()
//{
// Color<T2,CH2> out;
// fora(i, 0, std::min(CH,CH2)) out(i) = operator()(i);
// return out;
//}
//template<typename T,int CH>
//template<typename COLOR>
//COLOR Color<T,CH>::cast()
//{
// COLOR out;
// fora(i, 0, std::min(CH,out.ch)) out(i) = operator()(i);
// return out;
//}
template<typename T>
inline bool operator==(const Color<T> &l, const Color<T> &r)
{
assert(l.ch == r.ch);
// if (l.ch != r.ch) return false;
fora(i, 0, l.ch) if (l(i) != r(i)) return false;
return true;
}
template<typename T>
inline bool operator!=(const Color<T> &l, const Color<T> &r)
{
return !(l==r);
}
template<typename T>
bool operator<(const Color<T> &l,const Color<T> &r)
{
assert(l.ch == r.ch);
double sum_l = 0, sum_r = 0;
fora(i, 0, l.ch) {
sum_l += pow(255,i) * l(i)*l(i);
sum_r += pow(255,i) * r(i)*r(i);
}
return sum_l < sum_r;
}
template<typename T>
inline Color<T>& Color<T>::operator/=(const Color<T> &rhs)
{
assert(ch == rhs.ch);
fora(i, 0, ch) data[i] /= rhs.data[i];
return *this;
}
template<typename T>
inline Color<T> operator/(const Color<T> &lhs, const Color<T> &rhs)
{
Color<T> out = lhs;
out /= rhs;
return out;
}
template<typename T>
inline Color<T>& Color<T>::operator/=(const T &c)
{
fora(i, 0, ch) data[i] /= c;
return *this;
}
template<typename T>
inline Color<T> operator/(const Color<T> &lhs, const T &c)
{
Color<T> out = lhs;
out /= c;
return out;
}
template<typename T>
inline Color<T>& Color<T>::operator+=(const T &c)
{
fora(i, 0, ch) data[i] += c;
return *this;
}
template<typename T>
inline Color<T>& Color<T>::operator+=(const Color<T> &rhs)
{
assert(ch == rhs.ch);
fora(i, 0, ch) data[i] += rhs.data[i];
return *this;
}
template<typename T>
std::ostream& operator<<(std::ostream &os, const Color<T> &c)
{
// os << std::string("Color<T=") + std::to_string(sizeof(T)) + ">" << ": w: " << Img3.w << ", h: " << Img3.h << ", ch: " << Img3.ch << ", alphaChannel: " << Img3.alphaChannel << ", sharedData: " << Img3.sharedData;
fora(i, 0, c.ch) os << std::to_string(c(i)) << " ";
// fora(i, 0, c.ch) os << c(i) << " ";
return os;
}
// -----------
// Img
// -----------
template<typename T>
Img<T>::Img(const Img &img)
{
w = img.w; h = img.h; ch = img.ch; alphaChannel = img.alphaChannel; sharedData = img.sharedData;
if (!sharedData) data = new T[ch*w*h];
// dataC = nullptr;
// updateColorData();
*this = img;
}
template<typename T>
Img<T>::Img() : data(nullptr), /*dataC(nullptr),*/ w(0), h(0), ch(0), alphaChannel(0), sharedData(false)
{}
template<typename T>
Img<T>::Img(int w, int h, int channels, int alphaChannel) : w(w), h(h), ch(channels), alphaChannel(alphaChannel), sharedData(false)
{
data = new T[ch*w*h]; clear();
// dataC = nullptr;
// updateColorData();
}
template<typename T>
Img<T>::Img(T *data, int w, int h, int channels) : data(data), w(w), h(h), ch(channels), alphaChannel(-1), sharedData(true)
{
assert(data != nullptr);
// dataC = nullptr;
// updateColorData();
}
template<typename T>
Img<T>::Img(T *data, int w, int h, int channels, int alphaChannel) : data(data), w(w), h(h), ch(channels), alphaChannel(alphaChannel), sharedData(true)
{
assert(data != nullptr);
// dataC = nullptr;
// updateColorData();
}
template<typename T>
Img<T>::Img(const Img &img, int nChannelsFactor, int alphaChannel) : w(img.w), h(img.h), ch(nChannelsFactor*img.ch), alphaChannel(alphaChannel), sharedData(sharedData)
{
data = new T[ch*w*h];
fora(y,0,h) fora(x,0,w) fora(c,0,img.ch) fora(c2,0,nChannelsFactor) {
operator()(x,y,c2*img.ch+c) = img(x,y,c);
}
}
template<typename T>
Img<T>::~Img()
{
if (!sharedData && data != nullptr) {
DEBUG_CMD_IMG(std::cout << debugPrefix() << ": Deleting " << std::to_string(getTotalBytes()) << " bytes" << std::endl;);
delete[] data;
data = nullptr;
}
// if (dataC != nullptr) delete[] dataC;
}
template<typename T>
bool Img<T>::isNull() const
{
return w == 0 && h == 0 && ch == 0;
}
template<typename T>
Img<T>& Img<T>::setNull()
{
if (!sharedData && data != nullptr) {
delete[] data;
data = nullptr;
}
w = 0; h = 0; ch = 0; alphaChannel = -1; sharedData = false;
return *this;
}
template<typename T>
const Img<T> Img<T>::nullImage() {
return Img();
}
template<typename T>
Img<T>& Img<T>::clear()
{
std::memset(data, 0, ch*w*h*getBytesPerChannel());
return *this;
}
template<typename T>
Img<T>& Img<T>::fill(const Color<T> &color)
{
assert(ch == color.ch);
fora(y,0,h) fora(x,0,w) fora(c,0,ch) {
operator()(x,y,c) = color(c);
}
return *this;
}
template<typename T>
Img<T>& Img<T>::fill(const T &value)
{
int i = 0;
while (i<w*h*ch) data[i++] = value;
return *this;
}
template<typename T>
template<typename U>
Img<U> Img<T>::cast() const
{
Img<U> img(w, h, ch, alphaChannel);
fora(y, 0, h) fora(x, 0, w) fora(c, 0, ch) img(x,y,c) = (U)operator()(x,y,c);
return img;
}
template<typename T>
Img<T> Img<T>::cast() const
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::cast: Conversion between the same types, doing just deep copy" << std::endl;);
return deepCopy();
}
template<typename T>
template<typename U>
Img<T>& Img<T>::cast(const Img<U> &img)
{
if (isNull()) initImage(img, false);
assert(img.w == w && img.h == h && img.ch == ch);
fora(y, 0, h) fora(x, 0, w) fora(c, 0, ch) operator()(x,y,c) = (T)img(x,y,c);
return *this;
}
template<typename T>
Img<T>& Img<T>::cast(const Img<T> &img)
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::cast: Conversion between the same types, doing just deep copy" << std::endl;);
deepCopy(img);
return *this;
}
template<typename T>
template<typename U>
Img<U> Img<T>::castAndConvert() const
{
Img<U> img(w, h, ch, alphaChannel);
fora(y, 0, h) fora(x, 0, w) fora(c, 0, ch) img(x,y,c) = (U)(operator()(x,y,c)*(Img<U>::getValuesPerChannel()/(double)getValuesPerChannel()));
return img;
}
template<typename T>
Img<T> Img<T>::castAndConvert() const
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::castAndConvert: Conversion between the same types, doing just deep copy" << std::endl;);
return deepCopy();
}
template<typename T>
template<typename U>
Img<T>& Img<T>::castAndConvert(const Img<U> &img) {
if (isNull()) initImage(img, false);
assert(img.w == w && img.h == h && img.ch == ch);
fora(y, 0, h) fora(x, 0, w) fora(c, 0, ch) operator()(x,y,c) = (T)(img(x,y,c)*(getValuesPerChannel()/(double)Img<U>::getValuesPerChannel()));
return *this;
}
template<typename T>
Img<T>& Img<T>::castAndConvert(const Img<T> &img)
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::castAndConvert: Conversion between the same types, doing just deep copy" << std::endl;);
deepCopy(img);
return *this;
}
template<typename T>
template<typename U>
Img<U> Img<T>::shallowCopyCastAndConvert() const
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::shallowCopyCastAndConvert: conversion to type U=" << std::to_string(sizeof(U)) << std::endl;);
return castAndConvert<U>();
}
template<typename T>
Img<T> Img<T>::shallowCopyCastAndConvert() const
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::shallowCopyCastAndConvert: Conversion between the same types, doing just shallow copy" << std::endl;);
return shallowCopy();
}
template<typename T>
template<typename U>
Img<T>& Img<T>::shallowCopyCastAndConvert(const Img<U> &img)
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::shallowCopyCastAndConvert: conversion from type U=" << std::to_string(sizeof(U)) << std::endl;);
castAndConvert<U>(img);
return *this;
}
template<typename T>
Img<T>& Img<T>::shallowCopyCastAndConvert(const Img<T> &img)
{
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::shallowCopyCastAndConvert: Conversion between the same types, doing just shallow copy" << std::endl;);
shallowCopy(img);
return *this;
}
template<typename T>
Img<T> Img<T>::deepCopy() const
{
Img img(w, h, ch, alphaChannel);
img.deepCopy(*this);
return img;
}
template<typename T>
Img<T>& Img<T>::deepCopy(const Img &img)
{
if (isNull()) initImage(img, false);
assert(img.w == w && img.h == h && img.ch == ch);
memcpy(data, img.data, ch*w*h*getBytesPerChannel());
return *this;
}
template<typename T>
Img<T> Img<T>::shallowCopy() const
{
return Img(data, w, h, ch, alphaChannel);
}
template<typename T>
const Img<const T>& Img<T>::constShallowCopy() const
{
return Img<const T>((const T*)data, w, h, ch, alphaChannel);
}
template<typename T>
Img<T>& Img<T>::shallowCopy(const Img &img)
{
if (isNull()) initImage(img, true);
assert(img.w == w && img.h == h && img.ch == ch);
if (!sharedData && data != nullptr) {
DEBUG_CMD_IMG(std::cout << debugPrefix() << ": Deleting " << std::to_string(getTotalBytes()) << " bytes" << std::endl;);
delete[] data;
}
data = img.data;
sharedData = true;
return *this;
}
template<typename T>
const Img<T>& Img<T>::operator=(const Img &img)
{
if (isNull()) initImage(img, img.sharedData);
if (sharedData) {
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::operator=: shared data: shallow copy" << std::endl;);
shallowCopy(img);
} else {
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::operator=: data not shared: deep copy" << std::endl;);
deepCopy(img);
}
return *this;
}
//template<typename T>
//Img<T>& Img<T>::operator=(Img &&img)
//{
// if(this != &other) { // no self assignment
// delete[] mArray; // delete this storage
// mArray = std::exchange(other.mArray, nullptr); // leave moved-from in valid state
// size = std::exchange(other.size, 0);
// }
// return *this;
//}
template<typename T>
const T& Img<T>::at(int x, int y, int channel) const
{
assert(channel >= 0 && channel < ch);
if (!(x >= 0 && x < w && y >= 0 && y < h)) throw(std::range_error(std::string("x:"+std::to_string(x)+" w:"+std::to_string(w))+" y:"+std::to_string(y)+" h:"+std::to_string(h)));
return data[ch*(y*w+x)+channel];
}
template<typename T>
T& Img<T>::at(int x, int y, int channel)
{
return const_cast<T&>(static_cast<const Img<T>&>(*this).at(x,y,channel));
}
template<typename T>
T Img<T>::sampleBilinearAt(double x, double y, int channel) const
{
int fx = floor(x), fy = floor(y);
const T& I0 = at(fx,fy,channel);
const T& I1 = at(fx+1,fy,channel);
const T& I2 = at(fx,fy+1,channel);
const T& I3 = at(fx+1,fy+1,channel);
return bilinearInterpolation(I0,I1,I2,I3,x-fx,y-fy);
}
template<typename T>
T Img<T>::sampleBilinear(double x, double y, int channel) const
{
int fx = floor(x), fy = floor(y);
const T& I0 = operator()(fx,fy,channel);
const T& I1 = operator()(fx+1,fy,channel);
const T& I2 = operator()(fx,fy+1,channel);
const T& I3 = operator()(fx+1,fy+1,channel);
return bilinearInterpolation(I0,I1,I2,I3,x-fx,y-fy);
}
template<typename T>
T Img<T>::sampleBilinear(double x, double y, int channel, BoundaryHandling bndHandling) const
{
int fx = floor(x), fy = floor(y);
const T& I0 = operator()(fx, fy, channel, bndHandling);
const T& I1 = operator()(fx+1, fy, channel, bndHandling);
const T& I2 = operator()(fx, fy+1, channel, bndHandling);
const T& I3 = operator()(fx+1, fy+1, channel, bndHandling);
return bilinearInterpolation(I0,I1,I2,I3,x-fx,y-fy);
}
template<typename T>
T Img<T>::sampleNearest(double x, double y, int channel) const
{
return operator()(round(x), round(y), channel);
}
template<typename T>
T Img<T>::sampleNearest(double x, double y, int channel, BoundaryHandling bndHandling) const
{
return operator()(round(x), round(y), channel, bndHandling);
}
template<typename T>
T Img<T>::sample(double x, double y, int channel, BoundaryHandling bndHandling, Sampling sampling) const
{
switch (sampling) {
case bilinear: return sampleBilinear(x, y, channel, bndHandling); break;
case nearest: return sampleNearest(x, y, channel, bndHandling); break;
default: return operator()(x, y, channel, bndHandling); break;
}
}
template<typename T>
Color<T> Img<T>::samplePixel(double x, double y, BoundaryHandling bndHandling, Sampling sampling) const
{
Color<T> color(ch);
switch (sampling) {
case bilinear: fora(i, 0, ch) color(i) = sampleBilinear(x, y, i, bndHandling); break;
case nearest: fora(i, 0, ch) color(i) = sampleNearest(x, y, i, bndHandling); break;
default: fora(i, 0, ch) color(i) = operator()(x, y, i, bndHandling); break;
}
return color;
}
template<typename T>
inline const T& Img<T>::operator()(int x, int y, int channel) const
{
return data[ch*(y*w+x)+channel];
}
template<typename T>
inline T& Img<T>::operator()(int x, int y, int channel)
{
return const_cast<T&>(static_cast<const Img<T>&>(*this)(x,y,channel));
}
template<typename T>
inline const T& Img<T>::operator()(int x, int y, int channel, BoundaryHandling bndHandling) const
{
switch (bndHandling) {
case reflect:
/* w-1-(x-(w-1)) */ /* h-1-(y-(h-1)) */
return operator()(x<0 ? -x : (x>w-1 ? 2*(w-1)-x : x), y<0 ? -y : (y>h-1 ? 2*(h-1)-y : y), channel);
break;
case clip:
default:
return operator()(x<0 ? 0 : (x>w-1 ? w-1 : x), y<0 ? 0 : (y>h-1 ? h-1 : y), channel);
break;
case none:
return operator()(x, y, channel);
break;
}
}
template<typename T>
inline T& Img<T>::operator()(int x, int y, int channel, BoundaryHandling bndHandling)
{
return const_cast<T&>(static_cast<const Img<T>&>(*this)(x,y,channel,bndHandling));
}
template<typename T>
inline const T& Img<T>::operator()(int index, int channel) const
{
return data[ch*index+channel];
}
template<typename T>
inline T& Img<T>::operator()(int index, int channel)
{
return const_cast<T&>(static_cast<const Img<T>&>(*this)(index,channel));
}
template<typename T>
inline const T& Img<T>::alpha(int x, int y) const
{
assert(alphaChannel != -1);
return data[ch*(y*w+x)+alphaChannel];
}
template<typename T>
inline T& Img<T>::alpha(int x, int y)
{
return const_cast<T&>(static_cast<const Img<T>&>(*this)(x,y,alphaChannel));
}
//template<typename T>
//inline const Color<T>& Img<T>::getPixel(int x, int y) const
//{
// return dataC[y*w+x];
//}
//template<typename T>
//inline Color<T>& Img<T>::getPixel(int x, int y)
//{
// return const_cast<Color<T>&>(static_cast<const Img<T>&>(*this).getPixel(x,y));
//}
template<typename T>
inline const Color<T> Img<T>::getPixel(int x, int y) const
{
return Color<T>(ch, &data[ch*(y*w+x)]);
}
// The result of this method is a shared color because move constructor is used.
template<typename T>
inline Color<T> Img<T>::getPixel(int x, int y)
{
return Color<T>(ch, &operator()(x,y,0));
}
//template<typename T>
//template<typename COLOR>
//inline const COLOR& Img<T>::getPixel(int x, int y) const
//{
// return (reinterpret_cast<COLOR*>(data))[y*w+x];
//}
//template<typename T>
//template<typename COLOR>
//inline COLOR& Img<T>::getPixel(int x, int y)
//{
// return const_cast<COLOR&>(static_cast<const Img<T>&>(*this).getPixel<COLOR>(x,y));
//}
template<typename T>
int Img<T>::getBytesPerChannel()
{
return sizeof(T);
}
template<typename T>
int Img<T>::getMaxValuesPerChannel()
{
return pow(2,sizeof(T)*8);
}
template<typename T>
int Img<T>::getValuesPerChannel() const
{
return valuesPerChannel > 0 ? valuesPerChannel : getMaxValuesPerChannel();
}
template<typename T>
void Img<T>::setValuesPerChannel(int val)
{
valuesPerChannel = val;
}
template<typename T>
int Img<T>::getTotalBytes()
{
return ch*w*h*getBytesPerChannel();
}
template<typename T>
int Img<T>::wh() const
{
return w*h;
}
template<typename T>
int Img<T>::whch() const
{
return w*h*ch;
}
template<typename T>
template<typename U>
Img<T>& Img<T>::initImage(const Img<U> &fromImg, bool sharedData)
{
w = fromImg.w;
h = fromImg.h;
ch = fromImg.ch;
alphaChannel = fromImg.alphaChannel;
this->sharedData = sharedData;
if (!sharedData) {
if (data != nullptr) delete[] data;
data = new T[ch*w*h];
clear();
}
updateColorData();
DEBUG_CMD_IMG(std::cout << debugPrefix() << "::initImage: w: " << w << ", h: " << h << ", ch: " << ch << ", alphaChannel: " << alphaChannel << ", sharedData: " << sharedData << std::endl;);
return *this;
}
template<typename T>
Img<T>& Img<T>::multiplyByAlpha()
{
fora(y, 0, h) fora(x, 0, w) {
double alpha = operator()(x,y,alphaChannel)/(double)(getValuesPerChannel()-1);
fora(c, 0, ch) {
if (c == alphaChannel) continue;
operator()(x,y,c) = operator()(x,y,c)*alpha;
}
}
return *this;
}
template<typename T>
Img<T>& Img<T>::divideByAlpha()
{
fora(y, 0, h) fora(x, 0, w) {
double alpha = operator()(x,y,alphaChannel)/(double)(getValuesPerChannel()-1);
if (alpha > 0) fora(c, 0, ch) {
if (c == alphaChannel) continue;
operator()(x,y,c) = operator()(x,y,c)/alpha;
}
}
return *this;
}
template<typename T>
Img<T> Img<T>::getChannel(int channel, int alphaChannel) const
{
assert(channel >= 0 && channel < ch);
Img img(w, h, 1, alphaChannel);
fora(i, 0, w*h) img(i,0) = operator()(i,channel);
return img;
}
template<typename T>
Img<T> Img<T>::getChannels(std::vector<int> channels, int alphaChannel) const
{
forlist(i, channels) assert(channels[i] >= 0 && channels[i] <= ch);
Img out(w, h, channels.size(), alphaChannel);
fora(y,0,h) fora(x,0,w) {
int c = 0;
forlist(i, channels) {
out(x,y,c) = operator()(x,y,channels[i]);
c++;
}
}
return out;
}
template<typename T>
Img<T> Img<T>::cloneChannels(int nChannelsFactor, int alphaChannel) const
{
Img out(w, h, nChannelsFactor, alphaChannel);
fora(y, 0, h) fora(x, 0, w) fora(c1, 0, ch) fora(c2, 0, nChannelsFactor) out(x,y,c2) = operator()(x,y,c1);
return out;
}
template<typename T>
Img<T>& Img<T>::replaceChannels(const Img &inImg, std::vector<int> inImgChannels, std::vector<int> thisImgChannels)
{
assert(inImgChannels.size() == thisImgChannels.size());
forlist(i, inImgChannels) assert(inImgChannels[i] >= 0 && inImgChannels[i] <= inImg.ch);
forlist(i, thisImgChannels) assert(thisImgChannels[i] >= 0 && thisImgChannels[i] <= ch);
fora(y,0,h) fora(x,0,w) {
forlist(i, inImgChannels) {
operator()(x,y,thisImgChannels[i]) = inImg(x,y,inImgChannels[i]);
}
}
return *this;
}
template<typename T>
Img<T>& Img<T>::swapChannels(int ch1, int ch2)
{
fora(y, 0, h) fora(x, 0, w) {
std::swap(operator()(x, y, ch1), operator()(x, y, ch2));
}
return *this;
}
template<typename T>
Img<T> Img<T>::getAlphaChannel() const
{
return getChannel(alphaChannel, alphaChannel);
}
template<typename T>
Img<T>& Img<T>::replaceAlpha(const Img<T> &alpha)
{
assert(w == alpha.w && h == alpha.h && alpha.ch == 1);
fora(i, 0, w*h) operator()(i,alphaChannel) = alpha(i,0);
return *this;
}
template<typename T>
void Img<T>::getBoundingBox(int &x1, int &y1, int &x2, int &y2, int channel, int minVal, int maxVal) const
{
x1 = w-1; y1 = h-1; x2 = 0; y2 = 0;
fora(y, 0, h) fora(x, 0, w) {
const T& c = operator()(x, y, channel);
if (c >= minVal && c <= maxVal) {
if (x < x1) x1 = x;
if (y < y1) y1 = y;
if (x > x2) x2 = x;
if (y > y2) y2 = y;
}
}
}
template<typename T>
Img<T> Img<T>::crop(int x1, int y1, int x2, int y2, int &modX1, int &modY1, int &modX2, int &modY2) const
{
assert(x2 >= x1 && y2 >= y1);
modX1 = x1 < 0 ? 0 : (x1 > this->w ? this->w-1 : x1);
modY1 = y1 < 0 ? 0 : (y1 > this->h ? this->h-1 : y1);
modX2 = x2 < 0 ? 0 : (x2 > this->w-1 ? this->w-1 : x2);
modY2 = y2 < 0 ? 0 : (y2 > this->h-1 ? this->h-1 : y2);
int w = modX2-modX1+1, h = modY2-modY1+1;
return crop(w, h, modX1, modY1);
}
template<typename T>
Img<T> Img<T>::crop(int w, int h, int shiftX, int shiftY) const
{
assert(w <= this->w && h <= this->h && shiftX >= 0 && shiftX+w <= this->w && shiftY >= 0 && shiftY+h <= this->h);
Img img(w, h, ch, alphaChannel);
fora(y, 0, h) fora(x, 0, w) fora(c, 0, ch) {
img(x,y,c) = operator()(x+shiftX,y+shiftY,c);
}
return img;
}
template<typename T>
Img<T> Img<T>::resize(int w, int h, int shiftX, int shiftY, const Color<T> &color) const
{
assert(w >= 0 && h >= 0);
// no resize - return a copy
if (w == this->w && h == this->h && shiftX == 0 && shiftY == 0) return deepCopy();
// resize
Img img(w, h, ch, alphaChannel);
fora(y, 0, h) fora(x, 0, w) fora(c, 0, ch) {
if (x-shiftX >= 0 && y-shiftY >= 0 && x-shiftX < this->w && y-shiftY < this->h) {
img(x,y,c) = operator()(x-shiftX,y-shiftY,c);
} else {
// fill new areas with specified color
if (c < color.ch) img(x,y,c) = color(c);
else img(x,y,c) = color(0); // if color does not specify all channels, use colors(0) for the rest
}
}
return img;
}
template<typename T>
Img<T> Img<T>::resize(int w, int h, int shiftX, int shiftY) const
{
return resize(w, h, shiftX, shiftY, Color<T>({0}));
}
template<typename T>
Img<T>& Img<T>::blendWithInPlace(const Img<T> &topImg)
{
assert(w == topImg.w && h == topImg.h && ch == topImg.ch && alphaChannel == topImg.alphaChannel);
double maxVal = getValuesPerChannel();
fora(y, 0, h) fora(x, 0, w) {
double topAlpha = topImg(x,y,topImg.alphaChannel) / maxVal;
double bottomAlpha = operator()(x,y,alphaChannel) / maxVal;
fora(c, 0, ch) {
if (c == alphaChannel) continue;
const T& top = topImg(x,y,c);
const T& bottom = operator()(x,y,c);
operator()(x,y,c) = alphaBlending(bottom, top, topAlpha);
}
operator()(x,y,alphaChannel) = alphaBlending(bottomAlpha, topAlpha, topAlpha) * maxVal;
}
return *this;
}
template<typename T>
inline float Img<T>::gauss(float x, float sigma) {
const float pi = 3.14159265358979323846;
return 1.0 / (sigma * sqrtf(2 * pi)) * expf(-(x*x) / (2*(sigma*sigma)));
}
template<typename T>
std::vector<float> Img<T>::genGaussKernel(float sigma)
{
const int M = 3 * ceil(sigma);
std::vector<float> K(M+1);
float sum = 0;
fora(i, 0, M+1) {
K[i] = gauss(i, sigma);
sum += i>0 ? 2*K[i] : K[i];
}
fora(i, 0, M+1) K[i] /= sum;
return K;
}
template<typename T>
Img<float> Img<T>::conv1D(const std::vector<float> &K, BoundaryHandling bndHandling)
{
Img<float> imgOut; imgOut.initImage(*this, false);
const int M = K.size()-1;
#pragma omp parallel for
fora(j, 0, h) fora(i, 0, w) {
fora(c, 0, ch) imgOut(i,j,c) += K[0] * operator()(i,j,c);
fora(k, i+1, i+M+1) {
fora(c, 0, ch) {
const T& i1 = operator()(k,j,c,bndHandling);
const T& i2 = operator()(2*i-k,j,c,bndHandling);
imgOut(i,j,c) += K[k-i] * (i1 + i2);
}
}
}
return imgOut;
}
template<typename T>
Img<T>& Img<T>::blur(float sigma)
{
if (sigma > 0) {
// generate kernel
const std::vector<float> &K = genGaussKernel(sigma);
// using separability property
Img<float> convx = transpose().conv1D(K);
Img<float> convxy = convx.transpose().conv1D(K).clamp(0.f, (float)(getValuesPerChannel()-1));
cast(convxy);
}
return *this;
}
template<typename T>
Img<T>& Img<T>::invert(T maxVal)
{
fora(y,0,h) fora(x,0,w) fora(c,0,ch) {
if (c == alphaChannel) continue;
operator()(x,y,c) = maxVal-operator()(x,y,c);
}
return *this;
}
template<typename T>
Img<T> Img<T>::transpose() const
{
Img out(h, w, ch, alphaChannel);
fora(y,0,h) fora(x,0,w) fora(c,0,ch) {
out(y,x,c) = operator()(x,y,c);
}
return out;
}
template<typename T>
Img<T>& Img<T>::clamp(T min, T max)
{
fora(y,0,h) fora(x,0,w) fora(c,0,ch) {
operator()(x,y,c) = std::max(min, std::min(operator()(x,y,c), max));
}
return *this;
}
template<typename T>
bool Img<T>::equalData(const Img<T> &img) const
{
if (w != img.w || h != img.h || ch != img.ch) return false;
const int n = ch*w*h;
fora(i, 0, n) if (data[i] != img.data[i]) return false;
return true;
}
template<typename T>
bool Img<T>::equalDimension(const Img<T> &img) const
{
if (w != img.w || h != img.h || ch != img.ch) return false;
return true;
}
template<typename T>
void Img<T>::computeCentroid(double &cx, double &cy, T threshold)
{
cx = 0; cy = 0;
int countX = 0, countY = 0;
fora(y,0,h) fora(x,0,w) {
if (operator()(x,y,alphaChannel) > threshold) {
cx += x; cy += y;
countX++; countY++;
}
}
cx /= countX; cy /= countY;
}
template<typename T>
Img<T> Img<T>::warp(const Img<T> &img, const Img<float> &Dx, const Img<float> &Dy, BoundaryHandling bndHandling, Sampling sampling)
{
assert(img.w == Dx.w && img.h == Dx.h);
assert(img.w == Dy.w && img.h == Dy.h);
assert(Dx.ch == 1 && Dy.ch == 1);
Img out(img.w, img.h, img.ch, img.alphaChannel);
fora(y,0,img.h) fora(x,0,img.w) fora(c,0,img.ch) {
float xPos = x + Dx(x,y,0);
float yPos = y + Dy(x,y,0);
out(x,y,c) = img.sample(xPos, yPos, c, bndHandling, sampling);
}
return out;
}
template<typename T>
Img<T> Img<T>::warp(const Img<float> &Dx, const Img<float> &Dy, BoundaryHandling bndHandling, Sampling sampling)
{
return warp(*this, Dx, Dy, bndHandling, sampling);
}
template<typename T>
void Img<T>::getColorsUsage(const Img &img, std::vector<Color<T>> &colors, std::vector<int> &count, const Img &alphaChannel)
{
using namespace std;
map<Color<T>,int> usageMap;
fora(y,0,img.h) fora(x,0,img.w) {
if (!alphaChannel.isNull() && alphaChannel(x,y,0) == 0) continue;
Color<T> color = img.getPixel(x,y);
usageMap[color]++;
}
vector<pair<Color<T>,int>> usage;
usage.insert(usage.end(), usageMap.begin(), usageMap.end());
sort(usage.begin(), usage.end(), [](const auto &l, const auto &r) {
return l.second > r.second;
});
colors.resize(usage.size());
count.resize(usage.size());
forlist(i, usage) {
colors[i] = usage[i].first;
count[i] = usage[i].second;
}
}
template<typename T>
void Img<T>::getColorsUsage(std::vector<Color<T>> &colors, std::vector<int> &count, const Img &alphaChannel)
{
getColorsUsage(*this, colors, count, alphaChannel);
}
template<typename T>
void Img<T>::getColorsUsage(const Img &img, std::vector<Color<T>> &colors, std::vector<int> &count)
{
getColorsUsage(img, colors, count, Img());
}
template<typename T>
void Img<T>::getColorsUsage(std::vector<Color<T>> &colors, std::vector<int> &count)
{
getColorsUsage(*this, colors, count);
}
template<typename T>
void Img<T>::reduceColors(const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold)
{
return reduceColors(*this, colors, count, threshold);
}
template<typename T>
void Img<T>::reduceColors(const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold, int &maxColors)
{
return reduceColors(*this, colors, count, threshold, maxColors);
}
template<typename T>
void Img<T>::reduceColors(Img &img, const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold)
{
int maxColors;
reduceColors(img, colors, count, threshold, maxColors);
}
template<typename T>
void Img<T>::reduceColors(Img &img, const std::vector<Color<T>> &colors, const std::vector<int> &count, double threshold, int &maxColors)
{
using namespace std;
int total = 0;
maxColors = 0;
forlist(i, count) total += count[i];
forlist(i, count) {
double r = count[i]/(double)total;
if (r < threshold) {
maxColors = i;
break;
}
}
reduceColors(img, colors, count, maxColors);
}
template<typename T>
void Img<T>::reduceColors(const std::vector<Color<T>> &colors, const std::vector<int> &count, int maxColors)
{
return reduceColors(*this, colors, count, maxColors);
}
template<typename T>
void Img<T>::reduceColors(Img &img, const std::vector<Color<T>> &colors, const std::vector<int> &count, int maxColors)
{
using namespace std;
map<Color<T>,Color<T>> replacement;
forlist(i, count) {
const Color<T> &c1 = colors[i];
Color<float> c1YUV; c1YUV.initColor(c1); RGBtoYUV(c1, c1YUV);
if (i >= maxColors) {
// for the current color, find the most similar color from ones that are allowed to be used
double min = numeric_limits<double>::infinity();
int id = -1;
forlist(j, colors) {
const Color<T> &c2 = colors[j];
Color<float> c2YUV; c2YUV.initColor(c2); RGBtoYUV(c2, c2YUV);
if (j >= maxColors) break;
double dist = 0;
fora(i, 0, c1.ch) dist += (c1YUV(i)-c2YUV(i)) * (c1YUV(i)-c2YUV(i));
if (min > dist) { min = dist; id = j; }
}
replacement[colors[i]] = colors[id];
}
}
replaceColors(img, replacement);
}
template<typename T>
void Img<T>::replaceColors(Img &img, const std::map<const Color<T>, Color<T> > &replacement)
{
fora(y,0,img.h) fora(x,0,img.w) {
if (img.alphaChannel > -1 && img(x,y,img.alphaChannel) == 0) continue;
Color<T> p = img.getPixel(x,y);
const Color<T> &q = replacement.begin()->first;
const int n = std::min(p.ch, q.ch);
const auto &itQ = replacement.find(p.head(n));
if (itQ != replacement.end()) {
Color<T> q = itQ->second;
const int n = std::min(p.ch, q.ch);
p.head(n) = q.head(n);
}
}
}
template<typename T>
void Img<T>::replaceColors(const std::map<const Color<T>, Color<T> > &replacement)
{
replaceColors(*this, replacement);
}
template<typename T>
void Img<T>::minMax(std::vector<T> &min, std::vector<T> &max) const
{
min.resize(ch);
max.resize(ch);
fora(c, 0, ch) {
min[c] = std::numeric_limits<T>::max();
max[c] = std::numeric_limits<T>::min();
}
fora(i, 0, wh()) {
fora(c, 0, ch) {
const float &val = operator()(i,c);
if (val < min[c]) min[c] = val;
if (val > max[c]) max[c] = val;
}
}
}
// incorrect
template<typename T>
Img<T> Img<T>::subsample(int subsampleFactor, Sampling sampling) const
{
Img<T> out(w/subsampleFactor,h/subsampleFactor,ch,alphaChannel);
fora(y, 0, out.h) fora(x, 0, out.w) fora(c, 0, ch) {
out(x,y,c) = sample(x*subsampleFactor, y*subsampleFactor, c, none, sampling);
}
return out;
}
template<typename T>
bool Img<T>::checkBounds(int x, int y, int c) const
{
return x >= 0 && y >= 0 && x < w && y < h && c >= 0 && c < ch;
}
template<typename T>
void Img<T>::updateColorData()
{
// if (dataC != nullptr) delete[] dataC;
// class Test {
//// unsigned char data[1];
// unsigned char *t;
// char a;
//// int a;
// };
// Test test;
// dataC = new Color<T>[w*h];
//// dataC = (Color<Tstd::malloc(w*h*sizeof(Color<T>));
// std::cout << sizeof(Color<T>) << std::endl;
// std::cout << sizeof(Test) << std::endl;
// fora(y,0,h) fora(x,0,w) {
// Color<T> &c = dataC[y*w+x];
// c.ch = ch;
// c.sharedData = true;
// c.data = &operator()(x,y,0);
// }
}
template<typename T>
std::string Img<T>::debugPrefix()
{
return std::string("Img<T=") + std::to_string(sizeof(T)) + ">";
}
template<typename T>
T Img<T>::bilinearInterpolation(T I0, T I1, T I2, T I3, double dx, double dy) {
return (I0 * (1.0 - dx) + I1 * dx) * (1.0 - dy) + (I2 * (1.0 - dx) + I3 * dx) * dy;
}
template<typename T>
double Img<T>::alphaBlending(double A, double B, double BAlpha)
{
return B + A*(1.0-BAlpha);
}
template<typename T>
std::ostream& operator<<(std::ostream &os, const Img<T> &img)
{
os << std::string("Img<T=") + std::to_string(sizeof(T)) + ">" << ": w: " << img.w << ", h: " << img.h << ", ch: " << img.ch << ", alphaChannel: " << img.alphaChannel << ", sharedData: " << img.sharedData;
return os;
}
template<typename T>
inline bool operator==(const Img<T> &I1, const Img<T> &I2)
{
if (I1.alphaChannel != I2.alphaChannel || I1.sharedData != I2.sharedData) return false;
return I1.equalData(I2);
}
template<typename T>
inline Img<T>& Img<T>::operator+=(const T &t)
{
fora(i, 0, w*h*ch) data[i] += t;
return *this;
}
template<typename T>
template<typename U>
inline Img<T>& Img<T>::operator-=(const U &t)
{
fora(i, 0, w*h*ch) data[i] -= t;
return *this;
}
template<typename T>
inline Img<T>& Img<T>::operator*=(const T &t)
{
fora(i, 0, w*h*ch) data[i] *= t;
return *this;
}
template<typename T>
inline Img<T>& Img<T>::operator/=(const T &t)
{
fora(i, 0, w*h*ch) data[i] /= t;
return *this;
}
template<typename T>
inline Img<T>& Img<T>::operator+=(const Img<T> &rhs)
{
assert(w == rhs.w && h == rhs.h && ch == rhs.ch);
fora(i, 0, w*h*ch) data[i] += rhs.data[i];
return *this;
}
template<typename T>
inline Img<T>& Img<T>::operator-=(const Img<T> &rhs)
{
assert(w == rhs.w && h == rhs.h && ch == rhs.ch);
fora(i, 0, w*h*ch) data[i] -= rhs.data[i];
return *this;
}
template<typename T>
inline Img<T>& Img<T>::operator*=(const Img<T> &rhs)
{
assert(w == rhs.w && h == rhs.h && ch == rhs.ch);
fora(i, 0, w*h*ch) data[i] *= rhs.data[i];
return *this;
}
template<typename T>
inline Img<T>& Img<T>::operator/=(const Img<T> &rhs)
{
assert(w == rhs.w && h == rhs.h && ch == rhs.ch);
fora(i, 0, w*h*ch) data[i] /= rhs.data[i];
return *this;
}
template<typename T>
inline Img<T> operator+(const Img<T> &lhs, const Img<T> &rhs)
{
Img<T> out = lhs.deepCopy();
out += rhs;
return out;
}
template<typename T>
inline Img<T> operator-(const Img<T> &lhs, const Img<T> &rhs)
{
Img<T> out = lhs.deepCopy();
out -= rhs;
return out;
}
template<typename T>
inline Img<T> operator*(const Img<T> &lhs, const Img<T> &rhs)
{
Img<T> out = lhs.deepCopy();
out *= rhs;
return out;
}
template<typename T>
inline Img<T> operator/(const Img<T> &lhs, const Img<T> &rhs)
{
Img<T> out = lhs.deepCopy();
out /= rhs;
return out;
}
template<typename T>
inline Img<T> operator+(const Img<T> &lhs, const T &c)
{
Img<T> out = lhs.deepCopy();
out += c;
return out;
}
template<typename T,typename U>
inline Img<T> operator-(const Img<T> &lhs, const U &c)
{
Img<T> out = lhs.deepCopy();
out -= c;
return out;
}
template<typename T>
inline Img<T> operator-(const T &c, const Img<T> &rhs)
{
Img<T> out = rhs.deepCopy();
fora(i, 0, out.w*out.h*out.ch) out.data[i] = c-out.data[i];
return out;
}
template<typename T,typename U>
inline Img<T> operator*(const Img<T> &lhs, const U &c)
{
Img<T> out = lhs.deepCopy();
out *= c;
return out;
}
template<typename T,typename U>
inline Img<T> operator/(const Img<T> &lhs, const U &c)
{
Img<T> out = lhs.deepCopy();
out /= c;
return out;
}
// other functions
template<typename T,typename U>
inline void RGBtoYUV(const Color<T> &in, Color<U> &out)
{
assert((in.ch == 3 || in.ch == 4) && out.ch == in.ch);
const U& c0 = in(0);
const U& c1 = in(1);
const U& c2 = in(2);
out(0) = 0.299 * c0 + 0.587 * c1 + 0.114 * c2;
out(1) = -0.147 * c0 + -0.289 * c1 + 0.436 * c2;
out(2) = 0.615 * c0 + -0.515 * c1 + -0.100 * c2;
}
template<typename T,typename U>
inline void YUVtoRGB(const Color<T> &in, Color<U> &out)
{
assert((in.ch == 3 || in.ch == 4) && out.ch == in.ch);
const U& c0 = in(0);
const U& c1 = in(1);
const U& c2 = in(2);
out(0) = 1.0 * c0 + 0.0 * c1 + 1.137 * c2;
out(1) = 1.0 * c0 + -0.397 * c1 + -0.580 * c2;
out(2) = 1.0 * c0 + 2.034 * c1 + 0.0 * c2;
}
template<typename T,typename U>
void RGBtoYUV(const Img<T> &in, Img<U> &out)
{
assert(in.w == out.w && in.h == out.h);
fora(y,0,in.h) fora(x,0,in.w) {
Color<T> cIn = in.getPixel(x,y);
Color<U> cOut = out.getPixel(x,y);
RGBtoYUV(cIn, cOut);
}
}
template<typename T,typename U>
void YUVtoRGB(const Img<T> &in, Img<U> &out)
{
assert(in.w == out.w && in.h == out.h);
fora(y,0,in.h) fora(x,0,in.w) {
Color<T> cIn = in.getPixel(x,y);
Color<U> cOut = out.getPixel(x,y);
YUVtoRGB(cIn, cOut);
}
}
#endif // IMAGE_H
|
GB_binop__eq_uint32.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__eq_uint32
// A.*B function (eWiseMult): GB_AemultB__eq_uint32
// A*D function (colscale): GB_AxD__eq_uint32
// D*A function (rowscale): GB_DxB__eq_uint32
// C+=B function (dense accum): GB_Cdense_accumB__eq_uint32
// C+=b function (dense accum): GB_Cdense_accumb__eq_uint32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__eq_uint32
// C=scalar+B GB_bind1st__eq_uint32
// C=scalar+B' GB_bind1st_tran__eq_uint32
// C=A+scalar GB_bind2nd__eq_uint32
// C=A'+scalar GB_bind2nd_tran__eq_uint32
// C type: bool
// A type: uint32_t
// B,b type: uint32_t
// BinaryOp: cij = (aij == bij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint32_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
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) \
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_UINT32 || GxB_NO_EQ_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (none)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__eq_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__eq_uint32
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *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_uint32
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// get the scalar b for C += b, of type uint32_t
uint32_t bwork = (*((uint32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__eq_uint32
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *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_uint32
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *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
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__eq_uint32
(
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__eq_uint32
(
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__eq_uint32
(
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
bool *Cx = (bool *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint32_t bij = Bx [p] ;
Cx [p] = (x == bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__eq_uint32
(
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 ;
bool *Cx = (bool *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint32_t aij = Ax [p] ;
Cx [p] = (aij == y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = (x == aij) ; \
}
GrB_Info GB_bind1st_tran__eq_uint32
(
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 \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#define GB_PHASE_2_OF_2
#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 typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = (aij == y) ; \
}
GrB_Info GB_bind2nd_tran__eq_uint32
(
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
uint32_t y = (*((const uint32_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
blake2bp.c
|
/*
BLAKE2 reference source code package - reference C implementations
Copyright 2012, Samuel Neves <[email protected]>. You may use this under the
terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at
your option. The terms of these licenses can be found at:
- CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
- OpenSSL license : https://www.openssl.org/source/license.html
- Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
More information about the BLAKE2 hash function can be found at
https://blake2.net.
*/
#include <u.h>
#include <libc.h>
#include "blake2.h"
#include "blake2-impl.h"
#define PARALLELISM_DEGREE 4
/*
blake2b_init_param defaults to setting the expecting output length
from the digest_length parameter block field.
In some cases, however, we do not want this, as the output length
of these instances is given by inner_length instead.
*/
static int blake2bp_init_leaf_param( blake2b_state *S, const blake2b_param *P )
{
int err = blake2b_init_param(S, P);
S->outlen = P->inner_length;
return err;
}
static int blake2bp_init_leaf( blake2b_state *S, u64int outlen, u64int keylen, u64int offset )
{
blake2b_param P[1];
P->digest_length = (u8int)outlen;
P->key_length = (u8int)keylen;
P->fanout = PARALLELISM_DEGREE;
P->depth = 2;
store32( &P->leaf_length, 0 );
store32( &P->node_offset, offset );
store32( &P->xof_length, 0 );
P->node_depth = 0;
P->inner_length = BLAKE2B_OUTBYTES;
memset( P->reserved, 0, sizeof( P->reserved ) );
memset( P->salt, 0, sizeof( P->salt ) );
memset( P->personal, 0, sizeof( P->personal ) );
return blake2bp_init_leaf_param( S, P );
}
static int blake2bp_init_root( blake2b_state *S, u64int outlen, u64int keylen )
{
blake2b_param P[1];
P->digest_length = (u8int)outlen;
P->key_length = (u8int)keylen;
P->fanout = PARALLELISM_DEGREE;
P->depth = 2;
store32( &P->leaf_length, 0 );
store32( &P->node_offset, 0 );
store32( &P->xof_length, 0 );
P->node_depth = 1;
P->inner_length = BLAKE2B_OUTBYTES;
memset( P->reserved, 0, sizeof( P->reserved ) );
memset( P->salt, 0, sizeof( P->salt ) );
memset( P->personal, 0, sizeof( P->personal ) );
return blake2b_init_param( S, P );
}
int blake2bp_init( blake2bp_state *S, u64int outlen )
{
u64int i;
if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1;
memset( S->buf, 0, sizeof( S->buf ) );
S->buflen = 0;
S->outlen = outlen;
if( blake2bp_init_root( S->R, outlen, 0 ) < 0 )
return -1;
for( i = 0; i < PARALLELISM_DEGREE; ++i )
if( blake2bp_init_leaf( S->S[i], outlen, 0, i ) < 0 ) return -1;
S->R->last_node = 1;
S->S[PARALLELISM_DEGREE - 1]->last_node = 1;
return 0;
}
int blake2bp_init_key( blake2bp_state *S, u64int outlen, const void *key, u64int keylen )
{
u64int i;
if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1;
if( !key || !keylen || keylen > BLAKE2B_KEYBYTES ) return -1;
memset( S->buf, 0, sizeof( S->buf ) );
S->buflen = 0;
S->outlen = outlen;
if( blake2bp_init_root( S->R, outlen, keylen ) < 0 )
return -1;
for( i = 0; i < PARALLELISM_DEGREE; ++i )
if( blake2bp_init_leaf( S->S[i], outlen, keylen, i ) < 0 ) return -1;
S->R->last_node = 1;
S->S[PARALLELISM_DEGREE - 1]->last_node = 1;
{
u8int block[BLAKE2B_BLOCKBYTES];
memset( block, 0, BLAKE2B_BLOCKBYTES );
memcpy( block, key, keylen );
for( i = 0; i < PARALLELISM_DEGREE; ++i )
blake2b_update( S->S[i], block, BLAKE2B_BLOCKBYTES );
memset( block, 0, BLAKE2B_BLOCKBYTES ); /* Burn the key from stack */
}
return 0;
}
int blake2bp_update( blake2bp_state *S, const void *pin, u64int inlen )
{
const unsigned char * in = (const unsigned char *)pin;
u64int left = S->buflen;
u64int fill = sizeof( S->buf ) - left;
u64int i;
if( left && inlen >= fill )
{
memcpy( S->buf + left, in, fill );
for( i = 0; i < PARALLELISM_DEGREE; ++i )
blake2b_update( S->S[i], S->buf + i * BLAKE2B_BLOCKBYTES, BLAKE2B_BLOCKBYTES );
in += fill;
inlen -= fill;
left = 0;
}
#if defined(_OPENMP)
#pragma omp parallel shared(S), num_threads(PARALLELISM_DEGREE)
#else
for( i = 0; i < PARALLELISM_DEGREE; ++i )
#endif
{
#if defined(_OPENMP)
u64int i = omp_get_thread_num();
#endif
u64int inlen__ = inlen;
const unsigned char *in__ = ( const unsigned char * )in;
in__ += i * BLAKE2B_BLOCKBYTES;
while( inlen__ >= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES )
{
blake2b_update( S->S[i], in__, BLAKE2B_BLOCKBYTES );
in__ += PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES;
inlen__ -= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES;
}
}
in += inlen - inlen % ( PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES );
inlen %= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES;
if( inlen > 0 )
memcpy( S->buf + left, in, inlen );
S->buflen = left + inlen;
return 0;
}
int blake2bp_final( blake2bp_state *S, void *out, u64int outlen )
{
u8int hash[PARALLELISM_DEGREE][BLAKE2B_OUTBYTES];
u64int i;
if(out == nil || outlen < S->outlen) {
return -1;
}
for( i = 0; i < PARALLELISM_DEGREE; ++i )
{
if( S->buflen > i * BLAKE2B_BLOCKBYTES )
{
u64int left = S->buflen - i * BLAKE2B_BLOCKBYTES;
if( left > BLAKE2B_BLOCKBYTES ) left = BLAKE2B_BLOCKBYTES;
blake2b_update( S->S[i], S->buf + i * BLAKE2B_BLOCKBYTES, left );
}
blake2b_final( S->S[i], hash[i], BLAKE2B_OUTBYTES );
}
for( i = 0; i < PARALLELISM_DEGREE; ++i )
blake2b_update( S->R, hash[i], BLAKE2B_OUTBYTES );
return blake2b_final( S->R, out, S->outlen );
}
int blake2bp( void *out, u64int outlen, const void *in, u64int inlen, const void *key, u64int keylen )
{
u8int hash[PARALLELISM_DEGREE][BLAKE2B_OUTBYTES];
blake2b_state S[PARALLELISM_DEGREE][1];
blake2b_state FS[1];
u64int i;
/* Verify parameters */
if ( nil == in && inlen > 0 ) return -1;
if ( nil == out ) return -1;
if( nil == key && keylen > 0 ) return -1;
if( !outlen || outlen > BLAKE2B_OUTBYTES ) return -1;
if( keylen > BLAKE2B_KEYBYTES ) return -1;
for( i = 0; i < PARALLELISM_DEGREE; ++i )
if( blake2bp_init_leaf( S[i], outlen, keylen, i ) < 0 ) return -1;
S[PARALLELISM_DEGREE - 1]->last_node = 1; /* mark last node */
if( keylen > 0 )
{
u8int block[BLAKE2B_BLOCKBYTES];
memset( block, 0, BLAKE2B_BLOCKBYTES );
memcpy( block, key, keylen );
for( i = 0; i < PARALLELISM_DEGREE; ++i )
blake2b_update( S[i], block, BLAKE2B_BLOCKBYTES );
memset( block, 0, BLAKE2B_BLOCKBYTES ); /* Burn the key from stack */
}
#if defined(_OPENMP)
#pragma omp parallel shared(S,hash), num_threads(PARALLELISM_DEGREE)
#else
for( i = 0; i < PARALLELISM_DEGREE; ++i )
#endif
{
#if defined(_OPENMP)
u64int i = omp_get_thread_num();
#endif
u64int inlen__ = inlen;
const unsigned char *in__ = ( const unsigned char * )in;
in__ += i * BLAKE2B_BLOCKBYTES;
while( inlen__ >= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES )
{
blake2b_update( S[i], in__, BLAKE2B_BLOCKBYTES );
in__ += PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES;
inlen__ -= PARALLELISM_DEGREE * BLAKE2B_BLOCKBYTES;
}
if( inlen__ > i * BLAKE2B_BLOCKBYTES )
{
const u64int left = inlen__ - i * BLAKE2B_BLOCKBYTES;
const u64int len = left <= BLAKE2B_BLOCKBYTES ? left : BLAKE2B_BLOCKBYTES;
blake2b_update( S[i], in__, len );
}
blake2b_final( S[i], hash[i], BLAKE2B_OUTBYTES );
}
if( blake2bp_init_root( FS, outlen, keylen ) < 0 )
return -1;
FS->last_node = 1; /* Mark as last node */
for( i = 0; i < PARALLELISM_DEGREE; ++i )
blake2b_update( FS, hash[i], BLAKE2B_OUTBYTES );
return blake2b_final( FS, out, outlen );;
}
#if defined(BLAKE2BP_SELFTEST)
#include <string.h>
#include "blake2-kat.h"
int main( void )
{
u8int key[BLAKE2B_KEYBYTES];
u8int buf[BLAKE2_KAT_LENGTH];
u64int i, step;
for( i = 0; i < BLAKE2B_KEYBYTES; ++i )
key[i] = ( u8int )i;
for( i = 0; i < BLAKE2_KAT_LENGTH; ++i )
buf[i] = ( u8int )i;
/* Test simple API */
for( i = 0; i < BLAKE2_KAT_LENGTH; ++i )
{
u8int hash[BLAKE2B_OUTBYTES];
blake2bp( hash, BLAKE2B_OUTBYTES, buf, i, key, BLAKE2B_KEYBYTES );
if( 0 != memcmp( hash, blake2bp_keyed_kat[i], BLAKE2B_OUTBYTES ) )
{
goto fail;
}
}
/* Test streaming API */
for(step = 1; step < BLAKE2B_BLOCKBYTES; ++step) {
for (i = 0; i < BLAKE2_KAT_LENGTH; ++i) {
u8int hash[BLAKE2B_OUTBYTES];
blake2bp_state S;
u8int * p = buf;
u64int mlen = i;
int err = 0;
if( (err = blake2bp_init_key(&S, BLAKE2B_OUTBYTES, key, BLAKE2B_KEYBYTES)) < 0 ) {
goto fail;
}
while (mlen >= step) {
if ( (err = blake2bp_update(&S, p, step)) < 0 ) {
goto fail;
}
mlen -= step;
p += step;
}
if ( (err = blake2bp_update(&S, p, mlen)) < 0) {
goto fail;
}
if ( (err = blake2bp_final(&S, hash, BLAKE2B_OUTBYTES)) < 0) {
goto fail;
}
if (0 != memcmp(hash, blake2bp_keyed_kat[i], BLAKE2B_OUTBYTES)) {
goto fail;
}
}
}
print("ok\n");
exits(nil);
return 0;
fail:
print("error\n");
return -1;
}
#endif
|
skein_fmt_plug.c
|
/* Skein cracker patch for JtR. Hacked together during April of 2013 by Dhiru
* Kholia <dhiru at openwall.com>.
*
* This software is Copyright (c) 2013 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_skein_256;
extern struct fmt_main fmt_skein_512;
#elif FMT_REGISTERS_H
john_register_one(&fmt_skein_256);
john_register_one(&fmt_skein_512);
#else
#include <string.h>
#include "arch.h"
#include "sph_skein.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
// OMP_SCALE tuned on core i7 quad core HT
// 256bt 512bt
// 1 - 233k 232k
// 64 - 5406k 5377k
// 128 - 6730k 6568k
// 256 - 7618k 7405k
// 512 - 8243k 8000k
// 1k - 8610k 8408k ** this level chosen
// 2k - 8804k 8610k
// 4k - 8688k 8648k
#ifndef OMP_SCALE
#ifdef __MIC__
#define OMP_SCALE 64
#else
#define OMP_SCALE 1024
#endif // __MIC__
#endif // OMP_SCALE
#endif // _OPENMP
#include "memdbg.h"
// Skein-256 or Skein-512 are the real format labels.
#define FORMAT_LABEL "Skein"
#define FORMAT_NAME ""
#define FORMAT_TAG "$skein$"
#define TAG_LENGTH (sizeof(FORMAT_TAG)-1)
#define ALGORITHM_NAME "Skein 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 125
#define BINARY_SIZE256 32
#define BINARY_SIZE512 64
#define CMP_SIZE 28 // skein224
#define SALT_SIZE 0
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define BINARY_ALIGN 4
#define SALT_ALIGN 1
static struct fmt_tests skein_256_tests[] = {
{"39CCC4554A8B31853B9DE7A1FE638A24CCE6B35A55F2431009E18780335D2621", ""},
{"$skein$39CCC4554A8B31853B9DE7A1FE638A24CCE6B35A55F2431009E18780335D2621", ""},
// john.pot uses lower case
{"$skein$39ccc4554a8b31853b9de7a1fe638a24cce6b35a55f2431009e18780335d2621", ""},
{"$skein$0977b339c3c85927071805584d5460d8f20da8389bbe97c59b1cfac291fe9527", "abc"},
{"$skein$8adf4f8a6fabd34384c661e6c0f91efe9750a18ec6c4d02bcaf05b8246a10dcc", "john"},
{"$skein$f2bf66b04f3e3e234d59f8126e52ba60baf2b0bca9aff437d87a6cf3675fe41a", "passweird"},
{NULL}
};
static struct fmt_tests skein_512_tests[] = {
{"71b7bce6fe6452227b9ced6014249e5bf9a9754c3ad618ccc4e0aae16b316cc8ca698d864307ed3e80b6ef1570812ac5272dc409b5a012df2a579102f340617a", "\xff"},
{"$skein$BC5B4C50925519C290CC634277AE3D6257212395CBA733BBAD37A4AF0FA06AF41FCA7903D06564FEA7A2D3730DBDB80C1F85562DFCC070334EA4D1D9E72CBA7A", ""},
// john.pot uses lower case
{"$skein$bc5b4c50925519c290cc634277ae3d6257212395cba733bbad37a4af0fa06af41fca7903d06564fea7a2d3730dbdb80c1f85562dfcc070334ea4d1d9e72cba7a", ""},
{"$skein$8f5dd9ec798152668e35129496b029a960c9a9b88662f7f9482f110b31f9f93893ecfb25c009baad9e46737197d5630379816a886aa05526d3a70df272d96e75", "abc"},
{"$skein$a2f4cbc67def0c97b3b47deeab86e116293db0220ad9953064d40fc4aeabf243d41040efb4e02b4b4883ae19b5c40129926cb5282ad450e1267f126de40224b7", "john"},
{"$skein$88fcd3b1d6b019c74b8853798b1fa7a1b92314748b79d4a8cf822646104b4aefedb7af721ec07bf1302df031411af55bda48d2177a69537f3e0bfb5d2fb1d656", "passweird"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_out)[BINARY_SIZE512 / sizeof(uint32_t)];
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
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);
crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt);
}
static void done(void)
{
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self, int len)
{
char *p;
p = ciphertext;
if (!strncmp(p, FORMAT_TAG, TAG_LENGTH))
p += TAG_LENGTH;
if (strlen(p) != len)
return 0;
while(*p)
if (atoi16[ARCH_INDEX(*p++)]==0x7f)
return 0;
return 1;
}
static int valid256(char *ciphertext, struct fmt_main *self)
{
return valid(ciphertext, self, 64);
}
static int valid512(char *ciphertext, struct fmt_main *self)
{
return valid(ciphertext, self, 128);
}
static char *split(char *ciphertext, int index, struct fmt_main *self)
{
static char out[TAG_LENGTH + BINARY_SIZE512*2 + 1];
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
ciphertext += TAG_LENGTH;
memcpy(out, FORMAT_TAG, TAG_LENGTH);
strnzcpylwr(out + TAG_LENGTH, ciphertext, BINARY_SIZE512*2 + 1);
return out;
}
static void *get_binary_256(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE256];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
p = strrchr(ciphertext, '$') + 1;
else
p = ciphertext;
for (i = 0; i < BINARY_SIZE256; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
static void *get_binary_512(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE512];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
p = strrchr(ciphertext, '$') + 1;
else
p = ciphertext;
for (i = 0; i < BINARY_SIZE512; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
#define COMMON_GET_HASH_VAR crypt_out
#include "common-get-hash.h"
static int crypt_256(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
sph_skein256_context ctx;
sph_skein256_init(&ctx);
sph_skein256(&ctx, saved_key[index], strlen(saved_key[index]));
sph_skein256_close(&ctx, (unsigned char*)crypt_out[index]);
}
return count;
}
static int crypt_512(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
sph_skein512_context ctx;
sph_skein512_init(&ctx);
sph_skein512(&ctx, saved_key[index], strlen(saved_key[index]));
sph_skein512_close(&ctx, (unsigned char*)crypt_out[index]);
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
#ifdef _OPENMP
for (; index < count; index++)
#endif
if (!memcmp(binary, crypt_out[index], CMP_SIZE))
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], CMP_SIZE);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void skein_set_key(char *key, int index)
{
strnzcpy(saved_key[index], key, sizeof(*saved_key));
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_skein_256 = {
{
"skein-256",
"Skein 256",
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE256,
BINARY_ALIGN,
SALT_SIZE,
BINARY_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 },
skein_256_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid256,
split,
get_binary_256,
fmt_default_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
skein_set_key,
get_key,
fmt_default_clear_keys,
crypt_256,
{
#define COMMON_GET_HASH_LINK
#include "common-get-hash.h"
},
cmp_all,
cmp_one,
cmp_exact
}
};
struct fmt_main fmt_skein_512 = {
{
"skein-512",
"Skein 512",
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE512,
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 },
skein_512_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid512,
split,
get_binary_512,
fmt_default_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
skein_set_key,
get_key,
fmt_default_clear_keys,
crypt_512,
{
#define COMMON_GET_HASH_LINK
#include "common-get-hash.h"
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
mrcore.c
|
/***************************************************************************
*
Copyright 2013 CertiVox IOM Ltd. *
*
This file is part of CertiVox MIRACL Crypto SDK. *
*
The CertiVox MIRACL Crypto SDK provides developers with an *
extensive and efficient set of cryptographic functions. *
For further information about its features and functionalities please *
refer to http://www.certivox.com *
*
* The CertiVox MIRACL Crypto SDK is free software: you can *
redistribute it and/or modify it under the terms of the *
GNU Affero General Public License as published by the *
Free Software Foundation, either version 3 of the License, *
or (at your option) any later version. *
*
* The CertiVox MIRACL Crypto SDK 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 Affero General Public License for more details. *
*
* You should have received a copy of the GNU Affero General Public *
License along with CertiVox MIRACL Crypto SDK. *
If not, see <http://www.gnu.org/licenses/>. *
*
You can be released from the requirements of the license by purchasing *
a commercial license. Buying such a license is mandatory as soon as you *
develop commercial activities involving the CertiVox MIRACL Crypto SDK *
without disclosing the source code of your own applications, or shipping *
the CertiVox MIRACL Crypto SDK with a closed source product. *
*
***************************************************************************/
/*
*
* MIRACL Core module - contains initialisation code and general purpose
* utilities
* mrcore.c
*
* Space can be saved by removing unneeded functions (mr_and ?)
*
*/
#include "miracl.h"
#include <stdlib.h>
#include <string.h>
#ifdef MR_FP
#include <math.h>
#endif
/*** Multi-Threaded Support ***/
#ifndef MR_GENERIC_MT
#ifdef MR_OPENMP_MT
#include <omp.h>
#define MR_MIP_EXISTS
miracl *mr_mip;
#pragma omp threadprivate(mr_mip)
miracl *get_mip()
{
return mr_mip;
}
void mr_init_threading()
{
}
void mr_end_threading()
{
}
#endif
#ifdef MR_WINDOWS_MT
#include <windows.h>
DWORD mr_key;
miracl *get_mip()
{
return (miracl *)TlsGetValue(mr_key);
}
void mr_init_threading()
{
mr_key=TlsAlloc();
}
void mr_end_threading()
{
TlsFree(mr_key);
}
#endif
#ifdef MR_UNIX_MT
#include <pthread.h>
pthread_key_t mr_key;
miracl *get_mip()
{
return (miracl *)pthread_getspecific(mr_key);
}
void mr_init_threading()
{
pthread_key_create(&mr_key,(void(*)(void *))NULL);
}
void mr_end_threading()
{
pthread_key_delete(mr_key);
}
#endif
#ifndef MR_WINDOWS_MT
#ifndef MR_UNIX_MT
#ifndef MR_OPENMP_MT
#ifdef MR_STATIC
miracl mip;
miracl *mr_mip=&mip;
#else
miracl *mr_mip=NULL; /* MIRACL's one and only global variable */
#endif
#define MR_MIP_EXISTS
miracl *get_mip()
{
return (miracl *)mr_mip;
}
#endif
#endif
#endif
#ifdef MR_MIP_EXISTS
void set_mip(miracl *mip)
{
mr_mip=mip;
}
#endif
#endif
/* See Advanced Windows by Jeffrey Richter, Chapter 12 for methods for
creating different instances of this global for each executing thread
when using Windows '95/NT
*/
#ifdef MR_STATIC
#if MIRACL==8
static const int mr_small_primes[]=
{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,
107,109,113,127,0};
#else
static const int mr_small_primes[]=
{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,
107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,
223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,
337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,
457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,
593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,
719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,
857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,
997,0};
#endif
#endif
#ifndef MR_STRIPPED_DOWN
#ifndef MR_NO_STANDARD_IO
static char *names[] =
{(char *)"your program",(char *)"innum",(char *)"otnum",(char *)"jack",(char *)"normalise",
(char *)"multiply",(char *)"divide",(char *)"incr",(char *)"decr",(char *)"premult",
(char *)"subdiv",(char *)"fdsize",(char *)"egcd",(char *)"cbase",
(char *)"cinnum",(char *)"cotnum",(char *)"nroot",(char *)"power",
(char *)"powmod",(char *)"bigdig",(char *)"bigrand",(char *)"nxprime",(char *)"isprime",
(char *)"mirvar",(char *)"mad",(char *)"multi_inverse",(char *)"putdig",
(char *)"add",(char *)"subtract",(char *)"mirsys",(char *)"xgcd",
(char *)"fpack",(char *)"dconv",(char *)"mr_shift",(char *)"mround",(char *)"fmul",
(char *)"fdiv",(char *)"fadd",(char *)"fsub",(char *)"fcomp",(char *)"fconv",
(char *)"frecip",(char *)"fpmul",(char *)"fincr",(char *)"",(char *)"ftrunc",
(char *)"frand",(char *)"sftbit",(char *)"build",(char *)"logb2",(char *)"expint",
(char *)"fpower",(char *)"froot",(char *)"fpi",(char *)"fexp",(char *)"flog",(char *)"fpowf",
(char *)"ftan",(char *)"fatan",(char *)"fsin",(char *)"fasin",(char *)"fcos",(char *)"facos",
(char *)"ftanh",(char *)"fatanh",(char *)"fsinh",(char *)"fasinh",(char *)"fcosh",
(char *)"facosh",(char *)"flop",(char *)"gprime",(char *)"powltr",(char *)"fft_mult",
(char *)"crt_init",(char *)"crt",(char *)"otstr",(char *)"instr",(char *)"cotstr",(char *)"cinstr",(char *)"powmod2",
(char *)"prepare_monty",(char *)"nres",(char *)"redc",(char *)"nres_modmult",(char *)"nres_powmod",
(char *)"nres_moddiv",(char *)"nres_powltr",(char *)"divisible",(char *)"remain",
(char *)"fmodulo",(char *)"nres_modadd",(char *)"nres_modsub",(char *)"nres_negate",
(char *)"ecurve_init",(char *)"ecurve_add",(char *)"ecurve_mult",
(char *)"epoint_init",(char *)"epoint_set",(char *)"epoint_get",(char *)"nres_powmod2",
(char *)"nres_sqroot",(char *)"sqroot",(char *)"nres_premult",(char *)"ecurve_mult2",
(char *)"ecurve_sub",(char *)"trial_division",(char *)"nxsafeprime",(char *)"nres_lucas",(char *)"lucas",
(char *)"brick_init",(char *)"pow_brick",(char *)"set_user_function",
(char *)"nres_powmodn",(char *)"powmodn",(char *)"ecurve_multn",
(char *)"ebrick_init",(char *)"mul_brick",(char *)"epoint_norm",(char *)"nres_multi_inverse",(char *)"",
(char *)"nres_dotprod",(char *)"epoint_negate",(char *)"ecurve_multi_add",
(char *)"ecurve2_init",(char *)"",(char *)"epoint2_set",(char *)"epoint2_norm",(char *)"epoint2_get",
(char *)"epoint2_comp",(char *)"ecurve2_add",(char *)"epoint2_negate",(char *)"ecurve2_sub",
(char *)"ecurve2_multi_add",(char *)"ecurve2_mult",(char *)"ecurve2_multn",(char *)"ecurve2_mult2",
(char *)"ebrick2_init",(char *)"mul2_brick",(char *)"prepare_basis",(char *)"strong_bigrand",
(char *)"bytes_to_big",(char *)"big_to_bytes",(char *)"set_io_buffer_size",
(char *)"epoint_getxyz",(char *)"epoint_double_add",(char *)"nres_double_inverse",
(char *)"double_inverse",(char *)"epoint_x",(char *)"hamming",(char *)"expb2",(char *)"bigbits",
(char *)"nres_lazy",(char *)"zzn2_imul",(char *)"nres_double_modadd",(char *)"nres_double_modsub",
/*155*/(char *)"",(char *)"zzn2_from_int",(char *)"zzn2_negate",(char *)"zzn2_conj",(char *)"zzn2_add",
(char *)"zzn2_sub",(char *)"zzn2_smul",(char *)"zzn2_mul",(char *)"zzn2_inv",(char *)"zzn2_timesi",(char *)"zzn2_powl",
(char *)"zzn2_from_bigs",(char *)"zzn2_from_big",(char *)"zzn2_from_ints",
(char *)"zzn2_sadd",(char *)"zzn2_ssub",(char *)"zzn2_times_irp",(char *)"zzn2_div2",
(char *)"zzn3_from_int",(char *)"zzn3_from_ints",(char *)"zzn3_from_bigs",
(char *)"zzn3_from_big",(char *)"zzn3_negate",(char *)"zzn3_powq",(char *)"zzn3_init",
(char *)"zzn3_add",(char *)"zzn3_sadd",(char *)"zzn3_sub",(char *)"zzn3_ssub",(char *)"zzn3_smul",
(char *)"zzn3_imul",(char *)"zzn3_mul",(char *)"zzn3_inv",(char *)"zzn3_div2",(char *)"zzn3_timesi",
(char *)"epoint_multi_norm",(char *)"mr_jsf",(char *)"epoint2_multi_norm",
(char *)"ecn2_compare",(char *)"ecn2_norm",(char *)"ecn2_set",(char *)"zzn2_txx",
(char *)"zzn2_txd",(char *)"nres_div2",(char *)"nres_div3",(char *)"zzn2_div3",
(char *)"ecn2_setx",(char *)"ecn2_rhs",(char *)"zzn2_qr",(char *)"zzn2_sqrt",(char *)"ecn2_add",(char *)"ecn2_mul2_jsf",(char *)"ecn2_mul",
(char *)"nres_div5",(char *)"zzn2_div5",(char *)"zzn2_sqr",(char *)"ecn2_add_sub",(char *)"ecn2_psi",(char *)"invmodp",
(char *)"zzn2_multi_inverse",(char *)"ecn2_multi_norm",(char *)"ecn2_precomp",(char *)"ecn2_mul4_gls_v",
(char *)"ecn2_mul2",(char *)"ecn2_precomp_gls",(char *)"ecn2_mul2_gls",
(char *)"ecn2_brick_init",(char *)"ecn2_mul_brick_gls",(char *)"ecn2_multn",(char *)"zzn3_timesi2",
(char *)"nres_complex",(char *)"zzn4_from_int",(char *)"zzn4_negate",(char *)"zzn4_conj",(char *)"zzn4_add",(char *)"zzn4_sadd",(char *)"zzn4_sub",(char *)"zzn4_ssub",(char *)"zzn4_smul",(char *)"zzn4_sqr",
(char *)"zzn4_mul",(char *)"zzn4_inv",(char *)"zzn4_div2",(char *)"zzn4_powq",(char *)"zzn4_tx",(char *)"zzn4_imul",(char *)"zzn4_lmul",(char *)"zzn4_from_big",
(char *)"ecn2_mult4"};
/* 0 - 243 (244 in all) */
#endif
#endif
#ifdef MR_NOASM
/* C only versions of muldiv/muldvd/muldvd2/muldvm */
/* Note that mr_large should be twice the size of mr_small */
mr_small muldiv(mr_small a,mr_small b,mr_small c,mr_small m,mr_small *rp)
{
mr_small q;
mr_large ldres,p=(mr_large)a*b+c;
q=(mr_small)(MR_LROUND(p/m));
*rp=(mr_small)(p-(mr_large)q*m);
return q;
}
#ifdef MR_FP_ROUNDING
mr_small imuldiv(mr_small a,mr_small b,mr_small c,mr_small m,mr_large im,mr_small *rp)
{
mr_small q;
mr_large ldres,p=(mr_large)a*b+c;
q=(mr_small)MR_LROUND(p*im);
*rp=(mr_small)(p-(mr_large)q*m);
return q;
}
#endif
#ifndef MR_NOFULLWIDTH
mr_small muldvm(mr_small a,mr_small c,mr_small m,mr_small *rp)
{
mr_small q;
union doubleword dble;
dble.h[MR_BOT]=c;
dble.h[MR_TOP]=a;
q=(mr_small)(dble.d/m);
*rp=(mr_small)(dble.d-(mr_large)q*m);
return q;
}
mr_small muldvd(mr_small a,mr_small b,mr_small c,mr_small *rp)
{
union doubleword dble;
dble.d=(mr_large)a*b+c;
*rp=dble.h[MR_BOT];
return dble.h[MR_TOP];
}
void muldvd2(mr_small a,mr_small b,mr_small *c,mr_small *rp)
{
union doubleword dble;
dble.d=(mr_large)a*b+*c+*rp;
*rp=dble.h[MR_BOT];
*c=dble.h[MR_TOP];
}
#endif
#endif
#ifdef MR_NOFULLWIDTH
/* no FULLWIDTH working, so supply dummies */
/*
mr_small muldvd(mr_small a,mr_small b,mr_small c,mr_small *rp)
{
return (mr_small)0;
}
mr_small muldvm(mr_small a,mr_small c,mr_small m,mr_small *rp)
{
return (mr_small)0;
}
void muldvd2(mr_small a,mr_small b,mr_small *c,mr_small *rp)
{
}
*/
#endif
#ifndef MR_NO_STANDARD_IO
static void mputs(char *s)
{ /* output a string */
int i=0;
while (s[i]!=0) fputc((int)s[i++],stdout);
}
#endif
void mr_berror(_MIPD_ int nerr)
{ /* Big number error routine */
#ifndef MR_STRIPPED_DOWN
int i;
#endif
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERCON)
{
mr_mip->ERNUM=nerr;
return;
}
#ifndef MR_NO_STANDARD_IO
#ifndef MR_STRIPPED_DOWN
mputs((char *)"\nMIRACL error from routine ");
if (mr_mip->depth<MR_MAXDEPTH) mputs(names[mr_mip->trace[mr_mip->depth]]);
else mputs((char *)"???");
fputc('\n',stdout);
for (i=mr_mip->depth-1;i>=0;i--)
{
mputs((char *)" called from ");
if (i<MR_MAXDEPTH) mputs(names[mr_mip->trace[i]]);
else mputs((char *)"???");
fputc('\n',stdout);
}
switch (nerr)
{
case 1 :
mputs((char *)"Number base too big for representation\n");
break;
case 2 :
mputs((char *)"Division by zero attempted\n");
break;
case 3 :
mputs((char *)"Overflow - Number too big\n");
break;
case 4 :
mputs((char *)"Internal result is negative\n");
break;
case 5 :
mputs((char *)"Input format error\n");
break;
case 6 :
mputs((char *)"Illegal number base\n");
break;
case 7 :
mputs((char *)"Illegal parameter usage\n");
break;
case 8 :
mputs((char *)"Out of space\n");
break;
case 9 :
mputs((char *)"Even root of a negative number\n");
break;
case 10:
mputs((char *)"Raising integer to negative power\n");
break;
case 11:
mputs((char *)"Attempt to take illegal root\n");
break;
case 12:
mputs((char *)"Integer operation attempted on Flash number\n");
break;
case 13:
mputs((char *)"Flash overflow\n");
break;
case 14:
mputs((char *)"Numbers too big\n");
break;
case 15:
mputs((char *)"Log of a non-positive number\n");
break;
case 16:
mputs((char *)"Flash to double conversion failure\n");
break;
case 17:
mputs((char *)"I/O buffer overflow\n");
break;
case 18:
mputs((char *)"MIRACL not initialised - no call to mirsys()\n");
break;
case 19:
mputs((char *)"Illegal modulus \n");
break;
case 20:
mputs((char *)"No modulus defined\n");
break;
case 21:
mputs((char *)"Exponent too big\n");
break;
case 22:
mputs((char *)"Unsupported Feature - check mirdef.h\n");
break;
case 23:
mputs((char *)"Specified double length type isn't double length\n");
break;
case 24:
mputs((char *)"Specified basis is NOT irreducible\n");
break;
case 25:
mputs((char *)"Unable to control Floating-point rounding\n");
break;
case 26:
mputs((char *)"Base must be binary (MR_ALWAYS_BINARY defined in mirdef.h ?)\n");
break;
case 27:
mputs((char *)"No irreducible basis defined\n");
break;
case 28:
mputs((char *)"Composite modulus\n");
break;
case 29:
mputs((char *)"Input/output error when reading from RNG device node\n");
break;
default:
mputs((char *)"Undefined error\n");
break;
}
exit(0);
#else
mputs((char *)"MIRACL error\n");
exit(0);
#endif
#endif
}
#ifndef MR_STRIPPED_DOWN
void mr_track(_MIPDO_ )
{ /* track course of program execution *
* through the MIRACL routines */
#ifndef MR_NO_STANDARD_IO
int i;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
for (i=0;i<mr_mip->depth;i++) fputc('-',stdout);
fputc('>',stdout);
mputs(names[mr_mip->trace[mr_mip->depth]]);
fputc('\n',stdout);
#endif
}
#endif
#ifndef MR_NO_RAND
mr_small brand(_MIPDO_ )
{ /* Marsaglia & Zaman random number generator */
int i,k;
mr_unsign32 pdiff,t;
mr_small r;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->lg2b>32)
{ /* underlying type is > 32 bits. Assume <= 64 bits */
mr_mip->rndptr+=2;
if (mr_mip->rndptr<NK-1)
{
r=(mr_small)mr_mip->ira[mr_mip->rndptr];
r=mr_shiftbits(r,mr_mip->lg2b-32);
r+=(mr_small)mr_mip->ira[mr_mip->rndptr+1];
return r;
}
}
else
{
mr_mip->rndptr++;
if (mr_mip->rndptr<NK) return (mr_small)mr_mip->ira[mr_mip->rndptr];
}
mr_mip->rndptr=0;
for (i=0,k=NK-NJ;i<NK;i++,k++)
{ /* calculate next NK values */
if (k==NK) k=0;
t=mr_mip->ira[k];
pdiff=t - mr_mip->ira[i] - mr_mip->borrow;
if (pdiff<t) mr_mip->borrow=0;
if (pdiff>t) mr_mip->borrow=1;
mr_mip->ira[i]=pdiff;
}
if (mr_mip->lg2b>32)
{ /* double up */
r=(mr_small)mr_mip->ira[0];
r=mr_shiftbits(r,mr_mip->lg2b-32);
r+=(mr_small)mr_mip->ira[1];
return r;
}
else return (mr_small)(mr_mip->ira[0]);
}
void irand(_MIPD_ mr_unsign32 seed)
{ /* initialise random number system */
int i,in;
mr_unsign32 t,m=1L;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
mr_mip->borrow=0L;
mr_mip->rndptr=0;
mr_mip->ira[0]=seed;
for (i=1;i<NK;i++)
{ /* fill initialisation vector */
in=(NV*i)%NK;
mr_mip->ira[in]=m;
t=m;
m=seed-m;
seed=t;
}
for (i=0;i<1000;i++) brand(_MIPPO_ ); /* "warm-up" & stir the generator */
}
#endif
mr_small mr_shiftbits(mr_small x,int n)
{
#ifdef MR_FP
int i;
mr_small dres;
if (n==0) return x;
if (n>0)
{
for (i=0;i<n;i++) x=x+x;
return x;
}
n=-n;
for (i=0;i<n;i++) x=MR_DIV(x,2.0);
return x;
#else
if (n==0) return x;
if (n>0) x<<=n;
else x>>=(-n);
return x;
#endif
}
mr_small mr_setbase(_MIPD_ mr_small nb)
{ /* set base. Pack as many digits as *
* possible into each computer word */
mr_small temp;
#ifdef MR_FP
mr_small dres;
#endif
#ifndef MR_NOFULLWIDTH
BOOL fits;
int bits;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
fits=FALSE;
bits=MIRACL;
while (bits>1)
{
bits/=2;
temp=((mr_small)1<<bits);
if (temp==nb)
{
fits=TRUE;
break;
}
if (temp<nb || (bits%2)!=0) break;
}
if (fits)
{
mr_mip->apbase=nb;
mr_mip->pack=MIRACL/bits;
mr_mip->base=0;
return 0;
}
#endif
mr_mip->apbase=nb;
mr_mip->pack=1;
mr_mip->base=nb;
#ifdef MR_SIMPLE_BASE
return 0;
#else
if (mr_mip->base==0) return 0;
temp=MR_DIV(MAXBASE,nb);
while (temp>=nb)
{
temp=MR_DIV(temp,nb);
mr_mip->base*=nb;
mr_mip->pack++;
}
#ifdef MR_FP_ROUNDING
mr_mip->inverse_base=mr_invert(mr_mip->base);
return mr_mip->inverse_base;
#else
return 0;
#endif
#endif
}
#ifdef MR_FLASH
BOOL fit(big x,big y,int f)
{ /* returns TRUE if x/y would fit flash format of length f */
int n,d;
n=(int)(x->len&(MR_OBITS));
d=(int)(y->len&(MR_OBITS));
if (n==1 && x->w[0]==1) n=0;
if (d==1 && y->w[0]==1) d=0;
if (n+d<=f) return TRUE;
return FALSE;
}
#endif
int mr_lent(flash x)
{ /* return length of big or flash in words */
mr_lentype lx;
lx=(x->len&(MR_OBITS));
#ifdef MR_FLASH
return (int)((lx&(MR_MSK))+((lx>>(MR_BTS))&(MR_MSK)));
#else
return (int)lx;
#endif
}
void zero(flash x)
{ /* set big/flash number to zero */
int i,n;
mr_small *g;
if (x==NULL) return;
#ifdef MR_FLASH
n=mr_lent(x);
#else
n=(x->len&MR_OBITS);
#endif
g=x->w;
for (i=0;i<n;i++)
g[i]=0;
x->len=0;
}
void uconvert(_MIPD_ unsigned int n ,big x)
{ /* convert unsigned integer n to big number format */
int m;
#ifdef MR_FP
mr_small dres;
#endif
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
zero(x);
if (n==0) return;
m=0;
#ifndef MR_SIMPLE_BASE
if (mr_mip->base==0)
{
#endif
#ifndef MR_NOFULLWIDTH
#if MR_IBITS > MIRACL
while (n>0)
{
x->w[m++]=(mr_small)(n%((mr_small)1<<(MIRACL)));
n/=((mr_small)1<<(MIRACL));
}
#else
x->w[m++]=(mr_small)n;
#endif
#endif
#ifndef MR_SIMPLE_BASE
}
else while (n>0)
{
x->w[m++]=MR_REMAIN((mr_small)n,mr_mip->base);
n=(unsigned int)((mr_small)n/mr_mip->base);
}
#endif
x->len=m;
}
void tconvert(_MIPD_ mr_utype n,big x)
{
mr_lentype s;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (n==0) {zero(x); return;}
s=0;
if (n<0)
{
s=MR_MSBIT;
n=(-n);
}
x->w[0]=n;
x->len=1;
x->len|=s;
}
void convert(_MIPD_ int n ,big x)
{ /* convert signed integer n to big number format */
mr_lentype s;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (n==0) {zero(x); return;}
s=0;
if (n<0)
{
s=MR_MSBIT;
n=(-n);
}
uconvert(_MIPP_ (unsigned int)n,x);
x->len|=s;
}
#ifndef MR_STATIC
#ifdef mr_dltype
void dlconv(_MIPD_ mr_dltype n,big x)
{ /* convert double length integer to big number format - rarely needed */
int m;
mr_lentype s;
#ifdef MR_FP
mr_small dres;
#endif
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
zero(x);
if (n==0) return;
s=0;
if (n<0)
{
s=MR_MSBIT;
n=(-n);
}
m=0;
#ifndef MR_SIMPLE_BASE
if (mr_mip->base==0)
{
#endif
#ifndef MR_NOFULLWIDTH
while (n>0)
{
x->w[m++]=(mr_small)(n%((mr_dltype)1<<(MIRACL)));
n/=((mr_dltype)1<<(MIRACL));
}
#endif
#ifndef MR_SIMPLE_BASE
}
else while (n>0)
{
x->w[m++]=(mr_small)MR_REMAIN(n,mr_mip->base);
n/=mr_mip->base;
}
#endif
x->len=(m|s);
}
#endif
void ulgconv(_MIPD_ unsigned long n,big x)
{ /* convert unsigned long integer to big number format - rarely needed */
int m;
#ifdef MR_FP
mr_small dres;
#endif
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
zero(x);
if (n==0) return;
m=0;
#ifndef MR_SIMPLE_BASE
if (mr_mip->base==0)
{
#endif
#ifndef MR_NOFULLWIDTH
#if MR_LBITS > MIRACL
while (n>0)
{
x->w[m++]=(mr_small)(n%(1L<<(MIRACL)));
n/=(1L<<(MIRACL));
}
#else
x->w[m++]=(mr_small)n;
#endif
#endif
#ifndef MR_SIMPLE_BASE
}
else while (n>0)
{
x->w[m++]=MR_REMAIN(n,mr_mip->base);
n=(unsigned long)((mr_small)n/mr_mip->base);
}
#endif
x->len=m;
}
void lgconv(_MIPD_ long n,big x)
{ /* convert signed long integer to big number format - rarely needed */
mr_lentype s;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (n==0) {zero(x); return;}
s=0;
if (n<0)
{
s=MR_MSBIT;
n=(-n);
}
ulgconv(_MIPP_ (unsigned long)n,x);
x->len|=s;
}
flash mirvar(_MIPD_ int iv)
{ /* initialize big/flash number */
flash x;
int align;
char *ptr;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return NULL;
MR_IN(23);
if (!(mr_mip->active))
{
mr_berror(_MIPP_ MR_ERR_NO_MIRSYS);
MR_OUT
return NULL;
}
/* OK, now I control alignment.... */
/* Allocate space for big, the length, the pointer, and the array */
/* Do it all in one memory allocation - this is quicker */
/* Ensure that the array has correct alignment */
x=(big)mr_alloc(_MIPP_ mr_size(mr_mip->nib-1),1);
if (x==NULL)
{
MR_OUT
return x;
}
ptr=(char *)&x->w;
align=(unsigned long)(ptr+sizeof(mr_small *))%sizeof(mr_small);
x->w=(mr_small *)(ptr+sizeof(mr_small *)+sizeof(mr_small)-align);
if (iv!=0) convert(_MIPP_ iv,x);
MR_OUT
return x;
}
#endif
flash mirvar_mem_variable(char *mem,int index,int sz)
{
flash x;
int align;
char *ptr;
int offset,r;
/* alignment */
offset=0;
r=(unsigned long)mem%MR_SL;
if (r>0) offset=MR_SL-r;
x=(big)&mem[offset+mr_size(sz)*index];
ptr=(char *)&x->w;
align=(unsigned long)(ptr+sizeof(mr_small *))%sizeof(mr_small);
x->w=(mr_small *)(ptr+sizeof(mr_small *)+sizeof(mr_small)-align);
return x;
}
flash mirvar_mem(_MIPD_ char *mem,int index)
{ /* initialize big/flash number from pre-allocated memory */
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return NULL;
return mirvar_mem_variable(mem,index,mr_mip->nib-1);
}
void set_user_function(_MIPD_ BOOL (*user)(void))
{
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return;
MR_IN(111)
if (!(mr_mip->active))
{
mr_berror(_MIPP_ MR_ERR_NO_MIRSYS);
MR_OUT
return;
}
mr_mip->user=user;
MR_OUT
}
#ifndef MR_STATIC
#ifndef MR_SIMPLE_IO
void set_io_buffer_size(_MIPD_ int len)
{
int i;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (len<0) return;
MR_IN(142)
for (i=0;i<mr_mip->IOBSIZ;i++) mr_mip->IOBUFF[i]=0;
mr_free(mr_mip->IOBUFF);
if (len==0)
{
MR_OUT
return;
}
mr_mip->IOBSIZ=len;
mr_mip->IOBUFF=(char *)mr_alloc(_MIPP_ len+1,1);
mr_mip->IOBUFF[0]='\0';
MR_OUT
}
#endif
#endif
/* Initialise a big from ROM given its fixed length */
BOOL init_big_from_rom(big x,int len,const mr_small *rom,int romsize,int *romptr)
{
int i;
zero(x);
x->len=len;
for (i=0;i<len;i++)
{
if (*romptr>=romsize) return FALSE;
#ifdef MR_AVR
x->w[i]=pgm_read_byte_near(&rom[*romptr]);
#else
x->w[i]=rom[*romptr];
#endif
(*romptr)++;
}
mr_lzero(x);
return TRUE;
}
/* Initialise an elliptic curve point from ROM */
BOOL init_point_from_rom(epoint *P,int len,const mr_small *rom,int romsize,int *romptr)
{
if (!init_big_from_rom(P->X,len,rom,romsize,romptr)) return FALSE;
if (!init_big_from_rom(P->Y,len,rom,romsize,romptr)) return FALSE;
P->marker=MR_EPOINT_NORMALIZED;
return TRUE;
}
#ifdef MR_GENERIC_AND_STATIC
miracl *mirsys(miracl *mr_mip,int nd,mr_small nb)
#else
miracl *mirsys(int nd,mr_small nb)
#endif
{ /* Initialize MIRACL system to *
* use numbers to base nb, and *
* nd digits or (-nd) bytes long */
/* In these cases mr_mip is passed as the first parameter */
#ifdef MR_GENERIC_AND_STATIC
return mirsys_basic(mr_mip,nd,nb);
#endif
#ifdef MR_GENERIC_MT
#ifndef MR_STATIC
miracl *mr_mip=mr_first_alloc();
return mirsys_basic(mr_mip,nd,nb);
#endif
#endif
/* In these cases mr_mip is a "global" pointer and the mip itself is allocated from the heap.
In fact mr_mip (and mip) may be thread specific if some multi-threading scheme is implemented */
#ifndef MR_STATIC
#ifdef MR_WINDOWS_MT
miracl *mr_mip=mr_first_alloc();
TlsSetValue(mr_key,mr_mip);
#endif
#ifdef MR_UNIX_MT
miracl *mr_mip=mr_first_alloc();
pthread_setspecific(mr_key,mr_mip);
#endif
#ifdef MR_OPENMP_MT
mr_mip=mr_first_alloc();
#endif
#ifndef MR_WINDOWS_MT
#ifndef MR_UNIX_MT
#ifndef MR_OPENMP_MT
mr_mip=mr_first_alloc();
#endif
#endif
#endif
#endif
#ifndef MR_GENERIC_MT
mr_mip=get_mip();
#endif
return mirsys_basic(mr_mip,nd,nb);
}
miracl *mirsys_basic(miracl *mr_mip,int nd,mr_small nb)
{
#ifndef MR_NO_RAND
int i;
#endif
mr_small b,nw;
#ifdef MR_FP
mr_small dres;
#endif
if (mr_mip==NULL) return NULL;
#ifndef MR_STRIPPED_DOWN
mr_mip->depth=0;
mr_mip->trace[0]=0;
mr_mip->depth++;
mr_mip->trace[mr_mip->depth]=29;
#endif
/* digest hardware configuration */
#ifdef MR_NO_STANDARD_IO
mr_mip->ERCON=TRUE;
#else
mr_mip->ERCON=FALSE;
#endif
#ifndef MR_STATIC
mr_mip->logN=0;
mr_mip->degree=0;
mr_mip->chin.NP=0;
#endif
mr_mip->user=NULL;
mr_mip->same=FALSE;
mr_mip->first_one=FALSE;
mr_mip->debug=FALSE;
mr_mip->AA=0;
#ifndef MR_AFFINE_ONLY
mr_mip->coord=MR_NOTSET;
#endif
#ifdef MR_NOFULLWIDTH
if (nb==0)
{
mr_berror(_MIPP_ MR_ERR_BAD_BASE);
MR_OUT
return mr_mip;
}
#endif
#ifndef MR_FP
#ifdef mr_dltype
#ifndef MR_NOFULLWIDTH
if (sizeof(mr_dltype)<2*sizeof(mr_utype))
{ /* double length type, isn't */
mr_berror(_MIPP_ MR_ERR_NOT_DOUBLE_LEN);
MR_OUT
return mr_mip;
}
#endif
#endif
#endif
if (nb==1 || nb>MAXBASE)
{
mr_berror(_MIPP_ MR_ERR_BAD_BASE);
MR_OUT
return mr_mip;
}
#ifdef MR_FP_ROUNDING
if (mr_setbase(_MIPP_ nb)==0)
{ /* unable in fact to control FP rounding */
mr_berror(_MIPP_ MR_ERR_NO_ROUNDING);
MR_OUT
return mr_mip;
}
#else
mr_setbase(_MIPP_ nb);
#endif
b=mr_mip->base;
#ifdef MR_SIMPLE_BASE
if (b!=0)
{
mr_berror(_MIPP_ MR_ERR_BAD_BASE);
MR_OUT
return mr_mip;
}
#endif
mr_mip->lg2b=0;
mr_mip->base2=1;
#ifndef MR_SIMPLE_BASE
if (b==0)
{
#endif
mr_mip->lg2b=MIRACL;
mr_mip->base2=0;
#ifndef MR_SIMPLE_BASE
}
else while (b>1)
{
b=MR_DIV(b,2);
mr_mip->lg2b++;
mr_mip->base2*=2;
}
#endif
#ifdef MR_ALWAYS_BINARY
if (mr_mip->base!=mr_mip->base2)
{
mr_berror(_MIPP_ MR_ERR_NOT_BINARY);
MR_OUT
return mr_mip;
}
#endif
/* calculate total space for bigs */
/*
big -> |int len|small *ptr| alignment space | size in words +1| alignment up to multiple of 4 |
*/
if (nd>0) nw=MR_ROUNDUP(nd,mr_mip->pack);
else nw=MR_ROUNDUP(8*(-nd),mr_mip->lg2b);
if (nw<1) nw=1;
mr_mip->nib=(int)(nw+1); /* add one extra word for small overflows */
#ifdef MR_STATIC
if (nw>MR_STATIC)
{
mr_berror(_MIPP_ MR_ERR_TOO_BIG);
MR_OUT
return mr_mip;
}
#endif
/* mr_mip->nib=(int)(nw+1); add one extra word for small overflows */
#ifdef MR_FLASH
mr_mip->workprec=mr_mip->nib;
mr_mip->stprec=mr_mip->nib;
while (mr_mip->stprec>2 && mr_mip->stprec>MR_FLASH/mr_mip->lg2b)
mr_mip->stprec=(mr_mip->stprec+1)/2;
if (mr_mip->stprec<2) mr_mip->stprec=2;
#endif
#ifndef MR_DOUBLE_BIG
mr_mip->check=ON;
#else
mr_mip->check=OFF;
#endif
#ifndef MR_SIMPLE_BASE
#ifndef MR_SIMPLE_IO
mr_mip->IOBASE=10; /* defaults */
#endif
#endif
mr_mip->ERNUM=0;
mr_mip->NTRY=6;
mr_mip->MONTY=ON;
#ifdef MR_FLASH
mr_mip->EXACT=TRUE;
mr_mip->RPOINT=OFF;
#endif
#ifndef MR_STRIPPED_DOWN
mr_mip->TRACER=OFF;
#endif
#ifndef MR_SIMPLE_IO
mr_mip->INPLEN=0;
mr_mip->IOBSIZ=MR_DEFAULT_BUFFER_SIZE;
#endif
#ifdef MR_STATIC
mr_mip->PRIMES=mr_small_primes;
#else
mr_mip->PRIMES=NULL;
#ifndef MR_SIMPLE_IO
mr_mip->IOBUFF=(char *)mr_alloc(_MIPP_ MR_DEFAULT_BUFFER_SIZE+1,1);
#endif
#endif
#ifndef MR_SIMPLE_IO
mr_mip->IOBUFF[0]='\0';
#endif
mr_mip->qnr=0;
mr_mip->cnr=0;
mr_mip->TWIST=0;
mr_mip->pmod8=0;
mr_mip->pmod9=0;
/* quick start for rng. irand(.) should be called first before serious use.. */
#ifndef MR_NO_RAND
mr_mip->ira[0]=0x55555555;
mr_mip->ira[1]=0x12345678;
for (i=2;i<NK;i++)
mr_mip->ira[i]=mr_mip->ira[i-1]+mr_mip->ira[i-2]+0x1379BDF1;
mr_mip->rndptr=NK;
mr_mip->borrow=0;
#endif
mr_mip->nib=2*mr_mip->nib+1;
#ifdef MR_FLASH
if (mr_mip->nib!=(mr_mip->nib&(MR_MSK)))
#else
if (mr_mip->nib!=(int)(mr_mip->nib&(MR_OBITS)))
#endif
{
mr_berror(_MIPP_ MR_ERR_TOO_BIG);
mr_mip->nib=(mr_mip->nib-1)/2;
MR_OUT
return mr_mip;
}
#ifndef MR_STATIC
mr_mip->workspace=(char *)memalloc(_MIPP_ MR_SPACES); /* grab workspace */
#else
memset(mr_mip->workspace,0,MR_BIG_RESERVE(MR_SPACES));
#endif
mr_mip->M=0;
mr_mip->fin=FALSE;
mr_mip->fout=FALSE;
mr_mip->active=ON;
mr_mip->nib=(mr_mip->nib-1)/2;
/* allocate memory for workspace variables */
#ifndef MR_DOUBLE_BIG
mr_mip->w0=mirvar_mem(_MIPP_ mr_mip->workspace,0); /* double length */
mr_mip->w1=mirvar_mem(_MIPP_ mr_mip->workspace,2);
mr_mip->w2=mirvar_mem(_MIPP_ mr_mip->workspace,3);
mr_mip->w3=mirvar_mem(_MIPP_ mr_mip->workspace,4);
mr_mip->w4=mirvar_mem(_MIPP_ mr_mip->workspace,5);
mr_mip->w5=mirvar_mem(_MIPP_ mr_mip->workspace,6); /* double length */
mr_mip->w6=mirvar_mem(_MIPP_ mr_mip->workspace,8); /* double length */
mr_mip->w7=mirvar_mem(_MIPP_ mr_mip->workspace,10); /* double length */
mr_mip->w8=mirvar_mem(_MIPP_ mr_mip->workspace,12);
mr_mip->w9=mirvar_mem(_MIPP_ mr_mip->workspace,13);
mr_mip->w10=mirvar_mem(_MIPP_ mr_mip->workspace,14);
mr_mip->w11=mirvar_mem(_MIPP_ mr_mip->workspace,15);
mr_mip->w12=mirvar_mem(_MIPP_ mr_mip->workspace,16);
mr_mip->w13=mirvar_mem(_MIPP_ mr_mip->workspace,17);
mr_mip->w14=mirvar_mem(_MIPP_ mr_mip->workspace,18);
mr_mip->w15=mirvar_mem(_MIPP_ mr_mip->workspace,19);
mr_mip->sru=mirvar_mem(_MIPP_ mr_mip->workspace,20);
mr_mip->modulus=mirvar_mem(_MIPP_ mr_mip->workspace,21);
mr_mip->pR=mirvar_mem(_MIPP_ mr_mip->workspace,22); /* double length */
mr_mip->A=mirvar_mem(_MIPP_ mr_mip->workspace,24);
mr_mip->B=mirvar_mem(_MIPP_ mr_mip->workspace,25);
mr_mip->one=mirvar_mem(_MIPP_ mr_mip->workspace,26);
#ifdef MR_KCM
mr_mip->big_ndash=mirvar_mem(_MIPP_ mr_mip->workspace,27);
mr_mip->ws=mirvar_mem(_MIPP_ mr_mip->workspace,28);
mr_mip->wt=mirvar_mem(_MIPP_ mr_mip->workspace,29); /* double length */
#endif
#ifdef MR_FLASH
#ifdef MR_KCM
mr_mip->pi=mirvar_mem(_MIPP_ mr_mip->workspace,31);
#else
mr_mip->pi=mirvar_mem(_MIPP_ mr_mip->workspace,27);
#endif
#endif
#else
/* w0-w7 are double normal length */
mr_mip->w0=mirvar_mem(_MIPP_ mr_mip->workspace,0); /* quad length */
mr_mip->w1=mirvar_mem(_MIPP_ mr_mip->workspace,4); /* double length */
mr_mip->w2=mirvar_mem(_MIPP_ mr_mip->workspace,6);
mr_mip->w3=mirvar_mem(_MIPP_ mr_mip->workspace,8);
mr_mip->w4=mirvar_mem(_MIPP_ mr_mip->workspace,10);
mr_mip->w5=mirvar_mem(_MIPP_ mr_mip->workspace,12); /* quad length */
mr_mip->w6=mirvar_mem(_MIPP_ mr_mip->workspace,16); /* quad length */
mr_mip->w7=mirvar_mem(_MIPP_ mr_mip->workspace,20); /* quad length */
mr_mip->w8=mirvar_mem(_MIPP_ mr_mip->workspace,24);
mr_mip->w9=mirvar_mem(_MIPP_ mr_mip->workspace,25);
mr_mip->w10=mirvar_mem(_MIPP_ mr_mip->workspace,26);
mr_mip->w11=mirvar_mem(_MIPP_ mr_mip->workspace,27);
mr_mip->w12=mirvar_mem(_MIPP_ mr_mip->workspace,28);
mr_mip->w13=mirvar_mem(_MIPP_ mr_mip->workspace,29);
mr_mip->w14=mirvar_mem(_MIPP_ mr_mip->workspace,30);
mr_mip->w15=mirvar_mem(_MIPP_ mr_mip->workspace,31);
mr_mip->sru=mirvar_mem(_MIPP_ mr_mip->workspace,32);
mr_mip->modulus=mirvar_mem(_MIPP_ mr_mip->workspace,33);
mr_mip->pR=mirvar_mem(_MIPP_ mr_mip->workspace,34); /* double length */
mr_mip->A=mirvar_mem(_MIPP_ mr_mip->workspace,36);
mr_mip->B=mirvar_mem(_MIPP_ mr_mip->workspace,37);
mr_mip->one=mirvar_mem(_MIPP_ mr_mip->workspace,38);
#ifdef MR_KCM
mr_mip->big_ndash=mirvar_mem(_MIPP_ mr_mip->workspace,39);
mr_mip->ws=mirvar_mem(_MIPP_ mr_mip->workspace,40);
mr_mip->wt=mirvar_mem(_MIPP_ mr_mip->workspace,41); /* double length */
#endif
#ifdef MR_FLASH
#ifdef MR_KCM
mr_mip->pi=mirvar_mem(_MIPP_ mr_mip->workspace,43);
#else
mr_mip->pi=mirvar_mem(_MIPP_ mr_mip->workspace,39);
#endif
#endif
#endif
MR_OUT
return mr_mip;
}
#ifndef MR_STATIC
/* allocate space for a number of bigs from the heap */
void *memalloc(_MIPD_ int num)
{
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
return mr_alloc(_MIPP_ mr_big_reserve(num,mr_mip->nib-1),1);
}
#endif
void memkill(_MIPD_ char *mem,int len)
{
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mem==NULL) return;
memset(mem,0,mr_big_reserve(len,mr_mip->nib-1));
#ifndef MR_STATIC
mr_free(mem);
#endif
}
#ifndef MR_STATIC
void mirkill(big x)
{ /* kill a big/flash variable, that is set it to zero
and free its memory */
if (x==NULL) return;
zero(x);
mr_free(x);
}
#endif
void mirexit(_MIPDO_ )
{ /* clean up after miracl */
int i;
#ifdef MR_WINDOWS_MT
miracl *mr_mip=get_mip();
#endif
#ifdef MR_UNIX_MT
miracl *mr_mip=get_mip();
#endif
#ifdef MR_OPENMP_MT
miracl *mr_mip=get_mip();
#endif
mr_mip->ERCON=FALSE;
mr_mip->active=OFF;
memkill(_MIPP_ mr_mip->workspace,MR_SPACES);
#ifndef MR_NO_RAND
for (i=0;i<NK;i++) mr_mip->ira[i]=0L;
#endif
#ifndef MR_STATIC
#ifndef MR_SIMPLE_IO
set_io_buffer_size(_MIPP_ 0);
#endif
if (mr_mip->PRIMES!=NULL) mr_free(mr_mip->PRIMES);
#else
#ifndef MR_SIMPLE_IO
for (i=0;i<=MR_DEFAULT_BUFFER_SIZE;i++)
mr_mip->IOBUFF[i]=0;
#endif
#endif
#ifndef MR_STATIC
mr_free(mr_mip);
#ifdef MR_WINDOWS_MT
TlsSetValue(mr_key, NULL); /* Thank you Thales */
#endif
#endif
#ifndef MR_GENERIC_MT
#ifndef MR_WINDOWS_MT
#ifndef MR_UNIX_MT
#ifndef MR_STATIC
mr_mip=NULL;
#endif
#endif
#endif
#endif
#ifdef MR_OPENMP_MT
mr_mip=NULL;
#endif
}
int exsign(flash x)
{ /* extract sign of big/flash number */
if ((x->len&(MR_MSBIT))==0) return PLUS;
else return MINUS;
}
void insign(int s,flash x)
{ /* assert sign of big/flash number */
if (x->len==0) return;
if (s<0) x->len|=MR_MSBIT;
else x->len&=MR_OBITS;
}
void mr_lzero(big x)
{ /* strip leading zeros from big number */
mr_lentype s;
int m;
s=(x->len&(MR_MSBIT));
m=(int)(x->len&(MR_OBITS));
while (m>0 && x->w[m-1]==0)
m--;
x->len=m;
if (m>0) x->len|=s;
}
#ifndef MR_SIMPLE_IO
int getdig(_MIPD_ big x,int i)
{ /* extract a packed digit */
int k;
mr_small n;
#ifdef MR_FP
mr_small dres;
#endif
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
i--;
n=x->w[i/mr_mip->pack];
if (mr_mip->pack==1) return (int)n;
k=i%mr_mip->pack;
for (i=1;i<=k;i++)
n=MR_DIV(n,mr_mip->apbase);
return (int)MR_REMAIN(n,mr_mip->apbase);
}
int numdig(_MIPD_ big x)
{ /* returns number of digits in x */
int nd;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (x->len==0) return 0;
nd=(int)(x->len&(MR_OBITS))*mr_mip->pack;
while (getdig(_MIPP_ x,nd)==0)
nd--;
return nd;
}
void putdig(_MIPD_ int n,big x,int i)
{ /* insert a digit into a packed word */
int j,k,lx;
mr_small m,p;
mr_lentype s;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return;
MR_IN(26)
s=(x->len&(MR_MSBIT));
lx=(int)(x->len&(MR_OBITS));
m=getdig(_MIPP_ x,i);
p=n;
i--;
j=i/mr_mip->pack;
k=i%mr_mip->pack;
for (i=1;i<=k;i++)
{
m*=mr_mip->apbase;
p*=mr_mip->apbase;
}
if (j>=mr_mip->nib && (mr_mip->check || j>=2*mr_mip->nib))
{
mr_berror(_MIPP_ MR_ERR_OVERFLOW);
MR_OUT
return;
}
x->w[j]=(x->w[j]-m)+p;
if (j>=lx) x->len=((j+1)|s);
mr_lzero(x);
MR_OUT
}
#endif
#ifndef MR_FP
void mr_and(big x,big y,big z)
{ /* z= bitwise logical AND of x and y */
int i,nx,ny,nz,nr;
if (x==y)
{
copy(x,z);
return;
}
#ifdef MR_FLASH
nx=mr_lent(x);
ny=mr_lent(y);
nz=mr_lent(z);
#else
ny=(y->len&(MR_OBITS));
nx=(x->len&(MR_OBITS));
nz=(z->len&(MR_OBITS));
#endif
if (ny<nx) nr=ny;
else nr=nx;
for (i=0;i<nr;i++)
z->w[i]=x->w[i]&y->w[i];
for (i=nr;i<nz;i++)
z->w[i]=0;
z->len=nr;
}
void mr_xor(big x,big y,big z)
{
int i,nx,ny,nz,nr;
if (x==y)
{
copy(x,z);
return;
}
#ifdef MR_FLASH
nx=mr_lent(x);
ny=mr_lent(y);
nz=mr_lent(z);
#else
ny=(y->len&(MR_OBITS));
nx=(x->len&(MR_OBITS));
nz=(z->len&(MR_OBITS));
#endif
if (ny<nx) nr=ny;
else nr=nx;
for (i=0;i<nr;i++)
z->w[i]=x->w[i]^y->w[i];
for (i=nr;i<nz;i++)
z->w[i]=0;
z->len=nr;
}
#endif
void copy(flash x,flash y)
{ /* copy x to y: y=x */
int i,nx,ny;
mr_small *gx,*gy;
if (x==y || y==NULL) return;
if (x==NULL)
{
zero(y);
return;
}
#ifdef MR_FLASH
ny=mr_lent(y);
nx=mr_lent(x);
#else
ny=(y->len&(MR_OBITS));
nx=(x->len&(MR_OBITS));
#endif
gx=x->w;
gy=y->w;
for (i=nx;i<ny;i++)
gy[i]=0;
for (i=0;i<nx;i++)
gy[i]=gx[i];
y->len=x->len;
}
void negify(flash x,flash y)
{ /* negate a big/flash variable: y=-x */
copy(x,y);
if (y->len!=0) y->len^=MR_MSBIT;
}
void absol(flash x,flash y)
{ /* y=abs(x) */
copy(x,y);
y->len&=MR_OBITS;
}
BOOL mr_notint(flash x)
{ /* returns TRUE if x is Flash */
#ifdef MR_FLASH
if ((((x->len&(MR_OBITS))>>(MR_BTS))&(MR_MSK))!=0) return TRUE;
#endif
return FALSE;
}
void mr_shift(_MIPD_ big x,int n,big w)
{ /* set w=x.(mr_base^n) by shifting */
mr_lentype s;
int i,bl;
mr_small *gw=w->w;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return;
copy(x,w);
if (w->len==0 || n==0) return;
MR_IN(33)
if (mr_notint(w)) mr_berror(_MIPP_ MR_ERR_INT_OP);
s=(w->len&(MR_MSBIT));
bl=(int)(w->len&(MR_OBITS))+n;
if (bl<=0)
{
zero(w);
MR_OUT
return;
}
if (bl>mr_mip->nib && mr_mip->check) mr_berror(_MIPP_ MR_ERR_OVERFLOW);
if (mr_mip->ERNUM)
{
MR_OUT
return;
}
if (n>0)
{
for (i=bl-1;i>=n;i--)
gw[i]=gw[i-n];
for (i=0;i<n;i++)
gw[i]=0;
}
else
{
n=(-n);
for (i=0;i<bl;i++)
gw[i]=gw[i+n];
for (i=0;i<n;i++)
gw[bl+i]=0;
}
w->len=(bl|s);
MR_OUT
}
int size(big x)
{ /* get size of big number; convert to *
* integer - if possible */
int n,m;
mr_lentype s;
if (x==NULL) return 0;
s=(x->len&MR_MSBIT);
m=(int)(x->len&MR_OBITS);
if (m==0) return 0;
if (m==1 && x->w[0]<(mr_small)MR_TOOBIG) n=(int)x->w[0];
else n=MR_TOOBIG;
if (s==MR_MSBIT) return (-n);
return n;
}
int mr_compare(big x,big y)
{ /* compare x and y: =1 if x>y =-1 if x<y *
* =0 if x=y */
int m,n,sig;
mr_lentype sx,sy;
if (x==y) return 0;
sx=(x->len&MR_MSBIT);
sy=(y->len&MR_MSBIT);
if (sx==0) sig=PLUS;
else sig=MINUS;
if (sx!=sy) return sig;
m=(int)(x->len&MR_OBITS);
n=(int)(y->len&MR_OBITS);
if (m>n) return sig;
if (m<n) return -sig;
while (m>0)
{ /* check digit by digit */
m--;
if (x->w[m]>y->w[m]) return sig;
if (x->w[m]<y->w[m]) return -sig;
}
return 0;
}
#ifdef MR_FLASH
void fpack(_MIPD_ big n,big d,flash x)
{ /* create floating-slash number x=n/d from *
* big integer numerator and denominator */
mr_lentype s;
int i,ld,ln;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return;
MR_IN(31)
ld=(int)(d->len&MR_OBITS);
if (ld==0) mr_berror(_MIPP_ MR_ERR_FLASH_OVERFLOW);
if (ld==1 && d->w[0]==1) ld=0;
if (x==d) mr_berror(_MIPP_ MR_ERR_BAD_PARAMETERS);
if (mr_notint(n) || mr_notint(d)) mr_berror(_MIPP_ MR_ERR_INT_OP);
s=(n->len&MR_MSBIT);
ln=(int)(n->len&MR_OBITS);
if (ln==1 && n->w[0]==1) ln=0;
if ((ld+ln>mr_mip->nib) && (mr_mip->check || ld+ln>2*mr_mip->nib))
mr_berror(_MIPP_ MR_ERR_FLASH_OVERFLOW);
if (mr_mip->ERNUM)
{
MR_OUT
return;
}
copy(n,x);
if (n->len==0)
{
MR_OUT
return;
}
s^=(d->len&MR_MSBIT);
if (ld==0)
{
if (x->len!=0) x->len|=s;
MR_OUT
return;
}
for (i=0;i<ld;i++)
x->w[ln+i]=d->w[i];
x->len=(s|(ln+((mr_lentype)ld<<MR_BTS)));
MR_OUT
}
void numer(_MIPD_ flash x,big y)
{ /* extract numerator of x */
int i,ln,ld;
mr_lentype s,ly;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return;
if (mr_notint(x))
{
s=(x->len&MR_MSBIT);
ly=(x->len&MR_OBITS);
ln=(int)(ly&MR_MSK);
if (ln==0)
{
if(s==MR_MSBIT) convert(_MIPP_ (-1),y);
else convert(_MIPP_ 1,y);
return;
}
ld=(int)((ly>>MR_BTS)&MR_MSK);
if (x!=y)
{
for (i=0;i<ln;i++) y->w[i]=x->w[i];
for (i=ln;i<mr_lent(y);i++) y->w[i]=0;
}
else for (i=0;i<ld;i++) y->w[ln+i]=0;
y->len=(ln|s);
}
else copy(x,y);
}
void denom(_MIPD_ flash x,big y)
{ /* extract denominator of x */
int i,ln,ld;
mr_lentype ly;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return;
if (!mr_notint(x))
{
convert(_MIPP_ 1,y);
return;
}
ly=(x->len&MR_OBITS);
ln=(int)(ly&MR_MSK);
ld=(int)((ly>>MR_BTS)&MR_MSK);
for (i=0;i<ld;i++)
y->w[i]=x->w[ln+i];
if (x==y) for (i=0;i<ln;i++) y->w[ld+i]=0;
else for (i=ld;i<mr_lent(y);i++) y->w[i]=0;
y->len=ld;
}
#endif
unsigned int igcd(unsigned int x,unsigned int y)
{ /* integer GCD, returns GCD of x and y */
unsigned int r;
if (y==0) return x;
while ((r=x%y)!=0)
x=y,y=r;
return y;
}
unsigned long lgcd(unsigned long x,unsigned long y)
{ /* long GCD, returns GCD of x and y */
unsigned long r;
if (y==0) return x;
while ((r=x%y)!=0)
x=y,y=r;
return y;
}
unsigned int isqrt(unsigned int num,unsigned int guess)
{ /* square root of an integer */
unsigned int sqr;
unsigned int oldguess=guess;
if (num==0) return 0;
if (num<4) return 1;
for (;;)
{ /* Newtons iteration */
/* sqr=guess+(((num/guess)-guess)/2); */
sqr=((num/guess)+guess)/2;
if (sqr==guess || sqr==oldguess)
{
if (sqr*sqr>num) sqr--;
return sqr;
}
oldguess=guess;
guess=sqr;
}
}
unsigned long mr_lsqrt(unsigned long num,unsigned long guess)
{ /* square root of a long */
unsigned long sqr;
unsigned long oldguess=guess;
if (num==0) return 0;
if (num<4) return 1;
for (;;)
{ /* Newtons iteration */
/* sqr=guess+(((num/guess)-guess)/2); */
sqr=((num/guess)+guess)/2;
if (sqr==guess || sqr==oldguess)
{
if (sqr*sqr>num) sqr--;
return sqr;
}
oldguess=guess;
guess=sqr;
}
}
mr_small sgcd(mr_small x,mr_small y)
{ /* integer GCD, returns GCD of x and y */
mr_small r;
#ifdef MR_FP
mr_small dres;
#endif
if (y==(mr_small)0) return x;
while ((r=MR_REMAIN(x,y))!=(mr_small)0)
x=y,y=r;
return y;
}
/* routines to support sliding-windows exponentiation *
* in various contexts */
int mr_testbit(_MIPD_ big x,int n)
{ /* return value of n-th bit of big */
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
#ifdef MR_FP
mr_small m,a,dres;
m=mr_shiftbits((mr_small)1,n%mr_mip->lg2b);
a=x->w[n/mr_mip->lg2b];
a=MR_DIV(a,m);
if ((MR_DIV(a,2.0)*2.0) != a) return 1;
#else
if ((x->w[n/mr_mip->lg2b] & ((mr_small)1<<(n%mr_mip->lg2b))) >0) return 1;
#endif
return 0;
}
void mr_addbit(_MIPD_ big x,int n)
{ /* add 2^n to positive x - where you know that bit is zero. Use with care! */
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
mr_lentype m=n/mr_mip->lg2b;
x->w[m]+=mr_shiftbits((mr_small)1,n%mr_mip->lg2b);
if (x->len<m+1) x->len=m+1;
}
int recode(_MIPD_ big e,int t,int w,int i)
{ /* recode exponent for Comb method */
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
int j,r;
r=0;
for (j=w-1;j>=0;j--)
{
r<<=1;
r|=mr_testbit(_MIPP_ e,i+j*t);
}
return r;
}
int mr_window(_MIPD_ big x,int i,int *nbs,int * nzs,int window_size)
{ /* returns sliding window value, max. of 5 bits, *
* (Note from version 5.23 this can be changed by *
* setting parameter window_size. This can be *
* a useful space-saver) starting at i-th bit of big x. *
* nbs is number of bits processed, nzs is the number of *
* additional trailing zeros detected. Returns valid bit *
* pattern 1x..x1 with no two adjacent 0's. So 10101 *
* will return 21 with nbs=5, nzs=0. 11001 will return 3,*
* with nbs=2, nzs=2, having stopped after the first 11..*/
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
int j,r,w;
w=window_size;
/* check for leading 0 bit */
*nbs=1;
*nzs=0;
if (!mr_testbit(_MIPP_ x,i)) return 0;
/* adjust window size if not enough bits left */
if (i-w+1<0) w=i+1;
r=1;
for (j=i-1;j>i-w;j--)
{ /* accumulate bits. Abort if two 0's in a row */
(*nbs)++;
r*=2;
if (mr_testbit(_MIPP_ x,j)) r+=1;
if (r%4==0)
{ /* oops - too many zeros - shorten window */
r/=4;
*nbs-=2;
*nzs=2;
break;
}
}
if (r%2==0)
{ /* remove trailing 0 */
r/=2;
*nzs=1;
(*nbs)--;
}
return r;
}
int mr_window2(_MIPD_ big x,big y,int i,int *nbs,int *nzs)
{ /* two bit window for double exponentiation */
int r,w;
BOOL a,b,c,d;
w=2;
*nbs=1;
*nzs=0;
/* check for two leading 0's */
a=mr_testbit(_MIPP_ x,i); b=mr_testbit(_MIPP_ y,i);
if (!a && !b) return 0;
if (i<1) w=1;
if (a)
{
if (b) r=3;
else r=2;
}
else r=1;
if (w==1) return r;
c=mr_testbit(_MIPP_ x,i-1); d=mr_testbit(_MIPP_ y,i-1);
if (!c && !d)
{
*nzs=1;
return r;
}
*nbs=2;
r*=4;
if (c)
{
if (d) r+=3;
else r+=2;
}
else r+=1;
return r;
}
int mr_naf_window(_MIPD_ big x,big x3,int i,int *nbs,int *nzs,int store)
{ /* returns sliding window value, using fractional windows *
* where "store" precomputed values are precalulated and *
* stored. Scanning starts at the i-th bit of x. nbs is *
* the number of bits processed. nzs is number of *
* additional trailing zeros detected. x and x3 (which is *
* 3*x) are combined to produce the NAF (non-adjacent *
* form). So if x=11011(27) and x3 is 1010001, the LSB is *
* ignored and the value 100T0T (32-4-1=27) processed, *
* where T is -1. Note x.P = (3x-x)/2.P. This value will *
* return +7, with nbs=4 and nzs=1, having stopped after *
* the first 4 bits. If it goes too far, it must backtrack *
* Note in an NAF non-zero elements are never side by side, *
* so 10T10T won't happen. NOTE: return value n zero or *
* odd, -21 <= n <= +21 */
int nb,j,r,biggest;
/* get first bit */
nb=mr_testbit(_MIPP_ x3,i)-mr_testbit(_MIPP_ x,i);
*nbs=1;
*nzs=0;
if (nb==0) return 0;
if (i==0) return nb;
biggest=2*store-1;
if (nb>0) r=1;
else r=(-1);
for (j=i-1;j>0;j--)
{
(*nbs)++;
r*=2;
nb=mr_testbit(_MIPP_ x3,j)-mr_testbit(_MIPP_ x,j);
if (nb>0) r+=1;
if (nb<0) r-=1;
if (abs(r)>biggest) break;
}
if (r%2!=0 && j!=0)
{ /* backtrack */
if (nb>0) r=(r-1)/2;
if (nb<0) r=(r+1)/2;
(*nbs)--;
}
while (r%2==0)
{ /* remove trailing zeros */
r/=2;
(*nzs)++;
(*nbs)--;
}
return r;
}
/* Some general purpose elliptic curve stuff */
BOOL point_at_infinity(epoint *p)
{
if (p==NULL) return FALSE;
if (p->marker==MR_EPOINT_INFINITY) return TRUE;
return FALSE;
}
#ifndef MR_STATIC
epoint* epoint_init(_MIPDO_ )
{ /* initialise epoint to general point at infinity. */
epoint *p;
char *ptr;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return NULL;
MR_IN(96)
/* Create space for whole structure in one heap access */
p=(epoint *)mr_alloc(_MIPP_ mr_esize(mr_mip->nib-1),1);
ptr=(char *)p+sizeof(epoint);
p->X=mirvar_mem(_MIPP_ ptr,0);
p->Y=mirvar_mem(_MIPP_ ptr,1);
#ifndef MR_AFFINE_ONLY
p->Z=mirvar_mem(_MIPP_ ptr,2);
#endif
p->marker=MR_EPOINT_INFINITY;
MR_OUT
return p;
}
#endif
epoint* epoint_init_mem_variable(_MIPD_ char *mem,int index,int sz)
{
epoint *p;
char *ptr;
int offset,r;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
offset=0;
r=(unsigned long)mem%MR_SL;
if (r>0) offset=MR_SL-r;
#ifndef MR_AFFINE_ONLY
if (mr_mip->coord==MR_AFFINE)
p=(epoint *)&mem[offset+index*mr_esize_a(sz)];
else
#endif
p=(epoint *)&mem[offset+index*mr_esize(sz)];
ptr=(char *)p+sizeof(epoint);
p->X=mirvar_mem_variable(ptr,0,sz);
p->Y=mirvar_mem_variable(ptr,1,sz);
#ifndef MR_AFFINE_ONLY
if (mr_mip->coord!=MR_AFFINE) p->Z=mirvar_mem_variable(ptr,2,sz);
#endif
p->marker=MR_EPOINT_INFINITY;
return p;
}
epoint* epoint_init_mem(_MIPD_ char *mem,int index)
{
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return NULL;
return epoint_init_mem_variable(_MIPP_ mem,index,mr_mip->nib-1);
}
#ifndef MR_STATIC
/* allocate space for a number of epoints from the heap */
void *ecp_memalloc(_MIPD_ int num)
{
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
#ifndef MR_AFFINE_ONLY
if (mr_mip->coord==MR_AFFINE)
return mr_alloc(_MIPP_ mr_ecp_reserve_a(num,mr_mip->nib-1),1);
else
#endif
return mr_alloc(_MIPP_ mr_ecp_reserve(num,mr_mip->nib-1),1);
}
#endif
void ecp_memkill(_MIPD_ char *mem,int num)
{
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mem==NULL) return;
#ifndef MR_AFFINE_ONLY
if (mr_mip->coord==MR_AFFINE)
memset(mem,0,mr_ecp_reserve_a(num,mr_mip->nib-1));
else
#endif
memset(mem,0,mr_ecp_reserve(num,mr_mip->nib-1));
#ifndef MR_STATIC
mr_free(mem);
#endif
}
#ifndef MR_STATIC
void epoint_free(epoint *p)
{ /* clean up point */
if (p==NULL) return;
zero(p->X);
zero(p->Y);
#ifndef MR_AFFINE_ONLY
if (p->marker==MR_EPOINT_GENERAL) zero(p->Z);
#endif
mr_free(p);
}
#endif
|
conversion.h
|
#pragma once
#include "infra/cast.h"
#include <algorithm>
#include <cmath>
namespace gdx {
template <template <typename> typename RasterType, typename T>
RasterType<T> replace_value(const RasterType<T>& ras, const T oldValue, const T newValue)
{
RasterType<T> result(ras.metadata());
std::transform(begin(ras), end(ras), begin(result), [oldValue, newValue](auto value) {
if constexpr (RasterType<T>::raster_type_has_nan) {
if (std::isfinite(value) && value == oldValue) {
return newValue;
}
} else if (value == oldValue) {
return newValue;
}
return value;
});
return result;
}
template <template <typename> typename RasterType, typename TSource, typename TDest>
RasterType<TDest> cast(const RasterType<TSource>& srcData)
{
constexpr bool srcHasNaN = RasterType<TSource>::raster_type_has_nan;
constexpr bool dstHasNaN = RasterType<TDest>::raster_type_has_nan;
auto resultMeta = srcData.metadata();
if constexpr (!dstHasNaN) {
if (resultMeta.nodata) {
if (std::isnan(*resultMeta.nodata)) {
// modify the NaN nodata when the resulting type does not support NaN values
resultMeta.nodata = static_cast<TDest>(*resultMeta.nodata);
} else if (!inf::fits_in_type<TDest>(resultMeta.nodata.value())) {
resultMeta.nodata = std::numeric_limits<TDest>::max();
}
}
}
RasterType<TDest> dstData(resultMeta);
if constexpr (!srcHasNaN && dstHasNaN) {
if (srcData.metadata().nodata) {
auto nodata = *srcData.metadata().nodata;
// nodata values will be replaced with nan
#pragma omp parallel for
for (std::size_t i = 0; i < srcData.size(); ++i) {
if (srcData[i] == nodata) {
dstData[i] = std::numeric_limits<TDest>::quiet_NaN();
} else {
dstData[i] = static_cast<TDest>(srcData[i]);
}
}
return resultMeta;
}
} else if constexpr (srcHasNaN && !dstHasNaN) {
if (resultMeta.nodata) {
auto nodata = static_cast<TDest>(*resultMeta.nodata);
// nan values need to be replaced with the nodata value
#pragma omp parallel for
for (std::size_t i = 0; i < srcData.size(); ++i) {
if (std::isnan(srcData[i]) || srcData[i] == srcData.metadata().nodata) {
dstData[i] = nodata;
} else {
dstData[i] = static_cast<TDest>(srcData[i]);
}
}
return resultMeta;
}
}
// No nodata conversions, regular copy
#pragma omp parallel for
for (std::size_t i = 0; i < srcData.size(); ++i) {
dstData[i] = static_cast<TDest>(srcData[i]);
}
return resultMeta;
}
}
|
GB_unop__identity_int8_int64.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_int8_int64)
// op(A') function: GB (_unop_tran__identity_int8_int64)
// C type: int8_t
// A type: int64_t
// cast: int8_t cij = (int8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int8_t z = (int8_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int8_t z = (int8_t) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int8_int64)
(
int8_t *Cx, // Cx and Ax may be aliased
const int64_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++)
{
int64_t aij = Ax [p] ;
int8_t z = (int8_t) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int64_t aij = Ax [p] ;
int8_t z = (int8_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_int8_int64)
(
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
|
omp_lock.c
|
// RUN: %libomp-compile-and-run
// RUN: env KMP_LOCK_KIND=tas KMP_SPIN_BACKOFF_PARAMS=2048,200 %libomp-run
// RUN: env KMP_LOCK_KIND=futex %libomp-run
#include <stdio.h>
#include "omp_testsuite.h"
omp_lock_t lck;
int test_omp_lock()
{
int nr_threads_in_single = 0;
int result = 0;
int nr_iterations = 0;
int i;
omp_init_lock(&lck);
#pragma omp parallel shared(lck)
{
#pragma omp for
for(i = 0; i < LOOPCOUNT; i++) {
omp_set_lock(&lck);
#pragma omp flush
nr_threads_in_single++;
#pragma omp flush
nr_iterations++;
nr_threads_in_single--;
result = result + nr_threads_in_single;
omp_unset_lock(&lck);
}
}
omp_destroy_lock(&lck);
return ((result == 0) && (nr_iterations == LOOPCOUNT));
}
int main()
{
int i;
int num_failed=0;
for(i = 0; i < REPETITIONS; i++) {
if(!test_omp_lock()) {
num_failed++;
}
}
return num_failed;
}
|
add.c
|
#include <stdio.h>
#include <omp.h>
int main(){
int A[10], B[10] = {0,1,2,3,4,5,6,7,8,9}, C[10] = {0,1,2,3,4,5,6,7,8,9}, i, m, k;
omp_set_dynamic(0);
m = omp_get_num_procs();
omp_set_num_threads(m);
printf("Parallel\n------------");
#pragma omp parallel for shared(A, B, C) private(i)
for(i = 0; i < 10; i++){
A[i] = B[i] + C[i];
printf("\nB[%d] + C[%d] = %d + %d = %d = A[%d] from thread %d of %d", i, i, B[i], C[i], A[i], i, omp_get_thread_num(), omp_get_num_threads());
}
return 0;
}
|
palshop_fmt_plug.c
|
/* This format is reverse engineered from InsidePro Hash Manager!
*
* This software is Copyright (c) 2016, Dhiru Kholia <dhiru.kholia at gmail.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.
*
* improved speed, JimF. Reduced amount of hex encoding.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_palshop;
#elif FMT_REGISTERS_H
john_register_one(&fmt_palshop);
#else
#include "arch.h"
#include "sha.h"
#include "md5.h"
#include <string.h>
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "base64_convert.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 1024
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "Palshop"
#define FORMAT_NAME "MD5(Palshop)"
#define ALGORITHM_NAME "MD5 + SHA1 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 125
#define BINARY_SIZE 10 /* 20 characters of "m2", now 10 binary bytes. */
#define SALT_SIZE 0
#define BINARY_ALIGN sizeof(uint32_t)
#define SALT_ALIGN sizeof(int)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define FORMAT_TAG "$palshop$"
#define TAG_LENGTH (sizeof(FORMAT_TAG) - 1)
static struct fmt_tests palshop_tests[] = {
{"$palshop$68b11ee90ed17ef14aa0f51af494c2c63ad7d281a9888cb593e", "123"},
{"ea3a8d0f4cd9e5e22ccede1ad59dd2c5c7e839348a8a519d505", "ABC"},
// http://leopard.500mb.net/HashGenerator/
{"$palshop$f2e3babc50b316e6e886f3062a37cead6d1bd16dd2bed49f7bc", "long password"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_out)[ (BINARY_SIZE+sizeof(uint32_t)-1) / sizeof(uint32_t)];
static size_t *saved_len;
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
static 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(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
saved_len = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_len));
}
static void done(void)
{
MEM_FREE(saved_len);
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *p = ciphertext;
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
p = ciphertext + TAG_LENGTH;
if (!p)
return 0;
if (!ishex_oddOK(p))
return 0;
if (strlen(p) != 51)
return 0;
return 1;
}
static void *get_binary(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE+1];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p = ciphertext;
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
p = ciphertext + TAG_LENGTH;
++p; // skip the first 'nibble'. Take next 10 bytes.
base64_convert(p, e_b64_hex, 20, out, e_b64_raw, 10, 0, 0);
return out;
}
static int get_hash_0(int index) { return crypt_out[index][0] & 0xf; }
static int get_hash_1(int index) { return crypt_out[index][0] & 0xff; }
static int get_hash_2(int index) { return crypt_out[index][0] & 0xfff; }
static int get_hash_3(int index) { return crypt_out[index][0] & 0xffff; }
static int get_hash_4(int index) { return crypt_out[index][0] & 0xfffff; }
static int get_hash_5(int index) { return crypt_out[index][0] & 0xffffff; }
static int get_hash_6(int index) { return crypt_out[index][0] & 0x7ffffff; }
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
{
unsigned char m1[53], buffer[16+20], *cp;
int i;
MD5_CTX mctx;
SHA_CTX sctx;
// m1 = md5($p)
MD5_Init(&mctx);
MD5_Update(&mctx, saved_key[index], saved_len[index]);
MD5_Final(buffer, &mctx);
// s1 = sha1($p)
SHA1_Init(&sctx);
SHA1_Update(&sctx, saved_key[index], saved_len[index]);
SHA1_Final(buffer+16, &sctx);
// data = m1[11:] + s1[:29] + m1[0:1] // 51 bytes!
cp = m1;
*cp++ = itoa16[buffer[5]&0xF];
for (i = 6; i < 25+6; ++i) {
cp[0] = itoa16[buffer[i]>>4];
cp[1] = itoa16[buffer[i]&0xF];
cp += 2;
}
cp[-1] = itoa16[buffer[0]>>4];
// m2
MD5_Init(&mctx);
MD5_Update(&mctx, m1, 51);
MD5_Final(buffer, &mctx);
// s2 = sha1(data)
// SHA1_Init(&sctx);
// SHA1_Update(&sctx, data, 51);
// SHA1_Final((unsigned char*)crypt_out[index], &sctx);
// hex_encode((unsigned char*)crypt_out[index], 20, s1);
// hash = m2[11:] + s2[:29] + m2[0], but starting 20 bytes should be enough!
//memcpy((unsigned char*)crypt_out[index], m2 + 11, 20);
// we actually take m2[12:32] (skipping that first 'odd' byte.0
// in binary now, skipping the unneeded hex conversion.
memcpy((unsigned char*)crypt_out[index], buffer+6, 10);
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
for (; index < count; index++)
if (*((uint32_t*)binary) == crypt_out[index][0])
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void palshop_set_key(char *key, int index)
{
saved_len[index] =
strnzcpyn(saved_key[index], key, sizeof(saved_key[index]));
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_palshop = {
{
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,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
{ FORMAT_TAG },
palshop_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
fmt_default_salt,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
palshop_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 */
|
ep.c
|
/*--------------------------------------------------------------------
NAS Parallel Benchmarks 2.3 OpenMP C versions - EP
This benchmark is an OpenMP C version of the NPB EP code.
The OpenMP C versions are developed by RWCP and derived from the serial
Fortran versions in "NPB 2.3-serial" developed by NAS.
Permission to use, copy, distribute and modify this software for any
purpose with or without fee is hereby granted.
This software is provided "as is" without express or implied warranty.
Send comments on the OpenMP C versions to [email protected]
Information on OpenMP activities at RWCP is available at:
http://pdplab.trc.rwcp.or.jp/pdperf/Omni/
Information on NAS Parallel Benchmarks 2.3 is available at:
http://www.nas.nasa.gov/NAS/NPB/
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
Author: P. O. Frederickson
D. H. Bailey
A. C. Woo
OpenMP C version: S. Satoh
--------------------------------------------------------------------*/
//#define DEBUG_ON_x
//#define DEBUG_ON_t1
//#define DEBUG_ON_q
#include "npb-C.h"
#include "npbparams.h"
/* parameters */
#define MK 12
#define MM (M - MK)
#define NN (1 << MM)
#define NK (1 << MK)
#define NQ 10
//#define EPSILON 1.0e-8
//#define A 1220703125.0
//#define S 271828183.0
#define EPSILON 1.0e-6
#define A 390625.0f
#define S 28183.0f
//#define TIMERS_ENABLED FALSE
#if defined(USE_POW)
#define r23 pow(0.5f, 11.0F)
#define r46 (r23*r23)
#define t23 pow(2.0f, 11.0F)
#define t46 (t23*t23)
#else
#define r23 (0.5f*0.5f*0.5f*0.5f*0.5f*0.5f*0.5f*0.5f*0.5f*0.5f*0.5f)
#define r46 (r23*r23)
#define t23 (2.0f*2.0f*2.0f*2.0f*2.0f*2.0f*2.0f*2.0f*2.0f*2.0f*2.0f)
#define t46 (t23*t23)
#endif
#ifndef _UNROLLFAC_
#define _UNROLLFAC_ 1
#endif
#ifdef _OPENARC_
#if _UNROLLFAC_ == 1
#pragma openarc #define _UNROLLFAC_ 1
#elif _UNROLLFAC_ == 6
#pragma openarc #define _UNROLLFAC_ 6
#elif _UNROLLFAC_ == 8
#pragma openarc #define _UNROLLFAC_ 8
#elif _UNROLLFAC_ == 32
#pragma openarc #define _UNROLLFAC_ 32
#elif _UNROLLFAC_ == 128
#pragma openarc #define _UNROLLFAC_ 128
#elif _UNROLLFAC_ == 1024
#pragma openarc #define _UNROLLFAC_ 1024
#endif
#pragma openarc #define NK 4096
#endif
/* global variables */
/* common /storage/ */
static float x[2*NK];
//#pragma omp threadprivate(x)
static float q[NQ];
/*--------------------------------------------------------------------
program EMBAR
c-------------------------------------------------------------------*/
/*
c This is the serial version of the APP Benchmark 1,
c the "embarassingly parallel" benchmark.
c
c M is the Log_2 of the number of complex pairs of uniform (0, 1) random
c numbers. MK is the Log_2 of the size of each batch of uniform random
c numbers. MK can be set for convenience on a given system, since it does
c not affect the results.
*/
int main(int argc, char **argv) {
float Mops, t1, t2, t3, t4, x1, x2, sx, sy, tm, an, tt, gc;
float dum[3] = { 1.0F, 1.0F, 1.0F };
int np, ierr, node, no_nodes, i, ik, kk, l, k, nit, ierrcode,
no_large_nodes, np_add, k_offset, j;
int nthreads = 1;
boolean verified;
char size[13+1]; /* character*13 */
//float t1, t2, t3, t4, x1, x2;
//int kk, i, ik, l;
//float qq[NQ]; /* private copy of q[0:NQ-1] */
float qq0;
float qq1;
float qq2;
float qq3;
float qq4;
float qq5;
float qq6;
float qq7;
float qq8;
float qq9;
float t1_randlc,t2_randlc,t3_randlc,t4_randlc,a1_randlc,a2_randlc,x1_randlc,x2_randlc,z_randlc, a_randlc;
int i_vranlc;
float x_vranlc;
float (*xx)[(NN/_UNROLLFAC_)];
int m;
/*
c Because the size of the problem is too large to store in a 32-bit
c integer for some classes, we put it into a string (for printing).
c Have to strip off the decimal point put in there by the floating
c point print statement (internal file)
*/
printf("\n\n NAS Parallel Benchmarks 2.3 OpenMP C version"
" - EP Benchmark\n");
sprintf(size, "%12.0f", pow(2.0F, M+1));
for (j = 13; j >= 1; j--) {
if (size[j] == '.') size[j] = ' ';
}
printf(" Number of random numbers generated: %13s\n", size);
verified = FALSE;
/*
c Compute the number of "batches" of random number pairs generated
c per processor. Adjust if the number of processors does not evenly
c divide the total number
*/
np = NN;
/*
c Call the random number generator functions and initialize
c the x-array to reduce the effects of paging on the timings.
c Also, call all mathematical functions that are used. Make
c sure these initializations cannot be eliminated as dead code.
*/
vranlc(0, &(dum[0]), dum[1], &(dum[2]));
dum[0] = randlc(&(dum[1]), dum[2]);
for (i = 0; i < 2*NK; i++) x[i] = -1.0e38;
Mops = log(sqrt(fabs(max(1.0F, 1.0F))));
timer_clear(1);
timer_clear(2);
timer_clear(3);
timer_start(1);
vranlc(0, &t1, A, x);
/* Compute AN = A ^ (2 * NK) (mod 2^46). */
t1 = A;
for ( i = 1; i <= MK+1; i++) {
t2 = randlc(&t1, t1);
}
an = t1;
tt = S;
gc = 0.0F;
sx = 0.0F;
sy = 0.0F;
for ( i = 0; i <= NQ - 1; i++) {
q[i] = 0.0F;
}
qq0 = 0.0F;
qq1 = 0.0F;
qq2 = 0.0F;
qq3 = 0.0F;
qq4 = 0.0F;
qq5 = 0.0F;
qq6 = 0.0F;
qq7 = 0.0F;
qq8 = 0.0F;
qq9 = 0.0F;
/*
c Each instance of this loop may be performed independently. We compute
c the k offsets separately to take into account the fact that some nodes
c have more numbers to generate than others
*/
k_offset = -1;
xx = (float (*)[NN/_UNROLLFAC_])malloc((2*NK)*(NN/_UNROLLFAC_)*sizeof(float));
#pragma acc kernels loop gang, worker, \
copyin(x[0:2*NK]), create(xx[0:2*NK][0:(NN/_UNROLLFAC_)]), \
private(t1, t2, t3, t4, x1, x2, k, kk, i, ik, m), \
private(l, t1_randlc, t2_randlc, t3_randlc, t4_randlc, a1_randlc, a2_randlc), \
private(x1_randlc, x2_randlc, z_randlc, a_randlc, i_vranlc, x_vranlc)
for (m = 0; m < (NN/_UNROLLFAC_); m++)
{
for (i = 0; i < 2*NK; i++) xx[i][m] = x[i];
for (k = 0; k <_UNROLLFAC_; k++)
{
//for (i = 0; i < NQ; i++) qq[i] = 0.0f;
//#pragma omp for reduction(+:sx,sy) schedule(static) nowait
kk = k_offset + (m+k*(NN/_UNROLLFAC_)) + 1;
t1 = S;
t2 = an;
/* Find starting seed t1 for this kk. */
for (i = 1; i <= 100; i++) {
ik = kk / 2;
if (2 * ik != kk) {
//t3 = randlc(&t1, t2);
a_randlc = t2;
t1_randlc = r23 * a_randlc;
a1_randlc = (int)t1_randlc;
a2_randlc = a_randlc - t23 * a1_randlc;
t1_randlc = r23 * t1;
x1_randlc = (int)t1_randlc;
x2_randlc = t1 - t23 * x1_randlc;
t1_randlc = a1_randlc * x2_randlc + a2_randlc * x1_randlc;
t2_randlc = (int)(r23 * t1_randlc);
z_randlc = t1_randlc - t23 * t2_randlc;
t3_randlc = t23 * z_randlc + a2_randlc * x2_randlc;
t4_randlc = (int)(r46 * t3_randlc);
t1 = t3_randlc - t46 * t4_randlc;
t3 = (r46 * t1);
}
if (ik == 0) break;
//t3 = randlc(&t2, t2);
a_randlc = t2;
t1_randlc = r23 * a_randlc;
a1_randlc = (int)t1_randlc;
a2_randlc = a_randlc - t23 * a1_randlc;
t1_randlc = r23 * t2;
x1_randlc = (int)t1_randlc;
x2_randlc = t2 - t23 * x1_randlc;
t1_randlc = a1_randlc * x2_randlc + a2_randlc * x1_randlc;
t2_randlc = (int)(r23 * t1_randlc);
z_randlc = t1_randlc - t23 * t2_randlc;
t3_randlc = t23 * z_randlc + a2_randlc * x2_randlc;
t4_randlc = (int)(r46 * t3_randlc);
t2 = t3_randlc - t46 * t4_randlc;
t3 = (r46 * t2);
kk = ik;
}
#ifdef DEBUG_ON_t1
printf("k = %d: t1 = %f\n", k-1, t1);
#endif
/* Compute uniform pseudorandom numbers. */
#ifdef TIMERS_ENABLED
if (TIMERS_ENABLED == TRUE) timer_start(3);
#endif
//vranlc(2*NK, &t1, A, x-1);
t1_randlc = r23 * A;
a1_randlc = (int)t1_randlc;
a2_randlc = A - t23 * a1_randlc;
x_vranlc = t1;
for (i_vranlc = 1; i_vranlc <= 2*NK; i_vranlc++) {
t1_randlc = r23 * x_vranlc;
x1_randlc = (int)t1_randlc;
x2_randlc = x_vranlc - t23 * x1_randlc;
t1_randlc = a1_randlc * x2_randlc + a2_randlc * x1_randlc;
t2_randlc = (int)(r23 * t1_randlc);
z_randlc = t1_randlc - t23 * t2_randlc;
t3_randlc = t23 * z_randlc + a2_randlc * x2_randlc;
t4_randlc = (int)(r46 * t3_randlc);
x_vranlc = t3_randlc - t46 * t4_randlc;
xx[i_vranlc-1][m] = r46 * x_vranlc;
}
t1 = x_vranlc;
#ifdef TIMERS_ENABLED
if (TIMERS_ENABLED == TRUE) timer_stop(3);
#endif
#ifdef DEBUG_ON_x
if( (3 <= k)&&(k <= 5) )
for (i = 30; i < 40; i++) printf("x[%d][%d] = %f\n",k-1,i,x[i]);
#endif
/*
c Compute Gaussian deviates by acceptance-rejection method and
c tally counts in concentric square annuli. This loop is not
c vectorizable.
*/
#ifdef TIMERS_ENABLED
if (TIMERS_ENABLED == TRUE) timer_start(2);
#endif
for ( i = 0; i < NK; i++) {
x1 = 2.0F * xx[2*i][m] - 1.0F;
x2 = 2.0F * xx[2*i+1][m] - 1.0F;
t1 = pow2(x1) + pow2(x2);
if (t1 <= 1.0F) {
t2 = sqrtf(-2.0F * logf(t1) / t1);
t3 = (x1 * t2); /* Xi */
t4 = (x2 * t2); /* Yi */
l = max(fabsf(t3), fabsf(t4));
//qq[l] += 1.0F; /* counts */
if( l == 0 ) { qq0 += 1.0F; }
else if( l == 1 ) { qq1 += 1.0F; }
else if( l == 2 ) { qq2 += 1.0F; }
else if( l == 3 ) { qq3 += 1.0F; }
else if( l == 4 ) { qq4 += 1.0F; }
else if( l == 5 ) { qq5 += 1.0F; }
else if( l == 6 ) { qq6 += 1.0F; }
else if( l == 7 ) { qq7 += 1.0F; }
else if( l == 8 ) { qq8 += 1.0F; }
else { qq9 += 1.0F; }
sx = sx + t3; /* sum of Xi */
sy = sy + t4; /* sum of Yi */
}
}
#ifdef TIMERS_ENABLED
if (TIMERS_ENABLED == TRUE) timer_stop(2);
#endif
#ifdef DEBUG_ON_q
printf("k = %d\n", k);
for (i = 0; i <= NQ - 1; i++) printf("qq[%d] = %f\n",i,qq[i]);
#endif
/*
//#pragma omp critical
{
for (i = 0; i <= NQ - 1; i++) q[i] += qq[i];
}
*/
}
} /* end of parallel region */
q[0] = qq0;
q[1] = qq1;
q[2] = qq2;
q[3] = qq3;
q[4] = qq4;
q[5] = qq5;
q[6] = qq6;
q[7] = qq7;
q[8] = qq8;
q[9] = qq9;
for (i = 0; i <= NQ-1; i++) {
gc = gc + q[i];
}
timer_stop(1);
tm = timer_read(1);
nit = 0;
if (M == 24) {
if((fabs((sx- (2.554318847656250e+02))/sx) <= EPSILON) &&
(fabs((sy- (-2.176109161376953e+02))/sy) <= EPSILON)) {
verified = TRUE;
}
} else if (M == 25) {
if ((fabs((sx- (5.110573425292969e+02))/sx) <= EPSILON) &&
(fabs((sy- (-4.353658142089844e+02))/sy) <= EPSILON)) {
verified = TRUE;
}
} else if (M == 28) {
if ((fabs((sx- (3.994430908203125e+03))/sx) <= EPSILON) &&
(fabs((sy- (-3.514263671875000e+03))/sy) <= EPSILON)) {
verified = TRUE;
}
} else if (M == 30) {
if ((fabs((sx- (1.699876171875000e+04))/sx) <= EPSILON) &&
(fabs((sy- (-1.385202929687500e+04))/sy) <= EPSILON)) {
verified = TRUE;
}
} else if (M == 32) {
if ((fabs((sx- (4.520392968750000e+04))/sx) <= EPSILON) &&
(fabs((sy- (-4.611721093750000e+04))/sy) <= EPSILON)) {
verified = TRUE;
}
}
Mops = pow(2.0F, M+1)/tm/1000000.0F;
printf("EP Benchmark Results: \n"
"Accelerator Elapsed Time = %10.4f\n"
"N = 2^%5d\n"
"No. Gaussian Pairs = %15.0f\n"
"Sums = %25.15e %25.15e\n"
"Counts:\n",
tm, M, gc, sx, sy);
for (i = 0; i <= NQ-1; i++) {
printf("%3d %15.0f\n", i, q[i]);
}
c_print_results("EP", CLASS, M+1, 0, 0, nit, nthreads,
tm, Mops,
"Random numbers generated",
verified, NPBVERSION, COMPILETIME,
CS1, CS2, CS3, CS4, CS5, CS6, CS7);
#ifdef TIMERS_ENABLED
if (TIMERS_ENABLED == TRUE) {
printf("Total time: %f", timer_read(1));
printf("Gaussian pairs: %f", timer_read(2));
printf("Random numbers: %f", timer_read(3));
}
#endif
return 0;
}
|
threshold.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD %
% T H H R R E SS H H O O L D D %
% T HHHHH RRRR EEE SSS HHHHH O O L D D %
% T H H R R E SS H H O O L D D %
% T H H R R EEEEE SSSSS H H OOO LLLLL DDDD %
% %
% %
% MagickCore Image Threshold Methods %
% %
% Software Design %
% John Cristy %
% October 1996 %
% %
% %
% 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/cache-view.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/configure.h"
#include "magick/constitute.h"
#include "magick/decorate.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/effect.h"
#include "magick/fx.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/montage.h"
#include "magick/option.h"
#include "magick/pixel-private.h"
#include "magick/quantize.h"
#include "magick/quantum.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/shear.h"
#include "magick/signature-private.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/threshold.h"
#include "magick/transform.h"
#include "magick/xml-tree.h"
/*
Define declarations.
*/
#define ThresholdsFilename "thresholds.xml"
/*
Typedef declarations.
*/
struct _ThresholdMap
{
char
*map_id,
*description;
size_t
width,
height;
ssize_t
divisor,
*levels;
};
/*
Static declarations.
*/
static const char
*MinimalThresholdMap =
"<?xml version=\"1.0\"?>"
"<thresholds>"
" <threshold map=\"threshold\" alias=\"1x1\">"
" <description>Threshold 1x1 (non-dither)</description>"
" <levels width=\"1\" height=\"1\" divisor=\"2\">"
" 1"
" </levels>"
" </threshold>"
" <threshold map=\"checks\" alias=\"2x1\">"
" <description>Checkerboard 2x1 (dither)</description>"
" <levels width=\"2\" height=\"2\" divisor=\"3\">"
" 1 2"
" 2 1"
" </levels>"
" </threshold>"
"</thresholds>";
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveThresholdImage() selects an individual threshold for each pixel
% based on the range of intensity values in its local neighborhood. This
% allows for thresholding of an image whose global intensity histogram
% doesn't contain distinctive peaks.
%
% The format of the AdaptiveThresholdImage method is:
%
% Image *AdaptiveThresholdImage(const Image *image,
% const size_t width,const size_t height,
% const ssize_t offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the local neighborhood.
%
% o height: the height of the local neighborhood.
%
% o offset: the mean offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
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);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*restrict indexes;
register const PixelPacket
*restrict p,
*restrict r;
register IndexPacket
*restrict threshold_indexes;
register PixelPacket
*restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_AdaptiveThresholdImage)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B i l e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BilevelImage() changes the value of individual pixels based on the
% intensity of each pixel channel. The result is a high-contrast image.
%
% More precisely each channel value of the image is 'thresholded' so that if
% it is equal to or less than the given value it is set to zero, while any
% value greater than that give is set to it maximum or QuantumRange.
%
% This function is what is used to implement the "-threshold" operator for
% the command line API.
%
% If the default channel setting is given the image is thresholded using just
% the gray 'intensity' of the image, rather than the individual channels.
%
% The format of the BilevelImageChannel method is:
%
% MagickBooleanType BilevelImage(Image *image,const double threshold)
% MagickBooleanType BilevelImageChannel(Image *image,
% const ChannelType channel,const double threshold)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o threshold: define the threshold values.
%
% Aside: You can get the same results as operator using LevelImageChannels()
% with the 'threshold' value for both the black_point and the white_point.
%
*/
MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold)
{
MagickBooleanType
status;
status=BilevelImageChannel(image,DefaultChannels,threshold);
return(status);
}
MagickExport MagickBooleanType BilevelImageChannel(Image *image,
const ChannelType channel,const double threshold)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace);
/*
Bilevel threshold image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if ((channel & SyncChannels) != 0)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 :
QuantumRange);
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 :
QuantumRange);
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 :
QuantumRange);
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 :
QuantumRange);
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <=
threshold ? 0 : QuantumRange);
else
SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <=
threshold ? OpaqueOpacity : TransparentOpacity);
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <=
threshold ? 0 : QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_BilevelImageChannel)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l a c k T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlackThresholdImage() is like ThresholdImage() but forces all pixels below
% the threshold into black while leaving all pixels at or above the threshold
% unchanged.
%
% The format of the BlackThresholdImage method is:
%
% MagickBooleanType BlackThresholdImage(Image *image,const char *threshold)
% MagickBooleanType BlackThresholdImageChannel(Image *image,
% const ChannelType channel,const char *threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BlackThresholdImage(Image *image,
const char *threshold)
{
MagickBooleanType
status;
status=BlackThresholdImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
GetMagickPixelPacket(image,&threshold);
flags=ParseGeometry(thresholds,&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;
threshold.opacity=geometry_info.psi;
if ((flags & PsiValue) == 0)
threshold.opacity=threshold.red;
threshold.index=geometry_info.chi;
if ((flags & ChiValue) == 0)
threshold.index=threshold.red;
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.opacity*=(MagickRealType) (QuantumRange/100.0);
threshold.index*=(MagickRealType) (QuantumRange/100.0);
}
if ((IsMagickGray(&threshold) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace);
/*
Black threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetPixelRed(q) < threshold.red))
SetPixelRed(q,0);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetPixelGreen(q) < threshold.green))
SetPixelGreen(q,0);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetPixelBlue(q) < threshold.blue))
SetPixelBlue(q,0);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetPixelOpacity(q) < threshold.opacity))
SetPixelOpacity(q,0);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetPixelIndex(indexes+x) < threshold.index))
SetPixelIndex(indexes+x,0);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_BlackThresholdImageChannel)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l a m p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampImage() set each pixel whose value is below zero to zero and any the
% pixel whose value is above the quantum range to the quantum range (e.g.
% 65535) otherwise the pixel value remains unchanged.
%
% The format of the ClampImageChannel method is:
%
% MagickBooleanType ClampImage(Image *image)
% MagickBooleanType ClampImageChannel(Image *image,
% const ChannelType channel)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
*/
static inline Quantum ClampPixel(const MagickRealType value)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
return((Quantum) value);
#else
if (value < 0.0f)
return(0.0f);
if (value >= (MagickRealType) QuantumRange)
return((Quantum) QuantumRange);
return(value);
#endif
}
MagickExport MagickBooleanType ClampImage(Image *image)
{
MagickBooleanType
status;
status=ClampImageChannel(image,DefaultChannels);
return(status);
}
MagickExport MagickBooleanType ClampImageChannel(Image *image,
const ChannelType channel)
{
#define ClampImageTag "Clamp/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelPacket
*restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
SetPixelRed(q,ClampPixel(GetPixelRed(q)));
SetPixelGreen(q,ClampPixel(GetPixelGreen(q)));
SetPixelBlue(q,ClampPixel(GetPixelBlue(q)));
SetPixelOpacity(q,ClampPixel(GetPixelOpacity(q)));
q++;
}
return(SyncImage(image));
}
/*
Clamp image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampPixel(GetPixelRed(q)));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampPixel(GetPixelGreen(q)));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampPixel(GetPixelBlue(q)));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampPixel(GetPixelOpacity(q)));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,ClampPixel(GetPixelIndex(indexes+x)));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ClampImageChannel)
#endif
proceed=SetImageProgress(image,ClampImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyThresholdMap() de-allocate the given ThresholdMap
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *DestroyThresholdMap(Threshold *map)
%
% A description of each parameter follows.
%
% o map: Pointer to the Threshold map to destroy
%
*/
MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
{
assert(map != (ThresholdMap *) NULL);
if (map->map_id != (char *) NULL)
map->map_id=DestroyString(map->map_id);
if (map->description != (char *) NULL)
map->description=DestroyString(map->description);
if (map->levels != (ssize_t *) NULL)
map->levels=(ssize_t *) RelinquishMagickMemory(map->levels);
map=(ThresholdMap *) RelinquishMagickMemory(map);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMapFile() look for a given threshold map name or alias in the
% given XML file data, and return the allocated the map when found.
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *GetThresholdMap(const char *xml,const char *filename,
% const char *map_id,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o map_id: ID of the map to look for in XML list.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMapFile(const char *xml,
const char *filename,const char *map_id,ExceptionInfo *exception)
{
const char
*attr,
*content;
double
value;
ThresholdMap
*map;
XMLTreeInfo
*description,
*levels,
*threshold,
*thresholds;
map = (ThresholdMap *)NULL;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *)NULL )
return(map);
for( threshold = GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *)NULL;
threshold = GetNextXMLTreeTag(threshold) ) {
attr = GetXMLTreeAttribute(threshold, "map");
if ( (attr != (char *)NULL) && (LocaleCompare(map_id,attr) == 0) )
break;
attr = GetXMLTreeAttribute(threshold, "alias");
if ( (attr != (char *)NULL) && (LocaleCompare(map_id,attr) == 0) )
break;
}
if ( threshold == (XMLTreeInfo *)NULL ) {
return(map);
}
description = GetXMLTreeChild(threshold,"description");
if ( description == (XMLTreeInfo *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
return(map);
}
levels = GetXMLTreeChild(threshold,"levels");
if ( levels == (XMLTreeInfo *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<levels>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
return(map);
}
/* The map has been found -- Allocate a Threshold Map to return */
map = (ThresholdMap *)AcquireMagickMemory(sizeof(ThresholdMap));
if ( map == (ThresholdMap *)NULL )
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
map->map_id = (char *)NULL;
map->description = (char *)NULL;
map->levels = (ssize_t *) NULL;
/* Assign Basic Attributes */
attr = GetXMLTreeAttribute(threshold, "map");
if ( attr != (char *)NULL )
map->map_id = ConstantString(attr);
content = GetXMLTreeContent(description);
if ( content != (char *)NULL )
map->description = ConstantString(content);
attr = GetXMLTreeAttribute(levels, "width");
if ( attr == (char *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels width>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
map->width = StringToUnsignedLong(attr);
if ( map->width == 0 ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
attr = GetXMLTreeAttribute(levels, "height");
if ( attr == (char *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels height>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
map->height = StringToUnsignedLong(attr);
if ( map->height == 0 ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
attr = GetXMLTreeAttribute(levels, "divisor");
if ( attr == (char *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
map->divisor = (ssize_t) StringToLong(attr);
if ( map->divisor < 2 ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
/* Allocate theshold levels array */
content = GetXMLTreeContent(levels);
if ( content == (char *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<levels>, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
sizeof(*map->levels));
if ( map->levels == (ssize_t *)NULL )
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
{ /* parse levels into integer array */
ssize_t i;
char *p;
for( i=0; i< (ssize_t) (map->width*map->height); i++) {
map->levels[i] = (ssize_t)strtol(content, &p, 10);
if ( p == content ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too few values, map \"%s\"", map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
if ( map->levels[i] < 0 || map->levels[i] > map->divisor ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
(double) map->levels[i],map_id);
thresholds = DestroyXMLTree(thresholds);
map = DestroyThresholdMap(map);
return(map);
}
content = p;
}
value=(double) strtol(content,&p,10);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too many values, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
}
thresholds = DestroyXMLTree(thresholds);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMap() load and search one or more threshold map files for the
% a map matching the given name or aliase.
%
% The format of the GetThresholdMap method is:
%
% ThresholdMap *GetThresholdMap(const char *map_id,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o map_id: ID of the map to look for.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
ThresholdMap
*map;
map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception);
if (map != (ThresholdMap *) NULL)
return(map);
options=GetConfigureOptions(ThresholdsFilename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),map_id,exception);
if (map != (ThresholdMap *) NULL)
return(map);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return((ThresholdMap *) NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L i s t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMapFile() lists the threshold maps and their descriptions
% in the given XML file data.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,const char*xml,
% const char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
const char *filename,ExceptionInfo *exception)
{
XMLTreeInfo *thresholds,*threshold,*description;
const char *map,*alias,*content;
assert( xml != (char *)NULL );
assert( file != (FILE *)NULL );
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *)NULL )
return(MagickFalse);
(void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
(void) FormatLocaleFile(file,
"----------------------------------------------------\n");
for( threshold = GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *)NULL;
threshold = GetNextXMLTreeTag(threshold) )
{
map = GetXMLTreeAttribute(threshold, "map");
if (map == (char *) NULL) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<map>");
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
alias = GetXMLTreeAttribute(threshold, "alias");
/* alias is optional, no if test needed */
description=GetXMLTreeChild(threshold,"description");
if ( description == (XMLTreeInfo *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
content=GetXMLTreeContent(description);
if ( content == (char *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "",
content);
}
thresholds=DestroyXMLTree(thresholds);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t T h r e s h o l d M a p s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMaps() lists the threshold maps and their descriptions
% as defined by "threshold.xml" to a file.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
MagickStatusType
status;
status=MagickFalse;
if ( file == (FILE *)NULL )
file = stdout;
options=GetConfigureOptions(ThresholdsFilename,exception);
(void) FormatLocaleFile(file,
"\n Threshold Maps for Ordered Dither Operations\n");
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
(void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
status|=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedDitherImage() uses the ordered dithering technique of reducing color
% images to monochrome using positional information to retain as much
% information as possible.
%
% WARNING: This function is deprecated, and is now just a call to
% the more more powerful OrderedPosterizeImage(); function.
%
% The format of the OrderedDitherImage method is:
%
% MagickBooleanType OrderedDitherImage(Image *image)
% MagickBooleanType OrderedDitherImageChannel(Image *image,
% const ChannelType channel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedDitherImage(Image *image)
{
MagickBooleanType
status;
status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception);
return(status);
}
MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image,
const ChannelType channel,ExceptionInfo *exception)
{
MagickBooleanType
status;
/*
Call the augumented function OrderedPosterizeImage()
*/
status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d P o s t e r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedPosterizeImage() will perform a ordered dither based on a number
% of pre-defined dithering threshold maps, but over multiple intensity
% levels, which can be different for different channels, according to the
% input argument.
%
% The format of the OrderedPosterizeImage method is:
%
% MagickBooleanType OrderedPosterizeImage(Image *image,
% const char *threshold_map,ExceptionInfo *exception)
% MagickBooleanType OrderedPosterizeImageChannel(Image *image,
% const ChannelType channel,const char *threshold_map,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold_map: A string containing the name of the threshold dither
% map to use, followed by zero or more numbers representing the number
% of color levels tho dither between.
%
% Any level number less than 2 will be equivalent to 2, and means only
% binary dithering will be applied to each color channel.
%
% No numbers also means a 2 level (bitmap) dither will be applied to all
% channels, while a single number is the number of levels applied to each
% channel in sequence. More numbers will be applied in turn to each of
% the color channels.
%
% For example: "o3x3,6" will generate a 6 level posterization of the
% image with a ordered 3x3 diffused pixel dither being applied between
% each level. While checker,8,8,4 will produce a 332 colormaped image
% with only a single checkerboard hash pattern (50% grey) between each
% color level, to basically double the number of color levels with
% a bare minimim of dithering.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
const char *threshold_map,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map,
exception);
return(status);
}
MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image,
const ChannelType channel,const char *threshold_map,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
LongPixelPacket
levels;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
ThresholdMap
*map;
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 (threshold_map == (const char *) NULL)
return(MagickTrue);
{
char
token[MaxTextExtent];
register const char
*p;
p=(char *)threshold_map;
while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
(*p != '\0'))
p++;
threshold_map=p;
while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
(*p != '\0')) {
if ((p-threshold_map) >= (MaxTextExtent-1))
break;
token[p-threshold_map] = *p;
p++;
}
token[p-threshold_map] = '\0';
map = GetThresholdMap(token, exception);
if ( map == (ThresholdMap *)NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","ordered-dither",threshold_map);
return(MagickFalse);
}
}
/* Set channel levels from extra comma separated arguments
Default to 2, the single value given, or individual channel values
*/
#if 1
{ /* parse directly as a comma separated list of integers */
char *p;
p = strchr((char *) threshold_map,',');
if ( p != (char *)NULL && isdigit((int) ((unsigned char) *(++p))) )
levels.index = (unsigned int) strtoul(p, &p, 10);
else
levels.index = 2;
levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0;
levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0;
levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0;
levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0;
levels.index = ((channel & IndexChannel) != 0
&& (image->colorspace == CMYKColorspace)) ? levels.index : 0;
/* if more than a single number, each channel has a separate value */
if ( p != (char *) NULL && *p == ',' ) {
p=strchr((char *) threshold_map,',');
p++;
if ((channel & RedChannel) != 0)
levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & GreenChannel) != 0)
levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & BlueChannel) != 0)
levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace)
levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & OpacityChannel) != 0)
levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
}
}
#else
/* Parse level values as a geometry */
/* This difficult!
* How to map GeometryInfo structure elements into
* LongPixelPacket structure elements, but according to channel?
* Note the channels list may skip elements!!!!
* EG -channel BA -ordered-dither map,2,3
* will need to map g.rho -> l.blue, and g.sigma -> l.opacity
* A simpler way is needed, probably converting geometry to a temporary
* array, then using channel to advance the index into ssize_t pixel packet.
*/
#endif
#if 0
printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n",
levels.red, levels.green, levels.blue, levels.opacity, levels.index);
#endif
{ /* Do the posterized ordered dithering of the image */
ssize_t
d;
/* d = number of psuedo-level divisions added between color levels */
d = map->divisor-1;
/* reduce levels to levels - 1 */
levels.red = levels.red ? levels.red-1 : 0;
levels.green = levels.green ? levels.green-1 : 0;
levels.blue = levels.blue ? levels.blue-1 : 0;
levels.opacity = levels.opacity ? levels.opacity-1 : 0;
levels.index = levels.index ? levels.index-1 : 0;
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
threshold,
t,
l;
/*
Figure out the dither threshold for this pixel
This must be a integer from 1 to map->divisor-1
*/
threshold = map->levels[(x%map->width) +map->width*(y%map->height)];
/* Dither each channel in the image as appropriate
Notes on the integer Math...
total number of divisions = (levels-1)*(divisor-1)+1)
t1 = this colors psuedo_level =
q->red * total_divisions / (QuantumRange+1)
l = posterization level 0..levels
t = dither threshold level 0..divisor-1 NB: 0 only on last
Each color_level is of size QuantumRange / (levels-1)
NB: All input levels and divisor are already had 1 subtracted
Opacity is inverted so 'off' represents transparent.
*/
if (levels.red) {
t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1));
l = t/d; t = t-l*d;
SetPixelRed(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red)));
}
if (levels.green) {
t = (ssize_t) (QuantumScale*GetPixelGreen(q)*
(levels.green*d+1));
l = t/d; t = t-l*d;
SetPixelGreen(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green)));
}
if (levels.blue) {
t = (ssize_t) (QuantumScale*GetPixelBlue(q)*
(levels.blue*d+1));
l = t/d; t = t-l*d;
SetPixelBlue(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue)));
}
if (levels.opacity) {
t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))*
(levels.opacity*d+1));
l = t/d; t = t-l*d;
SetPixelOpacity(q,ClampToQuantum((MagickRealType)
((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/
levels.opacity)));
}
if (levels.index) {
t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)*
(levels.index*d+1));
l = t/d; t = t-l*d;
SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+
(t>=threshold))*(MagickRealType) QuantumRange/levels.index)));
}
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_OrderedPosterizeImageChannel)
#endif
proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
}
map=DestroyThresholdMap(map);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P e r c e p t i b l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PerceptibleImage() set each pixel whose value is less than |epsilon| to
% epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
% unchanged.
%
% The format of the PerceptibleImageChannel method is:
%
% MagickBooleanType PerceptibleImage(Image *image,const double epsilon)
% MagickBooleanType PerceptibleImageChannel(Image *image,
% const ChannelType channel,const double epsilon)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o epsilon: the epsilon threshold (e.g. 1.0e-9).
%
*/
static inline Quantum PerceptibleThreshold(const Quantum quantum,
const double epsilon)
{
double
sign;
sign=(double) quantum < 0.0 ? -1.0 : 1.0;
if ((sign*quantum) >= epsilon)
return(quantum);
return((Quantum) (sign*epsilon));
}
MagickExport MagickBooleanType PerceptibleImage(Image *image,
const double epsilon)
{
MagickBooleanType
status;
status=PerceptibleImageChannel(image,DefaultChannels,epsilon);
return(status);
}
MagickExport MagickBooleanType PerceptibleImageChannel(Image *image,
const ChannelType channel,const double epsilon)
{
#define PerceptibleImageTag "Perceptible/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelPacket
*restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon));
SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon));
SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon));
SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon));
q++;
}
return(SyncImage(image));
}
/*
Perceptible image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x),
epsilon));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_PerceptibleImageChannel)
#endif
proceed=SetImageProgress(image,PerceptibleImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n d o m T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RandomThresholdImage() 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 RandomThresholdImage method is:
%
% MagickBooleanType RandomThresholdImageChannel(Image *image,
% const char *thresholds,ExceptionInfo *exception)
% MagickBooleanType RandomThresholdImageChannel(Image *image,
% const ChannelType 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 low,high thresholds. If the
% string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4
% is performed instead.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RandomThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=RandomThresholdImageChannel(image,DefaultChannels,thresholds,
exception);
return(status);
}
MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickStatusType
flags;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickRealType
min_threshold,
max_threshold;
RandomInfo
**restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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 (thresholds == (const char *) NULL)
return(MagickTrue);
GetMagickPixelPacket(image,&threshold);
min_threshold=0.0;
max_threshold=(MagickRealType) QuantumRange;
flags=ParseGeometry(thresholds,&geometry_info);
min_threshold=geometry_info.rho;
max_threshold=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
max_threshold=min_threshold;
if (strchr(thresholds,'%') != (char *) NULL)
{
max_threshold*=(MagickRealType) (0.01*QuantumRange);
min_threshold*=(MagickRealType) (0.01*QuantumRange);
}
else
if (((max_threshold == min_threshold) || (max_threshold == 1)) &&
(min_threshold <= 8))
{
/*
Backward Compatibility -- ordered-dither -- IM v 6.2.9-6.
*/
status=OrderedPosterizeImageChannel(image,channel,thresholds,exception);
return(status);
}
/*
Random threshold image.
*/
status=MagickTrue;
progress=0;
if (channel == CompositeChannels)
{
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
random_info=AcquireRandomInfoThreadSet();
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#endif
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
IndexPacket
index;
MagickRealType
intensity;
intensity=GetPixelIntensity(image,q);
if (intensity < min_threshold)
threshold.index=min_threshold;
else if (intensity > max_threshold)
threshold.index=max_threshold;
else
threshold.index=(MagickRealType)(QuantumRange*
GetPseudoRandomValue(random_info[id]));
index=(IndexPacket) (intensity <= threshold.index ? 0 : 1);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_RandomThresholdImageChannel)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
random_info=AcquireRandomInfoThreadSet();
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#endif
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register IndexPacket
*restrict indexes;
register PixelPacket
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
if ((MagickRealType) GetPixelRed(q) < min_threshold)
threshold.red=min_threshold;
else
if ((MagickRealType) GetPixelRed(q) > max_threshold)
threshold.red=max_threshold;
else
threshold.red=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & GreenChannel) != 0)
{
if ((MagickRealType) GetPixelGreen(q) < min_threshold)
threshold.green=min_threshold;
else
if ((MagickRealType) GetPixelGreen(q) > max_threshold)
threshold.green=max_threshold;
else
threshold.green=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & BlueChannel) != 0)
{
if ((MagickRealType) GetPixelBlue(q) < min_threshold)
threshold.blue=min_threshold;
else
if ((MagickRealType) GetPixelBlue(q) > max_threshold)
threshold.blue=max_threshold;
else
threshold.blue=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & OpacityChannel) != 0)
{
if ((MagickRealType) GetPixelOpacity(q) < min_threshold)
threshold.opacity=min_threshold;
else
if ((MagickRealType) GetPixelOpacity(q) > max_threshold)
threshold.opacity=max_threshold;
else
threshold.opacity=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold)
threshold.index=min_threshold;
else
if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold)
threshold.index=max_threshold;
else
threshold.index=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ?
0 : QuantumRange);
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ?
0 : QuantumRange);
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ?
0 : QuantumRange);
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <=
threshold.opacity ? 0 : QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <=
threshold.index ? 0 : QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_RandomThresholdImageChannel)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W h i t e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WhiteThresholdImage() is like ThresholdImage() but forces all pixels above
% the threshold into white while leaving all pixels at or below the threshold
% unchanged.
%
% The format of the WhiteThresholdImage method is:
%
% MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold)
% MagickBooleanType WhiteThresholdImageChannel(Image *image,
% const ChannelType channel,const char *threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
const char *threshold)
{
MagickBooleanType
status;
status=WhiteThresholdImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
flags=ParseGeometry(thresholds,&geometry_info);
GetMagickPixelPacket(image,&threshold);
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;
threshold.opacity=geometry_info.psi;
if ((flags & PsiValue) == 0)
threshold.opacity=threshold.red;
threshold.index=geometry_info.chi;
if ((flags & ChiValue) == 0)
threshold.index=threshold.red;
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.opacity*=(MagickRealType) (QuantumRange/100.0);
threshold.index*=(MagickRealType) (QuantumRange/100.0);
}
if ((IsMagickGray(&threshold) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace);
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*restrict indexes;
register ssize_t
x;
register PixelPacket
*restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetPixelRed(q) > threshold.red))
SetPixelRed(q,QuantumRange);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetPixelGreen(q) > threshold.green))
SetPixelGreen(q,QuantumRange);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetPixelBlue(q) > threshold.blue))
SetPixelBlue(q,QuantumRange);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetPixelOpacity(q) > threshold.opacity))
SetPixelOpacity(q,QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index)
SetPixelIndex(indexes+x,QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_WhiteThresholdImageChannel)
#endif
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
|
ddd_in_h.h
|
//****************************************************************************************
//
// Copyright (c) 2015-2020, Yoshifumi Nakamura <[email protected]>
// Copyright (c) 2015-2020, Yuta Mukai <[email protected]>
// Copyright (c) 2018-2020, Ken-Ichi Ishikawa <[email protected]>
// Copyright (c) 2019-2020, Issaku Kanamori <[email protected]>
//
//
// 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.
//
//----------------------------------------------------------------------------------------
// ACKNOWLEDGMENT
//
// This software has been developed in a co-design working group for the lattice QCD
// supported by MEXT's programs for the Development and Improvement for the Next
// Generation Ultra High-Speed Computer System, under its Subsidies for Operating the
// Specific Advanced Large Research Facilities, and Priority Issue 9
// (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by
// using the Supercomputer Fugaku.
//
//****************************************************************************************
#ifndef _DDD_IN_H_H
#define _DDD_IN_H_H
//---------------------------------------------------------------------------------------- mult D in bulk
void ddd_in_h_(sch_t * __restrict__ out, const sch_t * __restrict__ in, const int *DEO)
//
// Multiply Wilson/Clover opeartor on a quark field in a even/odd domain
//
// oute = Dee ine
// or
// outo = Dee ino
//
// out : output quark field in an even/odd domain
// in : input quark field in an even/odd domain
// DEO : even/odd-domain index, 0 for even domain, 1 for odd domain
//
{
const __restrict__ pgluh_t gx = &gluh[vols*0 + NDIM*vols*(*DEO)];
const __restrict__ pgluh_t gy = &gluh[vols*1 + NDIM*vols*(*DEO)];
const __restrict__ pgluh_t gz = &gluh[vols*2 + NDIM*vols*(*DEO)];
const __restrict__ pgluh_t gt = &gluh[vols*3 + NDIM*vols*(*DEO)];
const __restrict__ pclvh_t cl = &clvh[ vols*(*DEO)];
#pragma omp parallel for collapse(3) schedule(static)
for(int t = 0; t < nt; ++t) {
for(int z = 0; z < nz; ++z) {
for(int y = 0; y < ny; ++y) {
for(int x = 0; x < nxs; ++x) {
int i0 = x + nxs*y + nxs*ny*z + nxs*ny*nz*t;
int ixf = (x+1) + nxs*y + nxs*ny*z + nxs*ny*nz*t;
int ixb = (x-1) + nxs*y + nxs*ny*z + nxs*ny*nz*t;
int iyf = x + (y+1)*nxs + nxs*ny*z + nxs*ny*nz*t;
int iyb = x + (y-1)*nxs + nxs*ny*z + nxs*ny*nz*t;
int izf = x + nxs*y + (z+1)*nxs*ny + nxs*ny*nz*t;
int izb = x + nxs*y + (z-1)*nxs*ny + nxs*ny*nz*t;
int itf = x + nxs*y + nxs*ny*z + (t+1)*nxs*ny*nz;
int itb = x + nxs*y + nxs*ny*z + (t-1)*nxs*ny*nz;
#ifdef PREFETCH
#endif
sch_t tmp0 __attribute__((aligned(_ALIGN_SIZE)));
for (int c = 0; c < 3; c++) {
for (int s = 0; s < 4; s++) {
for (int ri = 0; ri < 2; ri++) {
for (int j = 0; j<VLENS; j++) {
tmp0.c[c][s][ri][j] = half(0.0f);
}
}
}
}
//
// X-forward
//
{
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
half ff[3][4][2][VLENS*2] __attribute__((aligned(4)));
if ( x != nxs-1 ) {
for(int c = 0; c < 3; ++c) {
for(int s = 0; s < 4; ++s) {
for(int ri = 0; ri < 2; ++ri) {
for(int j = 0; j < VLENS; ++j) {
ff[c][s][ri][j ] = in[i0 ].c[c][s][ri][j];
ff[c][s][ri][j+VLENS] = in[ixf].c[c][s][ri][j];
}
}
}
}
} else {
for(int c = 0; c < 3; ++c) {
for(int s = 0; s < 4; ++s) {
for(int ri = 0; ri < 2; ++ri) {
for(int j = 0; j < VLENS; ++j) {
ff[c][s][ri][j ] = in[i0 ].c[c][s][ri][j];
ff[c][s][ri][j+VLENS] = half(0.0f);
}
}
}
}
}
__mult_x_forw_pre_2_(a,ff); // with forward simd-site-shift
__mult_u_y_(ua,a,(*(gx + i0)));
__mult_x_forw_pst_(tmp0,ua);
}
//
// X-backward
//
{
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
half ff_in[3][4][2][VLENS*2] __attribute__((aligned(4)));
half ff_g [3][3][2][VLENS*2] __attribute__((aligned(4)));
if ( x != 0 ) {
for(int c = 0; c < 3; ++c) {
for(int s = 0; s < 4; ++s) {
for(int ri = 0; ri < 2; ++ri) {
for(int j = 0; j < VLENS; ++j) {
ff_in[c][s][ri][j ] = in[ixb].c[c][s][ri][j];
ff_in[c][s][ri][j+VLENS] = in[i0 ].c[c][s][ri][j];
}
}
}
}
//
// load link U. WITHOUT taking Hermitian-conjugate
//
for (int c2 = 0; c2 < 3; ++c2) {
for (int c1 = 0; c1 < 3; ++c1) {
for(int ri = 0; ri < 2; ++ri) {
for(int j = 0; j < VLENS; ++j) {
ff_g[c2][c1][ri][j ] = (*(gx+ixb)).c[c2][c1][ri][j];
ff_g[c2][c1][ri][j+VLENS] = (*(gx+i0 )).c[c2][c1][ri][j];
}
}
}
}
} else {
for (int c = 0; c < 3; ++c) {
for (int s = 0; s < 4; ++s) {
for(int ri = 0; ri < 2; ++ri) {
for(int j = 0; j < VLENS; ++j) {
ff_in[c][s][ri][j ] = half(0.0f);
ff_in[c][s][ri][j+VLENS] = in[i0 ].c[c][s][ri][j];
}
}
}
}
//
// load link U. WITHOUT taking Hermitian-conjugate
//
for (int c2 = 0; c2 < 3; ++c2) {
for (int c1 = 0; c1 < 3; ++c1) {
for(int ri = 0; ri < 2; ++ri) {
for(int j = 0; j < VLENS; ++j) {
ff_g[c2][c1][ri][j ] = half(0.0f);
ff_g[c2][c1][ri][j+VLENS] = (*(gx+i0 )).c[c2][c1][ri][j];
}
}
}
}
}
__mult_x_back_pre_2_(a,ff_in);// with backward simd-site-shift
__mult_udag_y_2_(ua,a,ff_g); // with backward simd-site-shift
__mult_x_back_pst_(tmp0,ua);
}
//
// Y-forward
//
#ifdef PREFETCH
#endif
if ( y != ny-1 ) {
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
__mult_y_forw_pre_(a,(*(in + iyf)));
__mult_u_y_(ua,a,(*(gy + i0)));
__mult_y_forw_pst_(tmp0,ua);
}
//
// Y-backward
//
#ifdef PREFETCH
#endif
if ( y != 0 ) {
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
__mult_y_back_pre_(a,(*(in + iyb)));
__mult_udag_y_(ua,a,(*(gy + iyb)));
__mult_y_back_pst_(tmp0,ua);
}
//
// Z-forward
//
#ifdef PREFETCH
#endif
if ( z != nz-1 ) {
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
__mult_z_forw_pre_(a,(*(in + izf)));
__mult_u_y_(ua,a,(*(gz + i0)));
__mult_z_forw_pst_(tmp0,ua);
}
//
// Z-backward
//
#ifdef PREFETCH
#endif
if ( z != 0 ) {
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
__mult_z_back_pre_(a,(*(in + izb)));
__mult_udag_y_(ua,a,(*(gz + izb)));
__mult_z_back_pst_(tmp0,ua);
}
//
// T-forward
//
#ifdef PREFETCH
#endif
if ( t != nt-1 ) {
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
__mult_t_forw_pre_(a,(*(in + itf)));
__mult_u_y_(ua,a,(*(gt + i0)));
__mult_t_forw_pst_(tmp0,ua);
}
//
// T-backward
//
#ifdef PREFETCH
#endif
if ( t != 0 ) {
__attribute__((aligned(_ALIGN_SIZE))) projsch_t a,ua;
__mult_t_back_pre_(a,(*(in + itb)));
__mult_udag_y_(ua,a,(*(gt + itb)));
__mult_t_back_pst_(tmp0,ua);
}
#ifdef PREFETCH
#endif
__mult_clvh(tmp0.cv, cl[i0].cv);
#ifdef PREFETCH
#endif
//#pragma loop norecurrence
for (int c = 0; c < 3; ++c){
for (int s = 0; s < 4; ++s){
for (int ri = 0; ri < 2; ++ri){
for (int j = 0; j < VLENS; ++j){
(*(out + i0)).c[c][s][ri][j] = (*(in + i0)).c[c][s][ri][j] + tmp0.c[c][s][ri][j] * (half)mkappa;
}
}
}
}
}
}
}
}
}
#endif
|
barrier-1.c
|
/* { dg-do compile } */
/* { dg-options "-fopenmp -fdump-tree-gimple" } */
void f1(void)
{
#pragma omp barrier
}
void f2(_Bool p)
{
if (p)
{
#pragma omp barrier
}
}
/* { dg-final { scan-tree-dump-times "GOMP_barrier" 2 "gimple" } } */
/* { dg-final { cleanup-tree-dump "gimple" } } */
|
GB_binop__ge_fp64.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__ge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__ge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__ge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__ge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__ge_fp64)
// A*D function (colscale): GB (_AxD__ge_fp64)
// D*A function (rowscale): GB (_DxB__ge_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__ge_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__ge_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ge_fp64)
// C=scalar+B GB (_bind1st__ge_fp64)
// C=scalar+B' GB (_bind1st_tran__ge_fp64)
// C=A+scalar GB (_bind2nd__ge_fp64)
// C=A'+scalar GB (_bind2nd_tran__ge_fp64)
// C type: bool
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = (aij >= bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
bool
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
double 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) \
double bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x >= y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_GE || GxB_NO_FP64 || GxB_NO_GE_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__ge_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__ge_fp64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__ge_fp64)
(
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 double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__ge_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__ge_fp64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__ge_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__ge_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__ge_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__ge_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__ge_fp64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__ge_fp64)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
double bij = GBX (Bx, p, false) ;
Cx [p] = (x >= bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__ge_fp64)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double aij = 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x >= aij) ; \
}
GrB_Info GB (_bind1st_tran__ge_fp64)
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij >= y) ; \
}
GrB_Info GB (_bind2nd_tran__ge_fp64)
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
exercise3.c
|
# include <math.h>
# include <omp.h>
# define np 400
# define nnmax 7
# define ndr (2 * np)
# define pi2 (2.0 * 3.141592653589793)
extern double s1[np][3], s2[np][3], s3[np][3];
extern int ldr[ndr][3];
void topol(double s[][3], double *q)
{
double siga;
double cc, cc1, cc2, cc3;
double ss, ss1, ss2, ss3;
int idr, n, is;
siga = 0.0;
for (idr = 0; idr <= ndr/2; idr += ndr/2) {
//we can not parallelise the outer loop because we need all s1 results in the final loop.
#pragma omp parallel for
for (n = 1; n < ndr/2; n++) {
s1[n][0] = s[ldr[idr+n][0]][0];
s1[n][1] = s[ldr[idr+n][0]][1];
s1[n][2] = s[ldr[idr+n][0]][2];
}
#pragma omp parallel for
for (n = 1; n < ndr/2; n++) {
s2[n][0] = s[ldr[idr+n][1]][0];
s2[n][1] = s[ldr[idr+n][1]][1];
s2[n][2] = s[ldr[idr+n][1]][2];
}
#pragma omp parallel for
for (n = 1; n < ndr/2; n++) {
s3[n][0] = s[ldr[idr+n][2]][0];
s3[n][1] = s[ldr[idr+n][2]][1];
s3[n][2] = s[ldr[idr+n][2]][2];
}
/***** cc = 1 + s1*s2 + s2*s3 + s3*s1 *****/
/***** ss = s1 * ( s2 x s3 ) *****/
#pragma omp parallel for \
shared(s1, s2, s3) \
private(cc1,cc2,cc3,cc,ss1,ss2,ss3,ss) \
reduction(+:siga)
for (is = 1; is < ndr/2; is++) {
cc1 = s1[is][0] * s2[is][0] + s1[is][1] * s2[is][1] + s1[is][2] * s2[is][2];
cc2 = s2[is][0] * s3[is][0] + s2[is][1] * s3[is][1] + s2[is][2] * s3[is][2];
cc3 = s3[is][0] * s1[is][0] + s3[is][1] * s1[is][1] + s3[is][2] * s1[is][2];
cc = 1.0 + cc1 + cc2 + cc3;
ss1 = s2[is][1] * s3[is][2] - s2[is][2] * s3[is][1];
ss2 = s2[is][2] * s3[is][0] - s2[is][0] * s3[is][2];
ss3 = s2[is][0] * s3[is][1] - s2[is][1] * s3[is][0];
ss = s1[is][0] * ss1 + s1[is][1] * ss2 + s1[is][2] * ss3;
siga += atan2(ss,cc);
}
}
*q = siga / pi2;
}
|
section_reduction.c
|
// Skip testing on 64 bit systems for now!
#ifndef __LP64__
#include <stdio.h>
#include <math.h>
#include "omp_testsuite.h"
int
check_section_reduction (FILE * logFile)
{
int sum = 7;
int known_sum;
double dpt, dsum = 0;
double dknown_sum;
double dt = 0.5; /* base of geometric row for + and - test */
double rounding_error = 1.E-9;
int diff;
double ddiff;
int product = 1;
int known_product;
int logic_and = 1;
int bit_and = 1;
int logic_or = 0;
int bit_or = 0;
int exclusiv_bit_or = 0;
int logics[1000];
int i;
int result = 0;
/* int my_islarger; */
/*int is_larger=1; */
dt = 1. / 3.;
known_sum = (999 * 1000) / 2 + 7;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(+:sum)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
sum = sum + i;
}
}
}
}
if (known_sum != sum)
{
++result;
fprintf (logFile,
"Error in sum with integers: Result was %d instead of %d\n",
sum, known_sum);
}
diff = (999 * 1000) / 2;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(-:diff)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
diff = diff - i;
}
}
}
}
if (diff != 0)
{
result++;
fprintf (logFile,
"Error in Difference with integers: Result was %d instead of 0.\n",
diff);
}
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
dknown_sum = (1 - dpt) / (1 - dt);
#pragma omp parallel
{
#pragma omp sections private(i) reduction(+:dsum)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
dsum += pow (dt, i);
}
}
}
}
if (fabs (dsum - dknown_sum) > rounding_error)
{
result++;
fprintf (logFile,
"Error in sum with doubles: Result was %f instead of %f (Difference: %E)\n",
dsum, dknown_sum, dsum - dknown_sum);
}
dpt = 1;
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
fprintf (logFile, "\n");
ddiff = (1 - dpt) / (1 - dt);
#pragma omp parallel
{
#pragma omp sections private(i) reduction(-:ddiff)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
ddiff -= pow (dt, i);
}
}
}
}
if (fabs (ddiff) > rounding_error)
{
result++;
fprintf (logFile,
"Error in Difference with doubles: Result was %E instead of 0.0\n",
ddiff);
}
known_product = 3628800;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(*:product)
{
#pragma omp section
{
for (i = 1; i < 3; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 3; i < 7; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 7; i < 11; i++)
{
product *= i;
}
}
}
}
if (known_product != product)
{
result++;
fprintf (logFile,
"Error in Product with integers: Result was %d instead of %d\n",
product, known_product);
}
for (i = 0; i < 1000; i++)
{
logics[i] = 1;
}
#pragma omp parallel
{
#pragma omp sections private(i) reduction(&&:logic_and)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
}
if (!logic_and)
{
result++;
fprintf (logFile, "Error in logic AND part 1\n");
}
logic_and = 1;
logics[501] = 0;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(&&:logic_and)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
}
if (logic_and)
{
result++;
fprintf (logFile, "Error in logic AND part 2\n");
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel
{
#pragma omp sections private(i) reduction(||:logic_or)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or || logics[i]);
}
}
}
}
if (logic_or)
{
result++;
fprintf (logFile, "\nError in logic OR part 1\n");
}
logic_or = 0;
logics[501] = 1;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(||:logic_or)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or || logics[i]);
}
}
}
}
if (!logic_or)
{
result++;
fprintf (logFile, "Error in logic OR part 2\n");
}
for (i = 0; i < 1000; ++i)
{
logics[i] = 1;
}
#pragma omp parallel
{
#pragma omp sections private(i) reduction(&:bit_and)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
}
}
if (!bit_and)
{
result++;
fprintf (logFile, "Error in BIT AND part 1\n");
}
bit_and = 1;
logics[501] = 0;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(&:bit_and)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = bit_and & logics[i];
}
}
}
}
if (bit_and)
{
result++;
fprintf (logFile, "Error in BIT AND part 2\n");
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel
{
#pragma omp sections private(i) reduction(|:bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
}
if (bit_or)
{
result++;
fprintf (logFile, "Error in BIT OR part 1\n");
}
bit_or = 0;
logics[501] = 1;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(|:bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
}
if (!bit_or)
{
result++;
fprintf (logFile, "Error in BIT OR part 2\n");
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel
{
#pragma omp sections private(i) reduction(^:exclusiv_bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
}
}
if (exclusiv_bit_or)
{
result++;
fprintf (logFile, "Error in EXCLUSIV BIT OR part 1\n");
}
exclusiv_bit_or = 0;
logics[501] = 1;
#pragma omp parallel
{
#pragma omp sections private(i) reduction(^:exclusiv_bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
}
}
if (!exclusiv_bit_or)
{
result++;
fprintf (logFile, "Error in EXCLUSIV BIT OR part 2\n");
}
/*printf("\nResult:%d\n",result); */
return (result == 0);
}
int
crosscheck_section_reduction (FILE * logFile)
{
int sum = 7;
int known_sum;
double dpt, dsum = 0;
double dknown_sum;
double dt = 0.5; /* base of geometric row for + and - test */
double rounding_error = 1.E-9;
int diff;
double ddiff;
int product = 1;
int known_product;
int logic_and = 1;
int bit_and = 1;
int logic_or = 0;
int bit_or = 0;
int exclusiv_bit_or;
int logics[1000];
int i;
int result = 0;
/* int my_islarger; */
/*int is_larger=1; */
known_sum = (999 * 1000) / 2 + 7;
dt = 1. / 3.;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
sum = sum + i;
}
}
}
}
if (known_sum != sum)
{
++result;
/*printf("\nError in Sum with integers\n"); */
}
diff = (999 * 1000) / 2;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
diff = diff - i;
}
}
}
}
if (diff != 0)
{
result++;
/*printf("\nError in Difference: Result was %d instead of 0.\n",diff); */
}
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
dknown_sum = (1 - dpt) / (1 - dt);
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
dsum += pow (dt, i);
}
}
}
}
if (fabs (dsum - dknown_sum) > rounding_error)
{
result++;
fprintf (logFile,
"Error in sum with doubles: Result was %f instead of %f (Difference: %E)\n",
dsum, dknown_sum, dsum - dknown_sum);
}
dpt = 1;
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
fprintf (logFile, "\n");
ddiff = (1 - dpt) / (1 - dt);
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
ddiff -= pow (dt, i);
}
}
}
}
if (fabs (ddiff) > rounding_error)
{
result++;
fprintf (logFile,
"Error in Difference with doubles: Result was %E instead of 0.0\n",
ddiff);
}
known_product = 3628800;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 1; i < 3; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 3; i < 7; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 7; i < 11; i++)
{
product *= i;
}
}
}
}
if (known_product != product)
{
result++;
/*printf("\nError in Product: Known Product: %d\tcalculated Product: %d\n\n",known_product,product); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 1;
}
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
}
if (!logic_and)
{
result++;
/*printf("Error in AND part 1\n"); */
}
logic_and = 1;
logics[501] = 0;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
}
if (logic_and)
{
result++;
/*printf("Error in AND part 2"); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or && logics[i]);
}
}
}
}
if (logic_or)
{
result++;
/*printf("\nError in OR part 1\n"); */
}
logic_or = 0;
logics[501] = 1;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or || logics[i]);
}
}
}
}
if (!logic_or)
{
result++;
/*printf("\nError in OR part 2\n"); */
}
for (i = 0; i < 1000; ++i)
{
logics[i] = 1;
}
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
}
}
if (!bit_and)
{
result++;
/*printf("Error in BIT AND part 1\n"); */
}
bit_and = 1;
logics[501] = 0;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = bit_and & logics[i];
}
}
}
}
if (bit_and)
{
result++;
/*printf("Error in BIT AND part 2"); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
}
if (bit_or)
{
result++;
/*printf("Error in BIT OR part 1\n"); */
}
bit_or = 0;
logics[501] = 1;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
}
if (!bit_or)
{
result++;
/*printf("Error in BIT OR part 2\n"); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
}
}
if (exclusiv_bit_or)
{
result++;
/*printf("Error in EXCLUSIV BIT OR part 1\n"); */
}
exclusiv_bit_or = 0;
logics[501] = 1;
#pragma omp parallel
{
#pragma omp sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
}
}
if (!exclusiv_bit_or)
{
result++;
/*printf("Error in EXCLUSIV BIT OR part 2\n"); */
}
/*printf("\nResult:%d\n",result); */
return (result == 0);
}
#else
#warning "Not tested on 64 bit systems"
#endif
|
GB_unop__abs_fp64_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 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__abs_fp64_fc64)
// op(A') function: GB (_unop_tran__abs_fp64_fc64)
// C type: double
// A type: GxB_FC64_t
// cast: GxB_FC64_t cij = (aij)
// unaryop: cij = cabs (aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = cabs (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = (aij) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = (aij) ; \
Cx [pC] = cabs (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_FP64 || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__abs_fp64_fc64)
(
double *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = (aij) ;
Cx [p] = cabs (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = (aij) ;
Cx [p] = cabs (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__abs_fp64_fc64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
_uniform_ld.c
|
/* The batman package: fast computation of exoplanet transit light curves
* Copyright (C) 2015 Laura Kreidberg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include "numpy/arrayobject.h"
#if defined (_OPENACC) && defined(__PGI)
# include <accelmath.h>
#else
# include <math.h>
#endif
#if defined (_OPENMP) && !defined(_OPENACC)
# include <omp.h>
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static PyObject *_uniform_ld(PyObject *self, PyObject *args)
{
int nthreads;
double p;
PyArrayObject *ds, *flux;
npy_intp dims[1];
if(!PyArg_ParseTuple(args, "Odi", &ds, &p, &nthreads)) return NULL; //parses function input
dims[0] = PyArray_DIMS(ds)[0];
flux = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_TYPE(ds)); //creates numpy array to store return flux values
double *f_array = PyArray_DATA(flux);
double *d_array = PyArray_DATA(ds);
if(fabs(p - 0.5) < 1.e-3) p = 0.5;
#if defined (_OPENMP) && !defined(_OPENACC)
omp_set_num_threads(nthreads); //specifies number of threads (if OpenMP is supported)
#endif
#if defined (_OPENACC)
#pragma acc parallel loop copyout(f_array[:dims[0]])
#elif defined (_OPENMP)
#pragma omp parallel for
#endif
for(int i=0; i<dims[0]; i++)
{
double d = d_array[i]; // separation of centers
if(d >= 1. + p) f_array[i] = 1.; //no overlap
if(p >= 1. && d <= p - 1.) f_array[i] = 0.; //total eclipse of the star
else if(d <= 1. - p) f_array[i] = 1. - p*p; //planet is fully in transit
else //planet is crossing the limb
{
double kap1=acos(fmin((1. - p*p + d*d)/2./d, 1.));
double kap0=acos(fmin((p*p + d*d - 1.)/2./p/d, 1.));
f_array[i] = 1. - (p*p*kap0 + kap1 - 0.5*sqrt(fmax(4.*d*d - pow(1. + d*d - p*p, 2.), 0.)))/M_PI;
}
}
return PyArray_Return((PyArrayObject *)flux);
}
static char _uniform_ld_doc[] = "This extension module returns a limb darkened light curve for a uniform stellar intensity profile.";
static PyMethodDef _uniform_ld_methods[] = {
{"_uniform_ld", _uniform_ld, METH_VARARGS, _uniform_ld_doc},{NULL}};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef _uniform_ld_module = {
PyModuleDef_HEAD_INIT,
"_uniform_ld",
_uniform_ld_doc,
-1,
_uniform_ld_methods
};
PyMODINIT_FUNC
PyInit__uniform_ld(void)
{
PyObject* module = PyModule_Create(&_uniform_ld_module);
if(!module)
{
return NULL;
}
import_array();
return module;
}
#else
void init_uniform_ld(void)
{
Py_InitModule("_uniform_ld", _uniform_ld_methods);
import_array();
}
#endif
|
Sema.h
|
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Sema class, which performs semantic analysis and
// builds ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMA_H
#define LLVM_CLANG_SEMA_SEMA_H
#include "clang/AST/ASTConcept.h"
#include "clang/AST/ASTFwd.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Availability.h"
#include "clang/AST/ComparisonCategories.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprConcepts.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExprOpenMP.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/LocInfoType.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtOpenMP.h"
#include "clang/AST/TypeLoc.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/DarwinSDKInfo.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenCLOptions.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/PragmaKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/CleanupInfo.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/SemaConcept.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Frontend/OpenMP/OMPConstants.h"
#include <deque>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
struct InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class ParsedAttr;
class BindingDecl;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class CoroutineBodyStmt;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPRequiresDecl;
class OMPDeclareReductionDecl;
class OMPDeclareSimdDecl;
class OMPClause;
struct OMPVarListLocTy;
struct OverloadCandidate;
enum class OverloadCandidateParamOrder : char;
enum OverloadCandidateRewriteKind : unsigned;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateInstantiationCallback;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class Capture;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class SemaPPCallbacks;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// The end location for the first pointer declarator in the file. Used for
/// placing fix-its.
SourceLocation PointerEndLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
/// Tracks expected type during expression parsing, for use in code completion.
/// The type is tied to a particular token, all functions that update or consume
/// the type take a start location of the token they are looking at as a
/// parameter. This avoids updating the type on hot paths in the parser.
class PreferredTypeBuilder {
public:
PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
void enterCondition(Sema &S, SourceLocation Tok);
void enterReturn(Sema &S, SourceLocation Tok);
void enterVariableInit(SourceLocation Tok, Decl *D);
/// Handles e.g. BaseType{ .D = Tok...
void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
const Designation &D);
/// Computing a type for the function argument may require running
/// overloading, so we postpone its computation until it is actually needed.
///
/// Clients should be very careful when using this funciton, as it stores a
/// function_ref, clients should make sure all calls to get() with the same
/// location happen while function_ref is alive.
///
/// The callback should also emit signature help as a side-effect, but only
/// if the completion point has been reached.
void enterFunctionArgument(SourceLocation Tok,
llvm::function_ref<QualType()> ComputeType);
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
SourceLocation OpLoc);
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
/// Handles all type casts, including C-style cast, C++ casts, etc.
void enterTypeCast(SourceLocation Tok, QualType CastType);
/// Get the expected type associated with this location, if any.
///
/// If the location is a function argument, determining the expected type
/// involves considering all function overloads and the arguments so far.
/// In this case, signature help for these function overloads will be reported
/// as a side-effect (only if the completion point has been reached).
QualType get(SourceLocation Tok) const {
if (!Enabled || Tok != ExpectedLoc)
return QualType();
if (!Type.isNull())
return Type;
if (ComputeType)
return ComputeType();
return QualType();
}
private:
bool Enabled;
/// Start position of a token for which we store expected type.
SourceLocation ExpectedLoc;
/// Expected type for a token starting at ExpectedLoc.
QualType Type;
/// A function to compute expected type at ExpectedLoc. It is only considered
/// if Type is null.
llvm::function_ref<QualType()> ComputeType;
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema final {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
///Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
/// Determine whether two declarations should be linked together, given that
/// the old declaration might not be visible and the new declaration might
/// not have external linkage.
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
if (isVisible(Old))
return true;
// See comment in below overload for why it's safe to compute the linkage
// of the new declaration here.
if (New->isExternallyDeclarable()) {
assert(Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl");
return true;
}
return false;
}
bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
QualType ResultTy,
ArrayRef<QualType> Args);
public:
/// The maximum alignment, same as in llvm::Value. We duplicate them here
/// because that allows us not to duplicate the constants in clang code,
/// which we must to since we can't directly use the llvm constants.
/// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
///
/// This is the greatest alignment value supported by load, store, and alloca
/// instructions, and global values.
static const unsigned MaxAlignmentExponent = 29;
static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions CurFPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
/// Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
/// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
/// `TransformTypos` in order to keep track of any TypoExprs that are created
/// recursively during typo correction and wipe them away if the correction
/// fails.
llvm::SmallVector<TypoExpr *, 2> TypoExprs;
/// pragma clang section kind
enum PragmaClangSectionKind {
PCSK_Invalid = 0,
PCSK_BSS = 1,
PCSK_Data = 2,
PCSK_Rodata = 3,
PCSK_Text = 4,
PCSK_Relro = 5
};
enum PragmaClangSectionAction {
PCSA_Set = 0,
PCSA_Clear = 1
};
struct PragmaClangSection {
std::string SectionName;
bool Valid = false;
SourceLocation PragmaLocation;
};
PragmaClangSection PragmaClangBSSSection;
PragmaClangSection PragmaClangDataSection;
PragmaClangSection PragmaClangRodataSection;
PragmaClangSection PragmaClangRelroSection;
PragmaClangSection PragmaClangTextSection;
enum PragmaMsStackAction {
PSK_Reset = 0x0, // #pragma ()
PSK_Set = 0x1, // #pragma (value)
PSK_Push = 0x2, // #pragma (push[, id])
PSK_Pop = 0x4, // #pragma (pop[, id])
PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
};
// #pragma pack and align.
class AlignPackInfo {
public:
// `Native` represents default align mode, which may vary based on the
// platform.
enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
// #pragma pack info constructor
AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
: PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
assert(Num == PackNumber && "The pack number has been truncated.");
}
// #pragma align info constructor
AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
: PackAttr(false), AlignMode(M),
PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
AlignPackInfo() : AlignPackInfo(Native, false) {}
// When a AlignPackInfo itself cannot be used, this returns an 32-bit
// integer encoding for it. This should only be passed to
// AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
static uint32_t getRawEncoding(const AlignPackInfo &Info) {
std::uint32_t Encoding{};
if (Info.IsXLStack())
Encoding |= IsXLMask;
Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
if (Info.IsPackAttr())
Encoding |= PackAttrMask;
Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
return Encoding;
}
static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
bool IsXL = static_cast<bool>(Encoding & IsXLMask);
AlignPackInfo::Mode M =
static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
int PackNumber = (Encoding & PackNumMask) >> 4;
if (Encoding & PackAttrMask)
return AlignPackInfo(M, PackNumber, IsXL);
return AlignPackInfo(M, IsXL);
}
bool IsPackAttr() const { return PackAttr; }
bool IsAlignAttr() const { return !PackAttr; }
Mode getAlignMode() const { return AlignMode; }
unsigned getPackNumber() const { return PackNumber; }
bool IsPackSet() const {
// #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
// attriute on a decl.
return PackNumber != UninitPackVal && PackNumber != 0;
}
bool IsXLStack() const { return XLStack; }
bool operator==(const AlignPackInfo &Info) const {
return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
Info.XLStack);
}
bool operator!=(const AlignPackInfo &Info) const {
return !(*this == Info);
}
private:
/// \brief True if this is a pragma pack attribute,
/// not a pragma align attribute.
bool PackAttr;
/// \brief The alignment mode that is in effect.
Mode AlignMode;
/// \brief The pack number of the stack.
unsigned char PackNumber;
/// \brief True if it is a XL #pragma align/pack stack.
bool XLStack;
/// \brief Uninitialized pack value.
static constexpr unsigned char UninitPackVal = -1;
// Masks to encode and decode an AlignPackInfo.
static constexpr uint32_t IsXLMask{0x0000'0001};
static constexpr uint32_t AlignModeMask{0x0000'0006};
static constexpr uint32_t PackAttrMask{0x00000'0008};
static constexpr uint32_t PackNumMask{0x0000'01F0};
};
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
SourceLocation PragmaPushLocation;
Slot(llvm::StringRef StackSlotLabel, ValueType Value,
SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation),
PragmaPushLocation(PragmaPushLocation) {}
};
void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel, ValueType Value) {
if (Action == PSK_Reset) {
CurrentValue = DefaultValue;
CurrentPragmaLocation = PragmaLocation;
return;
}
if (Action & PSK_Push)
Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
PragmaLocation);
else if (Action & PSK_Pop) {
if (!StackSlotLabel.empty()) {
// If we've got a label, try to find it and jump there.
auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
return x.StackSlotLabel == StackSlotLabel;
});
// If we found the label so pop from there.
if (I != Stack.rend()) {
CurrentValue = I->Value;
CurrentPragmaLocation = I->PragmaLocation;
Stack.erase(std::prev(I.base()), Stack.end());
}
} else if (!Stack.empty()) {
// We do not have a label, just pop the last entry.
CurrentValue = Stack.back().Value;
CurrentPragmaLocation = Stack.back().PragmaLocation;
Stack.pop_back();
}
}
if (Action & PSK_Set) {
CurrentValue = Value;
CurrentPragmaLocation = PragmaLocation;
}
}
// MSVC seems to add artificial slots to #pragma stacks on entering a C++
// method body to restore the stacks on exit, so it works like this:
//
// struct S {
// #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
// void Method {}
// #pragma <name>(pop, InternalPragmaSlot)
// };
//
// It works even with #pragma vtordisp, although MSVC doesn't support
// #pragma vtordisp(push [, id], n)
// syntax.
//
// Push / pop a named sentinel slot.
void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
assert((Action == PSK_Push || Action == PSK_Pop) &&
"Can only push / pop #pragma stack sentinels!");
Act(CurrentPragmaLocation, Action, Label, CurrentValue);
}
// Constructors.
explicit PragmaStack(const ValueType &Default)
: DefaultValue(Default), CurrentValue(Default) {}
bool hasValue() const { return CurrentValue != DefaultValue; }
SmallVector<Slot, 2> Stack;
ValueType DefaultValue; // Value used for PSK_Reset action.
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
/// Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
PragmaStack<MSVtorDispMode> VtorDispStack;
PragmaStack<AlignPackInfo> AlignPackStack;
// The current #pragma align/pack values and locations at each #include.
struct AlignPackIncludeState {
AlignPackInfo CurrentValue;
SourceLocation CurrentPragmaLocation;
bool HasNonDefaultValue, ShouldWarnOnInclude;
};
SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
// Segment #pragmas.
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
// This stack tracks the current state of Sema.CurFPFeatures.
PragmaStack<FPOptionsOverride> FpPragmaStack;
FPOptionsOverride CurFPFeatureOverrides() {
FPOptionsOverride result;
if (!FpPragmaStack.hasValue()) {
result = FPOptionsOverride();
} else {
result = FpPragmaStack.CurrentValue;
}
return result;
}
// RAII object to push / pop sentinel slots for all MS #pragma stacks.
// Actions should be performed only if we enter / exit a C++ method body.
class PragmaStackSentinelRAII {
public:
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
~PragmaStackSentinelRAII();
private:
Sema &S;
StringRef SlotLabel;
bool ShouldAct;
};
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// This an attribute introduced by \#pragma clang attribute.
struct PragmaAttributeEntry {
SourceLocation Loc;
ParsedAttr *Attribute;
SmallVector<attr::SubjectMatchRule, 4> MatchRules;
bool IsUsed;
};
/// A push'd group of PragmaAttributeEntries.
struct PragmaAttributeGroup {
/// The location of the push attribute.
SourceLocation Loc;
/// The namespace of this push group.
const IdentifierInfo *Namespace;
SmallVector<PragmaAttributeEntry, 2> Entries;
};
SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
/// The declaration that is currently receiving an attribute from the
/// #pragma attribute stack.
const Decl *PragmaAttributeCurrentTargetDecl;
/// This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// Used to control the generation of ExprWithCleanups.
CleanupInfo Cleanup;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression.
SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
/// Store a set of either DeclRefExprs or MemberExprs that contain a reference
/// to a variable (constant) that may or may not be odr-used in this Expr, and
/// we won't know until all lvalue-to-rvalue and discarded value conversions
/// have been applied to all subexpressions of the enclosing full expression.
/// This is cleared at the end of each full expression.
using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
llvm::SmallPtrSet<Expr *, 4>>;
MaybeODRUseExprSet MaybeODRUseExprs;
std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
/// Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
/// The index of the first FunctionScope that corresponds to the current
/// context.
unsigned FunctionScopesStart = 0;
ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
FunctionScopes.end());
}
/// Stack containing information needed when in C++2a an 'auto' is encountered
/// in a function declaration parameter type specifier in order to invent a
/// corresponding template parameter in the enclosing abbreviated function
/// template. This information is also present in LambdaScopeInfo, stored in
/// the FunctionScopes stack.
SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
/// The index of the first InventedParameterInfo that refers to the current
/// context.
unsigned InventedParameterInfosStart = 0;
ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
return llvm::makeArrayRef(InventedParameterInfos.begin() +
InventedParameterInfosStart,
InventedParameterInfos.end());
}
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
/// Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
/// All the external declarations encoutered and used in the TU.
SmallVector<VarDecl *, 4> ExternalDeclarations;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedOverridingExceptionSpecChecks;
/// All the function redeclarations seen during a class definition that had
/// their exception spec checks delayed, plus the prior declaration they
/// should be checked against. Except during error recovery, the new decl
/// should always be a friend declaration, as that's the only valid way to
/// redeclare a special member before its class is complete.
SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
DelayedEquivalentExceptionSpecChecks;
typedef llvm::MapVector<const FunctionDecl *,
std::unique_ptr<LateParsedTemplate>>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
// Does the work necessary to deal with a SYCL kernel lambda. At the moment,
// this just marks the list of lambdas required to name the kernel.
void AddSYCLKernelLambda(const FunctionDecl *FD);
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
unsigned SavedFunctionScopesStart;
unsigned SavedInventedParameterInfosStart;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
SavedFunctionScopesStart(S.FunctionScopesStart),
SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
// Any saved FunctionScopes do not refer to this context.
S.FunctionScopesStart = S.FunctionScopes.size();
S.InventedParameterInfosStart = S.InventedParameterInfos.size();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
S.FunctionScopesStart = SavedFunctionScopesStart;
S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// Whether the AST is currently being rebuilt to correct immediate
/// invocations. Immediate invocation candidates and references to consteval
/// functions aren't tracked when this is set.
bool RebuildingImmediateInvocation = false;
/// Used to change context to isConstantEvaluated without pushing a heavy
/// ExpressionEvaluationContextRecord object.
bool isConstantEvaluatedOverride;
bool isConstantEvaluated() {
return ExprEvalContexts.back().isConstantEvaluated() ||
isConstantEvaluatedOverride;
}
/// RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
bool PushedCodeSynthesisContext = false;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC) {
S.PushFunctionScope();
S.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
if (auto *FD = dyn_cast<FunctionDecl>(DC))
FD->setWillHaveBody(true);
else
assert(isa<ObjCMethodDecl>(DC));
}
void addContextNote(SourceLocation UseLoc) {
assert(!PushedCodeSynthesisContext);
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
Ctx.PointOfInstantiation = UseLoc;
Ctx.Entity = cast<Decl>(S.CurContext);
S.pushCodeSynthesisContext(Ctx);
PushedCodeSynthesisContext = true;
}
~SynthesizedFunctionScope() {
if (PushedCodeSynthesisContext)
S.popCodeSynthesisContext();
if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
FD->setWillHaveBody(false);
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// The C++ "std::align_val_t" enum class, which is defined by the C++
/// standard library.
LazyDeclPtr StdAlignValT;
/// The C++ "std::experimental" namespace, where the experimental parts
/// of the standard library resides.
NamespaceDecl *StdExperimentalNamespaceCache;
/// The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// The C++ "std::coroutine_traits" template, which is defined in
/// \<coroutine_traits>
ClassTemplateDecl *StdCoroutineTraitsCache;
/// The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// Caches identifiers/selectors for NSFoundation APIs.
std::unique_ptr<NSAPI> NSAPIObj;
/// The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// id<NSCopying> type.
QualType QIDNSCopying;
/// will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum class ExpressionEvaluationContext {
/// The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// The current expression occurs within a braced-init-list within
/// an unevaluated operand. This is mostly like a regular unevaluated
/// context, except that we still instantiate constexpr functions that are
/// referenced here so that we can perform narrowing checks correctly.
UnevaluatedList,
/// The current expression occurs within a discarded statement.
/// This behaves largely similarly to an unevaluated operand in preventing
/// definitions from being required, but not in other ways.
DiscardedStatement,
/// The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
/// Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// The expression evaluation context.
ExpressionEvaluationContext Context;
/// Whether the enclosing context needed a cleanup.
CleanupInfo ParentCleanup;
/// The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
MaybeODRUseExprSet SavedMaybeODRUseExprs;
/// The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
/// Expressions appearing as the LHS of a volatile assignment in this
/// context. We produce a warning for these when popping the context if
/// they are not discarded-value expressions nor unevaluated operands.
SmallVector<Expr*, 2> VolatileAssignmentLHSs;
/// Set of candidates for starting an immediate invocation.
llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
/// Set of DeclRefExprs referencing a consteval function when used in a
/// context not already known to be immediately invoked.
llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
/// \brief Describes whether we are in an expression constext which we have
/// to handle differently.
enum ExpressionKind {
EK_Decltype, EK_TemplateArgument, EK_Other
} ExprContext;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
CleanupInfo ParentCleanup,
Decl *ManglingContextDecl,
ExpressionKind ExprContext)
: Context(Context), ParentCleanup(ParentCleanup),
NumCleanupObjects(NumCleanupObjects), NumTypos(0),
ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
bool isUnevaluated() const {
return Context == ExpressionEvaluationContext::Unevaluated ||
Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
Context == ExpressionEvaluationContext::UnevaluatedList;
}
bool isConstantEvaluated() const {
return Context == ExpressionEvaluationContext::ConstantEvaluated;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// Emit a warning for all pending noderef expressions that we recorded.
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
/// Compute the mangling number context for a lambda expression or
/// block literal. Also return the extra mangling decl if any.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
std::tuple<MangleNumberingContext *, Decl *>
getCurrentMangleNumberContext(const DeclContext *DC);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl *MD)
: Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
class SpecialMemberOverloadResultEntry
: public llvm::FastFoldingSetNode,
public SpecialMemberOverloadResult {
public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
};
/// A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
/// A cache of the flags available in enumerations with the flag_bits
/// attribute.
mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
/// The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
const TranslationUnitKind TUKind;
llvm::BumpPtrAllocator BumpAlloc;
/// The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Determine if VD, which must be a variable or function, is an external
/// symbol that nonetheless can't be referenced from outside this translation
/// unit because its type has no linkage and it's not extern "C".
bool isExternalWithNoLinkageType(ValueDecl *VD);
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// List of SourceLocations where 'self' is implicitly retained inside a
/// block.
llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
ImplicitlyRetainedSelfLocs;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
/// Kinds of defaulted comparison operator functions.
enum class DefaultedComparisonKind : unsigned char {
/// This is not a defaultable comparison operator.
None,
/// This is an operator== that should be implemented as a series of
/// subobject comparisons.
Equal,
/// This is an operator<=> that should be implemented as a series of
/// subobject comparisons.
ThreeWay,
/// This is an operator!= that should be implemented as a rewrite in terms
/// of a == comparison.
NotEqual,
/// This is an <, <=, >, or >= that should be implemented as a rewrite in
/// terms of a <=> comparison.
Relational,
};
/// The function definitions which were renamed as part of typo-correction
/// to match their respective declarations. We want to keep track of them
/// to ensure that we don't emit a "redefinition" error if we encounter a
/// correctly named definition after the renamed definition.
llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
/// Stack of types that correspond to the parameter entities that are
/// currently being copy-initialized. Can be empty.
llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
void ReadMethodPool(Selector Sel);
void updateOutOfDateSelector(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the CurFPFeatures state on entry/exit of compound
/// statements.
class FPFeaturesStateRAII {
public:
FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
OldOverrides = S.FpPragmaStack.CurrentValue;
}
~FPFeaturesStateRAII() {
S.CurFPFeatures = OldFPFeaturesState;
S.FpPragmaStack.CurrentValue = OldOverrides;
}
FPOptionsOverride getOverrides() { return OldOverrides; }
private:
Sema& S;
FPOptions OldFPFeaturesState;
FPOptionsOverride OldOverrides;
};
void addImplicitTypedef(StringRef Name, QualType T);
bool WarnedStackExhausted = false;
/// Increment when we find a reference; decrement when we find an ignored
/// assignment. Ultimately the value is 0 if every reference is an ignored
/// assignment.
llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
/// This virtual key function only exists to limit the emission of debug info
/// describing the Sema class. GCC and Clang only emit debug info for a class
/// with a vtable when the vtable is emitted. Sema is final and not
/// polymorphic, but the debug info size savings are so significant that it is
/// worth adding a vtable just to take advantage of this optimization.
virtual void anchor();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getCurFPFeatures() { return CurFPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
StringRef Platform);
///Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// Warn that the stack is nearly exhausted.
void warnStackExhausted(SourceLocation Loc);
/// Run some code with "sufficient" stack space. (Currently, at least 256K is
/// guaranteed). Produces a warning if we're low on stack space and allocates
/// more in that case. Use this in code that may recurse deeply (for example,
/// in template instantiation) to avoid stack overflow.
void runWithSufficientStackSpace(SourceLocation Loc,
llvm::function_ref<void()> Fn);
/// Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. ImmediateDiagBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class ImmediateDiagBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
// This is a cunning lie. DiagnosticBuilder actually performs move
// construction in its copy constructor (but due to varied uses, it's not
// possible to conveniently express this as actual move construction). So
// the default copy ctor here is fine, because the base class disables the
// source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
// in that case anwyay.
ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
~ImmediateDiagBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First clear the diagnostic
// builder itself so it won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template <typename T>
friend const ImmediateDiagBuilder &
operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
// It is necessary to limit this to rvalue reference to avoid calling this
// function with a bitfield lvalue argument since non-const reference to
// bitfield is not allowed.
template <typename T, typename = typename std::enable_if<
!std::is_lvalue_reference<T>::value>::type>
const ImmediateDiagBuilder &operator<<(T &&V) const {
const DiagnosticBuilder &BaseDiag = *this;
BaseDiag << std::move(V);
return *this;
}
};
/// A generic diagnostic builder for errors which may or may not be deferred.
///
/// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
/// which are not allowed to appear inside __device__ functions and are
/// allowed to appear in __host__ __device__ functions only if the host+device
/// function is never codegen'ed.
///
/// To handle this, we use the notion of "deferred diagnostics", where we
/// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
///
/// This class lets you emit either a regular diagnostic, a deferred
/// diagnostic, or no diagnostic at all, according to an argument you pass to
/// its constructor, thus simplifying the process of creating these "maybe
/// deferred" diagnostics.
class SemaDiagnosticBuilder {
public:
enum Kind {
/// Emit no diagnostics.
K_Nop,
/// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
K_Immediate,
/// Emit the diagnostic immediately, and, if it's a warning or error, also
/// emit a call stack showing how this function can be reached by an a
/// priori known-emitted function.
K_ImmediateWithCallStack,
/// Create a deferred diagnostic, which is emitted only if the function
/// it's attached to is codegen'ed. Also emit a call stack as with
/// K_ImmediateWithCallStack.
K_Deferred
};
SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
FunctionDecl *Fn, Sema &S);
SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
~SemaDiagnosticBuilder();
bool isImmediate() const { return ImmediateDiag.hasValue(); }
/// Convertible to bool: True if we immediately emitted an error, false if
/// we didn't emit an error or we created a deferred error.
///
/// Example usage:
///
/// if (SemaDiagnosticBuilder(...) << foo << bar)
/// return ExprError();
///
/// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
/// want to use these instead of creating a SemaDiagnosticBuilder yourself.
operator bool() const { return isImmediate(); }
template <typename T>
friend const SemaDiagnosticBuilder &
operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
if (Diag.ImmediateDiag.hasValue())
*Diag.ImmediateDiag << Value;
else if (Diag.PartialDiagId.hasValue())
Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
<< Value;
return Diag;
}
// It is necessary to limit this to rvalue reference to avoid calling this
// function with a bitfield lvalue argument since non-const reference to
// bitfield is not allowed.
template <typename T, typename = typename std::enable_if<
!std::is_lvalue_reference<T>::value>::type>
const SemaDiagnosticBuilder &operator<<(T &&V) const {
if (ImmediateDiag.hasValue())
*ImmediateDiag << std::move(V);
else if (PartialDiagId.hasValue())
S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
return *this;
}
friend const SemaDiagnosticBuilder &
operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
if (Diag.ImmediateDiag.hasValue())
PD.Emit(*Diag.ImmediateDiag);
else if (Diag.PartialDiagId.hasValue())
Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
return Diag;
}
void AddFixItHint(const FixItHint &Hint) const {
if (ImmediateDiag.hasValue())
ImmediateDiag->AddFixItHint(Hint);
else if (PartialDiagId.hasValue())
S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
}
friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
return ExprError();
}
friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
return StmtError();
}
operator ExprResult() const { return ExprError(); }
operator StmtResult() const { return StmtError(); }
operator TypeResult() const { return TypeError(); }
operator DeclResult() const { return DeclResult(true); }
operator MemInitResult() const { return MemInitResult(true); }
private:
Sema &S;
SourceLocation Loc;
unsigned DiagID;
FunctionDecl *Fn;
bool ShowCallStack;
// Invariant: At most one of these Optionals has a value.
// FIXME: Switch these to a Variant once that exists.
llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
llvm::Optional<unsigned> PartialDiagId;
};
/// Is the last error level diagnostic immediate. This is used to determined
/// whether the next info diagnostic should be immediate.
bool IsLastErrorImmediate = true;
/// Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
bool DeferHint = false);
/// Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
bool DeferHint = false);
/// Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
/// Whether deferrable diagnostics should be deferred.
bool DeferDiags = false;
/// RAII class to control scope of DeferDiags.
class DeferDiagsRAII {
Sema &S;
bool SavedDeferDiags = false;
public:
DeferDiagsRAII(Sema &S, bool DeferDiags)
: S(S), SavedDeferDiags(S.DeferDiags) {
S.DeferDiags = DeferDiags;
}
~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
};
/// Whether uncompilable error has occurred. This includes error happens
/// in deferred diagnostics.
bool hasUncompilableErrorOccurred() const;
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
/// Invent a new identifier for parameters of abbreviated templates.
IdentifierInfo *
InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
unsigned Index);
void emitAndClearUnusedLocalTypedefWarnings();
private:
/// Function or variable declarations to be checked for whether the deferred
/// diagnostics should be emitted.
llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
public:
// Emit all deferred diagnostics.
void emitDeferredDiags();
enum TUFragmentKind {
/// The global module fragment, between 'module;' and a module-declaration.
Global,
/// A normal translation unit fragment. For a non-module unit, this is the
/// entire translation unit. Otherwise, it runs from the module-declaration
/// to the private-module-fragment (if any) or the end of the TU (if not).
Normal,
/// The private module fragment, between 'module :private;' and the end of
/// the translation unit.
Private
};
void ActOnStartOfTranslationUnit();
void ActOnEndOfTranslationUnit();
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD, CapturedRegionKind K,
unsigned OpenMPCaptureLevel = 0);
/// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
/// time after they've been popped.
class PoppedFunctionScopeDeleter {
Sema *Self;
public:
explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
void operator()(sema::FunctionScopeInfo *Scope) const;
};
using PoppedFunctionScopePtr =
std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
PoppedFunctionScopePtr
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
QualType BlockType = QualType());
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const;
void setFunctionHasBranchIntoScope();
void setFunctionHasBranchProtectedScope();
void setFunctionHasIndirectGoto();
void setFunctionHasMustTail();
void PushCompoundScope(bool IsStmtExpr);
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// Get the innermost lambda enclosing the current location, if any. This
/// looks through intervening non-lambda scopes such as local functions and
/// blocks.
sema::LambdaScopeInfo *getEnclosingLambda() const;
/// Retrieve the current lambda scope info, if any.
/// \param IgnoreNonLambdaCapturingScope true if should find the top-most
/// lambda scope info ignoring all inner capturing scopes that are not
/// lambda scopes.
sema::LambdaScopeInfo *
getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
/// Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// Retrieve the current function, if any, that should be analyzed for
/// potential availability violations.
sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
/// Called before parsing a function declarator belonging to a function
/// declaration.
void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
unsigned TemplateParameterDepth);
/// Called after parsing a function declarator belonging to a function
/// declaration.
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
SourceLocation AttrLoc);
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
SourceLocation AttrLoc);
/// Same as above, but constructs the AddressSpace index if not provided.
QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
SourceLocation AttrLoc);
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
/// Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
QualType BuildFunctionType(QualType T,
MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI);
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
QualType BuildReadPipeType(QualType T,
SourceLocation Loc);
QualType BuildWritePipeType(QualType T,
SourceLocation Loc);
QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
/// Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Stmt *E);
/// Determine whether the callee of a particular function call can throw.
/// E, D and Loc are all optional.
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
SourceLocation Loc = SourceLocation());
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const PartialDiagnostic &NoThrowDiagID,
const FunctionProtoType *Superset,
SourceLocation SuperLoc,
const FunctionProtoType *Subset,
SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const FunctionProtoType *Target,
SourceLocation TargetLoc,
const FunctionProtoType *Source,
SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
TypeDiagnoser() {}
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
protected:
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
std::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
assert(DiagID != 0 && "no diagnostic for type diagnoser");
}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, std::index_sequence_for<Ts...>());
DB << T;
}
};
/// Do a check to make sure \p Name looks like a legal argument for the
/// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
/// is invalid for the given declaration.
///
/// \p AL is used to provide caret diagnostics in case of a malformed name.
///
/// \returns true if the name is a valid swift name for \p D, false otherwise.
bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
const ParsedAttr &AL, bool IsAsync);
/// A derivative of BoundTypeDiagnoser for which the diagnostic's type
/// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
/// For example, a diagnostic with no other parameters would generally have
/// the form "...%select{incomplete|sizeless}0 type %1...".
template <typename... Ts>
class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
public:
SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
: BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
this->emit(DB, std::index_sequence_for<Ts...>());
DB << T->isSizelessType() << T;
}
};
enum class CompleteTypeKind {
/// Apply the normal rules for complete types. In particular,
/// treat all sizeless types as incomplete.
Normal,
/// Relax the normal rules for complete types so that they include
/// sizeless built-in types.
AcceptSizeless,
// FIXME: Eventually we should flip the default to Normal and opt in
// to AcceptSizeless rather than opt out of it.
Default = AcceptSizeless
};
private:
/// Methods for marking which expressions involve dereferencing a pointer
/// marked with the 'noderef' attribute. Expressions are checked bottom up as
/// they are parsed, meaning that a noderef pointer may not be accessed. For
/// example, in `&*p` where `p` is a noderef pointer, we will first parse the
/// `*p`, but need to check that `address of` is called on it. This requires
/// keeping a container of all pending expressions and checking if the address
/// of them are eventually taken.
void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
void CheckAddressOfNoDeref(const Expr *E);
void CheckMemberAccessOfNoDeref(const MemberExpr *E);
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
struct ModuleScope {
SourceLocation BeginLoc;
clang::Module *Module = nullptr;
bool ModuleInterface = false;
bool ImplicitGlobalModuleFragment = false;
VisibleModuleSet OuterVisibleModules;
};
/// The modules we're currently parsing.
llvm::SmallVector<ModuleScope, 16> ModuleScopes;
/// Namespace definitions that we will export when they finish.
llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
/// Get the module whose scope we are currently within.
Module *getCurrentModule() const {
return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
}
VisibleModuleSet VisibleModules;
public:
/// Get the module owning an entity.
Module *getOwningModule(const Decl *Entity) {
return Entity->getOwningModule();
}
/// Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND);
bool isModuleVisible(const Module *M, bool ModulePrivate = false);
// When loading a non-modular PCH files, this is used to restore module
// visibility.
void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
VisibleModules.setVisible(Mod, ImportLoc);
}
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return D->isUnconditionallyVisible() || isVisibleSlow(D);
}
/// Determine whether any declaration of an entity is visible.
bool
hasVisibleDeclaration(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
}
bool hasVisibleDeclarationSlow(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules);
bool hasVisibleMergedDefinition(NamedDecl *Def);
bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
/// Determine if \p D and \p Suggested have a structurally compatible
/// layout as described in C11 6.2.7/1.
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is an explicit
/// specialization declaration for a specialization of a template. (For a
/// member specialization, use hasVisibleMemberSpecialization.)
bool hasVisibleExplicitSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is a member
/// specialization declaration (as opposed to an instantiated declaration).
bool hasVisibleMemberSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if \p A and \p B are equivalent internal linkage declarations
/// from different modules, and thus an ambiguity error can be downgraded to
/// an extension warning.
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
const NamedDecl *B);
void diagnoseEquivalentInternalLinkageDeclarations(
SourceLocation Loc, const NamedDecl *D,
ArrayRef<const NamedDecl *> Equiv);
bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
bool isCompleteType(SourceLocation Loc, QualType T,
CompleteTypeKind Kind = CompleteTypeKind::Default) {
return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
}
bool RequireCompleteType(SourceLocation Loc, QualType T,
CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
CompleteTypeKind Kind, unsigned DiagID);
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser) {
return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
}
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
}
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
template <typename... Ts>
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &... Args) {
SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
}
/// Get the type of expression E, triggering instantiation to complete the
/// type if necessary -- that is, if the expression refers to a templated
/// static data member of incomplete array type.
///
/// May still return an incomplete type if instantiation was not possible or
/// if the type is incomplete for a different reason. Use
/// RequireCompleteExprType instead if a diagnostic is expected for an
/// incomplete expression type.
QualType getCompletedType(Expr *E);
void completeExprArrayBound(Expr *E);
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
}
template <typename... Ts>
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
const Ts &... Args) {
SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T,
TagDecl *OwnedTagDecl = nullptr);
QualType getDecltypeForParenthesizedExpr(Expr *E);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
struct SkipBodyInfo {
SkipBodyInfo()
: ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
New(nullptr) {}
bool ShouldSkip;
bool CheckSameAsPrevious;
NamedDecl *Previous;
NamedDecl *New;
};
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false, bool HasTrailingDot = false,
ParsedType ObjectType = nullptr,
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
bool IsClassTemplateDeductionContext = true,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool IsTemplateName = false);
/// Attempt to behave like MSVC in situations where lookup of an unqualified
/// type name has failed in a dependent context. In these situations, we
/// automatically form a DependentTypeName that will retry lookup in a related
/// scope during instantiation.
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
SourceLocation NameLoc,
bool IsTemplateTypeArg);
/// Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
/// This name is not a type or template in this context, but might be
/// something else.
NC_Unknown,
/// Classification failed; an error has been produced.
NC_Error,
/// The name has been typo-corrected to a keyword.
NC_Keyword,
/// The name was classified as a type.
NC_Type,
/// The name was classified as a specific non-type, non-template
/// declaration. ActOnNameClassifiedAsNonType should be called to
/// convert the declaration to an expression.
NC_NonType,
/// The name was classified as an ADL-only function name.
/// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
/// result to an expression.
NC_UndeclaredNonType,
/// The name denotes a member of a dependent type that could not be
/// resolved. ActOnNameClassifiedAsDependentNonType should be called to
/// convert the result to an expression.
NC_DependentNonType,
/// The name was classified as an overload set, and an expression
/// representing that overload set has been formed.
/// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
/// expression referencing the overload set.
NC_OverloadSet,
/// The name was classified as a template whose specializations are types.
NC_TypeTemplate,
/// The name was classified as a variable template name.
NC_VarTemplate,
/// The name was classified as a function template name.
NC_FunctionTemplate,
/// The name was classified as an ADL-only function template name.
NC_UndeclaredTemplate,
/// The name was classified as a concept name.
NC_Concept,
};
class NameClassification {
NameClassificationKind Kind;
union {
ExprResult Expr;
NamedDecl *NonTypeDecl;
TemplateName Template;
ParsedType Type;
};
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification OverloadSet(ExprResult E) {
NameClassification Result(NC_OverloadSet);
Result.Expr = E;
return Result;
}
static NameClassification NonType(NamedDecl *D) {
NameClassification Result(NC_NonType);
Result.NonTypeDecl = D;
return Result;
}
static NameClassification UndeclaredNonType() {
return NameClassification(NC_UndeclaredNonType);
}
static NameClassification DependentNonType() {
return NameClassification(NC_DependentNonType);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
static NameClassification Concept(TemplateName Name) {
NameClassification Result(NC_Concept);
Result.Template = Name;
return Result;
}
static NameClassification UndeclaredTemplate(TemplateName Name) {
NameClassification Result(NC_UndeclaredTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ExprResult getExpression() const {
assert(Kind == NC_OverloadSet);
return Expr;
}
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
NamedDecl *getNonTypeDecl() const {
assert(Kind == NC_NonType);
return NonTypeDecl;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate || Kind == NC_Concept ||
Kind == NC_UndeclaredTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
case NC_Concept:
return TNK_Concept_template;
case NC_UndeclaredTemplate:
return TNK_Undeclared_template;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name, SourceLocation NameLoc,
const Token &NextToken,
CorrectionCandidateCallback *CCC = nullptr);
/// Act on the result of classifying a name as an undeclared (ADL-only)
/// non-type declaration.
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
SourceLocation NameLoc);
/// Act on the result of classifying a name as an undeclared member of a
/// dependent base class.
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsAddressOfOperand);
/// Act on the result of classifying a name as a specific non-type
/// declaration.
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
NamedDecl *Found,
SourceLocation NameLoc,
const Token &NextToken);
/// Act on the result of classifying a name as an overload set.
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
/// Describes the detailed kind of a template name. Used in diagnostics.
enum class TemplateNameKindForDiagnostics {
ClassTemplate,
FunctionTemplate,
VarTemplate,
AliasTemplate,
TemplateTemplateParam,
Concept,
DependentTemplate
};
TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name);
/// Determine whether it's plausible that E was intended to be a
/// template-name.
bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
if (!getLangOpts().CPlusPlus || E.isInvalid())
return false;
Dependent = false;
if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
return !DRE->hasExplicitTemplateArgs();
if (auto *ME = dyn_cast<MemberExpr>(E.get()))
return !ME->hasExplicitTemplateArgs();
Dependent = true;
if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
return !DSDRE->hasExplicitTemplateArgs();
if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
return !DSME->hasExplicitTemplateArgs();
// Any additional cases recognized here should also be handled by
// diagnoseExprIntendedAsTemplateName.
return false;
}
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
SourceLocation Less,
SourceLocation Greater);
void warnOnReservedIdentifier(const NamedDecl *D);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
QualType &T, SourceLocation Loc,
unsigned FailedFoldDiagID);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name, SourceLocation Loc,
bool IsTemplateId);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation(),
SourceLocation UnalignedQualLoc = SourceLocation());
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
const LookupResult &R);
NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
NamedDecl *getShadowedDeclaration(const BindingDecl *D,
const LookupResult &R);
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
const LookupResult &R);
void CheckShadow(Scope *S, VarDecl *D);
/// Warn if 'E', which is an expression that is about to be modified, refers
/// to a shadowing declaration.
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
private:
/// Map of current shadowing declarations to shadowed declarations. Warn if
/// it looks like the user is trying to modify the shadowing declaration.
llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
public:
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope,
ArrayRef<BindingDecl *> Bindings = None);
NamedDecl *
ActOnDecompositionDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists);
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
void CheckVariableDeclarationType(VarDecl *NewVD);
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
Expr *Init);
void CheckCompleteVariableDeclaration(VarDecl *VD);
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
enum class CheckConstexprKind {
/// Diagnose issues that are non-constant or that are extensions.
Diagnose,
/// Identify whether this function satisfies the formal rules for constexpr
/// functions in the current lanugage mode (with no extensions).
CheckValid
};
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
CheckConstexprKind Kind);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsMemberSpecialization);
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
QualType NewT, QualType OldT);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
bool IsDefinition);
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC);
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
// Contexts where using non-trivial C union types can be disallowed. This is
// passed to err_non_trivial_c_union_in_invalid_context.
enum NonTrivialCUnionContext {
// Function parameter.
NTCUC_FunctionParam,
// Function return.
NTCUC_FunctionReturn,
// Default-initialized object.
NTCUC_DefaultInitializedObject,
// Variable with automatic storage duration.
NTCUC_AutoVar,
// Initializer expression that might copy from another object.
NTCUC_CopyInit,
// Assignment.
NTCUC_Assignment,
// Compound literal.
NTCUC_CompoundLiteral,
// Block capture.
NTCUC_BlockCapture,
// lvalue-to-rvalue conversion of volatile type.
NTCUC_LValueToRValueVolatile,
};
/// Emit diagnostics if the initializer or any of its explicit or
/// implicitly-generated subexpressions require copying or
/// default-initializing a type that is or contains a C union type that is
/// non-trivial to copy or default-initialize.
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
// These flags are passed to checkNonTrivialCUnion.
enum NonTrivialCUnionKind {
NTCUK_Init = 0x1,
NTCUK_Destruct = 0x2,
NTCUK_Copy = 0x4,
};
/// Emit diagnostics if a non-trivial C union type or a struct that contains
/// a non-trivial C union is used in an invalid context.
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
NonTrivialCUnionContext UseContext,
unsigned NonTrivialKind);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
void ActOnUninitializedDecl(Decl *dcl);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void CheckStaticLocalForDllExport(VarDecl *VD);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(
FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
SkipBodyInfo *SkipBody = nullptr);
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineFunctionDef(FunctionDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
/// Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
QualType ReturnTy, NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
SourceLocation SemiLoc);
enum class ModuleDeclKind {
Interface, ///< 'export module X;'
Implementation, ///< 'module X;'
};
/// The parser has processed a module-declaration that begins the definition
/// of a module interface or implementation.
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
SourceLocation ModuleLoc, ModuleDeclKind MDK,
ModuleIdPath Path, bool IsFirstDecl);
/// The parser has processed a global-module-fragment declaration that begins
/// the definition of the global module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
/// The parser has processed a private-module-fragment declaration that begins
/// the definition of the private module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
/// \param PrivateLoc The location of the 'private' keyword.
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
SourceLocation PrivateLoc);
/// The parser has processed a module import declaration.
///
/// \param StartLoc The location of the first token in the declaration. This
/// could be the location of an '@', 'export', or 'import'.
/// \param ExportLoc The location of the 'export' keyword, if any.
/// \param ImportLoc The location of the 'import' keyword.
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path);
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, Module *M,
ModuleIdPath Path = {});
/// The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument,
ExplicitSpecialization,
PartialSpecialization
};
/// Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
MissingImportKind MIK, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
SourceLocation LBraceLoc);
Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
SourceLocation RBraceLoc);
/// We've found a use of a templated declaration that would trigger an
/// implicit instantiation. Check that any relevant explicit specializations
/// and partial specializations are visible, and diagnose if not.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
/// Retrieve a suitable printing policy for diagnostics.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// Retrieve a suitable printing policy for diagnostics.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
RecordDecl *&AnonRecord);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation,
RecordDecl *&AnonRecord);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
/// Common ways to introduce type names without a tag for use in diagnostics.
/// Keep in sync with err_tag_reference_non_tag.
enum NonTagKind {
NTK_NonStruct,
NTK_NonClass,
NTK_NonUnion,
NTK_NonEnum,
NTK_Typedef,
NTK_TypeAlias,
NTK_Template,
NTK_TypeAliasTemplate,
NTK_TemplateTemplateArgument,
};
/// Given a non-tag type declaration, returns an enum useful for indicating
/// what kind of non-tag type this is.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc, const ParsedAttributesView &Attr,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
bool &IsDependent, SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, bool IsTemplateParamOrArg,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart, Declarator &D,
Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
const ParsedAttr &MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
enum TrivialABIHandling {
/// The triviality of a method unaffected by "trivial_abi".
TAH_IgnoreTrivialABI,
/// The triviality of a method affected by "trivial_abi".
TAH_ConsiderTrivialABI
};
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
bool Diagnose = false);
/// For a defaulted function, the kind of defaulted function that it is.
class DefaultedFunctionKind {
CXXSpecialMember SpecialMember : 8;
DefaultedComparisonKind Comparison : 8;
public:
DefaultedFunctionKind()
: SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
}
DefaultedFunctionKind(CXXSpecialMember CSM)
: SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)
: SpecialMember(CXXInvalid), Comparison(Comp) {}
bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
bool isComparison() const {
return Comparison != DefaultedComparisonKind::None;
}
explicit operator bool() const {
return isSpecialMember() || isComparison();
}
CXXSpecialMember asSpecialMember() const { return SpecialMember; }
DefaultedComparisonKind asComparison() const { return Comparison; }
/// Get the index of this function kind for use in diagnostics.
unsigned getDiagnosticIndex() const {
static_assert(CXXInvalid > CXXDestructor,
"invalid should have highest index");
static_assert((unsigned)DefaultedComparisonKind::None == 0,
"none should be equal to zero");
return SpecialMember + (unsigned)Comparison;
}
};
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
return getDefaultedFunctionKind(MD).asSpecialMember();
}
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
return getDefaultedFunctionKind(FD).asComparison();
}
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac, const ParsedAttributesView &AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
/// Perform ODR-like check for C/ObjC when merging tag types from modules.
/// Differently from C++, actually parse the body and reject / error out
/// in case of a structural mismatch.
bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
SkipBodyInfo &SkipBody);
typedef void *SkippedDefinitionContext;
/// Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
bool IsAbstract,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceRange BraceRange);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, bool IsFixed,
const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
const ParsedAttributesView &Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
const ParsedAttributesView &Attr);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Enter a template parameter scope, after it's been associated with a particular
/// DeclContext. Causes lookup within the scope to chain through enclosing contexts
/// in the correct order.
void EnterTemplatedContext(Scope *S, DeclContext *DC);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// Don't merge availability attributes at all.
AMK_None,
/// Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override,
/// Merge availability attributes for an implementation of
/// a protocol requirement.
AMK_ProtocolImplementation,
/// Merge availability attributes for an implementation of
/// an optional protocol requirement.
AMK_OptionalProtocolImplementation
};
/// Describes the kind of priority given to an availability attribute.
///
/// The sum of priorities deteremines the final priority of the attribute.
/// The final priority determines how the attribute will be merged.
/// An attribute with a lower priority will always remove higher priority
/// attributes for the specified platform when it is being applied. An
/// attribute with a higher priority will not be applied if the declaration
/// already has an availability attribute with a lower priority for the
/// specified platform. The final prirority values are not expected to match
/// the values in this enumeration, but instead should be treated as a plain
/// integer value. This enumeration just names the priority weights that are
/// used to calculate that final vaue.
enum AvailabilityPriority : int {
/// The availability attribute was specified explicitly next to the
/// declaration.
AP_Explicit = 0,
/// The availability attribute was applied using '#pragma clang attribute'.
AP_PragmaClangAttribute = 1,
/// The availability attribute for a specific platform was inferred from
/// an availability attribute for another platform.
AP_InferredFromOtherPlatform = 2
};
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *
mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Platform, bool Implicit,
VersionTuple Introduced, VersionTuple Deprecated,
VersionTuple Obsoleted, bool IsUnavailable,
StringRef Message, bool IsStrict, StringRef Replacement,
AvailabilityMergeKind AMK, int Priority);
TypeVisibilityAttr *
mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
TypeVisibilityAttr::VisibilityType Vis);
VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
VisibilityAttr::VisibilityType Vis);
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
const AttributeCommonInfo &CI,
bool BestCase,
MSInheritanceModel Model);
FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Format, int FormatIdx,
int FirstArg);
SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
const AttributeCommonInfo &CI,
const IdentifierInfo *Ident);
MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
StringRef Name);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
const AttributeCommonInfo &CI);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
const InternalLinkageAttr &AL);
WebAssemblyImportNameAttr *mergeImportNameAttr(
Decl *D, const WebAssemblyImportNameAttr &AL);
WebAssemblyImportModuleAttr *mergeImportModuleAttr(
Decl *D, const WebAssemblyImportModuleAttr &AL);
EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
const EnforceTCBLeafAttr &AL);
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous);
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
bool ConsiderCudaAttrs = true,
bool ConsiderRequiresClauses = true);
enum class AllowedExplicit {
/// Allow no explicit functions to be used.
None,
/// Allow explicit conversion functions but not explicit constructors.
Conversions,
/// Allow both explicit conversion functions and explicit constructors.
All
};
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
AllowedExplicit AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess,
bool Diagnose = true);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsFunctionConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
bool CanPerformAggregateInitializationForOverloadResolution(
const InitializedEntity &Entity, InitListExpr *From);
bool IsStringInit(Expr *Init, const ArrayType *AT);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
/// Check that the lifetime of the initializer (and its subobjects) is
/// sufficient for initializing the entity, and perform lifetime extension
/// (when permitted) if not.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE,
NamedDecl *Dest = nullptr);
/// Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
using ADLCallKind = CallExpr::ADLCallKind;
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = true,
bool AllowExplicitConversion = false,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool FirstArgumentIsBase = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false,
OverloadCandidateParamOrder PO = {});
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
OverloadCandidateParamOrder PO = {});
void AddTemplateOverloadCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
bool PartialOverloading = false, bool AllowExplicit = true,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
OverloadCandidateParamOrder PO = {});
bool CheckNonDependentConversions(
FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
ConversionSequenceList &Conversions, bool SuppressUserConversions,
CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
Expr::Classification ObjectClassification = {},
OverloadCandidateParamOrder PO = {});
void AddConversionCandidate(
CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddTemplateConversionCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddNonMemberOperatorCandidates(
const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
OverloadCandidateParamOrder PO = {});
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(
NamedDecl *Found, FunctionDecl *Fn,
OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
QualType DestType = QualType(), bool TakingAddress = false);
// Emit as a series of 'note's all template and non-templates identified by
// the expression Expr
void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
bool TakingAddress = false);
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
/// Find the failed Boolean condition within a given Boolean
/// constant expression, and describe it with a string.
std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// non-ArgDependent DiagnoseIfAttrs.
///
/// Argument-dependent diagnose_if attributes should be checked each time a
/// function is used as a direct callee of a function call.
///
/// Returns true if any errors were emitted.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
const Expr *ThisArg,
ArrayRef<const Expr *> Args,
SourceLocation Loc);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// ArgDependent DiagnoseIfAttrs.
///
/// Argument-independent diagnose_if attributes should be checked on every use
/// of a function.
///
/// Returns true if any errors were emitted.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
SourceLocation Loc);
/// Returns whether the given function's address can be taken or not,
/// optionally emitting a diagnostic if the address can't be taken.
///
/// Returns false if taking the address of the function is illegal.
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
bool Complain = false,
SourceLocation Loc = SourceLocation());
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
bool resolveAndFixAddressOfSingleOverloadCandidate(
ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
SourceRange OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
void AddOverloadedCallCandidates(
LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
SourceLocation RangeLoc,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true,
bool CalleesAddressIsTaken=false);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
NestedNameSpecifierLoc NNSLoc,
DeclarationNameInfo DNI,
const UnresolvedSetImpl &Fns,
bool PerformADL = true);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
UnaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *input, bool RequiresADL = true);
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
OverloadedOperatorKind Op,
const UnresolvedSetImpl &Fns,
ArrayRef<Expr *> Args, bool RequiresADL = true);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
BinaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
bool RequiresADL = true,
bool AllowRewrittenCandidates = true,
FunctionDecl *DefaultedFn = nullptr);
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
FunctionDecl *DefaultedFn);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
bool AllowRecovery = false);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up a name following ~ in a destructor name. This is an ordinary
/// lookup, but prefers tags to typedefs.
LookupDestructorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// Look up the name of an OpenMP user-defined reduction operation.
LookupOMPReductionName,
/// Look up the name of an OpenMP user-defined mapper.
LookupOMPMapperName,
/// Look up any declaration with any name.
LookupAnyName
};
/// Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists and is visible.
ForVisibleRedeclaration,
/// The lookup results will be used for redeclaration of a name
/// with external linkage; non-visible lookup results with external linkage
/// may also be found.
ForExternalRedeclaration
};
RedeclarationKind forRedeclarationInCurContext() {
// A declaration with an owning module for linkage can never link against
// anything that is not visible. We don't need to check linkage here; if
// the context has internal linkage, redeclaration lookup won't find things
// from other TUs, and we can't safely compute linkage yet in general.
if (cast<Decl>(CurContext)
->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
return ForVisibleRedeclaration;
return ForExternalRedeclaration;
}
/// The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// The lookup resulted in an error.
LOLR_Error,
/// The lookup found no match but no diagnostic was issued.
LOLR_ErrorNoDiagnostic,
/// The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplatePack,
};
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState &&other) noexcept;
TypoExprState &operator=(TypoExprState &&other) noexcept;
};
/// The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, SourceLocation TypoLoc);
// The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupBuiltin(LookupResult &R);
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
UnresolvedSetImpl &Functions);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
bool IsUDSuffix);
LiteralOperatorLookupResult
LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
bool AllowRaw, bool AllowTemplate,
bool AllowStringTemplate, bool DiagnoseMissing,
StringLiteral *StringLit = nullptr);
bool isKnownName(StringRef name);
/// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
enum class FunctionEmissionStatus {
Emitted,
CUDADiscarded, // Discarded due to CUDA/HIP hostness
OMPDiscarded, // Discarded due to OpenMP hostness
TemplateDiscarded, // Discarded due to uninstantiated templates
Unknown,
};
FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
bool Final = false);
// Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool LoadExternal = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool IncludeDependentBases = false,
bool LoadExternal = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param RecoverUncorrectedTypos If true, when typo correction fails, it
/// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult CorrectDelayedTyposInExpr(
Expr *E, VarDecl *InitDecl = nullptr,
bool RecoverUncorrectedTypos = false,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult CorrectDelayedTyposInExpr(
ExprResult ER, VarDecl *InitDecl = nullptr,
bool RecoverUncorrectedTypos = false,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid()
? ER
: CorrectDelayedTyposInExpr(ER.get(), InitDecl,
RecoverUncorrectedTypos, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
/// Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
ArrayRef<Expr *> SubExprs,
QualType T = QualType());
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
SourceLocation Loc);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
FunctionDecl *FD);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
// Helper for delayed processing of attributes.
void ProcessDeclAttributeDelayed(Decl *D,
const ParsedAttributesView &AttrList);
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const ParsedAttributesView &AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Handles semantic checking for features that are common to all attributes,
/// such as checking whether a parameter was properly specified, or the
/// correct number of arguments were passed, etc. Returns true if the
/// attribute has been diagnosed.
bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A);
bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckAttrTarget(const ParsedAttr &CurrAttr);
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
StringRef &Str,
SourceLocation *ArgLocation = nullptr);
llvm::Error isValidSectionSpecifier(StringRef Str);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceModel SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
SourceLocation Loc);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Process the attributes before creating an attributed statement. Returns
/// the semantic attributes that have been processed.
void ProcessStmtAttributes(Stmt *Stmt,
const ParsedAttributesWithRange &InAttrs,
SmallVectorImpl<const Attr *> &OutAttrs);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
ObjCInterfaceDecl *IDecl,
SourceLocation AtEnd);
void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
unsigned &Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
/// Returns default addr space for method qualifiers.
LangAS getDefaultCXXMethodAddrSpace() const;
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// - Returns instance or factory methods in global method pool for
/// given selector. It checks the desired kind first, if none is found, and
/// parameter checkTheOther is set, it then checks the other kind. If no such
/// method or only one method is found, function returns false; otherwise, it
/// returns true.
bool
CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool InstanceFirst, bool CheckTheOther,
const ObjCObjectType *TypeBound = nullptr);
bool
AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R, bool receiverIdOrClass,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
void
DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
/// Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg() : E(nullptr) { }
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(
ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
StmtResult ActOnExprStmtError();
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt(bool IsStmtExpr);
void ActOnAfterCompoundStatementLeadingPragmas();
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
S.ActOnStartOfCompoundStmt(IsStmtExpr);
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
SourceLocation DotDotDotLoc, ExprResult RHS,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList,
Stmt *SubStmt);
class ConditionResult;
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
SourceLocation LParenLoc, Stmt *InitStmt,
ConditionResult Cond, SourceLocation RParenLoc,
Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
SourceLocation LParenLoc, Stmt *InitStmt,
ConditionResult Cond, SourceLocation RParenLoc,
Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
SourceLocation LParenLoc, Stmt *InitStmt,
ConditionResult Cond,
SourceLocation RParenLoc);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
ConditionResult Cond, SourceLocation RParenLoc,
Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc, SourceLocation CondLParen,
Expr *Cond, SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First,
ConditionResult Second,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *Begin, Stmt *End,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params,
unsigned OpenMPCaptureLevel = 0);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
struct NamedReturnInfo {
const VarDecl *Candidate;
enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
Status S;
bool isMoveEligible() const { return S != None; };
bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
};
enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
NamedReturnInfo getNamedReturnInfo(
Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
QualType ReturnType);
ExprResult
PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const NamedReturnInfo &NRInfo, Expr *Value,
bool SupressSimplerImplicitMoves = false);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
NamedReturnInfo &NRInfo,
bool SupressSimplerImplicitMoves);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
unsigned NumLabels,
SourceLocation RParenLoc);
void FillInlineAsmIdentifierInfo(Expr *Res,
llvm::InlineAsmIdentifierInfo &Info);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// If VD is set but not otherwise used, diagnose, for a parameter or a
/// variable.
void DiagnoseUnusedButSetDecl(const VarDecl *VD);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
/// Warn if we're implicitly casting from a _Nullable pointer type to a
/// _Nonnull one.
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
SourceLocation Loc);
/// Warn when implicitly casting 0 to nullptr.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
ParsingClassDepth++;
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
ParsingClassDepth--;
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass,
bool ObjCPropertyAccess,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReceiver = nullptr);
bool makeUnavailableInSystemHeader(SourceLocation loc,
UnavailableAttr::ImplicitReason reason);
/// Issue any -Wunguarded-availability warnings in \c FD
void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
bool ObjCPropertyAccess = false,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReciever = nullptr);
void NoteDeletedFunction(FunctionDecl *FD);
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult CheckUnevaluatedOperand(Expr *E);
void CheckUnusedVolatileAssignment(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
//
// MightBeOdrUse indicates whether the use could possibly be an odr-use, and
// should usually be true. This only needs to be set to false if the lack of
// odr-use cannot be determined from the current context (for instance,
// because the name denotes a virtual function and was written without an
// explicit nested-name-specifier).
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool MightBeOdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
void MarkMemberReferenced(MemberExpr *E);
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
unsigned CapturingScopeIndex);
ExprResult CheckLValueToRValueConversionOperand(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
/// Mark all of the declarations referenced within a particular AST node as
/// referenced. Used when template instantiation instantiates a non-dependent
/// type -- entities referenced by the type are now referenced.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// Try to convert an expression \p E to type \p Ty. Returns the result of the
/// conversion.
ExprResult tryConvertExprToType(Expr *E, QualType Ty);
/// Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
/// Similar, but diagnostic is only produced if all the specified statements
/// are reachable.
bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
CorrectionCandidateCallback *CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool DiagnoseDependentMemberLookup(LookupResult &R);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
CorrectionCandidateCallback &CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
IdentifierInfo *II);
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
/// If \p D cannot be odr-used in the current expression evaluation context,
/// return a reason explaining why. Otherwise, return NOUR_None.
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
NestedNameSpecifierLoc NNS,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(
const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
UnresolvedLookupExpr *AsULE = nullptr);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance,
const Scope *S);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult
BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, const Scope *S,
TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentKind IK);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
SourceLocation LParen,
SourceLocation RParen,
TypeSourceInfo *TSI);
ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
SourceLocation LParen,
SourceLocation RParen,
ParsedType ParsedTy);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
bool isQualifiedMemberAccess(Expr *E);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
SourceRange ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
Expr *ColumnIdx,
SourceLocation RBLoc);
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
Expr *LowerBound,
SourceLocation ColonLocFirst,
SourceLocation ColonLocSecond,
Expr *Length, Expr *Stride,
SourceLocation RBLoc);
ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
SourceLocation RParenLoc,
ArrayRef<Expr *> Dims,
ArrayRef<SourceRange> Brackets);
/// Data structure for iterator expression.
struct OMPIteratorData {
IdentifierInfo *DeclIdent = nullptr;
SourceLocation DeclIdentLoc;
ParsedType Type;
OMPIteratorExpr::IteratorRange Range;
SourceLocation AssignLoc;
SourceLocation ColonLoc;
SourceLocation SecColonLoc;
};
ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
SourceLocation LLoc, SourceLocation RLoc,
ArrayRef<OMPIteratorData> Data);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
SourceLocation OpLoc,
const CXXScopeSpec &SS, FieldDecl *Field,
DeclAccessPair FoundDecl,
const DeclarationNameInfo &MemberNameInfo);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr);
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false,
bool AllowRecovery = false);
Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
MultiExprArg CallArgs);
enum class AtomicArgumentOrder { API, AST };
ExprResult
BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
SourceLocation RParenLoc, MultiExprArg Args,
AtomicExpr::AtomicOp Op,
AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
ExprResult
BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
Expr *Config = nullptr, bool IsExecConfig = false,
ADLCallKind UsesADL = ADLCallKind::NotADL);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult BuildInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation EqualOrColonLoc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
UnresolvedSetImpl &Functions);
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc);
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc, unsigned TemplateDepth);
// Handle the final expression in a statement expression.
ExprResult ActOnStmtExprResult(ExprResult E);
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
// __builtin_COLUMN()
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc,
SourceLocation RPLoc);
// Build a potentially resolved SourceLocExpr.
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc, SourceLocation RPLoc,
DeclContext *ParentContext);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// The symbol exists.
IER_Exists,
/// The symbol does not exist.
IER_DoesNotExist,
/// The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc, IdentifierInfo *Ident,
SourceLocation LBrace,
const ParsedAttributesView &AttrList,
UsingDirectiveDecl *&UsingDecl);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
NamespaceDecl *lookupStdExperimentalNamespace();
CXXRecordDecl *getStdBadAlloc() const;
EnumDecl *getStdAlignValT() const;
private:
// A cache representing if we've fully checked the various comparison category
// types stored in ASTContext. The bit-index corresponds to the integer value
// of a ComparisonCategoryType enumerator.
llvm::SmallBitVector FullyCheckedComparisonCategories;
ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
CXXScopeSpec &SS,
ParsedType TemplateTypeTy,
IdentifierInfo *MemberOrBase);
public:
enum class ComparisonCategoryUsage {
/// The '<=>' operator was used in an expression and a builtin operator
/// was selected.
OperatorInExpression,
/// A defaulted 'operator<=>' needed the comparison category. This
/// typically only applies to 'std::strong_ordering', due to the implicit
/// fallback return value.
DefaultedOperator,
};
/// Lookup the specified comparison category types in the standard
/// library, an check the VarDecls possibly returned by the operator<=>
/// builtins for that type.
///
/// \return The type of the comparison category type corresponding to the
/// specified Kind, or a null type if an error occurs
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
SourceLocation Loc,
ComparisonCategoryUsage Usage);
/// Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const FunctionDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
SourceLocation NamespcLoc, CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
const ParsedAttributesView &AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void FilterUsingLookup(Scope *S, LookupResult &lookup);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc,
const LookupResult *R = nullptr,
const UsingDecl *UD = nullptr);
NamedDecl *BuildUsingDeclaration(
Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList, bool IsInstantiation,
bool IsUsingIfExists);
NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation EnumLoc,
SourceLocation NameLoc, EnumDecl *ED);
NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
ArrayRef<NamedDecl *> Expansions);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
/// Given a derived-class using shadow declaration for a constructor and the
/// correspnding base class constructor, find or create the implicit
/// synthesized derived class constructor to use for this initialization.
CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
ConstructorUsingShadowDecl *DerivedShadow);
Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation TypenameLoc, CXXScopeSpec &SS,
UnqualifiedId &Name, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation EnumLoc, const DeclSpec &);
Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc, UnqualifiedId &Name,
const ParsedAttributesView &AttrList,
TypeResult Type, Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
/// Build a CXXConstructExpr whose constructor has already been resolved if
/// it denotes an inherited constructor.
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// Instantiate or parse a C++ default argument expression as necessary.
/// Return true on error.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
ParmVarDecl *Param);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E) { CalledStmt(E); }
/// Integrate an invoked statement into the collected data.
void CalledStmt(Stmt *S);
/// Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_NoexceptFalse;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
/// Check the given noexcept-specifier, convert its expression, and compute
/// the appropriate ExceptionSpecificationType.
ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
ExceptionSpecificationType &EST);
/// Check the given exception-specification and update the
/// exception specification information with the results.
void checkExceptionSpecification(bool IsTopLevel,
ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI);
/// Determine if we're in a case where we need to (incorrectly) eagerly
/// parse an exception specification to work around a libstdc++ bug.
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
/// Add an exception-specification to the given member function
/// (or member function template). The exception-specification was parsed
/// after the method itself was declared.
void actOnDelayedExceptionSpecification(Decl *Method,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr);
class InheritedConstructorInfo;
/// Determine if a special member function should have a deleted
/// definition when it is defaulted.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
InheritedConstructorInfo *ICI = nullptr,
bool Diagnose = false);
/// Produce notes explaining why a defaulted function was defined as deleted.
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
/// Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
/// Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// Check a completed declaration of an implicit special member.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
/// Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
/// Wrap the expression in a ConstantExpr if it is a potential immediate
/// invocation.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
QualType DeclInitType, MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr *> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
// Checks that the vector type should be initialized from a scalar
// by splatting the value rather than populating a single element.
// This is the case for AltiVecVector types as well as with
// AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
/// ActOnCXXNamedCast - Parse
/// {dynamic,static,reinterpret,const,addrspace}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
ExprResult Operand,
SourceLocation RParenLoc);
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
Expr *Operand, SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc,
Optional<unsigned> NumExpansions);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// Build a CXXThisExpr and mark it referenced in the current context.
Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
void MarkThisReferenced(CXXThisExpr *This);
/// Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr,
bool ByCopy = false);
/// Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
ExprResult
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
SourceLocation AtLoc, SourceLocation RParen);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenOrBraceLoc,
MultiExprArg Exprs,
SourceLocation RParenOrBraceLoc,
bool ListInitialization);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc,
bool ListInitialization);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Optional<Expr *> ArraySize,
SourceRange DirectInitRange,
Expr *Initializer);
/// Determine whether \p FD is an aligned allocation or deallocation
/// function that is unavailable.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
/// Produce diagnostics if \p FD is an aligned allocation or deallocation
/// function that is unavailable.
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
SourceLocation Loc);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
/// The scope in which to find allocation functions.
enum AllocationFunctionScope {
/// Only look for allocation functions in the global scope.
AFS_Global,
/// Only look for allocation functions in the scope of the
/// allocated class.
AFS_Class,
/// Look for allocation functions in both the global scope
/// and in the scope of the allocated class.
AFS_Both
};
/// Finds the overloads of operator new and delete that are appropriate
/// for the allocation.
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
AllocationFunctionScope NewScope,
AllocationFunctionScope DeleteScope,
QualType AllocType, bool IsArray,
bool &PassAlignment, MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
ArrayRef<QualType> Params);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
bool Overaligned,
DeclarationName Name);
FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
CXXRecordDecl *RD);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
bool IsDelete, bool CallCanBeVirtual,
bool WarnOnNonAbstractTypes,
SourceLocation DtorLoc);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the binary type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
MaterializeTemporaryExpr *
CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
bool BoundToLvalueReference);
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
return ActOnFinishFullExpr(
Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue, bool IsConstexpr = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
// Complete an enum decl, maybe without a scope spec.
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
CXXScopeSpec *SS = nullptr);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
/// Keeps information about an identifier in a nested-name-spec.
///
struct NestedNameSpecInfo {
/// The type of the object, if we're parsing nested-name-specifier in
/// a member access expression.
ParsedType ObjectType;
/// The identifier preceding the '::'.
IdentifierInfo *Identifier;
/// The location of the identifier.
SourceLocation IdentifierLoc;
/// The location of the '::'.
SourceLocation CCLoc;
/// Creates info object for the most typical case.
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
: ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
CCLoc(ColonColonLoc) {
}
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, QualType ObjectType)
: ObjectType(ParsedType::make(ObjectType)), Identifier(II),
IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
}
};
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo);
bool BuildCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
/// The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param IdInfo Parser information about an identifier in the
/// nested-name-spec.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \param OnlyNamespace If true, only considers namespaces in lookup.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo,
bool EnteringContext);
/// The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params,
ConstexprSpecKind ConstexprKind,
Expr *TrailingRequiresClause);
/// Number lambda for linkage purposes if necessary.
void handleLambdaNumbering(
CXXRecordDecl *Class, CXXMethodDecl *Method,
Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
/// Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
ParsedType actOnLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
return ParsedType::make(buildLambdaInitCaptureInitialization(
Loc, ByRef, EllipsisLoc, None, Id,
InitKind != LambdaCaptureInitKind::CopyInit, Init));
}
QualType buildLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
Expr *&Init);
/// Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType,
SourceLocation EllipsisLoc,
IdentifierInfo *Id,
unsigned InitStyle, Expr *Init);
/// Add an init-capture to a lambda scope.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief This is called after parsing the explicit template parameter list
/// on a lambda (if it exists) in C++2a.
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> TParams,
SourceLocation RAngleLoc,
ExprResult RequiresClause);
/// Introduce the lambda parameters into scope.
void addLambdaParameters(
ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
CXXMethodDecl *CallOperator, Scope *CurScope);
/// Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// Does copying/destroying the captured variable have side effects?
bool CaptureHasSideEffects(const sema::Capture &From);
/// Diagnose if an explicit lambda capture is unused. Returns true if a
/// diagnostic is emitted.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
const sema::Capture &From);
/// Build a FieldDecl suitable to hold the given capture.
FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
/// Initialize the given capture with a suitable expression.
ExprResult BuildCaptureInit(const sema::Capture &Capture,
SourceLocation ImplicitCaptureLoc,
bool IsOpenMPMapping = false);
/// Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// Get the return type to use for a lambda's conversion function(s) to
/// function pointer type, given the type of the call operator.
QualType
getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
CallingConv CC);
/// Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
/// Check whether the given expression is a valid constraint expression.
/// A diagnostic is emitted if it is not, false is returned, and
/// PossibleNonPrimary will be set to true if the failure might be due to a
/// non-primary expression being used as an atomic constraint.
bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
bool *PossibleNonPrimary = nullptr,
bool IsTrailingRequiresClause = false);
private:
/// Caches pairs of template-like decls whose associated constraints were
/// checked for subsumption and whether or not the first's constraints did in
/// fact subsume the second's.
llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
/// Caches the normalized associated constraints of declarations (concepts or
/// constrained declarations). If an error occurred while normalizing the
/// associated constraints of the template or concept, nullptr will be cached
/// here.
llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
NormalizationCache;
llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
SatisfactionCache;
public:
const NormalizedConstraint *
getNormalizedAssociatedConstraints(
NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
/// \brief Check whether the given declaration's associated constraints are
/// at least as constrained than another declaration's according to the
/// partial ordering of constraints.
///
/// \param Result If no error occurred, receives the result of true if D1 is
/// at least constrained than D2, and false otherwise.
///
/// \returns true if an error occurred, false otherwise.
bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
NamedDecl *D2, ArrayRef<const Expr *> AC2,
bool &Result);
/// If D1 was not at least as constrained as D2, but would've been if a pair
/// of atomic constraints involved had been declared in a concept and not
/// repeated in two separate places in code.
/// \returns true if such a diagnostic was emitted, false otherwise.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
/// \brief Check whether the given list of constraint expressions are
/// satisfied (as if in a 'conjunction') given template arguments.
/// \param Template the template-like entity that triggered the constraints
/// check (either a concept or a constrained entity).
/// \param ConstraintExprs a list of constraint expressions, treated as if
/// they were 'AND'ed together.
/// \param TemplateArgs the list of template arguments to substitute into the
/// constraint expression.
/// \param TemplateIDRange The source range of the template id that
/// caused the constraints check.
/// \param Satisfaction if true is returned, will contain details of the
/// satisfaction, with enough information to diagnose an unsatisfied
/// expression.
/// \returns true if an error occurred and satisfaction could not be checked,
/// false otherwise.
bool CheckConstraintSatisfaction(
const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
/// \brief Check whether the given non-dependent constraint expression is
/// satisfied. Returns false and updates Satisfaction with the satisfaction
/// verdict if successful, emits a diagnostic and returns true if an error
/// occured and satisfaction could not be determined.
///
/// \returns true if an error occurred, false otherwise.
bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
ConstraintSatisfaction &Satisfaction);
/// Check whether the given function decl's trailing requires clause is
/// satisfied, if any. Returns false and updates Satisfaction with the
/// satisfaction verdict if successful, emits a diagnostic and returns true if
/// an error occured and satisfaction could not be determined.
///
/// \returns true if an error occurred, false otherwise.
bool CheckFunctionConstraints(const FunctionDecl *FD,
ConstraintSatisfaction &Satisfaction,
SourceLocation UsageLoc = SourceLocation());
/// \brief Ensure that the given template arguments satisfy the constraints
/// associated with the given template, emitting a diagnostic if they do not.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateArgs The converted, canonicalized template arguments.
///
/// \param TemplateIDRange The source range of the template id that
/// caused the constraints check.
///
/// \returns true if the constrains are not satisfied or could not be checked
/// for satisfaction, false if the constraints are satisfied.
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied.
/// \param First whether this is the first time an unsatisfied constraint is
/// diagnosed for this error.
void
DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
bool First = true);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied.
void
DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
bool First = true);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
MutableArrayRef<ObjCDictionaryElement> Elements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
SourceLocation ColonLoc,
const ParsedAttributesView &Attrs);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// Mark destructors of virtual bases of this class referenced. In the Itanium
/// C++ ABI, this is done when emitting a destructor for any non-abstract
/// class. In the Microsoft C++ ABI, this is done any time a class's
/// destructor is referenced.
void MarkVirtualBaseDestructorsReferenced(
SourceLocation Location, CXXRecordDecl *ClassDecl,
llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
/// Do semantic checks to allow the complete destructor variant to be emitted
/// when the destructor is defined in another translation unit. In the Itanium
/// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
/// can be emitted in separate TUs. To emit the complete variant, run a subset
/// of the checks performed when emitting a regular destructor.
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
CXXDestructorDecl *Dtor);
/// The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
bool ConstexprOnly = false);
/// Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
/// Check class-level dllimport/dllexport attribute. The caller must
/// ensure that referenceDLLExportedClassMethods is called some point later
/// when all outer classes of Class are complete.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
void referenceDLLExportedClassMethods();
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
/// Add gsl::Pointer attribute to std::container::iterator
/// \param ND The declaration that introduces the name
/// std::container::iterator. \param UnderlyingRecord The record named by ND.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
/// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
/// Add [[gsl::Pointer]] attributes for std:: types.
void inferGslPointerAttribute(TypedefNameDecl *TD);
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
/// Check that the C++ class annoated with "trivial_abi" satisfies all the
/// conditions that are needed for the attribute to have an effect.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
Decl *TagDecl, SourceLocation LBrac,
SourceLocation RBrac,
const ParsedAttributesView &AttrList);
void ActOnFinishCXXMemberDecls();
void ActOnFinishCXXNonNestedClass();
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Decl *Template,
llvm::function_ref<Scope *()> EnterScope);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
StorageClass &SC);
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
CXXSpecialMember CSM);
void CheckDelayedMemberExceptionSpecs();
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
DefaultedComparisonKind DCK);
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
FunctionDecl *Spaceship);
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
DefaultedComparisonKind DCK);
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class,
MutableArrayRef<CXXBaseSpecifier *> Bases);
void ActOnBaseSpecifiers(Decl *ClassDecl,
MutableArrayRef<CXXBaseSpecifier *> Bases);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbiguousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath,
bool IgnoreAccess = false);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult
CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *DecomposedClass,
DeclAccessPair Field);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
QualType BaseType);
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
DeclAccessPair Found, QualType ObjectType,
SourceLocation Loc,
const PartialDiagnostic &Diag);
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
DeclAccessPair Found,
QualType ObjectType) {
return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
SourceLocation(), PDiag());
}
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool isAbstractType(SourceLocation Loc, QualType T);
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true,
bool AllowNonTemplateFunctions = false);
/// Try to interpret the lookup result D as a template-name.
///
/// \param D A declaration found by name lookup.
/// \param AllowFunctionTemplates Whether function templates should be
/// considered valid results.
/// \param AllowDependent Whether unresolved using declarations (that might
/// name templates) should be considered valid results.
static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
/// Whether and why a template name is required in this lookup.
class RequiredTemplateKind {
public:
/// Template name is required if TemplateKWLoc is valid.
RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
: TemplateKW(TemplateKWLoc) {}
/// Template name is unconditionally required.
RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {}
SourceLocation getTemplateKeywordLoc() const {
return TemplateKW.getValueOr(SourceLocation());
}
bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
bool isRequired() const { return TemplateKW != SourceLocation(); }
explicit operator bool() const { return isRequired(); }
private:
llvm::Optional<SourceLocation> TemplateKW;
};
enum class AssumedTemplateKind {
/// This is not assumed to be a template name.
None,
/// This is assumed to be a template name because lookup found nothing.
FoundNothing,
/// This is assumed to be a template name because lookup found one or more
/// functions (but no function templates).
FoundFunctions,
};
bool LookupTemplateName(
LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
bool EnteringContext, bool &MemberOfUnknownSpecialization,
RequiredTemplateKind RequiredTemplate = SourceLocation(),
AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
const UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization,
bool Disambiguation = false);
/// Try to resolve an undeclared template name as a type template.
///
/// Sets II to the identifier corresponding to the template name, and updates
/// Name to a corresponding (typo-corrected) type template name and TNK to
/// the corresponding kind, if possible.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
TemplateNameKind &TNK,
SourceLocation NameLoc,
IdentifierInfo *&II);
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
SourceLocation NameLoc,
bool Diagnose = true);
/// Determine whether a particular identifier might be the name in a C++1z
/// deduction-guide declaration.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
SourceLocation NameLoc,
ParsedTemplateTy *Template = nullptr);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
NamedDecl *Instantiation,
bool InstantiatedFromMember,
const NamedDecl *Pattern,
const NamedDecl *PatternDef,
TemplateSpecializationKind TSK,
bool Complain = true);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg, bool HasTypeConstraint);
bool ActOnTypeConstraint(const CXXScopeSpec &SS,
TemplateIdAnnotation *TypeConstraint,
TemplateTypeParmDecl *ConstrainedParameter,
SourceLocation EllipsisLoc);
bool BuildTypeConstraint(const CXXScopeSpec &SS,
TemplateIdAnnotation *TypeConstraint,
TemplateTypeParmDecl *ConstrainedParameter,
SourceLocation EllipsisLoc,
bool AllowUnexpandedPack);
bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
DeclarationNameInfo NameInfo,
ConceptDecl *NamedConcept,
const TemplateArgumentListInfo *TemplateArgs,
TemplateTypeParmDecl *ConstrainedParameter,
SourceLocation EllipsisLoc);
bool AttachTypeConstraint(AutoTypeLoc TL,
NonTypeTemplateParmDecl *ConstrainedParameter,
SourceLocation EllipsisLoc);
bool RequireStructuralType(QualType T, SourceLocation Loc);
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
SourceLocation Loc);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> Params,
SourceLocation RAngleLoc,
Expr *RequiresClause);
/// The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC,
SkipBodyInfo *SkipBody = nullptr);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
bool SuppressDiagnostic = false);
DeclResult CheckClassTemplate(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
QualType NTTPType,
SourceLocation Loc);
/// Get a template argument mapping the given template parameter to itself,
/// e.g. for X in \c template<int X>, this would return an expression template
/// argument referencing X.
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
SourceLocation Location);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false, bool IsClassName = false);
/// Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
/// Get the specialization of the given variable template corresponding to
/// the specified argument list, or a null-but-valid result if the arguments
/// are dependent.
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
/// Form a reference to the specialization of the given variable template
/// corresponding to the specified argument list, or a null-but-valid result
/// if the arguments are dependent.
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult
CheckConceptTemplateId(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &ConceptNameInfo,
NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
const TemplateArgumentListInfo *TemplateArgs);
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnTemplateName(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
TemplateTy &Template, bool AllowInjectedClassName = false);
DeclResult ActOnClassTemplateSpecialization(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
TemplateDecl *PrimaryTemplate,
unsigned NumExplicitArgs,
ArrayRef<TemplateArgument> Args);
void CheckTemplatePartialSpecialization(
ClassTemplatePartialSpecializationDecl *Partial);
void CheckTemplatePartialSpecialization(
VarTemplatePartialSpecializationDecl *Partial);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(
FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous, bool QualifiedFriend = false);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult ActOnExplicitInstantiation(
Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
TemplateTy Template, SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
/// contain the converted forms of the template arguments as written.
/// Otherwise, \p TemplateArgs will not be modified.
///
/// \param ConstraintsNotSatisfied If provided, and an error occured, will
/// receive true if the cause for the error is the associated constraints of
/// the template not being satisfied by the template arguments.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted,
bool UpdateArgsWithConversions = true,
bool *ConstraintsNotSatisfied = nullptr);
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
TemplateParameterList *Params,
TemplateArgumentLoc &Arg);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateII The identifier used to name the template.
/// \param TemplateIILoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc,
TypeSourceInfo **TSI,
bool DeducedTSTContext);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc,
bool DeducedTSTContext = true);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
//===--------------------------------------------------------------------===//
// C++ Concepts
//===--------------------------------------------------------------------===//
Decl *ActOnConceptDefinition(
Scope *S, MultiTemplateParamsArg TemplateParameterLists,
IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
RequiresExprBodyDecl *
ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
ArrayRef<ParmVarDecl *> LocalParameters,
Scope *BodyScope);
void ActOnFinishRequiresExpr();
concepts::Requirement *ActOnSimpleRequirement(Expr *E);
concepts::Requirement *ActOnTypeRequirement(
SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
concepts::Requirement *ActOnCompoundRequirement(Expr *E,
SourceLocation NoexceptLoc);
concepts::Requirement *
ActOnCompoundRequirement(
Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
TemplateIdAnnotation *TypeConstraint, unsigned Depth);
concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
concepts::ExprRequirement *
BuildExprRequirement(
Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
concepts::ExprRequirement *
BuildExprRequirement(
concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
bool IsSatisfied, SourceLocation NoexceptLoc,
concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
concepts::TypeRequirement *
BuildTypeRequirement(
concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
concepts::NestedRequirement *
BuildNestedRequirement(
concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
RequiresExprBodyDecl *Body,
ArrayRef<ParmVarDecl *> LocalParameters,
ArrayRef<concepts::Requirement *> Requirements,
SourceLocation ClosingBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// An arbitrary expression.
UPPC_Expression = 0,
/// The base type of a class type.
UPPC_BaseType,
/// The type of an arbitrary declaration.
UPPC_DeclarationType,
/// The type of a data member.
UPPC_DataMemberType,
/// The size of a bit-field.
UPPC_BitFieldWidth,
/// The expression in a static assertion.
UPPC_StaticAssertExpression,
/// The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// The enumerator value.
UPPC_EnumeratorValue,
/// A using declaration.
UPPC_UsingDeclaration,
/// A friend declaration.
UPPC_FriendDeclaration,
/// A declaration qualifier.
UPPC_DeclarationQualifier,
/// An initializer.
UPPC_Initializer,
/// A default argument.
UPPC_DefaultArgument,
/// The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// The type of an exception.
UPPC_ExceptionType,
/// Partial specialization.
UPPC_PartialSpecialization,
/// Microsoft __if_exists.
UPPC_IfExists,
/// Microsoft __if_not_exists.
UPPC_IfNotExists,
/// Lambda expression.
UPPC_Lambda,
/// Block expression.
UPPC_Block,
/// A type constraint.
UPPC_TypeConstraint,
// A requirement in a requires-expression.
UPPC_Requirement,
// A requires-clause.
UPPC_RequiresClause,
};
/// Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// If the given requirees-expression contains an unexpanded reference to one
/// of its own parameter packs, diagnose the error.
///
/// \param RE The requiress-expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
/// If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param NNS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
/// Given a template argument that contains an unexpanded parameter pack, but
/// which has already been substituted, attempt to determine the number of
/// elements that will be produced once this argument is fully-expanded.
///
/// This is intended for use when transforming 'sizeof...(Arg)' in order to
/// avoid actually expanding the pack where possible.
Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
/// Adjust the type \p ArgFunctionType to match the calling convention,
/// noreturn, and optionally the exception specification of \p FunctionType.
/// Deduction often wants to ignore these properties when matching function
/// types.
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
bool AdjustExceptionSpec = false);
/// Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// Template argument deduction was successful.
TDK_Success = 0,
/// The declaration was invalid; do nothing.
TDK_Invalid,
/// Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// Template argument deduction did not deduce a value for every
/// expansion of an expanded template parameter pack.
TDK_IncompletePack,
/// Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// After substituting deduced template arguments, a dependent
/// parameter type did not match the corresponding argument.
TDK_DeducedMismatch,
/// After substituting deduced template arguments, an element of
/// a dependent parameter type did not match the corresponding element
/// of the corresponding argument (when deducing from an initializer list).
TDK_DeducedMismatchNested,
/// A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// Checking non-dependent argument conversions failed.
TDK_NonDependentConversionFailure,
/// The deduced arguments did not satisfy the constraints associated
/// with the template.
TDK_ConstraintsNotSatisfied,
/// Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure,
/// CUDA Target attributes do not match.
TDK_CUDATargetMismatch
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
unsigned ArgIdx, QualType OriginalArgType)
: OriginalParamType(OriginalParamType),
DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) {}
QualType OriginalParamType;
bool DecomposedParam;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult FinishTemplateArgumentDeduction(
FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false,
llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
TemplateDeductionResult DeduceTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
bool PartialOverloading,
llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
/// Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// Completely replace the \c auto in \p TypeWithAuto by
/// \p Replacement. This does not retain any \c auto type sugar.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult
DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None,
bool IgnoreConstraints = false);
DeduceAutoResult
DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None,
bool IgnoreConstraints = false);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
/// Declare implicit deduction guides for a class template if we've
/// not already done so.
void DeclareImplicitDeductionGuides(TemplateDecl *Template,
SourceLocation Loc);
QualType DeduceTemplateSpecializationFromInitializer(
TypeSourceInfo *TInfo, const InitializedEntity &Entity,
const InitializationKind &Kind, MultiExprArg Init);
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
QualType Type, TypeSourceInfo *TSI,
SourceRange Range, bool DirectInit,
Expr *Init);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(
FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
unsigned NumCallArguments2, bool Reversed = false);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
unsigned Depth, llvm::SmallBitVector &Used);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
struct CodeSynthesisContext {
/// The kind of template instantiation we are performing
enum SynthesisKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template parameter whose argument is
/// being instantiated, the Template is the template, and the
/// TemplateArgs/NumTemplateArguments provide the template arguments as
/// specified.
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
/// a TemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are computing the exception specification for a defaulted special
/// member function.
ExceptionSpecEvaluation,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation,
/// We are instantiating a requirement of a requires expression.
RequirementInstantiation,
/// We are checking the satisfaction of a nested requirement of a requires
/// expression.
NestedRequirementConstraintsCheck,
/// We are declaring an implicit special member function.
DeclaringSpecialMember,
/// We are declaring an implicit 'operator==' for a defaulted
/// 'operator<=>'.
DeclaringImplicitEqualityComparison,
/// We are defining a synthesized function (such as a defaulted special
/// member).
DefiningSynthesizedFunction,
// We are checking the constraints associated with a constrained entity or
// the constraint expression of a concept. This includes the checks that
// atomic constraints have the type 'bool' and that they can be constant
// evaluated.
ConstraintsCheck,
// We are substituting template arguments into a constraint expression.
ConstraintSubstitution,
// We are normalizing a constraint expression.
ConstraintNormalization,
// We are substituting into the parameter mapping of an atomic constraint
// during normalization.
ParameterMappingSubstitution,
/// We are rewriting a comparison operator in terms of an operator<=>.
RewritingOperatorAsSpaceship,
/// We are initializing a structured binding.
InitializingStructuredBinding,
/// We are marking a class as __dllexport.
MarkingClassDllexported,
/// Added for Template instantiation observation.
/// Memoization means we are _not_ instantiating a template because
/// it is already instantiated (but we entered a context where we
/// would have had to if it was not already instantiated).
Memoization
} Kind;
/// Was the enclosing context a non-instantiation SFINAE context?
bool SavedInNonInstantiationSFINAEContext;
/// The point of instantiation or synthesis within the source code.
SourceLocation PointOfInstantiation;
/// The entity that is being synthesized.
Decl *Entity;
/// The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
// FIXME: Wrap this union around more members, or perhaps store the
// kind-specific members in the RAII object owning the context.
union {
/// The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// The special member being declared or defined.
CXXSpecialMember SpecialMember;
};
ArrayRef<TemplateArgument> template_arguments() const {
assert(Kind != DeclaringSpecialMember);
return {TemplateArgs, NumTemplateArgs};
}
/// The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
CodeSynthesisContext()
: Kind(TemplateInstantiation),
SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
DeductionInfo(nullptr) {}
/// Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
};
/// List of active code synthesis contexts.
///
/// This vector is treated as a stack. As synthesis of one entity requires
/// synthesis of another, additional contexts are pushed onto the stack.
SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
/// Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
/// Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm::DenseSet<Module*> LookupModulesCache;
/// Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm::DenseSet<Module*> &getLookupModules();
/// Map from the most recent declaration of a namespace to the most
/// recent visible declaration of that namespace.
llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
/// Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// The number of \p CodeSynthesisContexts that are not template
/// instantiations and, therefore, should not be counted as part of the
/// instantiation depth.
///
/// When the instantiation depth reaches the user-configurable limit
/// \p LangOptions::InstantiationDepth we will abort instantiation.
// FIXME: Should we have a similar limit for other forms of synthesis?
unsigned NonInstantiationEntries;
/// The depth of the context stack at the point when the most recent
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant context stacks
/// when there are multiple errors or warnings in the same instantiation.
// FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
unsigned LastEmittedCodeSynthesisContextDepth = 0;
/// The template instantiation callbacks to trace or track
/// instantiations (objects can be chained).
///
/// This callbacks is used to print, trace or track template
/// instantiations as they are being constructed.
std::vector<std::unique_ptr<TemplateInstantiationCallback>>
TemplateInstCallbacks;
/// The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// Note that we are instantiating a class template,
/// function template, variable template, alias template,
/// or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateParameter Param, TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting either explicitly-specified or
/// deduced template arguments during function template argument deduction.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
CodeSynthesisContext::SynthesisKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template declaration.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument for a function
/// parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
struct ConstraintsCheck {};
/// \brief Note that we are checking the constraints associated with some
/// constrained entity (a concept declaration or a template with associated
/// constraints).
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintsCheck, NamedDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
struct ConstraintSubstitution {};
/// \brief Note that we are checking a constraint expression associated
/// with a template declaration or as part of the satisfaction check of a
/// concept.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintSubstitution, NamedDecl *Template,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange);
struct ConstraintNormalization {};
/// \brief Note that we are normalizing a constraint expression.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintNormalization, NamedDecl *Template,
SourceRange InstantiationRange);
struct ParameterMappingSubstitution {};
/// \brief Note that we are subtituting into the parameter mapping of an
/// atomic constraint during constraint normalization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParameterMappingSubstitution, NamedDecl *Template,
SourceRange InstantiationRange);
/// \brief Note that we are substituting template arguments into a part of
/// a requirement of a requires expression.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
concepts::Requirement *Req,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are checking the satisfaction of the constraint
/// expression inside of a nested requirement.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
concepts::NestedRequirement *Req, ConstraintsCheck,
SourceRange InstantiationRange = SourceRange());
/// Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
/// Determine whether we are already instantiating this
/// specialization in some surrounding active instantiation.
bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
private:
Sema &SemaRef;
bool Invalid;
bool AlreadyInstantiating;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = None,
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
void popCodeSynthesisContext();
/// Determine whether we are currently performing template instantiation.
bool inTemplateInstantiation() const {
return CodeSynthesisContexts.size() > NonInstantiationEntries;
}
void PrintContextStack() {
if (!CodeSynthesisContexts.empty() &&
CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
PrintInstantiationStack();
LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
}
if (PragmaAttributeCurrentTargetDecl)
PrintPragmaAttributeInstantiationPoint();
}
void PrintInstantiationStack();
void PrintPragmaAttributeInstantiationPoint();
/// Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
bool PrevLastDiagnosticIgnored;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
PrevLastDiagnosticIgnored(
SemaRef.getDiagnostics().isLastDiagnosticIgnored())
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
SemaRef.getDiagnostics().setLastDiagnosticIgnored(
PrevLastDiagnosticIgnored);
}
/// Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
/// Queue of implicit template instantiations that cannot be performed
/// eagerly.
SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
class GlobalEagerInstantiationScope {
public:
GlobalEagerInstantiationScope(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
void perform() {
if (Enabled) {
S.DefineUsedVTables();
S.PerformPendingInstantiations();
}
}
~GlobalEagerInstantiationScope() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
} else {
// Template instantiations in the PCH may be delayed until the TU.
S.PendingInstantiations.swap(SavedPendingInstantiations);
S.PendingInstantiations.insert(S.PendingInstantiations.end(),
SavedPendingInstantiations.begin(),
SavedPendingInstantiations.end());
}
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class LocalEagerInstantiationScope {
public:
LocalEagerInstantiationScope(Sema &S) : S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
~LocalEagerInstantiationScope() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
/// A helper class for building up ExtParameterInfos.
class ExtParameterInfoBuilder {
SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
bool HasInteresting = false;
public:
/// Set the ExtParameterInfo for the parameter at the given index,
///
void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
assert(Infos.size() <= index);
Infos.resize(index);
Infos.push_back(info);
if (!HasInteresting)
HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
}
/// Return a pointer (suitable for setting in an ExtProtoInfo) to the
/// ExtParameterInfo array we've built up.
const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams) {
if (!HasInteresting) return nullptr;
Infos.resize(numParams);
return Infos.data();
}
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity,
bool AllowDeducedTST = false);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
Qualifiers ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
bool SubstExceptionSpec(SourceLocation Loc,
FunctionProtoType::ExceptionSpecInfo &ESI,
SmallVectorImpl<QualType> &ExceptionStorage,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams,
ExtParameterInfoBuilder &ParamInfos);
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateParameterList *
SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateArgumentListInfo &Outputs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the name and return type of a defaulted 'operator<=>' to form
/// an implicit 'operator=='.
FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
FunctionDecl *Spaceship);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
void
InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
bool usesPartialOrExplicitSpecialization(
SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
ParmVarDecl *Param);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
bool CheckInstantiatedFunctionTemplateConstraints(
SourceLocation PointOfInstantiation, FunctionDecl *Decl,
ArrayRef<TemplateArgument> TemplateArgs,
ConstraintSatisfaction &Satisfaction);
FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
const TemplateArgumentList *Args,
SourceLocation Loc);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false,
VarTemplateSpecializationDecl *PrevVTSD = nullptr);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool FindingInstantiatedContext = false);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(
Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName, SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
SmallVectorImpl<SourceLocation> &ProtocolLocs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryInterface(
SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc,
const ParsedAttributesView &AttrList);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
ArrayRef<IdentifierLocPair> IdentList,
const ParsedAttributesView &attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
ArrayRef<IdentifierLocPair> ProtocolId,
SmallVectorImpl<Decl *> &Protocols);
void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
SourceLocation ProtocolLoc,
IdentifierInfo *TypeArgId,
SourceLocation TypeArgLoc,
bool SelectProtocolFirst = false);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C type parameter type.
QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
void ProcessPropertyDecl(ObjCPropertyDecl *property);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc,
ObjCPropertyQueryKind QueryKind);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
ParsedAttributesView ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
unsigned CNumArgs, // c-style args
const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
void deduceOpenCLAddressSpace(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// The message is sent to 'super'.
ObjCSuperMessage,
/// The message is an instance message.
ObjCInstanceMessage,
/// The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs, bool Diagnose = true);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr, bool Diagnose = true);
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
bool Diagnose = true);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
ObjCMethodDecl *overridden);
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaClangSection - Called on well formed \#pragma clang section
void ActOnPragmaClangSection(SourceLocation PragmaLoc,
PragmaClangSectionAction Action,
PragmaClangSectionKind SecKind, StringRef SecName);
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
StringRef SlotLabel, Expr *Alignment);
enum class PragmaAlignPackDiagnoseKind {
NonDefaultStateAtInclude,
ChangedStateAtExit
};
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
SourceLocation IncludeLoc);
void DiagnoseUnterminatedPragmaAlignPack();
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
SourceLocation PragmaLoc,
MSVtorDispMode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName, int SectionFlags,
NamedDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName);
/// Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// Called on #pragma clang __debug dump II
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
StringRef Value);
/// Are precise floating point semantics currently enabled?
bool isPreciseFPEnabled() {
return !CurFPFeatures.getAllowFPReassociate() &&
!CurFPFeatures.getNoSignedZero() &&
!CurFPFeatures.getAllowReciprocal() &&
!CurFPFeatures.getAllowApproxFunc();
}
/// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
PragmaFloatControlKind Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT and
/// \#pragma clang fp contract
void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
/// Called on well formed
/// \#pragma clang fp reassociate
void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
/// ActOnPragmaFenvAccess - Called on well formed
/// \#pragma STDC FENV_ACCESS
void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
/// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
void ActOnPragmaFPExceptions(SourceLocation Loc,
LangOptions::FPExceptionModeKind);
/// Called to set constant rounding mode for floating point operations.
void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
/// Called to set exception behavior for floating point operations.
void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
SourceLocation PragmaLoc,
attr::ParsedSubjectMatchRuleSet Rules);
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Called on well-formed '\#pragma clang attribute pop'.
void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Adds the attributes that have been specified using the
/// '\#pragma clang attribute push' directives to the given declaration.
void AddPragmaAttributes(Scope *S, Decl *D);
void DiagnoseUnterminatedPragmaAttribute();
/// Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
bool IsPackExpansion);
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
Expr *OE);
/// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
/// declaration.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *ParamExpr);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
/// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Annot, MutableArrayRef<Expr *> Args);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *MaxThreads, Expr *MinBlocks);
/// AddModeAttr - Adds a mode attribute to a particular declaration.
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
bool InInstantiation = false);
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
ParameterABI ABI);
enum class RetainOwnershipKind {NS, CF, OS};
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
RetainOwnershipKind K, bool IsTemplateInstantiation);
/// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
/// attribute to a particular declaration.
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
/// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
/// particular declaration.
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
//===--------------------------------------------------------------------===//
// C++ Coroutines TS
//
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
StringRef Keyword);
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
UnresolvedLookupExpr* Lookup);
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
bool buildCoroutineParameterMoves(SourceLocation Loc);
VarDecl *buildCoroutinePromise(SourceLocation Loc);
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
SourceLocation FuncLoc);
/// Check that the expression co_await promise.final_suspend() shall not be
/// potentially-throwing.
bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
//===--------------------------------------------------------------------===//
// OpenMP directives and clauses.
//
private:
void *VarDataSharingAttributesStack;
struct DeclareTargetContextInfo {
struct MapInfo {
OMPDeclareTargetDeclAttr::MapTypeTy MT;
SourceLocation Loc;
};
/// Explicitly listed variables and functions in a 'to' or 'link' clause.
llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
/// The 'device_type' as parsed from the clause.
OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
/// The directive kind, `begin declare target` or `declare target`.
OpenMPDirectiveKind Kind;
/// The directive location.
SourceLocation Loc;
DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
: Kind(Kind), Loc(Loc) {}
};
/// Number of nested '#pragma omp declare target' directives.
SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
/// Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult
VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
bool StrictlyPositive = true,
bool SuppressExprDiags = false);
/// Returns OpenMP nesting level for current directive.
unsigned getOpenMPNestingLevel() const;
/// Adjusts the function scopes index for the target-based regions.
void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
unsigned Level) const;
/// Returns the number of scopes associated with the construct on the given
/// OpenMP level.
int getNumberOfConstructScopes(unsigned Level) const;
/// Push new OpenMP function region for non-capturing function.
void pushOpenMPFunctionRegion();
/// Pop OpenMP function region for non-capturing function.
void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
/// Analyzes and checks a loop nest for use by a loop transformation.
///
/// \param Kind The loop transformation directive kind.
/// \param NumLoops How many nested loops the directive is expecting.
/// \param AStmt Associated statement of the transformation directive.
/// \param LoopHelpers [out] The loop analysis result.
/// \param Body [out] The body code nested in \p NumLoops loop.
/// \param OriginalInits [out] Collection of statements and declarations that
/// must have been executed/declared before entering the
/// loop.
///
/// \return Whether there was any error.
bool checkTransformableLoopNest(
OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
Stmt *&Body,
SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
&OriginalInits);
/// Helper to keep information about the current `omp begin/end declare
/// variant` nesting.
struct OMPDeclareVariantScope {
/// The associated OpenMP context selector.
OMPTraitInfo *TI;
/// The associated OpenMP context selector mangling.
std::string NameSuffix;
OMPDeclareVariantScope(OMPTraitInfo &TI);
};
/// Return the OMPTraitInfo for the surrounding scope, if any.
OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
return OMPDeclareVariantScopes.empty() ? nullptr
: OMPDeclareVariantScopes.back().TI;
}
/// The current `omp begin/end declare variant` scopes.
SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
/// The current `omp begin/end assumes` scopes.
SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
/// All `omp assumes` we encountered so far.
SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
public:
/// The declarator \p D defines a function in the scope \p S which is nested
/// in an `omp begin/end declare variant` scope. In this method we create a
/// declaration for \p D and rename \p D according to the OpenMP context
/// selector of the surrounding scope. Return all base functions in \p Bases.
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
SmallVectorImpl<FunctionDecl *> &Bases);
/// Register \p D as specialization of all base functions in \p Bases in the
/// current `omp begin/end declare variant` scope.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
/// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
/// Can we exit an OpenMP declare variant scope at the moment.
bool isInOpenMPDeclareVariantScope() const {
return !OMPDeclareVariantScopes.empty();
}
/// Given the potential call expression \p Call, determine if there is a
/// specialization via the OpenMP declare variant mechanism available. If
/// there is, return the specialized call expression, otherwise return the
/// original \p Call.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
SourceLocation LParenLoc, MultiExprArg ArgExprs,
SourceLocation RParenLoc, Expr *ExecConfig);
/// Handle a `omp begin declare variant`.
void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
/// Handle a `omp end declare variant`.
void ActOnOpenMPEndDeclareVariant();
/// Checks if the variant/multiversion functions are compatible.
bool areMultiversionVariantFunctionsCompatible(
const FunctionDecl *OldFD, const FunctionDecl *NewFD,
const PartialDiagnostic &NoProtoDiagID,
const PartialDiagnosticAt &NoteCausedDiagIDAt,
const PartialDiagnosticAt &NoSupportDiagIDAt,
const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
bool ConstexprSupported, bool CLinkageMayDiffer);
/// Function tries to capture lambda's captured variables in the OpenMP region
/// before the original lambda is captured.
void tryCaptureOpenMPLambdas(ValueDecl *V);
/// Return true if the provided declaration \a VD should be captured by
/// reference.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
/// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
unsigned OpenMPCaptureLevel) const;
/// Check if the specified variable is used in one of the private
/// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
/// constructs.
VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
unsigned StopAt = 0);
ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
ExprObjectKind OK, SourceLocation Loc);
/// If the current region is a loop-based region, mark the start of the loop
/// construct.
void startOpenMPLoop();
/// If the current region is a range loop-based region, mark the start of the
/// loop construct.
void startOpenMPCXXRangeFor();
/// Check if the specified variable is used in 'private' clause.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
unsigned CapLevel) const;
/// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
/// for \p FD based on DSA for the provided corresponding captured declaration
/// \p D.
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
/// Check if the specified variable is captured by 'target' directive.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
unsigned CaptureLevel) const;
/// Check if the specified global variable must be captured by outer capture
/// regions.
/// \param Level Relative level of nested OpenMP construct for that
/// the check is performed.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
unsigned CaptureLevel) const;
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// End analysis of clauses.
void EndOpenMPClause();
/// Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
OpenMPDirectiveKind Kind);
/// Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Called on well-formed '#pragma omp allocate'.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
ArrayRef<Expr *> VarList,
ArrayRef<OMPClause *> Clauses,
DeclContext *Owner = nullptr);
/// Called on well-formed '#pragma omp [begin] assume[s]'.
void ActOnOpenMPAssumesDirective(SourceLocation Loc,
OpenMPDirectiveKind DKind,
ArrayRef<StringRef> Assumptions,
bool SkippedClauses);
/// Check if there is an active global `omp begin assumes` directive.
bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
/// Check if there is an active global `omp assumes` directive.
bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
/// Called on well-formed '#pragma omp end assumes'.
void ActOnOpenMPEndAssumesDirective();
/// Called on well-formed '#pragma omp requires'.
DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
ArrayRef<OMPClause *> ClauseList);
/// Check restrictions on Requires directive
OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
ArrayRef<OMPClause *> Clauses);
/// Check if the specified type is allowed to be used in 'omp declare
/// reduction' construct.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name,
ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
/// Initialize declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
/// Initialize declare reduction construct initializer.
/// \return omp_priv variable.
VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
VarDecl *OmpPrivParm);
/// Called at the end of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
/// Check variable declaration in 'omp declare mapper' construct.
TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
/// Check if the specified type is allowed to be used in 'omp declare
/// mapper' construct.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare mapper'.
DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
Decl *PrevDeclInScope = nullptr);
/// Build the mapper variable of '#pragma omp declare mapper'.
ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
QualType MapperType,
SourceLocation StartLoc,
DeclarationName VN);
bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
const ValueDecl *getOpenMPDeclareMapperVarName() const;
/// Called on the start of target region i.e. '#pragma omp declare target'.
bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
/// Called at the end of target region i.e. '#pragma omp end declare target'.
const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
/// Called once a target context is completed, that can be when a
/// '#pragma omp end declare target' was encountered or when a
/// '#pragma omp declare target' without declaration-definition-seq was
/// encountered.
void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
/// Searches for the provided declaration name for OpenMP declare target
/// directive.
NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id);
/// Called on correct id-expression from the '#pragma omp declare target'.
void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
OMPDeclareTargetDeclAttr::MapTypeTy MT,
OMPDeclareTargetDeclAttr::DevTypeTy DT);
/// Check declaration inside target region.
void
checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
SourceLocation IdLoc = SourceLocation());
/// Finishes analysis of the deferred functions calls that may be declared as
/// host/nohost during device/host compilation.
void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
const FunctionDecl *Callee,
SourceLocation Loc);
/// Return true inside OpenMP declare target region.
bool isInOpenMPDeclareTargetContext() const {
return !DeclareTargetNesting.empty();
}
/// Return true inside OpenMP target region.
bool isInOpenMPTargetExecutionDirective() const;
/// Return the number of captured regions created for an OpenMP directive.
static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
/// Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
/// an OpenMP loop directive.
StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
/// End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
using VarsWithInheritedDSAType =
llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
/// Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '#pragma omp tile' after parsing of its clauses and
/// the associated statement.
StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '#pragma omp unroll' after parsing of its clauses
/// and the associated statement.
StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp depobj'.
StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp scan'.
StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target data' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target enter data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target exit data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target parallel' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp taskloop' after parsing of the
/// associated statement.
StmtResult
ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target update'.
StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp distribute parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target simd' after parsing of
/// the associated statement.
StmtResult
ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target teams distribute' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for
/// simd' after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp interop'.
StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp dispatch' after parsing of the
// /associated statement.
StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp masked' after parsing of the
// /associated statement.
StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Checks correctness of linear modifiers.
bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
SourceLocation LinLoc);
/// Checks that the specified declaration matches requirements for the linear
/// decls.
bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
OpenMPLinearClauseKind LinKind, QualType Type,
bool IsDeclareSimd = false);
/// Called on well-formed '\#pragma omp declare simd' after parsing of
/// the associated method/function.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
/// Checks '\#pragma omp declare variant' variant function and original
/// functions after parsing of the associated method/function.
/// \param DG Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \param TI The trait info object representing the match clause.
/// \returns None, if the function/variant function are not compatible with
/// the pragma, pair of original function/variant ref expression otherwise.
Optional<std::pair<FunctionDecl *, Expr *>>
checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
OMPTraitInfo &TI, SourceRange SR);
/// Called on well-formed '\#pragma omp declare variant' after parsing of
/// the associated method/function.
/// \param FD Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \param TI The context traits associated with the function variant.
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
OMPTraitInfo &TI, SourceRange SR);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'allocator' clause.
OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation NameModifierLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simdlen' clause.
OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-form 'sizes' clause.
OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-form 'full' clauses.
OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-form 'partial' clauses.
OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'ordered' clause.
OMPClause *
ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
SourceLocation LParenLoc = SourceLocation(),
Expr *NumForLoops = nullptr);
/// Called on well-formed 'grainsize' clause.
OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_tasks' clause.
OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'hint' clause.
OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'detach' clause.
OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'order' clause.
OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(
OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
SourceLocation StartLoc, SourceLocation LParenLoc,
ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
SourceLocation EndLoc);
/// Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(
OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'acq_rel' clause.
OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'acquire' clause.
OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'release' clause.
OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'relaxed' clause.
OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'init' clause.
OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
bool IsTarget, bool IsTargetSync,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation VarLoc,
SourceLocation EndLoc);
/// Called on well-formed 'use' clause.
OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation VarLoc, SourceLocation EndLoc);
/// Called on well-formed 'destroy' clause.
OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation VarLoc,
SourceLocation EndLoc);
/// Called on well-formed 'novariants' clause.
OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nocontext' clause.
OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'filter' clause.
OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'threads' clause.
OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simd' clause.
OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nogroup' clause.
OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reverse_offload' clause.
OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dynamic_allocators' clause.
OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'atomic_default_mem_order' clause.
OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
CXXScopeSpec &ReductionOrMapperIdScopeSpec,
DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
SourceLocation ExtraModifierLoc,
ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
ArrayRef<SourceLocation> MotionModifiersLoc);
/// Called on well-formed 'inclusive' clause.
OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'exclusive' clause.
OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'allocate' clause.
OMPClause *
ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation ColonLoc,
SourceLocation LParenLoc, SourceLocation EndLoc);
/// Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(
ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
SourceLocation LPKindLoc, SourceLocation ColonLoc,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
/// Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reduction' clause.
OMPClause *ActOnOpenMPReductionClause(
ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ModifierLoc, SourceLocation ColonLoc,
SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'task_reduction' clause.
OMPClause *ActOnOpenMPTaskReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'in_reduction' clause.
OMPClause *ActOnOpenMPInReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'linear' clause.
OMPClause *
ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
SourceLocation ColonLoc, SourceLocation EndLoc);
/// Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'depobj' pseudo clause.
OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
SourceLocation DepLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc);
/// Called on well-formed 'device' clause.
OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
Expr *Device, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ModifierLoc,
SourceLocation EndLoc);
/// Called on well-formed 'map' clause.
OMPClause *
ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc,
CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
SourceLocation MapLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'num_teams' clause.
OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'thread_limit' clause.
OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'priority' clause.
OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dist_schedule' clause.
OMPClause *ActOnOpenMPDistScheduleClause(
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
SourceLocation CommaLoc, SourceLocation EndLoc);
/// Called on well-formed 'defaultmap' clause.
OMPClause *ActOnOpenMPDefaultmapClause(
OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
SourceLocation KindLoc, SourceLocation EndLoc);
/// Called on well-formed 'to' clause.
OMPClause *
ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
ArrayRef<SourceLocation> MotionModifiersLoc,
CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'from' clause.
OMPClause *
ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
ArrayRef<SourceLocation> MotionModifiersLoc,
CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'use_device_ptr' clause.
OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'use_device_addr' clause.
OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'is_device_ptr' clause.
OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'nontemporal' clause.
OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Data for list of allocators.
struct UsesAllocatorsData {
/// Allocator.
Expr *Allocator = nullptr;
/// Allocator traits.
Expr *AllocatorTraits = nullptr;
/// Locations of '(' and ')' symbols.
SourceLocation LParenLoc, RParenLoc;
};
/// Called on well-formed 'uses_allocators' clause.
OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc,
ArrayRef<UsesAllocatorsData> Data);
/// Called on well-formed 'affinity' clause.
OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc, Expr *Modifier,
ArrayRef<Expr *> Locators);
/// The kind of conversion being performed.
enum CheckedConversionKind {
/// An implicit conversion.
CCK_ImplicitConversion,
/// A C-style cast.
CCK_CStyleCast,
/// A functional-style cast.
CCK_FunctionalCast,
/// A cast other than a C-style cast.
CCK_OtherCast,
/// A conversion for an operand of a builtin overloaded operator.
CCK_ForBuiltinOverloadedOp
};
static bool isCast(CheckedConversionKind CCK) {
return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
CCK == CCK_OtherCast;
}
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult
ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_PRValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK = CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
bool Diagnose = true);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This function is a no-op if the operand has a function type
// or an array type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
/// If \p E is a prvalue denoting an unmaterialized temporary, materialize
/// it as an xvalue. In C++98, the result will still be a prvalue, because
/// we don't have xvalues there.
ExprResult TemporaryMaterializationConversion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check whether the given statement can have musttail applied to it,
/// issuing a diagnostic and returning false if not. In the success case,
/// the statement is rewritten to remove implicit nodes from the return
/// value.
bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
private:
/// Check whether the given statement can have musttail applied to it,
/// issuing a diagnostic and returning false if not.
bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
public:
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
/// Context in which we're performing a usual arithmetic conversion.
enum ArithConvKind {
/// An arithmetic operation.
ACK_Arithmetic,
/// A bitwise operation.
ACK_BitwiseOp,
/// A comparison.
ACK_Comparison,
/// A conditional (?:) operator.
ACK_Conditional,
/// A compound assignment expression.
ACK_CompAssign,
};
// UsualArithmeticConversions - performs the UsualUnaryConversions on it's
// operands and then handles various conversions that are common to binary
// operators (C99 6.3.1.8). If both operands aren't arithmetic, this
// routine returns the first non-arithmetic type found. The client is
// responsible for emitting appropriate error diagnostics.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, ArithConvKind ACK);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatibleFunctionPointer - The assignment is between two function
/// pointers types that are not compatible, but we accept them as an
/// extension.
IncompatibleFunctionPointer,
/// IncompatiblePointerSign - The assignment is between two pointers types
/// which point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
/// changes address spaces in nested pointer types which is not allowed.
/// For instance, converting __private int ** to __generic int ** is
/// illegal even though __private could be converted to __generic.
IncompatibleNestedPointerAddressSpaceMismatch,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and optionally prepare for a conversion of
/// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
/// is true.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind,
bool ConvertRHS = true);
/// Check assignment constraints for an assignment of RHS to LHSType.
///
/// \param LHSType The destination type for the assignment.
/// \param RHS The source expression for the assignment.
/// \param Diagnose If \c true, diagnostics may be produced when checking
/// for assignability. If a diagnostic is produced, \p RHS will be
/// set to ExprError(). Note that this function may still return
/// without producing a diagnostic, even for an invalid assignment.
/// \param DiagnoseCFAudited If \c true, the target is a function parameter
/// in an audited Core Foundation API and does not need to be checked
/// for ARC retain issues.
/// \param ConvertRHS If \c true, \p RHS will be updated to model the
/// conversions necessary to perform the assignment. If \c false,
/// \p Diagnose must also be \c false.
AssignConvertType CheckSingleAssignmentConstraints(
QualType LHSType, ExprResult &RHS, bool Diagnose = true,
bool DiagnoseCFAudited = false, bool ConvertRHS = true);
// If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
ExprResult PerformQualificationConversion(
Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
CheckedConversionKind CCK = CCK_ImplicitConversion);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, bool IsCompAssign = false);
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
ExprResult &RHS,
SourceLocation QuestionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool ConvertArgs = true);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool ConvertArgs = true) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite =
FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool, bool AllowBoolConversion);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
/// Type checking for matrix binary operators.
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
bool IsCompAssign);
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign);
bool isValidSveBitcast(QualType srcType, QualType destType);
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
bool areVectorTypesSameSize(QualType srcType, QualType destType);
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible - The two types are reference-compatible.
Ref_Compatible
};
// Fake up a scoped enumeration that still contextually converts to bool.
struct ReferenceConversionsScope {
/// The conversions that would be performed on an lvalue of type T2 when
/// binding a reference of type T1 to it, as determined when evaluating
/// whether T1 is reference-compatible with T2.
enum ReferenceConversions {
Qualification = 0x1,
NestedQualification = 0x2,
Function = 0x4,
DerivedToBase = 0x8,
ObjC = 0x10,
ObjCLifetime = 0x20,
LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
};
};
using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
ReferenceConversions *Conv = nullptr);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// Type-check an expression that's being passed to an
/// __unknown_anytype parameter.
ExprResult checkUnknownAnyArg(SourceLocation callLoc,
Expr *result, QualType ¶mType);
// CheckMatrixCast - Check type constraints for matrix casts.
// We allow casting between matrixes of the same dimensions i.e. when they
// have the same number of rows and column. Returns true if the cast is
// invalid.
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
CastKind &Kind);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
/// Prepare `SplattedExpr` for a vector splat operation, adding
/// implicit casts if necessary.
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
/// Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds for ARC and Weak.
ARCConversionResult CheckObjCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool Diagnose = true,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage, SourceLocation lbrac,
SourceLocation rbrac, SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage);
/// If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
class ConditionResult {
Decl *ConditionVar;
FullExprArg Condition;
bool Invalid;
bool HasKnownValue;
bool KnownValue;
friend class Sema;
ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
bool IsConstexpr)
: ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
HasKnownValue(IsConstexpr && Condition.get() &&
!Condition.get()->isValueDependent()),
KnownValue(HasKnownValue &&
!!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
explicit ConditionResult(bool Invalid)
: ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
HasKnownValue(false), KnownValue(false) {}
public:
ConditionResult() : ConditionResult(false) {}
bool isInvalid() const { return Invalid; }
std::pair<VarDecl *, Expr *> get() const {
return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
Condition.get());
}
llvm::Optional<bool> getKnownValue() const {
if (!HasKnownValue)
return None;
return KnownValue;
}
};
static ConditionResult ConditionError() { return ConditionResult(true); }
enum class ConditionKind {
Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
Switch ///< An integral condition for a 'switch' statement.
};
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr, ConditionKind CK);
ConditionResult ActOnConditionVariable(Decl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
bool IsConstexpr = false);
/// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
/// found in an explicit(bool) specifier.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
/// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
/// Returns true if the explicit specifier is now resolved.
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual SemaDiagnosticBuilder
diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
SourceLocation Loc) = 0;
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
virtual ~VerifyICEDiagnoser() {}
};
enum AllowFoldKind {
NoFold,
AllowFold,
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
AllowFoldKind CanFold = NoFold);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
AllowFoldKind CanFold = NoFold);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr,
AllowFoldKind CanFold = NoFold);
ExprResult VerifyIntegerConstantExpression(Expr *E,
AllowFoldKind CanFold = NoFold) {
return VerifyIntegerConstantExpression(E, nullptr, CanFold);
}
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
private:
unsigned ForceCUDAHostDeviceDepth = 0;
public:
/// Increments our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. So long as this count is greater
/// than zero, all functions encountered will be __host__ __device__.
void PushForceCUDAHostDevice();
/// Decrements our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. Returns false if the count is 0
/// before incrementing, so you can emit an error.
bool PopForceCUDAHostDevice();
/// Diagnostics that are emitted only if we discover that the given function
/// must be codegen'ed. Because handling these correctly adds overhead to
/// compilation, this is currently only enabled for CUDA compilations.
llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
std::vector<PartialDiagnosticAt>>
DeviceDeferredDiags;
/// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
/// key in a hashtable, both the FD and location are hashed.
struct FunctionDeclAndLoc {
CanonicalDeclPtr<FunctionDecl> FD;
SourceLocation Loc;
};
/// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
/// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
/// same deferred diag twice.
llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
/// An inverse call graph, mapping known-emitted functions to one of their
/// known-emitted callers (plus the location of the call).
///
/// Functions that we can tell a priori must be emitted aren't added to this
/// map.
llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
/* Caller = */ FunctionDeclAndLoc>
DeviceKnownEmittedFns;
/// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurContext is a __host__ function, does not emit any diagnostics
/// unless \p EmitOnBothSides is true.
/// - If CurContext is a __device__ or __global__ function, emits the
/// diagnostics immediately.
/// - If CurContext is a __host__ __device__ function and we are compiling for
/// the device, creates a diagnostic which is emitted if and when we realize
/// that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in CUDA device code.
/// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
/// return ExprError();
/// // Otherwise, continue parsing as normal.
SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
unsigned DiagID);
/// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
/// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the device, emits the diagnostics immediately.
/// - If CurContext is a non-`declare target` function and we are compiling
/// for the device, creates a diagnostic which is emitted if and when we
/// realize that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
SemaDiagnosticBuilder
diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
/// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as host code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the host, emits the diagnostics immediately.
/// - If CurContext is a non-host function, just ignore it.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
unsigned DiagID, FunctionDecl *FD);
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
FunctionDecl *FD = nullptr);
SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
const PartialDiagnostic &PD,
FunctionDecl *FD = nullptr) {
return targetDiag(Loc, PD.getDiagID(), FD) << PD;
}
/// Check if the expression is allowed to be used in expressions for the
/// offloading devices.
void checkDeviceDecl(ValueDecl *D, SourceLocation Loc);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
/// Determines whether the given function is a CUDA device/host/kernel/etc.
/// function.
///
/// Use this rather than examining the function's attributes yourself -- you
/// will get it wrong. Returns CFT_Host if D is null.
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
bool IgnoreImplicitHDAttr = false);
CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
enum CUDAVariableTarget {
CVT_Device, /// Emitted on device side with a shadow variable on host side
CVT_Host, /// Emitted on host side only
CVT_Both, /// Emitted on both sides with different addresses
CVT_Unified, /// Emitted as a unified address, e.g. managed variables
};
/// Determines whether the given variable is emitted on host or device side.
CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
/// Gets the CUDA target for the current context.
CUDAFunctionTarget CurrentCUDATarget() {
return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
}
static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
// CUDA function call preference. Must be ordered numerically from
// worst to best.
enum CUDAFunctionPreference {
CFP_Never, // Invalid caller/callee combination.
CFP_WrongSide, // Calls from host-device to host or device
// function that do not match current compilation
// mode.
CFP_HostDevice, // Any calls to host/device functions.
CFP_SameSide, // Calls from host-device to host or device
// function matching current compilation mode.
CFP_Native, // host-to-host or device-to-device calls.
};
/// Identifies relative preference of a given Caller/Callee
/// combination, based on their host/device attributes.
/// \param Caller function which needs address of \p Callee.
/// nullptr in case of global context.
/// \param Callee target function
///
/// \returns preference value for particular Caller/Callee combination.
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
const FunctionDecl *Callee);
/// Determines whether Caller may invoke Callee, based on their CUDA
/// host/device attributes. Returns false if the call is not allowed.
///
/// Note: Will return true for CFP_WrongSide calls. These may appear in
/// semantically correct CUDA programs, but only if they're never codegen'ed.
bool IsAllowedCUDACall(const FunctionDecl *Caller,
const FunctionDecl *Callee) {
return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
}
/// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
/// depending on FD and the current compilation settings.
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
const LookupResult &Previous);
/// May add implicit CUDAConstantAttr attribute to VD, depending on VD
/// and current compilation settings.
void MaybeAddCUDAConstantAttr(VarDecl *VD);
public:
/// Check whether we're allowed to call Callee from the current context.
///
/// - If the call is never allowed in a semantically-correct program
/// (CFP_Never), emits an error and returns false.
///
/// - If the call is allowed in semantically-correct programs, but only if
/// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
/// be emitted if and when the caller is codegen'ed, and returns true.
///
/// Will only create deferred diagnostics for a given SourceLocation once,
/// so you can safely call this multiple times without generating duplicate
/// deferred errors.
///
/// - Otherwise, returns true without emitting any diagnostics.
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
/// Set __device__ or __host__ __device__ attributes on the given lambda
/// operator() method.
///
/// CUDA lambdas by default is host device function unless it has explicit
/// host or device attribute.
void CUDASetLambdaAttrs(CXXMethodDecl *Method);
/// Finds a function in \p Matches with highest calling priority
/// from \p Caller context and erases all functions with lower
/// calling priority.
void EraseUnwantedCUDAMatches(
const FunctionDecl *Caller,
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \return true if \p CD can be considered empty according to CUDA
/// (E.2.3.1 in CUDA 7.5 Programming guide).
bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
// \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
// case of error emits appropriate diagnostic and invalidates \p Var.
//
// \details CUDA allows only empty constructors as initializers for global
// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
// __shared__ variables whether they are local or not (they all are implicitly
// static in CUDA). One exception is that CUDA allows constant initializers
// for __constant__ and __device__ variables.
void checkAllowedCUDAInitializer(VarDecl *VD);
/// Check whether NewFD is a valid overload for CUDA. Emits
/// diagnostics and invalidates NewFD if not.
void checkCUDATargetOverload(FunctionDecl *NewFD,
const LookupResult &Previous);
/// Copies target attributes from the template TD to the function FD.
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
/// Returns the name of the launch configuration function. This is the name
/// of the function that will be called to configure kernel call, with the
/// parameters specified via <<<>>>.
std::string getCudaConfigureFuncName() const;
/// \name Code completion
//@{
/// Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// Code completion occurs within a class, struct, or union.
PCC_Class,
/// Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// Code completion occurs following one or more template
/// headers.
PCC_Template,
/// Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// Code completion occurs within an expression.
PCC_Expression,
/// Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// Code completion occurs where only a type is permitted.
PCC_Type,
/// Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteExpression(Scope *S, QualType PreferredType,
bool IsParenthesized = false);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement,
QualType PreferredType);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
QualType PreferredType);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
const VirtSpecifiers *VS = nullptr);
void CodeCompleteBracketDeclarator(Scope *S);
void CodeCompleteCase(Scope *S);
/// Determines the preferred type of the current function argument, by
/// examining the signatures of all possible overloads.
/// Returns null if unknown or ambiguous, or if code completion is off.
///
/// If the code completion point has been reached, also reports the function
/// signatures that were considered.
///
/// FIXME: rename to GuessCallArgumentType to reduce confusion.
QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
SourceLocation Loc,
ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
CXXScopeSpec SS,
ParsedType TemplateTypeTy,
ArrayRef<Expr *> ArgExprs,
IdentifierInfo *II,
SourceLocation OpenParLoc);
void CodeCompleteInitializer(Scope *S, Decl *D);
/// Trigger code completion for a record of \p BaseType. \p InitExprs are
/// expressions in the initializer list seen so far and \p D is the current
/// Designation being parsed.
void CodeCompleteDesignator(const QualType BaseType,
llvm::ArrayRef<Expr *> InitExprs,
const Designation &D);
void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
bool IsUsingDeclaration, QualType BaseType,
QualType PreferredType);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteAfterFunctionEquals(Declarator &D);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(
ArrayRef<IdentifierLocPair> Protocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
SourceLocation ClassNameLoc,
bool IsBaseExprStatement);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
void CodeCompleteNaturalLanguage();
void CodeCompleteAvailabilityPlatformName();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto, SourceLocation Loc);
void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
StringRef ParamName, QualType ArgTy, QualType ParamTy);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
const Expr *ThisArg, ArrayRef<const Expr *> Args,
bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckOSLogFormatStringArg(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
bool WantCDE);
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
ArrayRef<int> ArgNums);
bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
ArrayRef<int> ArgNums);
bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
CallExpr *TheCall);
bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
bool SemaBuiltinComplex(CallExpr *TheCall);
bool SemaBuiltinVSX(CallExpr *TheCall);
bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
bool IsDelete);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
int High, bool RangeIsError = true);
bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
unsigned Multiple);
bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
unsigned ArgBits);
bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
unsigned ArgBits);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc);
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
// Matrix builtin handling.
ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
ExprResult CallResult);
ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
ExprResult CallResult);
ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
ExprResult CallResult);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_OSLog,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
bool FormatStringHasSArg(const StringLiteral *FExpr);
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl);
void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckFreeArguments(const CallExpr *E);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
public:
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
private:
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(const Expr *E);
/// Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// Check if there is a field shadowing.
void CheckShadowInheritedFields(const SourceLocation &Loc,
DeclarationName FieldName,
const CXXRecordDecl *RD,
bool DeclIsField = true);
/// Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const ArrayRef<const Expr *> ExprArgs,
SourceLocation CallSiteLoc);
/// Check if we are taking the address of a packed field
/// as this may be a problem if the pointer value is dereferenced.
void CheckAddressOfPackedMember(Expr *rhs);
/// The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Nullable_result = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
/// The handler for the FileChanged preprocessor events.
///
/// Used for diagnostics that implement custom semantic analysis for #include
/// directives, like -Wpragma-pack.
sema::SemaPPCallbacks *SemaPPCallbackHandler;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
bool isCFError(RecordDecl *D);
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// Determine the number of levels of enclosing template parameters. This is
/// only usable while parsing. Note that this does not include dependent
/// contexts in which no template parameters have yet been declared, such as
/// in a terse function template or generic lambda before the first 'auto' is
/// encountered.
unsigned getTemplateDepth(Scope *S) const;
/// To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
// Emitting members of dllexported classes is delayed until the class
// (including field initializers) is fully parsed.
SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
private:
int ParsingClassDepth = 0;
class SavePendingParsedClassStateRAII {
public:
SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
~SavePendingParsedClassStateRAII() {
assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
swapSavedState();
}
private:
Sema &S;
decltype(DelayedOverridingExceptionSpecChecks)
SavedOverridingExceptionSpecChecks;
decltype(DelayedEquivalentExceptionSpecChecks)
SavedEquivalentExceptionSpecChecks;
void swapSavedState() {
SavedOverridingExceptionSpecChecks.swap(
S.DelayedOverridingExceptionSpecChecks);
SavedEquivalentExceptionSpecChecks.swap(
S.DelayedEquivalentExceptionSpecChecks);
}
};
/// Helper class that collects misaligned member designations and
/// their location info for delayed diagnostics.
struct MisalignedMember {
Expr *E;
RecordDecl *RD;
ValueDecl *MD;
CharUnits Alignment;
MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment)
: E(E), RD(RD), MD(MD), Alignment(Alignment) {}
explicit MisalignedMember(Expr *E)
: MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
bool operator==(const MisalignedMember &m) { return this->E == m.E; }
};
/// Small set of gathered accesses to potentially misaligned members
/// due to the packed attribute.
SmallVector<MisalignedMember, 4> MisalignedMembers;
/// Adds an expression to the set of gathered misaligned members.
void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment);
public:
/// Diagnoses the current set of gathered accesses. This typically
/// happens at full expression level. The set is cleared after emitting the
/// diagnostics.
void DiagnoseMisalignedMembers();
/// This function checks if the expression is in the sef of potentially
/// misaligned members and it is converted to some pointer type T with lower
/// or equal alignment requirements. If so it removes it. This is used when
/// we do not want to diagnose such misaligned access (e.g. in conversions to
/// void*).
void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
/// This function calls Action when it determines that E designates a
/// misaligned member due to the packed attribute. This is used to emit
/// local diagnostics like in reference binding.
void RefersToMemberWithReducedAlignment(
Expr *E,
llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
Action);
/// Describes the reason a calling convention specification was ignored, used
/// for diagnostics.
enum class CallingConventionIgnoredReason {
ForThisTarget = 0,
VariadicFunction,
ConstructorDestructor,
BuiltinFunction
};
/// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurLexicalContext is a kernel function or it is known that the
/// function will be emitted for the device, emits the diagnostics
/// immediately.
/// - If CurLexicalContext is a function and we are compiling
/// for the device, but we don't know that this function will be codegen'ed
/// for devive yet, creates a diagnostic which is emitted if and when we
/// realize that the function will be codegen'ed.
///
/// Example usage:
///
/// Diagnose __float128 type usage only from SYCL device code if the current
/// target doesn't support it
/// if (!S.Context.getTargetInfo().hasFloat128Type() &&
/// S.getLangOpts().SYCLIsDevice)
/// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
unsigned DiagID);
/// Check whether we're allowed to call Callee from the current context.
///
/// - If the call is never allowed in a semantically-correct program
/// emits an error and returns false.
///
/// - If the call is allowed in semantically-correct programs, but only if
/// it's never codegen'ed, creates a deferred diagnostic to be emitted if
/// and when the caller is codegen'ed, and returns true.
///
/// - Otherwise, returns true without emitting any diagnostics.
///
/// Adds Callee to DeviceCallGraph if we don't know if its caller will be
/// codegen'ed yet.
bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
};
/// RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
bool Entered = true;
public:
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other,
bool ShouldEnter = true)
: Actions(Actions), Entered(ShouldEnter) {
if (Entered)
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
ExprContext);
}
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(
NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
}
enum InitListTag { InitList };
EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
bool ShouldEnter = true)
: Actions(Actions), Entered(false) {
// In C++11 onwards, narrowing checks are performed on the contents of
// braced-init-lists, even when they occur within unevaluated operands.
// Therefore we still need to instantiate constexpr functions used in such
// a context.
if (ShouldEnter && Actions.isUnevaluatedContext() &&
Actions.getLangOpts().CPlusPlus11) {
Actions.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::UnevaluatedList);
Entered = true;
}
}
~EnterExpressionEvaluationContext() {
if (Entered)
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// The template function declaration to be late parsed.
Decl *D;
};
template <>
void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
AlignPackInfo Value);
} // end namespace clang
namespace llvm {
// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
// SourceLocation.
template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
static FunctionDeclAndLoc getEmptyKey() {
return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
}
static FunctionDeclAndLoc getTombstoneKey() {
return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
}
static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
FDL.Loc.getHashValue());
}
static bool isEqual(const FunctionDeclAndLoc &LHS,
const FunctionDeclAndLoc &RHS) {
return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
}
};
} // namespace llvm
#endif
|
shape.h
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
/*
* shape.h
*
* Created on: Dec 28, 2015
* Author: agibsonccc
*/
#ifndef SHAPE_H_
#define SHAPE_H_
#include <cstring>
#include <cstdio>
#include "../dll.h"
#include "../nd4jmalloc.h"
#include "../templatemath.h"
#include "../helpers/logger.h"
#include "../pointercast.h"
#include "../cnpy/cnpy.h"
#include <op_boilerplate.h>
#define MAX_DIMENSION 0x7fffffff
#define MAX_NUM_THREADS 1024
#define MAX_RANK 32
#define MAX_SHAPEINFOLENGTH 2*MAX_RANK+4
#define MAX_COORD 3
#define PREALLOC_SIZE 33554432
#ifdef __CUDACC__
#include <cuda.h>
#include <cuda_runtime.h>
#include <helpers/sharedmem.h>
#endif
#ifdef __CUDACC__
#define INLINEDEF inline
#else
#define INLINEDEF inline
#endif
#include "../pairwise_util.h"
#include <stdint.h>
#include <array/ArrayOptions.h>
typedef unsigned int uint;
namespace shape {
/**
* Shape information approximating
* the information on an ndarray
*/
struct ND4J_EXPORT ShapeInformation {
_CUDA_HD ShapeInformation(Nd4jLong *shape_ = nullptr, Nd4jLong *stride_ = nullptr, char order_ = 0, int rank_ = 0, int offset_ = 0, int elementWiseStride_ = 0)
: shape(shape_), stride(stride_), order(order_), rank(rank_), offset(offset_), elementWiseStride(elementWiseStride_)
{}
Nd4jLong *shape;
Nd4jLong *stride;
char order;
int rank;
int offset;
int elementWiseStride;
};
/**
* Indexing information
* for bounds checking
*/
struct ND4J_EXPORT CurrentIndexing {
int numElementsPerThread;
int blockStartingIndex;
int startingThreadIndex;
int endingThreadIndex;
};
ND4J_EXPORT _CUDA_HD bool shapeEquals(const int shape1Rank, const Nd4jLong *shape1, const int shape2Rank, const Nd4jLong *shape2);
ND4J_EXPORT _CUDA_HD Nd4jLong* detachShape(Nd4jLong *originalShape);
ND4J_EXPORT _CUDA_HD Nd4jLong* copyShape(Nd4jLong *originalShape);
ND4J_EXPORT _CUDA_HD bool shapeEquals(const Nd4jLong *shapeInfo1, const Nd4jLong *shapeInfo2);
ND4J_EXPORT _CUDA_HD bool strideEquals(int shape1Rank,Nd4jLong *shape1,int shape2Rank,Nd4jLong *shape2);
ND4J_EXPORT _CUDA_HD bool strideEquals(Nd4jLong *shapeInfo1,Nd4jLong *shapeInfo2);
ND4J_EXPORT _CUDA_HD bool strideEquals(Nd4jLong *stride1,int rank1,Nd4jLong *stride2,int rank2);
ND4J_EXPORT _CUDA_HD bool equalsSoft(const Nd4jLong *shapeA, const Nd4jLong *shapeB);
ND4J_EXPORT _CUDA_HD bool equalsTypesAndShapesSoft(const Nd4jLong *shapeA, const Nd4jLong *shapeB);
ND4J_EXPORT _CUDA_HD bool equalsStrict(const Nd4jLong *shapeA, const Nd4jLong *shapeB);
ND4J_EXPORT _CUDA_HD bool haveSameOffsets(const Nd4jLong *shapeA, const Nd4jLong *shapeB);
ND4J_EXPORT _CUDA_HD int sizeAt(const Nd4jLong *shape, const int dim);
template <typename T>
ND4J_EXPORT _CUDA_HD void fill(T* buffer, T value, Nd4jLong length);
ND4J_EXPORT _CUDA_HD void traceNew(int id);
ND4J_EXPORT _CUDA_HD int tadIndexForLinear(int linearIndex, int tadLength);
ND4J_EXPORT _CUDA_HD int tadLength(Nd4jLong *shapeInfo, int *dimension, int dimensionLength);
ND4J_EXPORT _CUDA_HD bool canReshape(const int oldRank, Nd4jLong* oldShape, const int newRank, Nd4jLong* newShape, bool isFOrder);
ND4J_EXPORT _CUDA_HD bool reshapeC(const int oldRank, const Nd4jLong* oldShapeInfo, const int newRank, const Nd4jLong* newShape, Nd4jLong* newShapeInfo);
/**
* Get the shape info buffer
* for the given rank and shape.
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeBuffer(int rank, nd4j::DataType dtype, Nd4jLong *shape);
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeBuffer(int rank, nd4j::DataType dtype, Nd4jLong *shape, Nd4jLong *buffer);
/**
* Get the shape info buffer
* for the given rank and shape.
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeBufferFortran(int rank, nd4j::DataType dtype, Nd4jLong *shape);
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeBufferFortran(int rank, nd4j::DataType dtype, Nd4jLong *shape, Nd4jLong *output);
//ND4J_EXPORT _CUDA_HD void doPermuteShapeBuffer(Nd4jLong *shapeBuffer, int* rearrange, Nd4jLong *tmpBuffer);
ND4J_EXPORT _CUDA_HD void doPermuteShapeBuffer(int rank, Nd4jLong *shapeBuffer, int *rearrange, Nd4jLong *tmpBuffer);
#ifdef __CUDACC__
template <typename T>
__device__ ND4J_EXPORT Nd4jLong *cuMalloc(Nd4jLong *buffer, long size, UnifiedSharedMemory *manager);
__device__ ND4J_EXPORT Nd4jLong *cuMalloc(Nd4jLong *buffer, long size);
#endif
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
ND4J_EXPORT _CUDA_HD Nd4jLong * calcStridesFortran(Nd4jLong *shape, int rank);
ND4J_EXPORT _CUDA_HD Nd4jLong * calcStridesFortran(Nd4jLong *shape, int rank, Nd4jLong* ret);
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* calcStrides(Nd4jLong *shape, int rank);
ND4J_EXPORT _CUDA_HD Nd4jLong* calcStrides(Nd4jLong *shape, int rank, Nd4jLong* ret);
ND4J_EXPORT _CUDA_HD void updateStrides(Nd4jLong *shape, const char order);
ND4J_EXPORT _CUDA_HD void updateStrides(const int rank, const Nd4jLong *shapeOnly, Nd4jLong *stridesOnly, const char order);
// check whether input dimensions are permuted, not permuted dimensions order have to be 0,....,rank-1
template <typename T>
ND4J_EXPORT _CUDA_HD bool isDimPermuted(const T* dimensions, const int dimSize);
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* calcStridesFortran(Nd4jLong *shape, int rank, int startNum);
ND4J_EXPORT _CUDA_HD Nd4jLong* calcStridesFortran(Nd4jLong *shape, int rank, int startNum, Nd4jLong* ret);
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* calcStrides(Nd4jLong *shape, int rank, int startNum);
ND4J_EXPORT _CUDA_HD Nd4jLong* calcStrides(Nd4jLong *shape, int rank, int startNum, Nd4jLong* ret);
/**
* @param toCopy the shape to copy
* @return a copy of the original struct
*/
ND4J_EXPORT _CUDA_HD ShapeInformation *shapeCopy( ShapeInformation *toCopy);
ND4J_EXPORT _CUDA_HD bool strideDescendingCAscendingF(const Nd4jLong *shapeBuffer);
ND4J_EXPORT _CUDA_HD bool isStrideSimple(const Nd4jLong* shapeInfo);
/**
* copy-past from java hasDefaultStridesForShape function
* check whether array is not permuted and has contiguous elements in memory
*/
ND4J_EXPORT _CUDA_HD bool areStridesDefault(const Nd4jLong* shapeInfo);
/**
* Compute the element wise stride
* for a given shape/stride configuration
* @param rank the rank of the shape/stride
* @param shape the shape
* @param stride the stride
* @param isFOrder 0 or 1 for whether the array is f
* ordered or not
* @return 0 if there is no element wise stride the
* element wise stride of reshape(1,length) otherwise
*/
ND4J_EXPORT _CUDA_HD int computeElementWiseStride(int rank, Nd4jLong *shape, Nd4jLong *stride, int isFOrder);
/**
* Compute the element wise stride
* for a given shape/stride configuration
* @param rank the rank of the shape/stride
* @param shape the shape
* @param stride the stride
* @param isFOrder 0 or 1 for whether the array is f
* ordered or not
* @return 0 if there is no element wise stride the
* element wise stride of reshape(1,length) otherwise
*/
ND4J_EXPORT _CUDA_HD int computeElementWiseStride(int rank, Nd4jLong *shape, Nd4jLong *stride, int isFOrder, Nd4jLong *dimension, int dimensionLength);
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeInfoOnlyShapeAndStride(Nd4jLong *shapeInfo, Nd4jLong *dimension, int dimensionLength,bool reverseCopyStride);
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeInfoOnlyShapeAndStride(Nd4jLong *shapeInfo, Nd4jLong *dimension, int dimensionLength,bool reverseCopyStride, Nd4jLong *buffer);
/**
*
* @param length
* @param shape
* @param rearrange
* @return
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *doPermuteSwap(int length, Nd4jLong *shape, int* rearrange);
/**
* In place permute swap
* @param length
* @param shape
* @param rearrange
*/
ND4J_EXPORT _CUDA_HD void doPermuteSwap(int length, Nd4jLong **shape, int* rearrange);
ND4J_EXPORT _CUDA_HD Nd4jLong *permuteShapeBuffer(Nd4jLong *shapeBuffer, int* rearrange);
ND4J_EXPORT _CUDA_HD void permuteShapeBufferInPlace(Nd4jLong *shapeBuffer, int* rearrange, Nd4jLong *out);
ND4J_EXPORT _CUDA_HD void doPermuteShapeInfo(Nd4jLong *shapeBuffer, const int *rearrange);
ND4J_EXPORT _CUDA_HD void doPermuteShapeInfo(Nd4jLong *shapeBuffer, const Nd4jLong *rearrange);
ND4J_EXPORT _CUDA_HD void doPermuteShapeBuffer(Nd4jLong *shapeBuffer, int* rearrange);
ND4J_EXPORT _CUDA_HD void doPermuteShapeBuffer(int rank,Nd4jLong *shapeBuffer, int* rearrange);
/**
* Rearrange the permute indexes
* according to which dimensions are specified.
*
* For example, dimension is implicitly:
* 0,1,2
*
* If you want to do a reduce along dimensions 0 and 1,
* you need to permute the indexes to be:
* 2,0,1
*
* which will give us the ability to ierate along an element
* wise stride.
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* createPermuteIndexes(int originalRank, int *dimension,int dimensionLength);
ND4J_EXPORT _CUDA_HD Nd4jLong* computeResultShape(Nd4jLong *originalShapeBuffer, int *dimension,int dimensionLength);
/**
* This method does inplace transpose of given shapeBuffer
*
* @param shapeBuffer
*/
ND4J_EXPORT _CUDA_HD void transposeInplace(Nd4jLong *shapeBuffer);
/**
* Get the ordering for the device
* @param length
* @param shape
* @param stride
* @param elementStride
* @return
*/
ND4J_EXPORT _CUDA_HD char getOrder(int length, Nd4jLong *shape, Nd4jLong *stride, int elementStride);
/**
* Ensure that every value in the re arrange
* array is unique
* @param arr
* @param shape
* @param arrLength
* @param shapeLength
* @return
*/
template <typename T>
ND4J_EXPORT _CUDA_HD int checkArrangeArray(T *arr, int arrLength, int shapeLength);
/**
* Permute the shape information
* @param info the shape information to permute
* @param rearrange the order to re arrange
* @param rank the rank of the rearrange array
*/
ND4J_EXPORT _CUDA_HD void permute(ShapeInformation **info, int *rearrange, int rank);
/**
* Returns whether the
* given shape is a vector or not
* @param shape the shape of the array
* @param rank the rank of cthe shape
*/
ND4J_EXPORT _CUDA_HD int isVector(Nd4jLong *shape, int rank);
/**
* When 1 dimension is the whole length of the
* array
*/
ND4J_EXPORT _CUDA_HD int oneDimEqualToLength(Nd4jLong *shape, int rank);
ND4J_EXPORT _CUDA_HD int oneDimEqualToLength(Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD int isVector(const Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD bool isLikeVector(Nd4jLong *shapeInfo, int& posOfNonUnityDim);
ND4J_EXPORT _CUDA_HD bool isCommonVector(const Nd4jLong *shapeInfo, int& posOfNonUnityDim);
ND4J_EXPORT _CUDA_HD bool isRowVector(const Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD bool isColumnVector(Nd4jLong *shapeInfo);
/**
* Returns whether the
* given shape is a vector or not
* @param shape the shape of the array
* @param rank the rank of the shape
*/
ND4J_EXPORT _CUDA_HD int isMatrix(Nd4jLong *shape, int rank);
INLINEDEF _CUDA_HD int isMatrix(Nd4jLong *shapeInfo);
/**
* Returns the shape portion of an information
* buffer
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeOf(Nd4jLong *buffer);
/**
* Return a copy of a buffer.
* This buffer allocates memory
* that must be freed elsewhere.
*/
template <typename T>
ND4J_EXPORT _CUDA_HD T* copyOf(Nd4jLong length, T *toCopy);
template <typename T>
ND4J_EXPORT _CUDA_HD T* copyOf(Nd4jLong length, T *toCopy, T *ret);
/**
* Return a copy of a buffer.
* This buffer allocates memory
* that must be freed elsewhere.
*/
template <typename T>
ND4J_EXPORT _CUDA_HD void copyTo(Nd4jLong length, T *from, T *to);
/**
* Return a copy of a buffer.
* This buffer allocates memory
* that must be freed elsewhere.
*/
ND4J_EXPORT _CUDA_HD void copyTo(int length, Nd4jLong *from, Nd4jLong *to, Nd4jLong *indexes);
/**
* Permute the given strides
* in the given rearrange order
* @param toPermute the buffer to permute
* @param shapeRank the length of the buffer to permute
* @param rearrange the rearrange order (must be 0 based indexes
* and all must be filled in)
* @return the rearranged array
*/
//ND4J_EXPORT _CUDA_HD Nd4jLong *permutedStrides(Nd4jLong *toPermute, int shapeRank, Nd4jLong *rearrange);
/**
* Return the slice (shape + 1 in pointer arithmetic)
* @param shape the shape to take the slice of
* @return the shape array - the first entry
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *slice(Nd4jLong *shape);
ND4J_EXPORT _CUDA_HD int slices(Nd4jLong *shapeBuffer);
ND4J_EXPORT _CUDA_HD Nd4jLong *sliceOfShapeBuffer(Nd4jLong sliceIdx, Nd4jLong *shapeBuffer);
/**
* Returns the length of the
* shape information buffer:
* rank * 2 + 3
* @param rank the rank to get the shape
* info length for
* @return rank * 2 + 4
*/
ND4J_EXPORT _CUDA_HD int shapeInfoLength(int rank);
ND4J_EXPORT _CUDA_HD int shapeInfoLength(Nd4jLong* shapeInfo);
ND4J_EXPORT _CUDA_HD int shapeInfoLength(const Nd4jLong* shapeInfo);
ND4J_EXPORT _CUDA_HD size_t shapeInfoByteLength(int rank);
ND4J_EXPORT _CUDA_HD size_t shapeInfoByteLength(const Nd4jLong* shapeInfo);
ND4J_EXPORT _CUDA_HD size_t shapeInfoByteLength(const Nd4jLong* shapeInfo);
/**
* Returns the rank portion of
* an information buffer
*/
ND4J_EXPORT _CUDA_HD int rank(const Nd4jLong *buffer);
ND4J_EXPORT _CUDA_HD int rank(const int *buffer);
ND4J_EXPORT _CUDA_HD int rank(const unsigned int *buffer);
// returns pointer on elementWiseStride
ND4J_EXPORT _CUDA_HD Nd4jLong* ews(Nd4jLong* shapeInfo);
/**
* Converts a raw int buffer of the layout:
* rank
* shape
* stride
* offset
* elementWiseStride
*
* where shape and stride are both straight int pointers
*/
ND4J_EXPORT _CUDA_HD ShapeInformation *infoFromBuffer(Nd4jLong *buffer);
/**
* Returns the stride portion of an information
* buffer
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *stride(Nd4jLong *buffer);
/**
* Compute the length of the given shape
*/
ND4J_EXPORT _CUDA_HD bool isEmpty(const Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD Nd4jLong length(const Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD Nd4jLong length(std::initializer_list<int>& shape);
ND4J_EXPORT _CUDA_HD Nd4jLong length(std::initializer_list<Nd4jLong>& shape);
/***
* Returns the offset portion of an information buffer
*/
ND4J_EXPORT _CUDA_HD Nd4jLong offset(Nd4jLong *buffer);
ND4J_EXPORT _CUDA_HD Nd4jLong& extra(Nd4jLong *buffer);
/**
* Returns the ordering
* for this shape information buffer
*/
ND4J_EXPORT _CUDA_HD char order(const Nd4jLong *buffer);
/**
* Returns the type
*/
ND4J_EXPORT _CUDA_HD Nd4jLong type(const Nd4jLong* shapeInfo);
/**
* Returns the element wise stride for this information
* buffer
*/
ND4J_EXPORT _CUDA_HD Nd4jLong elementWiseStride(const Nd4jLong *buffer);
/**
* Returns the element wise stride for this information
* buffer
* relative to a dimension and ordering for a reduction index
*/
ND4J_EXPORT _CUDA_HD Nd4jLong reductionIndexElementWiseStride(Nd4jLong *buffer, int *dimension, int dimensionLength);
/**
* Returns whether
* the given shape info buffer
* represents a scalar shape
*/
ND4J_EXPORT _CUDA_HD int isScalar(Nd4jLong *info);
/**
* Returns whether
* the given shape information
* represents a scalar
* shape or not
*/
ND4J_EXPORT _CUDA_HD int isScalar(volatile ShapeInformation *info);
/**
* Return a copy of this array with the
* given index omitted
*
* @param data the data to copy
* @param indexes the index of the item to remove
* @param dataLength the length of the data array
* @param indexesLength the length of the data array
* @return the new array with the omitted
*
* item
*/
template <typename T1, typename T2>
ND4J_EXPORT _CUDA_HD void removeIndex(T1 *data, T2 *indexes, Nd4jLong dataLength, Nd4jLong indexesLength, T1 *out);
/**
* Return a copy of this array with the
* given index omitted
*
* @param data the data to copy
* @param indexes the index of the item to remove
* @param dataLength the length of the data array
* @param indexesLength the length of the data array
* @return the new array with the omitted
*
* item
*/
template <typename T1, typename T2>
ND4J_EXPORT _CUDA_HD T1* removeIndex(T1 *data, T2 *indexes, Nd4jLong dataLength, Nd4jLong indexesLength);
/**
* Iterate over a given set of indexes
* the begin and end indexes are 0 based.
* 1 padding is automatically assumed for the ending.
*
* For example if you want to iterate over 0 to 4
* it will go to 4 rather than 3.
*
* indexes should be the indexes to exclude
* indexes length should be the length of indexes
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* everyIndexBut(Nd4jLong *indexes,int indexesLength,int begin,int end);
/**
* Computes the offset for accessing
* a global element given the shape information
* and the offset to be read.
*/
//#ifdef __CUDACC__
// __device__
//#endif
// ND4J_EXPORT int tadOffset(shape::ShapeInformation *xInfo, int offset);
/**
* Returns a shape
* forces the given length to be 2.
* @param shape the shape to modify
* @param dimension the dimension (row or column)
* for the shape to be returned as
* @return the new shape
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* ensureVectorShape(Nd4jLong *shape);
ND4J_EXPORT _CUDA_HD Nd4jLong* createScalarShapeInfo();
ND4J_EXPORT _CUDA_HD Nd4jLong* createScalarShapeInfo(Nd4jLong *ret);
/**
* Generate an int buffer
* up to the given length
* at the specified increment
*
*/
template <typename T>
ND4J_EXPORT _CUDA_HD T* range(int from, int to, int increment);
/**
* Range between from and two with an
* increment of 1
*/
template <typename T>
ND4J_EXPORT _CUDA_HD T* range(int from, int to);
/**
* Keep the given indexes
* in the data
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *keep(volatile Nd4jLong *data, int* index, int indexLength, int dataLength);
/**
* Generate reverse copy of the data
* @param data
* @param length
* @return
*/
template <typename T>
ND4J_EXPORT _CUDA_HD T* reverseCopy(T *data, Nd4jLong length);
template <typename T>
ND4J_EXPORT _CUDA_HD void reverseCopyTo(T *from, T *to, Nd4jLong length);
template <typename T>
ND4J_EXPORT _CUDA_HD void reverseCopyTo(T *from, T *to, Nd4jLong *indexes, Nd4jLong length);
template <typename T1, typename T2>
ND4J_EXPORT _CUDA_H void convertT(T1 *from, T2 *to, Nd4jLong length);
/**
*
* @param arr1
* @param arr1Length
* @param arr2
* @param arr2Length
* @return
*/
template <typename T>
ND4J_EXPORT _CUDA_HD T* concat(T* arr1, Nd4jLong arr1Length, T* arr2, Nd4jLong arr2Length);
/**
*
* @param numArrays
* @param numTotalElements
* @param arr
* @param lengths
* @return
*/
template <typename T>
ND4J_EXPORT _CUDA_HD T* concat(int numArrays, int numTotalElements, Nd4jLong **arr, Nd4jLong *lengths);
/**
* Get the length per slice of the
* given shape and the dimension
* @param rank the rank of the shape
* @param shape the shape of to get
* the length per slice for
* @param dimension the dimension to
* get the length per slice for
* @param dimensionLength the length of the dimension array
* @return the length per slice of the given shape
* along the given dimension
*/
ND4J_EXPORT _CUDA_HD Nd4jLong lengthPerSlice(int rank, Nd4jLong *shape, int *dimension, int dimensionLength);
/**
* calculates the offset for a tensor
* @param index
* @param arr
* @param tensorShape
* @return
*/
ND4J_EXPORT _CUDA_HD Nd4jLong sliceOffsetForTensor(int rank,
int index,
Nd4jLong *shape,
Nd4jLong *tensorShape,
int tensorShapeLength,
int *dimension,
int dimensionLength);
/**
* calculates the offset for a tensor
* @param index
* @param arr
* @param tensorShape
* @return
*/
ND4J_EXPORT _CUDA_HD Nd4jLong sliceOffsetForTensor(int index,int tensorLength,int lengthPerSlice2);
/**
* Computes the tensor along dimension
* offset
* @param index the index to get the offset for the tad for
* @param rank the rank of the shapes and strides
* @param info the shape information to use for tad
* @param dimension the dimensions to use for computing the tensor along dimensions
*/
// ND4J_EXPORT _CUDA_HD int offset(int index,
// int rank,
// shape::ShapeInformation *info,
// Nd4jLong *dimension,
// int dimensionLength);
/**
* Computes the number
* of tensors along
* a given dimension
*/
ND4J_EXPORT _CUDA_HD Nd4jLong tensorsAlongDimension(int rank,
volatile int length,
volatile Nd4jLong *shape,
int *dimension,
int dimensionLength);
/**
* Computes the number
* of tensors along
* a given dimension
*/
ND4J_EXPORT _CUDA_HD Nd4jLong tensorsAlongDimension(Nd4jLong *shapeInfo, int *dimension, int dimensionLength);
/**
* Returns the tensor along dimension
* for the given block index
* @param blockSize
* @param blockIdx
* @param i
* @return
*/
ND4J_EXPORT _CUDA_HD int tadForBlockIndex(int blockSize, int blockIdx, int i);
/**
* Computes the number of tads per block
*
*/
ND4J_EXPORT _CUDA_HD int tadsPerBlock(int blockSize, int tads);
// ND4J_EXPORT _CUDA_HD Nd4jLong *tadShapeInfo(int index, Nd4jLong *xShapeInfo, Nd4jLong *dimension,
// int dimensionLength);
/**
* Returns a shape buffer
* for the shape information metadata.
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *toShapeBuffer( ShapeInformation *info);
ND4J_EXPORT _CUDA_HD Nd4jLong *toShapeBuffer( ShapeInformation *info, Nd4jLong* ret);
/**
* Returns the number of elements per thread
*/
//#ifdef __CUDACC__
// __device__
//#endif
// int numElementsPerThread(int N);
/**
* Returns the block starting index
*/
//#ifdef __CUDACC__
// __device__
//#endif
// int blockStartingIndex(int N);
/**
* Returns the thread starting index
*/
//#ifdef __CUDACC__
// __device__
//#endif
// int threadStartingIndex(int N, int stride, int offset);
/**
* Returns the thread ending index
*/
//#ifdef __CUDACC__
// __device__
//#endif
// int threadEndingIndex(int N, int stride, int offset);
/**
* Returns indexing information
* for the current kernel invocation
*/
//#ifdef __CUDACC__
// __device__
//#endif
// CurrentIndexing *currentIndex(int N, int offset, int stride);
/** Given an linear index, element wise stride
* and the length of each tad
* map a linear index to a tad
* @param i the index to map
* @param the element wise stride for the tads
* @param numElementsPerTad the number of elements
* per tad
*/
ND4J_EXPORT _CUDA_HD int tadIndex(int i, int elementWiseStride, int numElementsPerTad);
/**
* Map a tad to a
* reduction index.
* @param tadIndexForOriginal the original tad index for the
* split up problem (eg: split is dimension 3 mapping to a 2,3 problem)
* @param tadsForReduced the number of tads for the shrunk down problem (eg: 2,3)
* @param tadsForOriginal the number of tads for the smaller problem (eg: 3)
*/
ND4J_EXPORT _CUDA_HD int reductionIndexForTad(int tadIndexForOriginal, int tadsForReduced,
int tadsForOriginal);
/**
* Computes the number of tads
* per reduce index for the
* reduction tad.
*/
ND4J_EXPORT _CUDA_HD int tadsPerReduceIndex(int tadsForReduce, int tadsForOriginal);
/**
* Maps a linear index to a reduction index
* @param i the linear index to map
* @param elementWiseStride the element wise stride
* for the multiple problem
* @param tadNum the number of tads for the shrunken problem
* @param originalTadNum the tad number for the reduced version of the problem
*/
ND4J_EXPORT _CUDA_HD int reductionIndexForLinear(int i, int elementWiseStride, int numElementsPerTad,
int tadNum, int originalTadNum);
/**
* Returns the prod of the data
* up to the given length
*/
ND4J_EXPORT _CUDA_HD int prod(Nd4jLong *data, int length);
ND4J_EXPORT _CUDA_HD Nd4jLong prodLong(const Nd4jLong *data, int length);
/**
* Returns the rear most left over item not present in
* the dimension array. This assumes that the dimension array is sorted.
*
* For example, given a dimension array of:
* 0,2
*
* and
*
* 12,4,2,1 in data
*
* You end up with 1 (data[3])
* since the first item won't match
* the last item of the dimension array
*/
// ND4J_EXPORT _CUDA_HD int rearMostLeftOverItem(Nd4jLong *data,int length,Nd4jLong *dimension,int dimensionLength);
/**
* Get an offset for retrieval
* from a data buffer
* based on the given
* shape stride and given indices
* @param baseOffset the offset to start from
* @param shape the shape of the array
* @param stride the stride of the array
* @param indices the indices to iterate over
* @return the double at the specified index
*/
ND4J_EXPORT _CUDA_HD Nd4jLong getOffset(Nd4jLong baseOffset, const Nd4jLong *shape, const Nd4jLong *stride, const Nd4jLong *indices,int rank);
ND4J_EXPORT _CUDA_HD Nd4jLong* createShapeInfo(Nd4jLong *shape, Nd4jLong *stride, int rank);
ND4J_EXPORT _CUDA_HD Nd4jLong* createShapeInfo(Nd4jLong *shape, Nd4jLong *stride, int rank, Nd4jLong *buffer);
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* ind2sub(int rank, Nd4jLong *shape, Nd4jLong index, Nd4jLong numIndices);
ND4J_EXPORT _CUDA_HD Nd4jLong *ind2sub(int rank, Nd4jLong *shape, Nd4jLong index);
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD void ind2sub(int rank,Nd4jLong *shape, Nd4jLong index, Nd4jLong numIndices,Nd4jLong *out);
/**
* Convert a linear index to
* the equivalent nd index.
* Infers the number of indices from the specified shape.
*
* @param shape the shape of the dimensions
* @param index the index to map
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD void ind2sub(int rank, Nd4jLong *shape, Nd4jLong index, Nd4jLong *out);
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index);
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD Nd4jLong* ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index, Nd4jLong numIndices);
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD void ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index, Nd4jLong numIndices, Nd4jLong *out);
/**
* Convert a linear index to
* the equivalent nd index.
* Infers the number of indices from the specified shape.
*
* @param shape the shape of the dimensions
* @param index the index to map
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD void ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index, Nd4jLong *out);
/**
* Convert the given index (such as 1,1)
* to a linear index
* @param shape the shape of the indexes to convert
* @param indices the index to convert
* @return the linear index given the shape
* and indices
*/
ND4J_EXPORT _CUDA_HD Nd4jLong sub2Ind(const int rank, const Nd4jLong *shape, const Nd4jLong *indices);
/**
* increment n-dimensional array by one iteration by changing coord appropriately
* for example we have array with shape {2, 3}:
* - if input coord = {0,1}, then output coord = {0,2}
* - if input coord = {0,2}, then output coord = {1,0}
* so the aim is to produce following subsequence of coord: {0,0}, {0,1}, {0,2}, {1,0}, {1,1}, {1,2}
*/
/* calculates an array buffer offset for given "index" using following formula: offset = coord_0*stride_0 + coord_1*stride_1 + ... + coord_{rank-1}*stride_{rank-1}
* arrLen - array length
*/
ND4J_EXPORT _CUDA_HD uint getIndexOffset(uint index, const uint *shapeInfo, uint arrLen);
ND4J_EXPORT _CUDA_HD Nd4jLong getIndexOffset(Nd4jLong index, const Nd4jLong *shapeInfo, Nd4jLong arrLen);
ND4J_EXPORT _CUDA_HD Nd4jLong getIndexOrderOffset(Nd4jLong index, const Nd4jLong *shapeInfo, Nd4jLong arrLen, const char order);
ND4J_EXPORT _CUDA_HD Nd4jLong indexOffset(Nd4jLong index, const Nd4jLong* lShapeInfo, const uint* uShapeInfo, Nd4jLong arrLen, const bool useUnsigned);
/**
* Compute the real linear indices for the given shape and stride
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *computeIndices(int rank, Nd4jLong *shape, Nd4jLong *stride);
/**
* Compute the real linear indices for the
* given shape buffer. Shape,stride and rank are derived
* from the buffer
*/
ND4J_EXPORT _CUDA_HD Nd4jLong *computeIndices( Nd4jLong *shapeBuffer);
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD void ind2subOrder(Nd4jLong *shapeInfo, Nd4jLong index, Nd4jLong numIndices,Nd4jLong *out);
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
ND4J_EXPORT _CUDA_HD void ind2subOrder(Nd4jLong *shapeInfo, Nd4jLong index,Nd4jLong *out);
ND4J_EXPORT _CUDA_HD void printShapeInfo(Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD void printShapeInfoLinear(const Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD void printShapeInfoLinear(const char *msg, const Nd4jLong *shapeInfo);
ND4J_EXPORT _CUDA_HD void printShapeInfoLinear(const char *msg, int rank, const Nd4jLong *shape, const Nd4jLong *strides);
ND4J_EXPORT _CUDA_HD void printIntArray(const Nd4jLong *arr, const int length);
ND4J_EXPORT _CUDA_HD void printIntArray(const int *arr, const int length);
ND4J_EXPORT _CUDA_HD void printArray(float *arr,int length);
template<typename T>
ND4J_EXPORT _CUDA_HD void printArray(T *arr,int length, const char *message);
ND4J_EXPORT _CUDA_HD Nd4jLong* shapeBufferOfNpy(int rank, unsigned int *shape,bool fortranOrder);
ND4J_EXPORT _CUDA_HD Nd4jLong *shapeBufferOfNpy(cnpy::NpyArray arr);
// ND4J_EXPORT _CUDA_HD Nd4jLong *shapeBufferOfNpyBuffer(char *buffer);
// this function checks the consistence of dimensions with array rank (negative dimensions, too large dimensions, too big number of dimensions)
// also sort input array of dimensions, this operation is also necessary for creating TAD object
ND4J_EXPORT _CUDA_H void checkDimensions(const int rank, std::vector<int>& dimensions);
// function calculates linear index of array min, min is sub-array of max, index to be returned is min-array's index and corresponds to maxIdx of max array
// dimsToExclude - should be sorted in increasing order
ND4J_EXPORT _CUDA_HD Nd4jLong subArrayIndex(const Nd4jLong maxIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude = nullptr, const int dimsLen = -1);
// function calculates absolute offset of min array, min is sub-array of max, offset to be returned corresponds to maxIdx of max array
// dimsToExclude - should be sorted in increasing order
ND4J_EXPORT _CUDA_HD Nd4jLong subArrayOffset(const Nd4jLong maxIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude = nullptr, const int dimsLen = -1);
// max array is outer for min array, min array is sub-array of max array
// function calculates the coordinates of min array (and saves them into minIdxs) given coordinates of max array (already stored in maxIdxs)
// dimsToExclude - should be sorted in increasing order
// dimsLen - length of dimsToExclude, if not set (= -1), then it is calculated as maxRank - minRank
ND4J_EXPORT _CUDA_HD void maxIndToMinInd(Nd4jLong* maxIdxs, Nd4jLong* minIdxs, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude = nullptr, const int dimsLen = -1);
// calculate indexes of max-array, these output indexes correspond to one minIdx index of min-array which is sub-array of max-array
// dimsToExclude - should be sorted in increasing order
ND4J_EXPORT _CUDA_HD int outerArrayIndexes(Nd4jLong* maxIdxs, const Nd4jLong minIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude = nullptr);
// calculate offsets of max-array, these output offsets correspond to one minIdx index of min-array which is sub-array of max-array
// dimsToExclude - should be sorted in increasing order
ND4J_EXPORT _CUDA_HD int outerArrayOffsets(Nd4jLong* maxOffsets, const Nd4jLong minIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude = nullptr);
// calculates offsets for numOfSubArrs sub-arrays, shape in this context means dominions excluded from outer array
// rank is equal to size of shape
ND4J_EXPORT void calcSubArrOffsets(const Nd4jLong numOfSubArrs, const int rank, const Nd4jLong* shape, const Nd4jLong* strides, Nd4jLong* subArrOffsets);
ND4J_EXPORT _CUDA_HD void shapeOldScalar(nd4j::DataType dtype, Nd4jLong* const buffer, const char order);
// calculate element-wise stride
// if array is scalar or unit length vector then ews = 1
// if array is common vector then ews = stride of non-unity dimension
// if strides are normal set ews = 1, otherwise ews = 0
ND4J_EXPORT _CUDA_HD void setEws(Nd4jLong* shapeInfo, Nd4jLong len);
//END HEADERS
//BEGIN IMPLEMENTATIONS
#ifdef __CUDACC__
template <typename T>
__device__ INLINEDEF Nd4jLong *cuMalloc(Nd4jLong *buffer, long size, UnifiedSharedMemory *manager) {
// if we go for 3 dimensions coord space or below - just use shared memory for that
if (size <= MAX_COORD * 4) {
Nd4jLong *ptr = new Nd4jLong[size / 4];//manager->getSharedCoordBuffer() + (threadIdx.x * MAX_COORD);
return ptr;
} else {
// otherwise go to preallocated global memory :(
int tid = blockIdx.x * blockDim.x + threadIdx.x;
if (tid * size > PREALLOC_SIZE - size) {
return (Nd4jLong *) malloc(size);
} else {
Nd4jLong *ret = buffer;
ret += (tid * size);
return ret;
}
}
}
#endif
#ifdef __CUDACC__
/**
* BEWARE: THIS METHOD DOES NOT CHECKS ALLOCATION BOUNDARIES
*/
__device__ INLINEDEF Nd4jLong *cuMalloc(Nd4jLong *buffer, long size) {
Nd4jLong *ret = buffer;
ret += (threadIdx.x * size);
return ret;
}
#endif
/**
* Length of a tad given
* the shape information
*/
INLINEDEF _CUDA_HD int tadLength(Nd4jLong *shapeInfo, int *dimension, int dimensionLength) {
if(dimensionLength == 1) {
return shape::shapeOf(shapeInfo)[dimension[0]];
}
else {
int ret = 1;
for(int i = 0; i < shape::rank(shapeInfo); i++) {
for(int j = 0; j < dimensionLength; j++) {
if(i == dimension[j])
ret *= shape::shapeOf(shapeInfo)[dimension[j]];
}
}
return ret;
}
}
/**
* Tad element wise stride:
* given the inner most dimension (the sorted dimension of the last)
* the element wise stride of the tad (disregarding order) is the
* last dimension's stride.
*
* For a given singular dimension this will just be the only entry.
* For example, given the following c order shape/stride:
* 2,2,3,2
* 12,6,2,1
*
* The tad element wise stride for 3 will be 1.
* For zero it wil be 12
*
* For 2,3 it's 1
*
* Note here that the multi dimensional 2,3 case
* is equivalent to the singular 3 case.
*
*
* Note that this is for the dimension that ultimately
* ends up removed.
*
* Again: this may not preserve ordering of the tad
* but maybe used for reductions.
*/
INLINEDEF _CUDA_HD int tadElementWiseStride(Nd4jLong *shapeInfo, int *dimension,int dimensionLength) {
return reductionIndexElementWiseStride(shapeInfo,dimension,dimensionLength);
}
INLINEDEF _CUDA_HD bool shapeEquals(const int shape1Rank, const Nd4jLong *shape1, const int shape2Rank, const Nd4jLong *shape2) {
if(shape1Rank != shape2Rank)
return false;
//rank not equals
for(int i = 0; i < shape1Rank; i++) {
if(shape1[i] != shape2[i])
return false;
}
return true;
}
INLINEDEF _CUDA_HD bool shapeEquals(const Nd4jLong *shapeInfo1, const Nd4jLong *shapeInfo2) {
return shape::shapeEquals(shape::rank(shapeInfo1), shape::shapeOf(const_cast<Nd4jLong*>(shapeInfo1)), shape::rank(shapeInfo2), shape::shapeOf(const_cast<Nd4jLong*>(shapeInfo2)));
}
INLINEDEF _CUDA_HD bool strideEquals(int shape1Rank,Nd4jLong *shape1,int shape2Rank,Nd4jLong *shape2) {
if(shape1Rank != shape2Rank)
return false;
//rank not equals
for(int i = 0; i < shape1Rank; i++) {
if(shape1[i] != shape2[i])
return false;
}
return true;
}
INLINEDEF _CUDA_HD bool strideEquals(Nd4jLong *shapeInfo1,Nd4jLong *shapeInfo2) {
return shape::strideEquals(shape::rank(shapeInfo1),shape::stride(shapeInfo1),shape::rank(shapeInfo2),shape::stride(shapeInfo2));
}
INLINEDEF _CUDA_HD bool strideEquals(Nd4jLong *stride1,int rank1 , Nd4jLong *stride2, int rank2) {
if(rank1 != rank2)
return false;
for(int i = 0; i < rank1; i++) {
if(stride1[i] != stride2[i])
return false;
}
return true;
}
INLINEDEF _CUDA_HD Nd4jLong *computeResultShape(Nd4jLong *originalShapeBuffer, int* dimension,int dimensionLength) {
Nd4jLong *retShape;
int retShapeLength;
if(dimensionLength == 1 && dimension[0] == 2147483647) {
retShape = new Nd4jLong[2];
retShape[0] = 1;
retShape[1] = 1;
retShapeLength = 2;
}
else {
retShape = shape::removeIndex<Nd4jLong, int>(shape::shapeOf(originalShapeBuffer), dimension, shape::shapeInfoLength(shape::rank(originalShapeBuffer)), dimensionLength);
retShapeLength = shape::rank(originalShapeBuffer) - dimensionLength;
}
//ensure vector is proper shape
if (retShapeLength == 1) {
if (dimension[0] == 0) {
auto newRetShape = new Nd4jLong[2]{1, retShape[0]};
delete[] retShape;
retShape = newRetShape;
retShapeLength = 2;
}
else {
auto newRetShape = new Nd4jLong[2]{retShape[0], 1};
delete[] retShape;
retShape = newRetShape;
retShapeLength = 2;
}
} else if (retShapeLength == 0) {
auto newRetShape = new Nd4jLong[2]{1, 1};
delete[] retShape;
retShape = newRetShape;
retShapeLength = 2;
}
auto ret = shape::shapeBuffer(retShapeLength, nd4j::ArrayOptions::dataType(originalShapeBuffer), retShape);
delete[] retShape;
return ret;
}
INLINEDEF _CUDA_HD Nd4jLong *shapeInfoOnlyShapeAndStride(Nd4jLong *shapeInfo, Nd4jLong *dimension, int dimensionLength,bool reverseCopyStride, Nd4jLong *buffer) {
Nd4jLong *theShape = shape::shapeOf(shapeInfo);
Nd4jLong *theStride = shape::stride(shapeInfo);
int rank = dimensionLength == 1 ? 2 : dimensionLength;
Nd4jLong *ret = buffer;
//set the rank
ret[0] = rank;
Nd4jLong *retShape = shape::shapeOf(ret);
Nd4jLong *retStride = shape::stride(ret);
int len = rank;
if(dimensionLength == 1) {
if(shape::isMatrix(theShape,shape::rank(shapeInfo))) {
if(dimension[0] == 0) {
Nd4jLong newStride[2] = {theStride[dimension[0]],1};
Nd4jLong newShape[2] = {theShape[dimension[0]],1};
retShape[0] = newShape[0];
retShape[1] = newShape[1];
retStride[0] = newStride[0];
retStride[1] = newStride[1];
}
else {
Nd4jLong newStride[2] = {theStride[dimension[0]],1};
Nd4jLong newShape[2] = {theShape[dimension[0]],1};
retShape[0] = newShape[0];
retShape[1] = newShape[1];
retStride[0] = newStride[0];
retStride[1] = newStride[1];
}
}
else {
Nd4jLong newStride[2] = {1,theStride[dimension[0]]};
Nd4jLong newShape[2] = {1,theShape[dimension[0]]};
retShape[0] = newShape[0];
retShape[1] = newShape[1];
retStride[0] = newStride[0];
retStride[1] = newStride[1];
}
}
else {
Nd4jLong *newIndexes = dimension;
if(reverseCopyStride)
shape::reverseCopyTo(theStride, retStride, newIndexes, len);
else
shape::copyTo(len, theStride, retStride, newIndexes);
shape::copyTo(len, theShape, retShape, newIndexes);
}
ret[shape::shapeInfoLength(rank) - 1] = shape::order(shapeInfo);
return ret;
}
INLINEDEF _CUDA_HD Nd4jLong *shapeInfoOnlyShapeAndStride(Nd4jLong *shapeInfo, Nd4jLong *dimension, int dimensionLength,bool reverseCopyStride) {
int rank = dimensionLength == 1 ? 2 : dimensionLength;
traceNew(4);
Nd4jLong *ret = new Nd4jLong[shape::shapeInfoLength(rank)];
return shapeInfoOnlyShapeAndStride(shapeInfo, dimension, dimensionLength, reverseCopyStride, ret);
}
INLINEDEF _CUDA_HD Nd4jLong * createShapeInfo(Nd4jLong *shape, Nd4jLong *stride, int rank) {
traceNew(5);
Nd4jLong *ret = new Nd4jLong[shape::shapeInfoLength(rank)];
return createShapeInfo(shape, stride, rank, ret);
}
INLINEDEF _CUDA_HD Nd4jLong * createShapeInfo(Nd4jLong *shape, Nd4jLong *stride, int rank, Nd4jLong *buffer) {
buffer[0] = rank;
Nd4jLong *retShape = shape::shapeOf(buffer);
Nd4jLong *retStride = shape::stride(buffer);
for(int i = 0;i < rank; i++) {
retShape[i] = shape[i];
retStride[i] = stride[i];
}
return buffer;
}
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
INLINEDEF _CUDA_HD Nd4jLong * calcStridesFortran(Nd4jLong *shape, int rank, int startNum) {
if (isVector(shape, rank)) {
traceNew(5);
Nd4jLong *ret = new Nd4jLong[2];
for (int i = 0; i < 2; i++)
ret[i] = 1;
return ret;
}
int dimensions = rank;
traceNew(6);
Nd4jLong *stride = new Nd4jLong[dimensions];
int st = startNum;
for (int j = 0; j < rank; j++) {
stride[j] = st;
st *= shape[j];
}
return stride;
}
INLINEDEF _CUDA_HD Nd4jLong * calcStridesFortran(Nd4jLong *shape, int rank, int startNum, Nd4jLong *ret) {
if (isVector(shape, rank)) {
for (int i = 0; i < 2; i++)
ret[i] = 1;
return ret;
}
int dimensions = rank;
int st = startNum;
for (int j = 0; j < rank; j++) {
ret[j] = st;
st *= shape[j];
}
return ret;
}
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
INLINEDEF _CUDA_HD Nd4jLong * calcStrides(Nd4jLong *shape, int rank, int startNum) {
traceNew(7);
Nd4jLong *stride = new Nd4jLong[rank];
if (rank == 1) {
stride[0] = 1;
return stride;
}
// if (shape::isVector(shape, rank)) {
// for (int i = 0; i < 2; i++)
// stride[i] = 1;
// return stride;
// }
int st = startNum;
for (int j = rank - 1; j >= 0; j--) {
stride[j] = st;
st *= shape[j];
}
return stride;
}
INLINEDEF _CUDA_HD Nd4jLong * calcStrides(Nd4jLong *shape, int rank, int startNum, Nd4jLong* ret) {
if (rank == 1) {
ret[0] = 1;
return ret;
}
// if (shape::isVector(shape, rank)) {
// for (int i = 0; i < 2; i++)
// ret[i] = 1;
// return ret;
// }
int st = startNum;
for (int j = rank - 1; j >= 0; j--) {
ret[j] = st;
st *= shape[j];
}
return ret;
}
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
INLINEDEF _CUDA_HD Nd4jLong * calcStridesFortran(Nd4jLong *shape, int rank) {
return calcStridesFortran(shape, rank, 1);
}
INLINEDEF _CUDA_HD Nd4jLong * calcStridesFortran(Nd4jLong *shape, int rank, Nd4jLong* ret) {
return calcStridesFortran(shape, rank, 1, ret);
}
/**
* Computes the standard packed array strides for a given shape.
*
* @param shape the shape of a matrix:
* @param startNum the start number for the strides
* @return the strides for a matrix of n dimensions
*/
INLINEDEF _CUDA_HD Nd4jLong* calcStrides(Nd4jLong *shape, int rank) {
return calcStrides(shape, rank, 1);
}
INLINEDEF _CUDA_HD Nd4jLong* calcStrides(Nd4jLong *shape, int rank, Nd4jLong* ret) {
return calcStrides(shape, rank, 1, ret);
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD void updateStrides(Nd4jLong *shapeInfo, const char order) {
int rank = shapeInfo[0];
int doubleRank = 2*rank;
if (rank > 0) {
if (order == 'c') {
shapeInfo[doubleRank] = 1; // set unity as last stride for c order
for (int j = 1; j < rank; ++j) {
shapeInfo[doubleRank - j] = shapeInfo[doubleRank - j + 1] * shapeInfo[rank + 1 - j];
}
} else {
shapeInfo[rank + 1] = 1; // set unity as first stride for f order
for (int j = rank + 1; j < doubleRank; ++j) {
shapeInfo[j + 1] = shapeInfo[j] * shapeInfo[j - rank];
}
}
}
// set last 2 elements in shapeInfo
shapeInfo[doubleRank + 2] = 1;
shapeInfo[doubleRank + 3] = (int)order;
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD void updateStrides(const int rank, const Nd4jLong *shapeOnly, Nd4jLong *stridesOnly, const char order) {
if (rank > 0) {
if (order == 'c') {
stridesOnly[rank - 1] = 1; // set unity as last stride for c order
for (int j = 1; j < rank; ++j)
stridesOnly[rank - 1 - j] = stridesOnly[rank - j] * shapeOnly[rank - j];
}
else {
stridesOnly[0] = 1; // set unity as first stride for f order
for (int j = 1; j < rank; ++j) {
stridesOnly[j] = stridesOnly[j - 1] * shapeOnly[j - 1];
}
}
}
}
// check whether input dimensions are permuted, not permuted dimensions order have to be 0,....,rank-1
template <typename T>
INLINEDEF _CUDA_HD bool isDimPermuted(const T* dimensions, const Nd4jLong dimSize ) {
for(int i=0; i<dimSize-1; ++i)
if(dimensions[i] > dimensions[i+1])
return true;
return false;
}
/**
* @param toCopy the shape to copy
* @return a copy of the original struct
*/
INLINEDEF _CUDA_HD ShapeInformation *shapeCopy( ShapeInformation *toCopy) {
auto copy = new ShapeInformation;
traceNew(8);
copy->shape = new Nd4jLong[toCopy->rank];
memcpy(copy->shape, toCopy->shape, toCopy->rank * sizeof(Nd4jLong));
traceNew(9);
copy->stride = new Nd4jLong[toCopy->rank];
for (int i = 0; i < toCopy->rank; i++) {
copy->stride[i] = toCopy->stride[i];
}
copy->order = toCopy->order;
copy->rank = toCopy->rank;
copy->offset = toCopy->offset;
copy->elementWiseStride = toCopy->elementWiseStride;
return copy;
}
INLINEDEF _CUDA_HD int computeElementWiseStride(int rank, Nd4jLong *shape, Nd4jLong *stride, int isFOrder) {
if (rank == 0)
return 1;
if(shape::isVector(shape,rank)) {
return stride[rank - 1];
}
else {
int oldnd;
Nd4jLong *oldDims = shape::copyOf(rank, shape);
Nd4jLong *oldStrides = shape::copyOf(rank, stride);
int np, op, last_stride;
int oldStart, oldStop, ok, newStart, newStop, nk;
traceNew(10);
auto newStrides = new Nd4jLong[rank];
oldnd = 0;
//set the shape to be 1 x length
int newShapeRank = 2;
auto newShape = new Nd4jLong[newShapeRank];
newShape[0] = 1;
newShape[1] = shape::prodLong(shape, rank);
/*
* Remove axes with dimension 1 from the old array. They have no effect
* but would need special cases since their strides do not matter.
*/
for (oldStart = 0; oldStart < rank; oldStart++) {
if (shape[oldStart] != 1) {
oldDims[oldnd] = shape[oldStart];
oldStrides[oldnd] = stride[oldStart];
oldnd++;
}
}
np = 1;
for (newStart = 0; newStart < newShapeRank; newStart++) {
np *= newShape[newStart];
}
op = 1;
for (oldStart = 0; oldStart < oldnd; oldStart++) {
op *= oldDims[oldStart];
}
if (np != op) {
/* different total sizes; no hope */
delete[] newStrides;
delete[] newShape;
delete[] oldStrides;
delete[] oldDims;
return 0;
}
if (np == 0) {
/* the current code does not handle 0-sized arrays, so give up */
delete[] newStrides;
delete[] newShape;
delete[] oldStrides;
delete[] oldDims;
return 0;
}
/* oldStart to oldStop and newStart to newStop give the axis ranges currently worked with */
oldStart = 0;
oldStop = 1;
newStart = 0;
newStop = 1;
while (newStart < newShapeRank && oldStart < oldnd) {
np = newShape[newStart];
op = oldDims[oldStart];
while (np != op) {
if (np < op) {
/* Misses trailing 1s, these are handled later */
np *= newShape[newStop++];
} else {
op *= oldDims[oldStop++];
}
}
/* Check whether the original axes can be combined */
for (ok = oldStart; ok < oldStop - 1; ok++) {
if (isFOrder) {
if (oldStrides[ok + 1] != oldDims[ok] * oldStrides[ok]) {
/* not contiguous enough */
delete[] newStrides;
delete[] newShape;
delete[] oldStrides;
delete[] oldDims;
return 0;
}
} else {
/* C order */
if (oldStrides[ok] != oldDims[ok + 1] * oldStrides[ok + 1]) {
/* not contiguous enough */
delete[] newStrides;
delete[] newShape;
delete[] oldStrides;
delete[] oldDims;
return 0;
}
}
}
/* Calculate new strides for all axes currently worked with */
if (isFOrder) {
newStrides[newStart] = oldStrides[oldStart];
for (nk = newStart + 1; nk < newStop; nk++) {
newStrides[nk] = newStrides[nk - 1] * newShape[nk - 1];
}
} else {
/* C order */
newStrides[newStop - 1] = oldStrides[oldStop - 1];
for (nk = newStop - 1; nk > newStart; nk--) {
newStrides[nk - 1] = newStrides[nk] * newShape[nk];
}
}
newStart = newStop++;
oldStart = oldStop++;
}
/*
* Set strides corresponding to trailing 1s of the new shape.
*/
if (newStart >= 1) {
last_stride = newStrides[newStart - 1];
} else {
last_stride = stride[rank - 1];
}
if (isFOrder) {
if (newStart >= 1)
last_stride *= newShape[newStart - 1];
}
for (nk = newStart; nk < newShapeRank; nk++) {
newStrides[nk] = last_stride;
}
//returns the last element of the new stride array
int ret = last_stride;
delete[] newStrides;
delete[] newShape;
delete[] oldStrides;
delete[] oldDims;
return ret;
}
}
INLINEDEF _CUDA_HD int computeElementWiseStride(int rank, Nd4jLong *shape, Nd4jLong *stride, int isFOrder,
Nd4jLong *dimension, int dimensionLength) {
if(dimensionLength == 1) {
return stride[dimension[0]];
}
return 0;
}
/**
* Get the shape info buffer
* for the given rank and shape.
*/
INLINEDEF _CUDA_HD Nd4jLong *shapeBuffer(int rank, nd4j::DataType dtype, Nd4jLong *shape) {
Nd4jLong *stride = shape::calcStrides(shape, rank);
traceNew(11);
auto shapeInfo = new shape::ShapeInformation();
shapeInfo->shape = shape;
shapeInfo->stride = stride;
shapeInfo->offset = 0;
shapeInfo->rank = rank;
int elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0);
shapeInfo->order = 'c';
shapeInfo->elementWiseStride = elementWiseStride;
auto shapeInfoBuffer = shape::toShapeBuffer(shapeInfo);
delete[] stride;
delete shapeInfo;
nd4j::ArrayOptions::setDataType(shapeInfoBuffer, dtype);
return shapeInfoBuffer;
}
/**
* This is special method, it returns ONLY 2D shapebuffer.
*
* This method is used only for SoftMax
*/
INLINEDEF _CUDA_HD Nd4jLong *shapeBuffer(int rank, nd4j::DataType dtype, Nd4jLong *shape, Nd4jLong *buffer) {
Nd4jLong stride[MAX_RANK];
shape::calcStrides(shape,rank, stride);
shape::ShapeInformation shapeInfo;
shapeInfo.shape = shape;
shapeInfo.stride = stride;
shapeInfo.offset = 0;
shapeInfo.rank = rank;
auto elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0);
shapeInfo.order = 'c';
shapeInfo.elementWiseStride = elementWiseStride;
shape::toShapeBuffer(&shapeInfo, buffer);
nd4j::ArrayOptions::setDataType(buffer, dtype);
return buffer;
}
/**
* Get the shape info buffer
* for the given rank and shape.
*/
INLINEDEF _CUDA_HD Nd4jLong *shapeBufferFortran(int rank, nd4j::DataType dtype, Nd4jLong *shape) {
auto stride = shape::calcStridesFortran(shape,rank);
traceNew(12);
auto shapeInfo = new shape::ShapeInformation();
shapeInfo->shape = shape;
shapeInfo->stride = stride;
shapeInfo->offset = 0;
shapeInfo->rank = rank;
int elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0);
shapeInfo->order = 'f';
shapeInfo->elementWiseStride = elementWiseStride;
auto shapeInfoBuffer = shape::toShapeBuffer(shapeInfo);
delete[] stride;
delete shapeInfo;
nd4j::ArrayOptions::setDataType(shapeInfoBuffer, dtype);
return shapeInfoBuffer;
}
INLINEDEF _CUDA_HD Nd4jLong *shapeBufferFortran(int rank, nd4j::DataType dtype, Nd4jLong *shape, Nd4jLong *output) {
Nd4jLong stride[MAX_RANK];
shape::calcStridesFortran(shape,rank, stride);
shape::ShapeInformation shapeInfo;
shapeInfo.shape = shape;
shapeInfo.stride = stride;
shapeInfo.offset = 0;
shapeInfo.rank = rank;
auto elementWiseStride = shape::computeElementWiseStride(rank, shape, stride, 0);
shapeInfo.order = 'f';
shapeInfo.elementWiseStride = elementWiseStride;
shape::toShapeBuffer(&shapeInfo, output);
nd4j::ArrayOptions::setDataType(output, dtype);
return output;
}
/**
* Compute the real linear indices for the given shape and stride
*/
INLINEDEF _CUDA_HD Nd4jLong *computeIndices(int rank, Nd4jLong *shape, Nd4jLong *stride) {
Nd4jLong length = shape::prodLong(shape,rank);
traceNew(13);
Nd4jLong *ret = new Nd4jLong[length];
for(int i = 0; i < length; i++) {
Nd4jLong *idx = shape::ind2sub(rank, shape, i);
ret[i] = shape::getOffset(0, shape, stride, idx, rank);
delete[] idx;
}
return ret;
}
/**
* Compute the real linear indices for the given shape and stride
*/
INLINEDEF _CUDA_HD Nd4jLong *computeIndices(Nd4jLong *shapeBuffer) {
return computeIndices(shape::rank(shapeBuffer),shape::shapeOf(shapeBuffer),shape::stride(shapeBuffer));
}
/**
* Convert the given index (such as 1,1)
* to a linear index
* @param shape the shape of the indexes to convert
* @param indices the index to convert
* @return the linear index given the shape
* and indices
*/
INLINEDEF _CUDA_HD Nd4jLong sub2Ind(const int rank, const Nd4jLong *shape, const Nd4jLong *indices) {
Nd4jLong index = indices[rank-1];
Nd4jLong shift = 1;
for(int i = rank-2; i >= 0; --i) {
shift *= shape[i+1];
index += shift * indices[i];
}
return index;
}
template <typename T>
INLINEDEF _CUDA_HD void fill(T* buffer, T value, Nd4jLong length) {
PRAGMA_OMP_SIMD
for (int e = 0; e < length; e++)
buffer[e] = value;
}
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD Nd4jLong* ind2sub(int rank, Nd4jLong *shape, Nd4jLong index, Nd4jLong numIndices) {
auto ret = new Nd4jLong[rank];
ind2sub(rank, shape, index, numIndices, ret);
return ret;
}
/**
* Convert a linear index to
* the equivalent nd index.
* Infers the number of indices from the specified shape.
*
* @param shape the shape of the dimensions
* @param index the index to map
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD Nd4jLong* ind2sub(int rank, Nd4jLong *shape, Nd4jLong index) {
return ind2sub(rank,shape, index, shape::prodLong(shape,rank));
}
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD void ind2sub(int rank, Nd4jLong *shape, Nd4jLong index, Nd4jLong numIndices, Nd4jLong *ret) {
int denom = numIndices;
for(int i = rank - 1; i >= 0; i--) {
denom /= shape[i];
ret[i] = index / denom;
index %= denom;
}
}
/**
* Convert a linear index to
* the equivalent nd index.
* Infers the number of indices from the specified shape.
*
* @param shape the shape of the dimensions
* @param index the index to map
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD void ind2sub(int rank,Nd4jLong *shape, Nd4jLong index, Nd4jLong *out) {
ind2sub(rank,shape, index, shape::prodLong(shape,rank),out);
}
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD Nd4jLong * ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index, Nd4jLong numIndices) {
auto ret = new Nd4jLong[rank];
ind2subC(rank, shape, index, numIndices, ret);
return ret;
}
/**
* Convert a linear index to
* the equivalent nd index.
* Infers the number of indices from the specified shape.
*
* @param shape the shape of the dimensions
* @param index the index to map
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD Nd4jLong *ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index) {
return ind2subC(rank,shape, index, shape::prodLong(shape,rank));
}
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param arrLen the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD void ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index, Nd4jLong arrLen, Nd4jLong *ret) {
for(int i = 0; i < rank; i++) {
arrLen /= shape[i];
if(arrLen > 0) {
ret[i] = index / arrLen;
index %= arrLen;
}
else
ret[i] = 0;
}
}
/**
* Convert a linear index to
* the equivalent nd index.
* Infers the number of indices from the specified shape.
*
* @param shape the shape of the dimensions
* @param index the index to map
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD void ind2subC(const int rank, const Nd4jLong *shape, Nd4jLong index, Nd4jLong *out) {
ind2subC(rank,shape, index,shape::prodLong(shape,rank),out);
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD Nd4jLong getIndexOffset(Nd4jLong index, const Nd4jLong *shapeInfo, Nd4jLong arrLen) {
const Nd4jLong ews = shapeInfo[shapeInfo[0] + shapeInfo[0] + 2];
if(ews > 0 && order(shapeInfo) == 'c')
if (ews == 1)
return index;
else
return ews * index;
Nd4jLong offset = 0;
for(int i = 1; i <= shapeInfo[0]; ++i) {
arrLen /= shapeInfo[i];
if(arrLen > 0 && shapeInfo[i] > 1) {
offset += (index / arrLen) * shapeInfo[i + shapeInfo[0]];
index %= arrLen;
}
}
return offset;
}
INLINEDEF _CUDA_HD uint getIndexOffset(uint index, const uint *shapeInfo, uint arrLen) {
const uint rank = shapeInfo[0];
const uint ews = shapeInfo[rank + rank + 2];
if(ews > 0 && shapeInfo[rank + rank + 3] == 99)
if (ews == 1)
return index;
else
return ews * index;
uint offset = 0;
for(uint i = 1; i <= rank; ++i) {
arrLen /= shapeInfo[i];
if(arrLen > 0 && shapeInfo[i] > 1) {
offset += (index / arrLen) * shapeInfo[i + rank];
index %= arrLen;
}
}
return offset;
}
INLINEDEF _CUDA_HD Nd4jLong indexOffset(Nd4jLong index, const Nd4jLong* lShapeInfo, const uint* uShapeInfo, Nd4jLong arrLen, const bool useUnsigned) {
if(useUnsigned)
return getIndexOffset(static_cast<uint>(index), uShapeInfo, static_cast<uint>(arrLen));
return getIndexOffset(index, lShapeInfo, arrLen);
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD Nd4jLong getIndexOrderOffset(Nd4jLong index, const Nd4jLong *shapeInfo, Nd4jLong arrLen, const char order) {
Nd4jLong offset = 0;
if(order == 'c') {
for(int i = 1; i <= *shapeInfo; ++i) {
arrLen /= shapeInfo[i];
if(arrLen > 0 && shapeInfo[i] > 1) {
offset += (index / arrLen) * shapeInfo[i + *shapeInfo];
index %= arrLen;
}
}
}
else {
for(int i = *shapeInfo; i >= 1 ; --i) {
arrLen /= shapeInfo[i];
if(arrLen > 0 && shapeInfo[i] > 1) {
offset += (index / arrLen) * shapeInfo[i + *shapeInfo];
index %= arrLen;
}
}
}
return offset;
}
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD void ind2subOrder(Nd4jLong *shapeInfo, Nd4jLong index, Nd4jLong numIndices, Nd4jLong *out) {
if(shape::order(shapeInfo) == 'f') {
shape::ind2sub(
shape::rank(shapeInfo),
shape::shapeOf(shapeInfo),
index,
numIndices,
out);
}
else {
shape::ind2subC(
shape::rank(shapeInfo),
shape::shapeOf(shapeInfo),
index,
numIndices,
out);
}
}
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
INLINEDEF _CUDA_HD void ind2subOrder(Nd4jLong *shapeInfo, Nd4jLong index, Nd4jLong *out) {
ind2subOrder(shapeInfo,index,shape::length(shapeInfo),out);
}
/**
* Convert a linear index to
* the equivalent nd index
* @param shape the shape of the dimensions
* @param index the index to map
* @param numIndices the number of total indices (typically prod of shape(
* @return the mapped indexes along each dimension
*/
/**
*
* @param length
* @param shape
* @param rearrange
* @return
*/
INLINEDEF _CUDA_HD Nd4jLong *doPermuteSwap(int length, Nd4jLong *shape, int *rearrange) {
traceNew(16);
Nd4jLong *ret = new Nd4jLong[length];
for (int i = 0; i < length; i++) {
ret[i] = shape[rearrange[i]];
}
return ret;
}
/**
*
* @param length
* @param shape
* @param rearrange
* @return
*/
INLINEDEF _CUDA_HD void doPermuteSwap(int length, Nd4jLong **shape, int *rearrange) {
if(length == 1) {
return;
}
else {
Nd4jLong *shapeDeref = *shape;
if(shape::prodLong(shapeDeref,length) < 2) {
return;
}
}
bool inOrder = true;
for(int i = 0; i < length - 1; i++) {
inOrder = inOrder && rearrange[i] + 1 == rearrange[i + 1];
}
//all in order, nothing to do
if(inOrder)
return;
Nd4jLong *shapeDeref = *shape;
//we know they are just reversed, dimension length of 2
if(length == 2) {
auto shapeFirst = shapeDeref[0];
auto shapeSecond = shapeDeref[1];
shapeDeref[0] = shapeSecond;
shapeDeref[1] = shapeFirst;
return;
}
else if(length == 1) {
//no permute
return;
}
auto temp = new Nd4jLong[length];
memcpy(temp,shapeDeref,sizeof(Nd4jLong) * length);
for (int i = 0; i < length; i++) {
shapeDeref[i] = temp[rearrange[i]];
}
delete[] temp;
}
INLINEDEF _CUDA_HD void permuteShapeBufferInPlace(Nd4jLong *shapeBuffer, int *rearrange, Nd4jLong *out) {
if(shapeBuffer != out)
memcpy(out,shapeBuffer,sizeof(Nd4jLong) * shape::shapeInfoLength(shape::rank(shapeBuffer)));
doPermuteShapeBuffer(shape::rank(shapeBuffer), shapeBuffer, rearrange, out);
}
INLINEDEF _CUDA_HD Nd4jLong *permuteShapeBuffer(Nd4jLong *shapeBuffer, int* rearrange) {
auto len = shape::shapeInfoLength(shape::rank(shapeBuffer));
Nd4jLong *copy = shape::copyOf(len, shapeBuffer);
doPermuteShapeBuffer(copy,rearrange);
return copy;
}
INLINEDEF _CUDA_HD void doPermuteShapeInfo(Nd4jLong *shapeInfo, const Nd4jLong *rearrange) {
const int rank = shape::rank(shapeInfo);
//check whether shape is like {1} or {1,1} or {1,1,1,1,...} - in this case we don't need permute
if(prodLong(shape::shapeOf(shapeInfo), rank) < 2)
return;
// check whether rearrange is like {0,1,2,3,...} - in this case we don't need permute as well
bool isPermutNecessary = false;
for(int i = 0; i < rank; ++i)
if(rearrange[i] != i) {
isPermutNecessary = true;
break;
}
if(!isPermutNecessary)
return;
// check whether rearrange contains correct indexes
for(int i = 0; i < rank; ++i)
if(rearrange[i] >= rank || rearrange[i] < 0) {
printf("shape::doPermuteShapeInfo function failed: rearrange indexes are incorrect !\n");
return;
}
// if everything is ok then perform permute
auto temp = new Nd4jLong[shape::shapeInfoLength(rank)];
memcpy(temp, shapeInfo, sizeof(Nd4jLong) * shape::shapeInfoLength(rank));
for (int i = 0; i < rank; ++i) {
shapeInfo[i + 1] = temp[rearrange[i] + 1];
shapeInfo[i + 1 + rank] = temp[rearrange[i] + 1 + rank];
}
shapeInfo[2 * rank + 2] = 0; // ews
shapeInfo[2 * rank + 3] = shape::getOrder(rank, shape::shapeOf(shapeInfo),shape::stride(shapeInfo),1); // order
delete[] temp;
}
INLINEDEF _CUDA_HD void doPermuteShapeInfo(Nd4jLong *shapeInfo, const int* rearrange) {
const int rank = shape::rank(shapeInfo);
//check whether shape is like {1} or {1,1} or {1,1,1,1,...} - in this case we don't need permute
if(prodLong(shape::shapeOf(shapeInfo), rank) < 2)
return;
// check whether rearrange is like {0,1,2,3,...} - in this case we don't need permute as well
bool isPermutNecessary = false;
for(int i = 0; i < rank; ++i)
if(rearrange[i] != i) {
isPermutNecessary = true;
break;
}
if(!isPermutNecessary)
return;
// check whether rearrange contains correct indexes
for(int i = 0; i < rank; ++i)
if(rearrange[i] >= rank || rearrange[i] < 0) {
printf("shape::doPermuteShapeInfo function failed: rearrange indexes are incorrect !\n");
return;
}
// if everything is ok then perform permute
auto temp = new Nd4jLong[shape::shapeInfoLength(rank)];
memcpy(temp, shapeInfo, sizeof(Nd4jLong) * shape::shapeInfoLength(rank));
for (int i = 0; i < rank; ++i) {
shapeInfo[i + 1] = temp[rearrange[i] + 1];
shapeInfo[i + 1 + rank] = temp[rearrange[i] + 1 + rank];
}
shapeInfo[shapeInfoLength(rank) - 2] = 0;
shapeInfo[shape::shapeInfoLength(rank) - 1] = shape::getOrder(rank, shape::shapeOf(shapeInfo),shape::stride(shapeInfo), 1);
delete[] temp;
}
INLINEDEF _CUDA_HD void doPermuteShapeBuffer(Nd4jLong *shapeBuffer,int *rearrange) {
//no swapping needs to happen
if(shape::isScalar(shapeBuffer)) {
return;
}
Nd4jLong *shapeRef = shapeBuffer;
//rank of the rearrange array == rank of shape buffer
int rearrageRank = shape::rank(shapeRef);
Nd4jLong *shape = shape::shapeOf(shapeRef);
Nd4jLong *stride = shape::stride(shapeRef);
shape::doPermuteSwap(rearrageRank,&shape,rearrange);
shape::doPermuteSwap(rearrageRank,&stride,rearrange);
shapeRef[shapeInfoLength(rearrageRank) - 2] = 0;
shapeRef[shape::shapeInfoLength(rearrageRank) - 1] = shape::getOrder(rearrageRank,shape,stride,1);
// doPermuteShapeInfo(shapeBuffer, rearrange); // possible fix of integer overflow issue when strides are too large
}
/*
INLINEDEF _CUDA_HD void doPermuteShapeBuffer(Nd4jLong *shapeBuffer, int *rearrange, Nd4jLong *tmpBuffer) {
auto shapeRef = shapeBuffer;
//rank of the rearrange array == rank of shape buffer
int rearrageRank = shape::rank(shapeRef);
auto shape = shape::shapeOf(shapeRef);
auto stride = shape::stride(shapeRef);
shape::copyOf(rearrageRank,rearrange, tmpBuffer);
shape::doPermuteSwap(rearrageRank,&shape, tmpBuffer);
shape::copyOf(rearrageRank,rearrange, tmpBuffer);
shape::doPermuteSwap(rearrageRank,&stride,tmpBuffer);
shapeRef[shapeInfoLength(rearrageRank) - 2] = 0;
shapeRef[shape::shapeInfoLength(rearrageRank) - 1] = shape::getOrder(rearrageRank,shape,stride,1);
}
*/
INLINEDEF _CUDA_HD void doPermuteShapeBuffer(int rank,Nd4jLong *shapeBuffer, int *rearrange) {
Nd4jLong *shapeRef = shapeBuffer;
//rank of the rearrange array == rank of shape buffer
int rearrageRank = rank;
Nd4jLong *shape = shape::shapeOf(shapeRef);
Nd4jLong *stride = shape::stride(shapeRef);
auto rearrangeCopy1 = shape::copyOf(rearrageRank, rearrange);
shape::doPermuteSwap(rearrageRank,&shape,rearrangeCopy1);
delete[] rearrangeCopy1;
auto rearrangeCopy2 = shape::copyOf(rearrageRank,rearrange);
shape::doPermuteSwap(rearrageRank, &stride, rearrangeCopy2);
shapeBuffer[shape::shapeInfoLength(rank) - 1] = shape::getOrder(rank,shape,stride,1);
shapeBuffer[shape::shapeInfoLength(rank) - 2] = 0;
delete[] rearrangeCopy2;
}
INLINEDEF _CUDA_HD void doPermuteShapeBuffer(int rank, Nd4jLong *shapeBuffer, int *rearrange, Nd4jLong *tmpBuffer) {
Nd4jLong *shapeRef = shapeBuffer;
//rank of the rearrange array == rank of shape buffer
int rearrageRank = rank;
auto shape = shape::shapeOf(shapeRef);
auto stride = shape::stride(shapeRef);
if(shapeBuffer != tmpBuffer)
shape::copyOf(rearrageRank,shapeBuffer, tmpBuffer);
shape::doPermuteSwap(rearrageRank,&shape,rearrange);
shape::doPermuteSwap(rearrageRank,&stride,rearrange);
shapeRef[shapeInfoLength(rank) - 2] = 0;
shapeRef[shape::shapeInfoLength(rank) - 1] = shape::getOrder(rank,shape,stride,1);
}
INLINEDEF _CUDA_HD Nd4jLong *createPermuteIndexes(int originalRank, int *dimension,int dimensionLength) {
int delta = originalRank - dimensionLength;
traceNew(17);
Nd4jLong *ret = new Nd4jLong[originalRank];
for(int i = 0; i < delta; i++) {
ret[i] = i + dimensionLength;
}
for(int i = delta; i < originalRank; i++) {
ret[i] = i - delta;
}
return ret;
}
/**
* Get the ordering for the device
* @param length
* @param shape
* @param stride
* @param elementStride
* @return
*/
INLINEDEF _CUDA_HD char getOrder(int length, Nd4jLong *shape, Nd4jLong *stride, int elementStride) {
int sd = -1;
int dim = -1;
int i = -1;
int cContiguous = 1;
int isFortran = 1;
sd = 1;
for (i = length - 1; i >= 0; --i) {
dim = shape[i];
if (stride[i] != sd) {
cContiguous = 0;
break;
}
/* contiguous, if it got this far */
if (dim == 0) {
break;
}
sd *= dim;
}
/* check if fortran contiguous */
sd = elementStride;
for (i = 0; i < length; ++i) {
dim = shape[i];
if (stride[i] != sd) {
isFortran = 0;
}
if (dim == 0) {
break;
}
sd *= dim;
}
if (isFortran && cContiguous)
return 'a';
else if (isFortran && !cContiguous)
return 'f';
else if (!isFortran && !cContiguous)
return 'c';
else
return 'c';
}
/**
* Ensure that every value in the re arrange
* array is unique
* @param arr
* @param shape
* @param arrLength
* @param shapeLength
* @return
*/
template <typename T>
INLINEDEF _CUDA_HD int checkArrangeArray(T *arr, int arrLength, int shapeLength) {
if (arrLength != shapeLength)
return -1;
for (int i = 0; i < arrLength; i++) {
if (arr[i] >= arrLength || arr[i] < 0)
return -1;
}
for (int i = 0; i < arrLength; i++) {
for (int j = 0; j < arrLength; j++) {
if (i != j && arr[i] == arr[j])
return -1;
}
}
return 1;
}
INLINEDEF _CUDA_HD void traceNew(int id) {
//printf("new happened: [%i]\n", id);
#ifndef __CUDACC__
//fflush(stdout);
#endif
}
/**
* Permute the shape information
* @param info the shape information to permute
* @param rearrange the order to re arrange
* @param rank the rank of the rearrange array
*/
INLINEDEF _CUDA_HD void permute(ShapeInformation **info, int *rearrange, int rank) {
ShapeInformation *infoDeref = *info;
checkArrangeArray(rearrange, rank, rank);
shape::doPermuteSwap(rank, &infoDeref->shape, rearrange);
shape::doPermuteSwap(rank, &infoDeref->stride, rearrange);
char order = getOrder(rank,
infoDeref->shape,
infoDeref->stride,
infoDeref->elementWiseStride);
infoDeref->order = order;
}
/**
* Returns whether the
* given shape is a vector or not
* @param shape the shape of the array
* @param rank the rank of the shape
*/
INLINEDEF _CUDA_HD int isVector(Nd4jLong *shape, int rank) {
if (rank == 0)
return 0;
if (rank == 1)
return 1;
if (rank > 2)
return 0;
else if (rank <= 2) {
if (shape[0] == 1 || shape[1] == 1)
return 1;
}
return 0;
}
INLINEDEF _CUDA_HD bool isLikeVector(Nd4jLong *shapeInfo, int& posOfNonUnityDim) {
int numOfNonUnity = 0;
for(int i = 1; i <= shapeInfo[0]; ++i) {
if(shapeInfo[i] != 1) {
++numOfNonUnity;
posOfNonUnityDim = i-1;
}
}
return numOfNonUnity == 1 && shapeInfo[0] > 2;
}
INLINEDEF _CUDA_HD bool isCommonVector(const Nd4jLong *shapeInfo, int& posOfNonUnityDim) {
if(rank(shapeInfo) > 0 && length(shapeInfo) == 1)
return true;
int numOfNonUnity = 0;
for(int i = 1; i <= shapeInfo[0]; ++i) {
if(shapeInfo[i] != 1) {
++numOfNonUnity;
posOfNonUnityDim = i-1;
}
}
return numOfNonUnity == 1;
}
INLINEDEF _CUDA_H Nd4jLong* detachShape(Nd4jLong *originalShape) {
Nd4jLong *newShape = new Nd4jLong[shape::shapeInfoLength(originalShape)];
memcpy(newShape, originalShape, shape::shapeInfoByteLength(originalShape));
return newShape;
}
INLINEDEF _CUDA_H Nd4jLong* copyShape(Nd4jLong *originalShape) {
Nd4jLong *newShape = new Nd4jLong[shape::shapeInfoLength(originalShape)];
memcpy(newShape, originalShape, shape::shapeInfoByteLength(originalShape));
return newShape;
}
INLINEDEF _CUDA_HD int isVector(const Nd4jLong *shapeInfo) {
return isVector(shape::shapeOf(const_cast<Nd4jLong*>(shapeInfo)), shape::rank(shapeInfo));
}
INLINEDEF _CUDA_HD bool isRowVector(const Nd4jLong *shapeInfo) {
bool isVector = shape::isVector(shapeInfo) == 1;
bool shapeFirstOne = shape::shapeOf(const_cast<Nd4jLong*>(shapeInfo))[0] == 1;
return isVector && shapeFirstOne;
}
INLINEDEF _CUDA_HD bool isColumnVector(Nd4jLong *shapeInfo) {
bool isVector = shape::isVector(shapeInfo) == 1;
bool shapeFirstOne = shape::shapeOf(shapeInfo)[0] == 1;
return isVector && !shapeFirstOne;
}
INLINEDEF _CUDA_HD int oneDimEqualToLength(Nd4jLong *shape, int rank) {
for(int i = 0; i < rank; i++) {
if(shape[i] == shape::prod(shape,rank))
return 1;
}
return 0;
}
INLINEDEF _CUDA_HD int oneDimEqualToLength(Nd4jLong *shapeInfo) {
return oneDimEqualToLength(shape::shapeOf(shapeInfo),shape::rank(shapeInfo));
}
/**
* Returns whether the
* given shape is a vector or not
* @param shape the shape of the array
* @param rank the rank of the shape
*/
INLINEDEF _CUDA_HD int isMatrix(Nd4jLong *shape, int rank) {
if (rank > 2)
return 0;
else if (rank <= 2) {
if (shape[0] == 1 || shape[1] == 1)
return 0;
}
return 1;
}
INLINEDEF _CUDA_HD int isMatrix(Nd4jLong *shapeInfo) {
return isMatrix(shape::shapeOf(shapeInfo),shape::rank(shapeInfo));
}
/**
* Returns the shape portion of an information
* buffer
*/
INLINEDEF _CUDA_HD Nd4jLong *shapeOf(Nd4jLong *buffer) {
return buffer + 1;
}
/**
* Return a copy of a buffer.
* This buffer allocates memory
* that must be freed elsewhere.
*/
template <typename T>
INLINEDEF _CUDA_HD T *copyOf(Nd4jLong length, T *toCopy) {
traceNew(18);
T *ret = new T[length];
return copyOf(length, toCopy, ret);
}
template <typename T>
INLINEDEF _CUDA_HD T* copyOf(Nd4jLong length, T *toCopy, T *ret) {
memcpy(ret, toCopy, sizeof(T)*length);
return ret;
}
/**
* Return a copy of a buffer.
* This buffer allocates memory
* that must be freed elsewhere.
*/
template <typename T>
INLINEDEF _CUDA_HD void copyTo(Nd4jLong length, T *from, T *to) {
memcpy(to, from, sizeof(T)*length);
}
/**
* Return a copy of a buffer.
* This buffer allocates memory
* that must be freed elsewhere.
*/
INLINEDEF _CUDA_HD void copyTo(int length, Nd4jLong *from, Nd4jLong *to, Nd4jLong *indexes) {
for(int i = 0; i < length; i++) {
to[i] = from[indexes[i]];
}
}
/**
* Permute the given strides
* in the given rearrange order
* @param toPermute the buffer to permute
* @param shapeRank the length of the buffer to permute
* @param rearrange the rearrange order (must be 0 based indexes
* and all must be filled in)
* @return the rearranged array
*/
/*
INLINEDEF _CUDA_HD Nd4jLong *permutedStrides(Nd4jLong *toPermute, int shapeRank, int *rearrange) {
Nd4jLong *strideCopy = copyOf(shapeRank, toPermute);
checkArrangeArray(rearrange, shapeRank, shapeRank);
Nd4jLong *newStride = doPermuteSwap(shapeRank, strideCopy, rearrange);
delete[] strideCopy;
return newStride;
}
*/
/**
* Return the slice (shape + 1 in pointer arithmetic)
* @param shape the shape to take the slice of
* @return the shape array - the first entry
*/
INLINEDEF _CUDA_HD Nd4jLong *slice(Nd4jLong *shape) {
return shape + 1;
}
INLINEDEF _CUDA_HD int slices(Nd4jLong *shapeBuffer) {
return static_cast<int>(shape::shapeOf(shapeBuffer)[0]);
}
INLINEDEF _CUDA_HD Nd4jLong *sliceOfShapeBuffer(Nd4jLong sliceIdx, Nd4jLong *shapeBuffer) {
int rank = shape::rank(shapeBuffer);
int newRank = rank - 1;
if(newRank < 2)
newRank = 2;
Nd4jLong *newShapeBuffer = new Nd4jLong[shape::shapeInfoLength(newRank)];
newShapeBuffer[0] = newRank;
Nd4jLong *currShape = shape::shapeOf(shapeBuffer);
Nd4jLong *currStride = shape::stride(shapeBuffer);
//initialize new shape and stride by taking the shape and stride + 1
//and adding to the shape information
//a slice is always just taking the existing shape and cutting the first index off
//of the shape and stride
Nd4jLong *newShape = shape::shapeOf(newShapeBuffer);
Nd4jLong *newStride = shape::stride(newShapeBuffer);
if(shape::isVector(shapeBuffer)) {
Nd4jLong *currShape = shape::shapeOf(shapeBuffer);
//row vector: slice index 0 is a valid index, just copy the whole thing
if(currShape[0] == 1) {
if(sliceIdx == 0) {
memcpy(newShapeBuffer,shapeBuffer,shape::shapeInfoByteLength(shape::rank(shapeBuffer)));
return newShapeBuffer;
}
}
//column vector: this will be a scalar
else {
delete[] newShapeBuffer;
Nd4jLong *scalar = shape::createScalarShapeInfo();
int offset = shape::offset(shapeBuffer);
scalar[shape::shapeInfoLength(2) - 3] = offset + sliceIdx;
return scalar;
}
}
else if(shape::isMatrix(shapeBuffer)) {
newShape[0] = 1;
newShape[1] = currShape[1];
newStride[0] = 1;
newStride[1] = currStride[1];
}
else {
for(int i = 0; i < newRank; i++) {
newShape[i] = currShape[i + 1];
newStride[i] = currStride[i + 1];
}
}
auto indices = new Nd4jLong[rank];
memset((void *) indices,0,rank * sizeof(Nd4jLong));
indices[0] = sliceIdx;
Nd4jLong offset = shape::getOffset(0,newShape,newStride,indices,rank);
newShapeBuffer[shape::shapeInfoLength(newRank) - 3] = offset;
if(shape::isMatrix(shapeBuffer)) {
newShapeBuffer[shape::shapeInfoLength(newRank) - 2] = currStride[1];
}
else {
newShapeBuffer[shape::shapeInfoLength(newRank) - 2] = shape::elementWiseStride(shapeBuffer);
}
newShapeBuffer[shape::shapeInfoLength(newRank) - 1] = shape::getOrder(newRank,newShape,newStride,1);
delete[] indices;
return newShapeBuffer;
}
/**
* Returns the length of the
* shape information buffer:
* rank * 2 + 3
* @param rank the rank to get the shape
* info length for
* @return rank * 2 + 4
*/
INLINEDEF _CUDA_HD int shapeInfoLength(int rank) {
//FIXME magic numbers
return rank * 2 + 4;
}
INLINEDEF _CUDA_HD int shapeInfoLength(Nd4jLong* shape) {
return shapeInfoLength(static_cast<int>(shape[0]));
}
INLINEDEF _CUDA_HD int shapeInfoLength(const Nd4jLong* shape) {
return shapeInfoLength(static_cast<int>(shape[0]));
}
INLINEDEF _CUDA_HD size_t shapeInfoByteLength(int rank) {
//FIXME magic numbers
return (rank * 2 + 4) * sizeof(Nd4jLong);
}
INLINEDEF _CUDA_HD size_t shapeInfoByteLength(const Nd4jLong* shapeInfo) {
//FIXME magic numbers
return shapeInfoByteLength((int) shapeInfo[0]);
}
/**
* Returns the rank portion of
* an information buffer
*/
INLINEDEF _CUDA_HD int rank(const Nd4jLong *buffer) {
return static_cast<int>(buffer[0]);
}
INLINEDEF _CUDA_HD int rank(const int *buffer) {
return buffer[0];
}
INLINEDEF _CUDA_HD int rank(const unsigned int *buffer) {
return static_cast<int>(buffer[0]);
}
INLINEDEF _CUDA_HD Nd4jLong* ews(Nd4jLong* shapeInfo) {
return shapeInfo + 2 * shapeInfo[0] + 2;
}
/**
* Converts a raw int buffer of the layout:
* rank
* shape
* stride
* offset
* elementWiseStride
*
* where shape and stride are both straight int pointers
*/
INLINEDEF _CUDA_HD ShapeInformation *infoFromBuffer(Nd4jLong *buffer) {
traceNew(19);
auto info = new ShapeInformation;
auto length = shapeInfoLength(rank(buffer));
auto rank = buffer[0];
//start after rank
info->shape = buffer + 1;
info->stride = buffer + (1 + rank);
info->rank = rank;
info->offset = buffer[length - 3];
info->elementWiseStride = buffer[length - 2];
Nd4jLong *stride = buffer + 1 + rank;
info->stride = stride;
info->order = (char) buffer[length - 1];
return info;
}
/**
* Returns the stride portion of an information
* buffer
*/
INLINEDEF _CUDA_HD Nd4jLong *stride(Nd4jLong *buffer) {
return buffer + (1 + rank(buffer));
}
INLINEDEF _CUDA_HD bool isEmpty(const Nd4jLong *shapeInfo) {
return ((shape::extra(const_cast<Nd4jLong*>(shapeInfo)) & ARRAY_EMPTY) == ARRAY_EMPTY);
}
/**
* Compute the length of the given shape
*/
INLINEDEF _CUDA_HD Nd4jLong length(const Nd4jLong *shapeInfo) {
int rank = shape::rank(shapeInfo);
if (rank == 0) {
if (isEmpty(shapeInfo))
return 0L;
else
return 1L;
}
if (rank == 1)
return shapeInfo[1];
return shape::prodLong(shape::shapeOf(const_cast<Nd4jLong*>(shapeInfo)), rank);
}
INLINEDEF _CUDA_HD Nd4jLong length(std::initializer_list<int>& shape) {
Nd4jLong ret = 1;
for (auto v : shape) {
ret *= v;
}
return ret;
}
INLINEDEF _CUDA_HD Nd4jLong length(std::initializer_list<Nd4jLong>& shape) {
Nd4jLong ret = 1;
for (auto v : shape) {
ret *= v;
}
return ret;
}
/***
* Returns the offset
* portion of an information buffer
*/
INLINEDEF _CUDA_HD Nd4jLong offset(Nd4jLong *buffer) {
return buffer[shape::shapeInfoLength(shape::rank(buffer)) - 3];
}
INLINEDEF _CUDA_HD Nd4jLong& extra(Nd4jLong *buffer) {
return buffer[shape::shapeInfoLength(shape::rank(buffer)) - 3];
}
/**
* Returns the ordering
* for this shape information buffer
*/
INLINEDEF _CUDA_HD char order(const Nd4jLong *buffer) {
//FIXME magic numbers
return static_cast<char>(buffer[(buffer[0] * 2 + 4) - 1]);
}
/**
* Returns type
*/
INLINEDEF _CUDA_HD Nd4jLong type(const Nd4jLong *shapeInfo) {
return shapeInfo[2 * shapeInfo[0] + 1];
}
/**
* Returns the element wise stride for this information
* buffer
*/
INLINEDEF _CUDA_HD Nd4jLong elementWiseStride(const Nd4jLong *buffer) {
return buffer[shapeInfoLength(static_cast<int>(buffer[0])) - 2];
}
/**
* Returns the element wise stride for this information
* buffer relative to a dimension and reduction index
*/
INLINEDEF _CUDA_HD Nd4jLong reductionIndexElementWiseStride(Nd4jLong* buffer, int* dimension, int dimensionLength) {
if(dimensionLength > 1) {
if(shape::order(buffer) == 'f') {
/**
* The element wise stride belongs to a reduction index.
* When used out of order, we can get rid of the data
* dependencies and rely on using the max dimension
* specified for stride instead.
* Say we take the sum(0,1) along arr
* we can use arr.stride(1) as a representation
* along which to iterate.
*/
if(shape::shapeOf(buffer)[dimension[dimensionLength - 1]] != 1) {
//int tadElementWiseStride = shape::stride(buffer)[dimension[dimensionLength - 1]];
//return tadElementWiseStride;
auto tadElementWiseStride = shape::stride(buffer)[dimension[0]];
return tadElementWiseStride;
}
return 1;
}
else {
/**
* The element wise stride belongs to a reduction index.
* When used out of order, we can get rid of the data
* dependencies and rely on using the max dimension
* specified for stride instead.
* Say we take the sum(0,1) along arr
* we can use arr.stride(1) as a representation
* along which to iterate.
*/
if(shape::shapeOf(buffer)[dimension[dimensionLength - 1]] != 1) {
auto tadElementWiseStride = shape::stride(buffer)[dimension[dimensionLength - 1]];
return tadElementWiseStride;
}
return 1;
}
}
else {
if(shape::order(buffer) == 'f') {
/**
* The element wise stride belongs to a reduction index.
* When used out of order, we can get rid of the data
* dependencies and rely on using the max dimension
* specified for stride instead.
* Say we take the sum(0,1) along arr
* we can use arr.stride(1) as a representation
* along which to iterate.
*/
auto tadElementWiseStride = shape::stride(buffer)[dimension[0]];
return tadElementWiseStride;
}
else {
/**
* The element wise stride belongs to a reduction index.
* When used out of order, we can get rid of the data
* dependencies and rely on using the max dimension
* specified for stride instead.
* Say we take the sum(0,1) along arr
* we can use arr.stride(1) as a representation
* along which to iterate.
*/
auto tadElementWiseStride = shape::stride(buffer)[dimension[dimensionLength - 1]];
return tadElementWiseStride;
}
}
}
/**
* Returns whether
* the given shape info buffer
* represents a scalar shape
*/
INLINEDEF _CUDA_HD int isScalar(Nd4jLong *info) {
const int rank = shape::rank(info);
if(rank > 2)
return 0;
if(rank == 0)
return 1;
if(rank == 1)
return shape::shapeOf(info)[0] == 1;
if(rank == 2)
return shape::shapeOf(info)[0] == 1 && shape::shapeOf(info)[1] == 1;
return 0;
}
/**
* Returns whether
* the given shape information
* represents a scalar
* shape or not
*/
INLINEDEF _CUDA_HD int isScalar(volatile ShapeInformation *info) {
const int rank = info->rank;
if(rank > 2)
return 0;
if(rank == 1)
return info->shape[0] == 1;
if(rank == 2)
return info->shape[0] == 1 && info->shape[1] == 1;
return 0;
}
/**
* Return a copy of this array with the
* given index omitted
*
* @param data the data to copy
* @param indexes the index of the item to remove
* @param dataLength the length of the data array
* @param indexesLength the length of the data array
* @return the new array with the omitted
*
* item
*/
template <typename T1, typename T2>
INLINEDEF _CUDA_HD void removeIndex(T1* data, T2 *indexes, Nd4jLong dataLength, Nd4jLong indexesLength, T1 *ret) {
int count = 0;
int absLength = dataLength - indexesLength;
for (int i = 0; i < dataLength && count < absLength; i++) {
int contains = 0;
for (int j = 0; j < indexesLength; j++) {
if (i == indexes[j]) {
contains = 1;
break;
}
}
if (!contains) {
ret[count] = data[i];
count++;
}
}
}
/**
* Return a copy of this array with the
* given index omitted
*
* @param data the data to copy
* @param indexes the index of the item to remove
* @param dataLength the length of the data array
* @param indexesLength the length of the data array
* @return the new array with the omitted
*
* item
*/
template <typename T1, typename T2>
INLINEDEF _CUDA_HD T1* removeIndex(T1 *data, T2 *indexes, Nd4jLong dataLength, Nd4jLong indexesLength) {
auto lengthOfArr = dataLength - indexesLength;
if(lengthOfArr < 0) {
printf("Remove index call created a <= 0 length array. This was likely not intended.");
}
auto ret = new T1[lengthOfArr];
memset(ret,0,sizeof(T1) * lengthOfArr);
removeIndex<T1, T2>(data, indexes, dataLength, indexesLength, ret);
return ret;
}
INLINEDEF _CUDA_HD Nd4jLong* everyIndexBut(Nd4jLong *indexes,int indexesLength,int begin,int end) {
int len = end - indexesLength;
traceNew(20);
auto ret = new Nd4jLong[len];
int retIdx = 0;
//not here that we do 0 based indexing for end - this assumes things like:
//0 to 4 are specified
for(int i = begin; i < end ; i++) {
bool found = false;
for(int j = 0; j < indexesLength; j++) {
if(indexes[j] == i) {
found = true;
break;
}
}
if(!found) {
ret[retIdx++] = i;
}
}
return ret;
}
/**
* Computes the offset for accessing
* a global element given the shape information
* and the offset to be read.
*/
#ifdef __CUDACC__
INLINEDEF __device__ int tadOffset(ShapeInformation *xInfo, int offset) {
return offset + threadIdx.x * xInfo->elementWiseStride;
}
#endif
/**
* Returns a shape
* forces the given length to be 2.
* @param shape the shape to modify
* @param dimension the dimension (row or column)
* for the shape to be returned as
* @return the new shape
*/
INLINEDEF _CUDA_HD Nd4jLong *ensureVectorShape(Nd4jLong *shape, int dimension) {
traceNew(21);
Nd4jLong *ret = new Nd4jLong[2];
if (dimension == 0) {
ret[0] = 1;
ret[1] = shape[0];
} else {
ret[0] = shape[0];
ret[1] = 1;
}
return ret;
}
/**
* Returns a shape
* forces the given length to be 2.
* @param shape the shape to modify
* @param dimension the dimension (row or column)
* for the shape to be returned as
* @return the new shape
*/
INLINEDEF _CUDA_HD Nd4jLong *ensureVectorShape(Nd4jLong *shape) {
return ensureVectorShape(shape, 0);
}
/**
* This method does STRICT comparison for two shape buffers
*
* @param shape
* @return
*/
INLINEDEF _CUDA_HD bool equalsStrict(const Nd4jLong *shapeA, const Nd4jLong *shapeB) {
if (shapeA[0] != shapeB[0])
return false;
if (shapeA[0] == 0)
return true;
// we do full comparison here
int length = shape::shapeInfoLength(shapeA[0]);
for (int e = 1; e < length; e++)
if (shapeA[e] != shapeB[e])
return false;
return true;
}
INLINEDEF _CUDA_HD bool haveSameOffsets(const Nd4jLong *shapeA, const Nd4jLong *shapeB) {
if (shapeA[0] != shapeB[0])
return false;
if (shapeA[0] == 0)
return true;
// we do full comparison here
int length = shape::shapeInfoLength(shapeA[0]);
for (int e = 1; e < length; e++) {
if(e == (length - 3)) continue; // type position, neglect it
if (shapeA[e] != shapeB[e])
return false;
}
return true;
}
INLINEDEF _CUDA_HD int sizeAt(const Nd4jLong *shape, const int dim) {
if (dim >= 0)
return shape[1+dim];
else
return shape[1+(rank(shape) + dim)];
}
/**
* This method does SOFT comparison for two shape buffers, we compare only rank & shapes
*
* @param shape
* @return
*/
INLINEDEF _CUDA_HD bool equalsSoft(const Nd4jLong *shapeA, const Nd4jLong *shapeB) {
if (shapeA[0] != shapeB[0])
return false;
if (shapeA[0] == 0)
return true;
// we compare only shapes, and ignoring stride & ews
auto length = shapeA[0];
for (int e = 1; e <= length; e++)
if (shapeA[e] != shapeB[e])
return false;
return true;
}
INLINEDEF _CUDA_HD bool equalsTypesAndShapesSoft(const Nd4jLong *shapeA, const Nd4jLong *shapeB) {
return equalsSoft(shapeA, shapeB) && shapeA[shapeInfoLength(shapeA) - 3] == shapeB[shapeInfoLength(shapeB) - 3];
}
/**
* Generate an int buffer
* up to the given length
* at the specified increment
*
*/
template <typename T>
INLINEDEF _CUDA_HD T* range(int from, int to, int increment) {
int diff = nd4j::math::nd4j_abs<int>(from - to);
int retLength = diff / increment;
T *ret;
traceNew(22);
if(diff / increment < 1)
ret = new T[1];
else
ret = new T[diff / increment];
if (from < to) {
int count = 0;
for (int i = from; i < to; i += increment) {
if (count >= retLength)
break;
ret[count++] = i;
}
} else if (from > to) {
int count = 0;
for (int i = from - 1; i >= to; i -= increment) {
if (count >= retLength)
break;
ret[count++] = i;
}
}
return ret;
}
/**
* Generate a range
* beginning at from and ending at to
* incrementing by 1
* @param from the start
* @param to the end
* @return the int array starting at from and ending at to
*/
template <typename T>
INLINEDEF _CUDA_HD T* range(int from, int to) {
return range<T>(from, to, 1);
}
/**
* Keep the given indexes in the data
* @param data
* @param index
* @param indexLength
* @param dataLength
* @return
*/
INLINEDEF _CUDA_HD Nd4jLong *keep(volatile Nd4jLong *data, int* index, int indexLength, int dataLength) {
traceNew(23);
Nd4jLong *ret = new Nd4jLong[indexLength];
int count = 0;
for (int i = 0; i < dataLength; i++) {
int contains = 0;
for (int j = 0; j < indexLength; j++) {
if (i == index[j]) {
contains = 1;
break;
}
}
if (contains)
ret[count++] = data[i];
}
return ret;
}
/**
* Generate a reverse
* copy of the data
*/
template <typename T>
INLINEDEF _CUDA_HD T* reverseCopy(T *data, Nd4jLong length) {
if (length < 1)
return nullptr;
traceNew(24);
T *copy = new T[length];
for (Nd4jLong i = 0; i <= length / 2; i++) {
T temp = data[i];
copy[i] = data[length - i - 1];
copy[length - i - 1] = temp;
}
return copy;
}
template <typename T>
INLINEDEF _CUDA_HD void reverseCopyTo(T *from, T *to, Nd4jLong length) {
if (length < 1)
return;
for (Nd4jLong i = 0; i <= length / 2; i++) {
T temp = from[i];
to[i] = from[length - i - 1];
to[length - i - 1] = temp;
}
}
template <typename T>
INLINEDEF _CUDA_HD void reverseCopyTo(T *from, T *to, Nd4jLong *indexes, Nd4jLong length) {
if (length < 1)
return;
for (Nd4jLong i = 0; i <= length / 2; i++) {
T temp = from[indexes[i]];
to[i] = from[indexes[length - i - 1]];
to[length - i - 1] = temp;
}
}
/**
*
* @param arr1
* @param arr1Length
* @param arr2
* @param arr2Length
* @return
*/
template <typename T>
INLINEDEF _CUDA_HD T* concat(T* arr1, Nd4jLong arr1Length, T* arr2, Nd4jLong arr2Length) {
traceNew(25);
T *ret = new T[arr1Length + arr2Length];
std::memcpy(ret, arr1, arr1Length * sizeof(T));
std::memcpy(ret + arr1Length, arr2, arr2Length * sizeof(T));
return ret;
}
/**
*
* @param numArrays
* @param numTotalElements
* @param arr
* @param lengths
* @return
*/
template <typename T>
INLINEDEF _CUDA_HD T *concat(Nd4jLong numArrays, Nd4jLong numTotalElements, T **arr, Nd4jLong *lengths) {
T* ret = new T[numTotalElements];
Nd4jLong count = 0;
for (Nd4jLong i = 0; i < numArrays; i++) {
for (Nd4jLong j = 0; j < lengths[i]; j++) {
ret[count++] = arr[i][j];
}
}
return ret;
}
/**
* Get the length per slice of the
* given shape and the dimension
* @param rank the rank of the shape
* @param shape the shape of to get
* the length per slice for
* @param dimension the dimension to
* get the length per slice for
* @param dimensionLength the length of the dimension array
* @return the length per slice of the given shape
* along the given dimension
*/
INLINEDEF _CUDA_HD Nd4jLong lengthPerSlice(int rank, Nd4jLong *shape, int* dimension, int dimensionLength) {
if(shape::isVector(shape,rank)) {
//return total length for row vectors
if(dimensionLength == 1 && shape[0] == 1) {
return shape::prod(shape,rank);
}
}
else if(rank == dimensionLength)
return shape::prod(shape,rank);
int absSelta = nd4j::math::nd4j_abs<int>(rank - dimensionLength);
traceNew(27);
auto ret2 = shape::removeIndex<Nd4jLong>(shape, dimension, rank, dimensionLength);
auto ret = prodLong(ret2, absSelta);
delete[] ret2;
return ret;
}
/**
* calculates the offset for a tensor
* @param index
* @param arr
* @param tensorShape
* @return
*/
INLINEDEF _CUDA_HD Nd4jLong sliceOffsetForTensor(int rank, int index, Nd4jLong *shape, Nd4jLong *tensorShape, int tensorShapeLength, int* dimension, int dimensionLength) {
auto tensorLength = prodLong(tensorShape, tensorShapeLength);
auto lengthPerSlice2 = lengthPerSlice(rank, shape, dimension, dimensionLength);
if (lengthPerSlice2 <= 0) {
return 0;
}
Nd4jLong offset = index * tensorLength / lengthPerSlice2;
return offset;
}
/**
* calculates the offset for a tensor
* @param index
* @param arr
* @param tensorShape
* @return
*/
INLINEDEF _CUDA_HD Nd4jLong sliceOffsetForTensor(int index,int tensorLength,int lengthPerSlice2) {
Nd4jLong offset = index * tensorLength / lengthPerSlice2;
return offset;
}
#ifdef __CUDACC__
/**
* Computes the offset for accessing
* a global element given the shape information
* and the offset to be read.
*/
INLINEDEF _CUDA_D int tadOffset(Nd4jLong *xInfo, int offset) {
return offset + threadIdx.x * elementWiseStride(xInfo);
}
#endif
/**
* Computes the number
* of tensors along
* a given dimension
*/
INLINEDEF _CUDA_HD Nd4jLong tensorsAlongDimension(volatile int rank, volatile int length,
volatile Nd4jLong *shape, int *dimension, int dimensionLength) {
Nd4jLong *tensorShape = shape::keep(shape, dimension, dimensionLength, rank);
Nd4jLong ret = length / shape::prodLong(tensorShape, dimensionLength);
delete[] tensorShape;
return ret;
}
/**
* Computes the number
* of tensors along
* a given dimension
*/
INLINEDEF _CUDA_HD Nd4jLong tensorsAlongDimension(Nd4jLong *shapeInfo, int *dimension, int dimensionLength) {
Nd4jLong *keepShape = shape::shapeOf(shapeInfo);
Nd4jLong *tensorShape = shape::keep(keepShape, dimension, dimensionLength, rank(shapeInfo));
Nd4jLong ret = shape::length(shapeInfo) / shape::prodLong(tensorShape, dimensionLength);
delete[] tensorShape;
return ret;
}
/**
* Get an offset for retrieval
* from a data buffer
* based on the given
* shape stride and given indices
* @param baseOffset the offset to start from
* @param shape the shape of the array
* @param stride the stride of the array
* @param indices the indices to iterate over
* @return the double at the specified index
*/
INLINEDEF _CUDA_HD Nd4jLong getOffset(Nd4jLong baseOffset, const Nd4jLong *shape, const Nd4jLong *stride, const Nd4jLong *indices, int rank) {
Nd4jLong offset = baseOffset;
for(int i = 0; i < rank; i++) {
if(indices[i] >= shape[i] && shape[i] != 1) {
#ifdef __CUDA_ARCH__
printf("D: Index %i [%lld] must not be >= shape[%lld].\n", i,indices[i],shape[i]);
#else
printf("H: Index %i [%lld] must not be >= shape[%lld].\n", i, (long long) indices[i], (long long) shape[i]);
#endif
#ifdef __CUDA_ARCH__
//if (threadIdx.x == 0 && blockIdx.x == 0)
// printShapeInfoLinear("getOffsetFailed", rank, shape, stride);
#endif
return -1;
}
if(shape[i] != 1) {
offset += indices[i] * stride[i];
}
}
return offset;
}
/**
* Returns the tensor along dimension
* for the given block index
* @param blockSize
* @param blockIdx
* @param i
* @return
*/
INLINEDEF _CUDA_HD int tadForBlockIndex(int blockSize, int blockIdx, int i) {
return blockIdx + i * blockSize;
}
/**
* Computes the number of tads per block
*
*/
INLINEDEF _CUDA_HD int tadsPerBlock(int blockSize, int tads) {
return nd4j::math::nd4j_ceil<double, int>(tads / (double) blockSize);
}
/**
* Returns a shape buffer
* for the shape information metadata.
*/
INLINEDEF _CUDA_HD Nd4jLong *toShapeBuffer( ShapeInformation *info) {
traceNew(29);
auto ret = new Nd4jLong[shapeInfoLength(info->rank)];
int count = 1;
int rank = info->rank;
ret[0] = info->rank;
for (int i = 0; i < rank; i++) {
ret[count++] = info->shape[i];
}
for (int i = 0; i < rank; i++) {
ret[count++] = info->stride[i];
}
ret[count++] = info->offset;
ret[count++] = info->elementWiseStride;
ret[count] = info->order;
return ret;
}
INLINEDEF _CUDA_HD Nd4jLong *toShapeBuffer( ShapeInformation *info, Nd4jLong* ret) {
int count = 1;
int rank = info->rank;
ret[0] = info->rank;
if (ret[0] == 0) {
ret[1] = 0;
ret[2] = 1;
ret[3] = 99;
return ret;
}
for (int i = 0; i < rank; i++) {
ret[count++] = info->shape[i];
}
for (int i = 0; i < rank; i++) {
ret[count++] = info->stride[i];
}
ret[count++] = info->offset;
ret[count++] = info->elementWiseStride;
ret[count++] = info->order;
return ret;
}
INLINEDEF _CUDA_HD void printIntArray(const Nd4jLong *arr, const int length) {
for(int i = 0; i < length; i++) {
printf(" %lld ", (long long) arr[i]);
}
printf("\n");
}
INLINEDEF _CUDA_HD void printIntArray(const int *arr, const int length) {
for(int i = 0; i < length; i++) {
printf(" %i ", arr[i]);
}
printf("\n");
}
INLINEDEF _CUDA_HD void printShapeInfo(Nd4jLong *shapeInfo) {
int rank = shape::rank(shapeInfo);
Nd4jLong *shape = shape::shapeOf(shapeInfo);
printf("Rank %d\n",rank);
printf("Shape:\n");
for(int i = 0; i < rank; i++) {
printf(" %lld ",(long long) shape[i]);
}
printf("\n");
Nd4jLong *stride = shape::stride(shapeInfo);
printf("Stride:\n");
for(int i = 0; i < rank; i++) {
printf(" %lld ", (long long) stride[i]);
}
printf("\n");
printf("Order %c\n",shape::order(shapeInfo));
}
INLINEDEF _CUDA_HD void printShapeInfoLinear(const Nd4jLong *shapeInfo) {
int rank = shape::rank(shapeInfo);
int lim = shape::shapeInfoLength(rank);
printf("ShapeInfo: [");
for (int i = 0; i < lim; i++) {
printf("%lld", (long long) shapeInfo[i]);
if (i < lim - 1) {
printf(", ");
}
}
printf("]\n");
#ifndef __CUDA_ARCH__
fflush(stdout);
#endif
}
INLINEDEF _CUDA_HD void printShapeInfoLinear(const char *msg, int rank, const Nd4jLong *shape, const Nd4jLong *strides) {
printf("%s : [", msg);
for (int i = 0; i < rank; i++) {
printf("%lld, ", (long long) shape[i]);
}
for (int i = 0; i < rank; i++) {
printf("%lld", (long long) strides[i]);
if (i < rank - 1)
printf(", ");
}
printf("]\n");
#ifndef __CUDA_ARCH__
fflush(stdout);
#endif
}
INLINEDEF _CUDA_HD void printShapeInfoLinear(const char *msg, const Nd4jLong *shapeInfo) {
int rank = shape::rank(shapeInfo);
int lim = shape::shapeInfoLength(rank);
printf("%s : [", msg);
for (int i = 0; i < lim; i++) {
printf("%lld", (long long) shapeInfo[i]);
if (i < lim - 1) {
printf(", ");
}
}
printf("]\n");
#ifndef __CUDACC__
fflush(stdout);
#endif
}
template <typename T>
INLINEDEF _CUDA_HD void printArray(void *varr,int length, const char * message) {
auto arr = reinterpret_cast<T*>(varr);
if (message != nullptr)
printf("%s: [", message);
else
printf("Array: [");
for (int i = 0; i < length; i ++) {
printf("%f", (float) arr[i]);
if (i + 1 < length) printf(", ");
}
printf("]\n");
#ifndef __CUDACC__
fflush(stdout);
#endif
}
INLINEDEF _CUDA_HD void printArray(float *arr,int length) {
printf("Array: [");
for (int i = 0; i < length; i ++) {
printf("%f", arr[i]);
if (i + 1 < length) printf(", ");
}
printf("]\n");
}
/**
* Given an linear index, element wise stride
* and the length of each tad
* map a linear index to a tad
* @param i the index to map
* @param the element wise stride for the tads
* @param numElementsPerTad the number of elements
* per tad
*/
INLINEDEF _CUDA_HD int tadIndex(int i, int elementWiseStride, int numElementsPerTad) {
return i / (numElementsPerTad * elementWiseStride);
}
/**
* Map a tad to a
* reduction index.
* @param tadIndexForOriginal the original tad index for the
* split up problem (eg: split is dimension 3 mapping to a 2,3 problem)
* @param tadsForReduced the number of tads for the shrunk down problem (eg: 2,3)
* @param tadsForOriginal the number of tads for the smaller problem (eg: 3)
*/
INLINEDEF _CUDA_HD int reductionIndexForTad(int tadIndexForOriginal, int tadsForReduced,
int tadsForOriginal) {
if (tadIndexForOriginal == 0)
return 0;
return tadIndexForOriginal / (tadsForOriginal / tadsForReduced);
}
INLINEDEF _CUDA_HD void transposeInplace(Nd4jLong *shapeBuffer) {
int rank = shape::rank(shapeBuffer);
Nd4jLong *shape = shape::shapeOf(shapeBuffer);
Nd4jLong *strides = shape::stride(shapeBuffer);
// swap shape
for (int e = 0; e < rank / 2; e++) {
int idx1 = rank - e - 1;
int idx2 = e;
int tmp = shape[idx2];
shape[idx2] = shape[idx1];
shape[idx1] = tmp;
}
// swap strides
for (int e = 0; e < rank / 2; e++) {
int idx1 = rank - e - 1;
int idx2 = e;
int tmp = strides[idx2];
strides[idx2] = strides[idx1];
strides[idx1] = tmp;
}
if (shape::order(shapeBuffer) == 'c')
shapeBuffer[shape::shapeInfoLength(shapeBuffer) - 1] = 102;
else
shapeBuffer[shape::shapeInfoLength(shapeBuffer) - 1] = 99;
}
/**
* Tad index for linear
* @param linearIndex
* @param tadLength
* @return
*/
INLINEDEF _CUDA_HD int tadIndexForLinear(int linearIndex, int tadLength) {
return linearIndex % tadLength;
}
/**
* Computes the number of tads
* per reduce index for the
* reduction tad.
*/
INLINEDEF _CUDA_HD int tadsPerReduceIndex(int tadsForReduce, int tadsForOriginal) {
return tadsForOriginal / tadsForReduce;
}
/**
* Maps a linear index to a reduction index
* @param i the linear index to map
* @param elementWiseStride the element wise stride
* for the multiple problem
* @param tadNum the number of tads for the shrunken problem
* @param originalTadNum the tad number for the reduced version of the problem
*/
INLINEDEF _CUDA_HD int reductionIndexForLinear(int i, int elementWiseStride, int numElementsPerTad,
int tadNum, int originalTadNum) {
int tad = tadIndex(i, elementWiseStride, numElementsPerTad);
return reductionIndexForTad(tad, tadNum, originalTadNum);
}
INLINEDEF _CUDA_HD Nd4jLong* createScalarShapeInfo() {
traceNew(30);
auto shape = new Nd4jLong[1];
shape[0] = 1;
auto stride = new Nd4jLong[1];
stride[0] = 1;
auto shapeInformation2 = new ShapeInformation();
shapeInformation2->rank = 1;
shapeInformation2->offset = 0;
shapeInformation2->stride = stride;
shapeInformation2->shape = shape;
shapeInformation2->elementWiseStride = 1;
shapeInformation2->order = 99;
Nd4jLong *ret = shape::toShapeBuffer(shapeInformation2);
delete shapeInformation2;
delete[] shape;
delete[] stride;
return ret;
}
INLINEDEF _CUDA_HD Nd4jLong* createScalarShapeInfo(Nd4jLong *ret) {
ret[0] = 2;
ret[1] = 1;
ret[2] = 1;
ret[3] = 1;
ret[4] = 1;
ret[5] = 0;
ret[6] = 1;
ret[7] = 99;
return ret;
}
/**
* Returns the prod of the data
* up to the given length
*/
INLINEDEF _CUDA_HD int prod(Nd4jLong *data, int length) {
int prod = 1;
for (int i = 0; i < length; i++) {
prod *= data[i];
}
return prod;
}
/**
* Returns the prod of the data
* up to the given length
*/
INLINEDEF _CUDA_HD Nd4jLong prodLong(const Nd4jLong *data, int length) {
Nd4jLong prod = 1;
for (int i = 0; i < length; i++) {
prod *= data[i];
}
return prod;
}
INLINEDEF _CUDA_HD int rearMostLeftOverItem(Nd4jLong *data, Nd4jLong *dimension,int dimensionLength) {
Nd4jLong *stride = shape::stride(data);
//corner case: return the final item when its greater than the max, since its guaranteed to be left over
//note here that strides are interpreted in reverse for tad
//start from the front rather than the back
int rank = shape::rank(data);
if(shape::order(data) == 'f') {
int dimIdx = dimensionLength - 1;
for(int i = rank - 1; i >= 0; i--) {
/**
* Needs to find an algorithm such that:
* looping backwards will find the highest dimension left
* that isn't included in the dimension index list.
*
* This can also be thought of as the last item of the first index
* of the difference between the full list of indices and
* the dimension indices.
*
* We should avoid excessive object creation by only looping backwards.
*/
if(dimension[dimIdx--] != i) {
int ret = stride[i];
return ret;
}
}
}
else {
int dimIdx = dimensionLength - 1;
for(int i = rank - 1; i >= 0; i--) {
/**
* Needs to find an algorithm such that:
* looping backwards will find the highest dimension left
* that isn't included in the dimension index list.
*
* This can also be thought of as the last item of the first index
* of the difference between the full list of indices and
* the dimension indices.
*
* We should avoid excessive object creation by only looping backwards.
*/
if(dimension[dimIdx--] != i) {
int ret = stride[i];
return ret;
}
}
}
int ret = stride[0];
return ret;
}
#ifdef __CUDACC__
__device__ INLINEDEF void sweepShapeInfoBuffer(Nd4jLong *shapeInfoBuffer, Nd4jLong *targetBuffer) {
// we read first element, to find out length of our shapeInfoBuffer
int rank = shapeInfoBuffer[0];
int len = shape::shapeInfoLength(rank);
for (int i = threadIdx.x; i < len; i += blockDim.x)
targetBuffer[i] = shapeInfoBuffer[i];
}
#endif
INLINEDEF _CUDA_HD Nd4jLong *shapeBufferOfNpy(cnpy::NpyArray arr) {
return shape::shapeBufferOfNpy(arr.shape.size(),(unsigned int*) arr.shape.data(),arr.fortranOrder);
}
// INLINEDEF _CUDA_HD Nd4jLong *shapeBufferOfNpyBuffer(char *buffer) {
// unsigned Nd4jLong *shape;
// unsigned int ndims, wordSize;
// bool fortranOrder;
// cnpy::parseNpyHeaderStr(std::string(buffer),wordSize,shape,ndims,fortranOrder);
// Nd4jLong * ret = shape::shapeBufferOfNpy(ndims,shape,fortranOrder);
// delete[] shape;
// return ret;
// }
INLINEDEF _CUDA_HD Nd4jLong *shapeBufferOfNpy(int rank, unsigned int* shape,bool fortranOrder) {
if(fortranOrder) {
Nd4jLong *shapeBufferRet = shape::shapeBufferFortran(rank, nd4j::FLOAT32,(Nd4jLong *) shape);
return shapeBufferRet;
}
else {
Nd4jLong *newShape = new Nd4jLong[rank];
for(int i = 0; i < rank; i++) {
newShape[i] = shape[i];
}
Nd4jLong *shapeBufferRet = shape::shapeBuffer(rank, nd4j::FLOAT32, newShape);
delete[] newShape;
return shapeBufferRet;
}
}
INLINEDEF _CUDA_HD bool strideDescendingCAscendingF(const Nd4jLong *shapeBuffer) {
int rank = shape::rank(shapeBuffer);
Nd4jLong *strides = shape::stride(const_cast<Nd4jLong*>(shapeBuffer));
char order = shape::order(shapeBuffer);
if (shape::isRowVector(shapeBuffer) && strides[0] == 1 && strides[1] == 1)
return true;
if (order == 'c') {
for (int i = 1; i < rank; i++)
if (strides[i-1] <= strides[i])
return false;
return true;
} else if (order == 'f') {
for (int i = 1; i < rank; i++)
if (strides[i-1] >= strides[i])
return false;
return true;
} else {
printf("Unknown order for array!\n");
return false;
}
}
INLINEDEF _CUDA_HD bool isStrideSimple(const Nd4jLong* shapeInfo) {
return (order(shapeInfo) == 'c') && (elementWiseStride(shapeInfo) > 0);
}
//////////////////////////////////////////////////////////////////////////
// copy-past from java hasDefaultStridesForShape function
INLINEDEF _CUDA_HD bool areStridesDefault(const Nd4jLong* shapeInfo) {
const int rank = shape::rank(shapeInfo);
if(rank == 0)
return true;
if(!strideDescendingCAscendingF(shapeInfo))
return false;
Nd4jLong defaultShapeInfo[MAX_SHAPEINFOLENGTH];
memcpy(defaultShapeInfo, shapeInfo, shape::shapeInfoByteLength(shapeInfo));
shape::updateStrides(defaultShapeInfo, shape::order(shapeInfo));
bool result = true;
for(int i = rank+1; i <= 2*rank; ++i)
if(defaultShapeInfo[i] != shapeInfo[i]) {
result = false;
break;
}
return result;
}
// INLINEDEF _CUDA_H bool reshapeC(const int oldRank, Nd4jLong* oldShape, const int newRank, Nd4jLong* newShapeOf, bool isFOrder, Nd4jLong* target) {
// int oldnd;
// Nd4jLong* olddims = shape::copyOf(oldRank, shape::shapeOf(oldShape));
// Nd4jLong* oldstrides = shape::copyOf(oldRank, shape::stride(oldShape));
// int np, op, last_stride;
// int oi, oj, ok, ni, nj, nk;
// Nd4jLong* newStrides = new Nd4jLong[newRank];
// oldnd = 0;
// /*
// * Remove axes with dimension 1 from the old array. They have no effect
// * but would need special cases since their strides do not matter.
// */
// for (oi = 0; oi < oldRank; oi++) {
// if (shape::shapeOf(oldShape)[oi] != 1) {
// olddims[oldnd] = shape::shapeOf(oldShape)[oi];
// oldstrides[oldnd] = shape::stride(oldShape)[oi];
// oldnd++;
// }
// }
// np = 1;
// for (ni = 0; ni < newRank; ni++) {
// np *= newShapeOf[ni];
// }
// op = 1;
// for (oi = 0; oi < oldnd; oi++) {
// op *= olddims[oi];
// }
// if (np != op) {
// /* different total sizes; no hope */
// delete[] olddims;
// delete[] oldstrides;
// delete[] newStrides;
// return false;
// }
// if (np == 0) {
// /* the current code does not handle 0-sized arrays, so give up */
// delete[] olddims;
// delete[] oldstrides;
// delete[] newStrides;
// return false;
// }
// /* oi to oj and ni to nj give the axis ranges currently worked with */
// oi = 0;
// oj = 1;
// ni = 0;
// nj = 1;
// while (ni < newRank && oi < oldnd) {
// np = newShapeOf[ni];
// op = olddims[oi];
// while (np != op) {
// if (np < op) {
// /* Misses trailing 1s, these are handled later */
// np *= newShapeOf[nj++];
// } else {
// op *= olddims[oj++];
// }
// }
// /* Check whether the original axes can be combined */
// for (ok = oi; ok < oj - 1; ok++) {
// if (isFOrder) {
// if (oldstrides[ok + 1] != olddims[ok] * oldstrides[ok]) {
// /* not contiguous enough */
// delete[] olddims;
// delete[] oldstrides;
// delete[] newStrides;
// return false;
// }
// } else {
// /* C order */
// if (oldstrides[ok] != olddims[ok + 1] * oldstrides[ok + 1]) {
// /* not contiguous enough */
// delete[] olddims;
// delete[] oldstrides;
// delete[] newStrides;
// return false;
// }
// }
// }
// /* Calculate new strides for all axes currently worked with */
// if (isFOrder) {
// newStrides[ni] = oldstrides[oi];
// for (nk = ni + 1; nk < nj; nk++) {
// newStrides[nk] = newStrides[nk - 1] * newShapeOf[nk - 1];
// }
// } else {
// /* C order */
// newStrides[nj - 1] = oldstrides[oj - 1];
// for (nk = nj - 1; nk > ni; nk--) {
// newStrides[nk - 1] = newStrides[nk] * newShapeOf[nk];
// }
// }
// ni = nj++;
// oi = oj++;
// }
// if (ni >= 1) {
// last_stride = newStrides[ni - 1];
// } else {
// last_stride = shape::elementWiseStride(oldShape);
// }
// if (isFOrder && ni >= 1) {
// last_stride *= newShapeOf[ni - 1];
// }
// for (nk = ni; nk < newRank; nk++) {
// newStrides[nk] = last_stride;
// }
// target[0] = newRank;
// int cnt = 1;
// for (int e = 0; e < newRank; e++)
// target[cnt++] = newShapeOf[e];
// for (int e = 0; e < newRank; e++)
// target[cnt++] = newStrides[e];
// target[shape::shapeInfoLength(newRank) - 3] = 0;
// target[shape::shapeInfoLength(newRank) - 2] = 0;
// target[shape::shapeInfoLength(newRank) - 1] = isFOrder ? 102 : 99;
// nd4j::ArrayOptions::setDataType(target, nd4j::ArrayOptions::dataType(oldShape));
// delete[] olddims;
// delete[] oldstrides;
// delete[] newStrides;
// return true;
// }
// INLINEDEF _CUDA_H bool reshapeC(const int oldRank, const Nd4jLong* oldShapeInfo, const int newRank, const Nd4jLong* newShape, const bool isFOrder, Nd4jLong* newShapeInfo) {
// // PLEASE NOTE !: reshaping not-permuted (ews=1) array in f order (except insertion/elimination of unities) will definitely cause allocation of new buffer for array elements
// // also this function takes into account identical shapes automatically, namely in that case oldShapeInfo is completely copied to newShapeInfo
// const int newOrder = isFOrder ? 102 : 99;
// const int oldOrder = oldShapeInfo[2 * oldRank + 3];
// newShapeInfo[0] = newRank;
// memcpy(newShapeInfo + 1, newShape, newRank * sizeof(Nd4jLong));
// Nd4jLong* newStrides = shape::stride(newShapeInfo);
// const Nd4jLong* oldShape = shape::shapeOf(const_cast<Nd4jLong*>(oldShapeInfo));
// const Nd4jLong* oldStrides = shape::stride(const_cast<Nd4jLong*>(oldShapeInfo));
// int oldStart(0), oldStop(1), newStart(0), newStop(1), newDim, oldDim;
// while (newStart < newRank && oldStart < oldRank) {
// newDim = newShape[newStart];
// oldDim = oldShape[oldStart];
// while (newDim != oldDim)
// if (newDim < oldDim) newDim *= newShape[newStop++];
// else oldDim *= oldShape[oldStop++];
// // ------ Check whether the original axes can be combined ------ //
// for (int i = oldStart; i < oldStop - 1; i++) {
// if(oldShape[i] == 1) { // ignore strides like {...,1,1,...}
// if(oldOrder == 102) ++oldStart;
// continue;
// }
// if(oldOrder == 102 && oldStrides[i + 1] != oldShape[i] * oldStrides[i])
// return false; // not contiguous enough
// if(oldOrder == 99 && oldStrides[i] != oldShape[i + 1] * oldStrides[i + 1])
// return false; // not contiguous enough
// }
// // ------ Calculate new strides for all axes currently worked with ------ //
// if(isFOrder) {
// newStrides[newStart] = oldStrides[oldStart];
// for (int i = newStart + 1; i < newStop; ++i)
// newStrides[i] = newStrides[i - 1] * newShape[i - 1];
// }
// else {
// newStrides[newStop - 1] = oldStrides[oldStop - 1];
// for (int i = newStop - 1; i > newStart; --i)
// newStrides[i - 1] = newStrides[i] * newShape[i];
// }
// newStart = newStop++;
// oldStart = oldStop++;
// }
// newShapeInfo[2 * newRank + 3] = shape::order(oldShapeInfo); // order
// newShapeInfo[2 * newRank + 2] = shape::elementWiseStride(oldShapeInfo); // ews
// newShapeInfo[2 * newRank + 1] = shape::type(oldShapeInfo); // type
// return true;
// }
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_H bool reshapeC(const int oldRank, const Nd4jLong* oldShapeInfo, const int newRank, const Nd4jLong* newShape, Nd4jLong* newShapeInfo) {
// PLEASE NOTE !: reshaping not-permuted (ews=1) array in f order (except insertion/elimination of unities) will definitely cause allocation of new buffer for array elements
// also this function takes into account identical shapes automatically, namely in that case oldShapeInfo is completely copied to newShapeInfo
newShapeInfo[0] = newRank;
memcpy(newShapeInfo + 1, newShape, newRank * sizeof(Nd4jLong));
Nd4jLong* newStrides = shape::stride(newShapeInfo);
const Nd4jLong* oldShape = shape::shapeOf(const_cast<Nd4jLong*>(oldShapeInfo));
const Nd4jLong* oldStrides = shape::stride(const_cast<Nd4jLong*>(oldShapeInfo));
int oldStart(0), oldStop(1), newStart(0), newStop(1), newDim, oldDim;
while (newStart < newRank && oldStart < oldRank) {
newDim = newShape[newStart];
oldDim = oldShape[oldStart];
while (newDim != oldDim)
if (newDim < oldDim) newDim *= newShape[newStop++];
else oldDim *= oldShape[oldStop++];
// ------ Check whether the original axes can be combined ------ //
for (int step = 1, i = oldStart; i < oldStop - 1; ++i) {
if(oldShape[i] == 1) // skip unity-dimension and its stride
continue;
while((i + step) < oldRank && oldShape[i + step] == 1)
++step; // skip following unity-dimensions and its strides if such are present
if((i + step) < oldRank && oldStrides[i] != oldShape[i + step] * oldStrides[i + step])
return false; // not contiguous enough
}
newStrides[newStop - 1] = oldStrides[oldStop - 1];
for (int i = newStop - 1; i > newStart; --i)
newStrides[i - 1] = newStrides[i] * newShape[i];
newStart = newStop++;
oldStart = oldStop++;
}
newShapeInfo[2 * newRank + 3] = shape::order(oldShapeInfo); // order
newShapeInfo[2 * newRank + 2] = shape::elementWiseStride(oldShapeInfo); // ews
newShapeInfo[2 * newRank + 1] = shape::type(oldShapeInfo); // type
return true;
}
INLINEDEF _CUDA_H bool canReshape(const int oldRank, Nd4jLong* oldShape, const int newRank, Nd4jLong* newShapeOf, bool isFOrder) {
int oldnd;
Nd4jLong* oldDims = shape::copyOf(oldRank, shape::shapeOf(oldShape));
Nd4jLong* oldStrides = shape::copyOf(oldRank, shape::stride(oldShape));
int np, op, last_stride;
int oldStart, oldStop, ok, newStart, newStop, nk;
auto newStrides = new Nd4jLong[newRank];
oldnd = 0;
/*
* Remove axes with dimension 1 from the old array. They have no effect
* but would need special cases since their strides do not matter.
*/
for (oldStart = 0; oldStart < oldRank; oldStart++) {
if (shape::shapeOf(oldShape)[oldStart] != 1) {
oldDims[oldnd] = shape::shapeOf(oldShape)[oldStart];
oldStrides[oldnd] = shape::stride(oldShape)[oldStart];
oldnd++;
}
}
np = 1;
for (newStart = 0; newStart < newRank; newStart++) {
np *= newShapeOf[newStart];
}
op = 1;
for (oldStart = 0; oldStart < oldnd; oldStart++) {
op *= oldDims[oldStart];
}
if (np != op) {
/* different total sizes; no hope */
delete[] oldDims;
delete[] oldStrides;
delete[] newStrides;
return false;
}
if (np == 0) {
/* the current code does not handle 0-sized arrays, so give up */
delete[] oldDims;
delete[] oldStrides;
delete[] newStrides;
return false;
}
/* oldStart to oldStop and newStart to newStop give the axis ranges currently worked with */
oldStart = 0;
oldStop = 1;
newStart = 0;
newStop = 1;
while (newStart < newRank && oldStart < oldnd) {
np = newShapeOf[newStart];
op = oldDims[oldStart];
while (np != op) {
if (np < op) {
/* Misses trailing 1s, these are handled later */
np *= newShapeOf[newStop++];
} else {
op *= oldDims[oldStop++];
}
}
/* Check whether the original axes can be combined */
for (ok = oldStart; ok < oldStop - 1; ok++) {
if (isFOrder) {
if (oldStrides[ok + 1] != oldDims[ok] * oldStrides[ok]) {
/* not contiguous enough */
delete[] oldDims;
delete[] oldStrides;
delete[] newStrides;
return false;
}
} else {
/* C order */
if (oldStrides[ok] != oldDims[ok + 1] * oldStrides[ok + 1]) {
/* not contiguous enough */
delete[] oldDims;
delete[] oldStrides;
delete[] newStrides;
return false;
}
}
}
/* Calculate new strides for all axes currently worked with */
if (isFOrder) {
newStrides[newStart] = oldStrides[oldStart];
for (nk = newStart + 1; nk < newStop; nk++) {
newStrides[nk] = newStrides[nk - 1] * newShapeOf[nk - 1];
}
} else {
/* C order */
newStrides[newStop - 1] = oldStrides[oldStop - 1];
for (nk = newStop - 1; nk > newStart; nk--) {
newStrides[nk - 1] = newStrides[nk] * newShapeOf[nk];
}
}
newStart = newStop++;
oldStart = oldStop++;
}
delete[] oldDims;
delete[] oldStrides;
delete[] newStrides;
return true;
}
// this function checks the consistence of dimensions with array rank (negative dimensions, too large dimensions, too big number of dimensions)
// also it sorts input array of dimensions, this operation is also necessary for creating TAD object
INLINEDEF _CUDA_H void checkDimensions(const int rank, std::vector<int>& dimensions) {
int dimSize = dimensions.size();
if(dimSize == 0)
throw std::runtime_error("shape::checkDimensions method: array of dimensions is empty!");
// check presence of negative dimensions and if they are present transform them to positive ones -dim -> rank - |dim|
for(auto& dim : dimensions)
if(dim < 0)
dim += rank;
// sort input array of dimensions, this operation is also necessary for creating TAD object in external methods
if (dimSize > 1) {
std::sort(dimensions.begin(), dimensions.end());
// remove duplicates if they are present
dimensions.erase(std::unique(dimensions.begin(), dimensions.end()), dimensions.end());
}
// check whether number of dimensions is to big (>rank)
dimSize = dimensions.size();
if(dimSize > rank)
throw std::runtime_error("shape::checkDimensions method: number of input dimensions is too big ( > rank of array)!");
// check if min dimension is still negative and whether max dimension is bigger then rank-1
if(dimensions[0] < 0 || dimensions.back() > (rank-1))
throw std::runtime_error("shape::checkDimensions method: the negative dimension is still present in input array after transform or the too big dimension is present ( > rank of array) !");
}
// max array is outer for min array, min array is sub-array of max array
// function calculates the coordinates of min array (and saves them into minIdxs) given coordinates of max array (already stored in maxIdxs)
INLINEDEF _CUDA_HD void maxIndToMinInd(Nd4jLong* maxIdxs, Nd4jLong* minIdxs, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude, int dimsLen) {
const auto maxRank = shape::rank(maxShapeInfo);
const auto minRank = shape::rank(minShapeInfo);
// if(minRank >= maxRank)
// throw std::runtime_error("shape::maxIndToMinInd method: rank of min array should be smaller then rank of max array!");
if(dimsLen == -1)
dimsLen = maxRank - minRank; // if size is not given (= -1) then it is equal to ranks difference
if(maxRank == minRank) {
if(dimsToExclude == nullptr) { // --> means dimsToExclude == {0,1,2,...,dimsLen-1}
for (int i = 0; i < maxRank; ++i) {
if(i < dimsLen)
minIdxs[i] = maxIdxs[i];
else {
if(maxIdxs[i] > minShapeInfo[i + 1])
minIdxs[i] = maxIdxs[i] % minShapeInfo[i + 1];
else if(maxIdxs[i] == minShapeInfo[i + 1])
minIdxs[i] = 0;
else
minIdxs[i] = maxIdxs[i];
}
}
}
else {
for (int i = 0, dim = 0; i < maxRank; ++i) {
if(dim < dimsLen && dimsToExclude[dim] == i) {
minIdxs[i] = maxIdxs[i];
++dim;
continue;
}
if(maxIdxs[i] > minShapeInfo[i + 1])
minIdxs[i] = maxIdxs[i] % minShapeInfo[i + 1];
else if(maxIdxs[i] == minShapeInfo[i + 1])
minIdxs[i] = 0;
else
minIdxs[i] = maxIdxs[i];
}
}
}
else {
if(dimsToExclude == nullptr) { // --> means dimsToExclude == {0,1,2,...,dimsLen-1}
for (int i = 0; i < minRank; ++i) {
if(maxIdxs[i + dimsLen] > minShapeInfo[i + 1])
minIdxs[i] = maxIdxs[i + dimsLen] % minShapeInfo[i + 1];
else if(maxIdxs[i + dimsLen] == minShapeInfo[i + 1])
minIdxs[i] = 0;
else
minIdxs[i] = maxIdxs[i + dimsLen];
}
}
else {
for (int minI = 0, maxI = 0, dim = 0; maxI < maxRank; ++maxI) {
if(dim < dimsLen && dimsToExclude[dim] == maxI) {
++dim;
continue;
}
if(maxIdxs[maxI] == minShapeInfo[minI + 1])
minIdxs[minI] = 0;
else if(maxIdxs[maxI] > minShapeInfo[minI + 1])
minIdxs[minI] = maxIdxs[maxI] % minShapeInfo[minI + 1];
else
minIdxs[minI] = maxIdxs[maxI];
++minI;
}
}
}
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD Nd4jLong subArrayIndex(const Nd4jLong maxIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude, const int dimsLen) {
Nd4jLong maxIdxs[MAX_RANK];
if(shape::order(maxShapeInfo) == 'c')
shape::ind2subC(shape::rank(maxShapeInfo), const_cast<Nd4jLong *>(maxShapeInfo)+1, const_cast<Nd4jLong&>(maxIdx), maxIdxs);
else
shape::ind2sub(shape::rank(maxShapeInfo), const_cast<Nd4jLong *>(maxShapeInfo)+1, const_cast<Nd4jLong&>(maxIdx), maxIdxs);
Nd4jLong minIdxs[MAX_RANK];
maxIndToMinInd(maxIdxs, minIdxs, maxShapeInfo, minShapeInfo, dimsToExclude, dimsLen);
return sub2Ind(shape::rank(minShapeInfo), minShapeInfo + 1, minIdxs);
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD Nd4jLong subArrayOffset(const Nd4jLong maxIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude, const int dimsLen) {
Nd4jLong maxIdxs[MAX_RANK];
if(shape::order(maxShapeInfo) == 'c')
shape::ind2subC(shape::rank(maxShapeInfo), const_cast<Nd4jLong *>(maxShapeInfo)+1, const_cast<Nd4jLong&>(maxIdx), maxIdxs);
else
shape::ind2sub(shape::rank(maxShapeInfo), const_cast<Nd4jLong *>(maxShapeInfo)+1, const_cast<Nd4jLong&>(maxIdx), maxIdxs);
Nd4jLong minIdxs[MAX_RANK];
maxIndToMinInd(maxIdxs, minIdxs, maxShapeInfo, minShapeInfo, dimsToExclude, dimsLen);
return getOffset(0, minShapeInfo + 1, minShapeInfo + shape::rank(minShapeInfo) + 1, minIdxs, shape::rank(minShapeInfo));
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD int outerArrayOffsets(Nd4jLong* maxOffsets, const Nd4jLong minIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude) {
const auto rankMin = shape::rank(minShapeInfo);
const auto rankMax = shape::rank(maxShapeInfo);
// if(rankMin >= rankMax)
// throw std::runtime_error("shape::subArrayIndex method: rank of min array should be smaller then rank of max array!");
// if(rankMax > MAX_RANK/2)
// throw std::runtime_error("shape::subArrayIndex method: rank of max array should be <= MAX_RANK/2 !");
const auto diff = rankMax - rankMin; // the size of dimsToExclude is equal to diff
Nd4jLong buffer[MAX_RANK];
Nd4jLong* indices = buffer;
Nd4jLong* increment = buffer + MAX_RANK/2;
int N, minI, maxI;
// calculate min per-dim-indices which corresponds to absolute minIdx index
if(order(minShapeInfo) == 'c')
shape::ind2subC(rankMin, minShapeInfo + 1, minIdx, indices);
else
shape::ind2sub(rankMin, const_cast<Nd4jLong*>(minShapeInfo) + 1, minIdx, indices);
// transform storage indices to contain per-dim max indices, purpose - memory saving
// fill increment array as well
if(dimsToExclude == nullptr) { // means dimsToExclude == {0,1,2,...,diff-1}
for(minI = rankMin - 1, maxI = rankMax-1; maxI >= diff; --maxI, --minI) {
increment[maxI] = (maxShapeInfo[maxI+1] == minShapeInfo[minI+1]) ? 0 : minShapeInfo[minI+1];
indices[maxI] = indices[minI];
}
for(maxI = 0; maxI < diff; ++maxI) {
increment[maxI] = 1;
indices[maxI] = 0;
}
}
else {
for(N = diff-1, minI = rankMin - 1, maxI = rankMax - 1; maxI >= 0; --maxI) {
if(N >= 0 && dimsToExclude[N] == maxI) {
increment[maxI] = 1;
indices[maxI] = 0;
--N;
}
else {
increment[maxI] = (maxShapeInfo[maxI+1] == minShapeInfo[minI+1]) ? 0 : minShapeInfo[minI+1];
indices[maxI] = indices[minI--];
}
}
}
maxI = rankMax-1;
N = 0;
int step;
maxOffsets[N++] = shape::getOffset(0, maxShapeInfo + 1, maxShapeInfo + rankMax + 1, indices, rankMax);
// nested loops - producing of absolute indices for max array
while(maxI >= 0) {
if(increment[maxI] != 0) {
indices[maxI] += increment[maxI];
if(indices[maxI] >= maxShapeInfo[maxI+1]) {
indices[maxI] %= increment[maxI]; // restore initial value of indices[maxI]
step = -1;
}
else {
maxOffsets[N++] = shape::getOffset(0, maxShapeInfo + 1, maxShapeInfo + rankMax + 1, indices, rankMax);
step = rankMax - 1 - maxI;
}
}
else if(maxI == rankMax - 1)
step = -1;
maxI += step;
}
return N;
}
//////////////////////////////////////////////////////////////////////
INLINEDEF _CUDA_HD int outerArrayIndexes(Nd4jLong* maxIdxs, const Nd4jLong minIdx, const Nd4jLong* maxShapeInfo, const Nd4jLong* minShapeInfo, const int* dimsToExclude) {
const auto rankMin = shape::rank(minShapeInfo);
const auto rankMax = shape::rank(maxShapeInfo);
// if(rankMin >= rankMax)
// throw std::runtime_error("shape::subArrayIndex method: rank of min array should be smaller then rank of max array!");
// if(rankMax > MAX_RANK/2)
// throw std::runtime_error("shape::subArrayIndex method: rank of max array should be <= MAX_RANK/2 !");
const auto diff = rankMax - rankMin; // the size of dimsToExclude is equal to diff
Nd4jLong buffer[MAX_RANK];
Nd4jLong* indices = buffer;
Nd4jLong* increment = buffer + MAX_RANK/2;
int N, minI, maxI;
// calculate min per-dim-indices which corresponds to absolute minIdx index
if(order(minShapeInfo) == 'c')
shape::ind2subC(rankMin, minShapeInfo + 1, minIdx, indices);
else
shape::ind2sub(rankMin, const_cast<Nd4jLong*>(minShapeInfo) + 1, minIdx, indices);
// transform storage indices to contain per-dim max indices, purpose - memory saving
// fill increment array as well
if(dimsToExclude == nullptr) { // means dimsToExclude == {0,1,2,...,diff-1}
for(minI = rankMin - 1, maxI = rankMax-1; maxI >= diff; --maxI, --minI) {
increment[maxI] = (maxShapeInfo[maxI+1] == minShapeInfo[minI+1]) ? 0 : minShapeInfo[minI+1];
indices[maxI] = indices[minI];
}
for(maxI = 0; maxI < diff; ++maxI) {
increment[maxI] = 1;
indices[maxI] = 0;
}
}
else {
for(N = diff-1, minI = rankMin - 1, maxI = rankMax - 1; maxI >= 0; --maxI) {
if(N >= 0 && dimsToExclude[N] == maxI) {
increment[maxI] = 1;
indices[maxI] = 0;
--N;
}
else {
increment[maxI] = (maxShapeInfo[maxI+1] == minShapeInfo[minI+1]) ? 0 : minShapeInfo[minI+1];
indices[maxI] = indices[minI--];
}
}
}
maxI = rankMax-1;
N = 0;
int step;
maxIdxs[N++] = sub2Ind(rankMax, maxShapeInfo + 1, indices);
// nested loops - producing of absolute indices for max array
while(maxI >= 0) {
if(increment[maxI] != 0) {
indices[maxI] += increment[maxI];
if(indices[maxI] >= maxShapeInfo[maxI+1]) {
indices[maxI] %= increment[maxI]; // restore initial value of indices[maxI]
step = -1;
}
else {
maxIdxs[N++] = sub2Ind(rankMax, maxShapeInfo + 1, indices);
step = rankMax - 1 - maxI;
}
}
else if(maxI == rankMax - 1)
step = -1;
maxI += step;
}
return N;
}
INLINEDEF _CUDA_HD void shapeOldScalar(nd4j::DataType dataType, Nd4jLong* const buffer, const char order) {
buffer[0] = 2;
buffer[1] = 1;
buffer[2] = 1;
buffer[3] = 1;
buffer[4] = 1;
buffer[6] = 1;
buffer[7] = (int)order;
nd4j::ArrayOptions::setDataType(buffer, dataType);
}
template <typename T1, typename T2>
INLINEDEF _CUDA_H void convertT(T1 *from, T2 *to, Nd4jLong length) {
for (Nd4jLong e = 0; e < length; e++)
to[e] = (T2) from[e];
};
//////////////////////////////////////////////////////////////////////
INLINEDEF void calcSubArrOffsets(const Nd4jLong numOfSubArrs, const int rank, const Nd4jLong* shape, const Nd4jLong* strides, Nd4jLong* subArrOffsets) {
// set offset for first sub-array, it is equal to zero always
subArrOffsets[0] = 0;
// choose whether to parallelize or not
if(numOfSubArrs > 1024 /*Environment::getInstance()->elementwiseThreshold()*/) {
#pragma omp parallel // PRAGMA_OMP_PARALLEL_ARGS(private(indexes))
{
Nd4jLong* indexes = new Nd4jLong[rank];
#pragma omp for simd schedule(guided) // PRAGMA_OMP_PARALLEL_FOR
for (Nd4jLong i = 1; i < numOfSubArrs; ++i) {
shape::ind2subC(rank, shape, i, indexes);
subArrOffsets[i] = 0;
for (int j = 0; j < rank; ++j)
if(shape[j] != 1)
subArrOffsets[i] += indexes[j] * strides[j];
}
delete []indexes;
}
}
else {
Nd4jLong rankMinusOne = rank - 1;
Nd4jLong i = 1, j = rankMinusOne;
Nd4jLong* idx = new Nd4jLong[rank];
Nd4jLong* currOffset = new Nd4jLong[rank];
memset(idx, 0, sizeof(Nd4jLong) * rank);
memset(currOffset, 0, sizeof(Nd4jLong) * rank);
// nested loops - calculation of sub-array offsets (subArrOffsets)
while(j >= 0) {
if(shape[j] == 1) { --j; continue; } // ignore dimensions equal to unity
if(j == rankMinusOne) { // last dimension
for(idx[j] = 1; idx[j] < shape[j]; ++idx[j])
subArrOffsets[i++] = subArrOffsets[i-1] + strides[j];
--j;
}
else if(idx[j] < shape[j] - 1) {
currOffset[j] += strides[j];
subArrOffsets[i++] = j ? currOffset[j] + currOffset[j-1] : currOffset[j];
++idx[j];
j = rankMinusOne;
}
else
currOffset[j--] = idx[j] = 0;
}
delete []idx;
delete []currOffset;
}
}
//////////////////////////////////////////////////////////////////////
INLINEDEF void _CUDA_HD setEws(Nd4jLong* shapeInfo, Nd4jLong len) {
const int rank = shape::rank(shapeInfo);
const Nd4jLong* shape = shape::shapeOf(shapeInfo);
const Nd4jLong* strides = shape::stride(shapeInfo);
const char order = shape::order(shapeInfo);
Nd4jLong* ews = shape::ews(shapeInfo);
if(len == -1) // calculate array length if it is not given
len = shape::length(shapeInfo);
if(len <= 1) { // empty, scalar or unity-vector case
*ews = 1;
return;
}
int nonUnityDim(0);
if(shape::isCommonVector(shapeInfo, nonUnityDim)) {
*ews = strides[nonUnityDim];
return;
}
// check last(c)/first(f) dimension, it should be equal to 1
if((order == 'c' && shape[rank - 1] != 1 && strides[rank - 1] != 1) || (order == 'f' && shape[0] != 1 && strides[0] != 1)) {
*ews = 0;
return;
}
Nd4jLong correctStride = 1;
if(order == 'c') {
for (int i = rank - 2; i >= 0 ; i--) {
correctStride *= shape[i + 1];
if(shape[i] == 1)
continue;
if(correctStride != strides[i]) {
*ews = 0;
return;
}
}
}
else {
for (int i = 1; i < rank; ++i) {
correctStride *= shape[i - 1];
if(shape[i] == 1)
continue;
if(correctStride != strides[i]) {
*ews = 0;
return;
}
}
}
*ews = 1;
}
}
#endif /* SHAPE_H_ */
|
geminate.c
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 1991-2000, University of Groningen, The Netherlands.
* Copyright (c) 2001-2004, The GROMACS development team,
* check out http://www.gromacs.org for more information.
* Copyright (c) 2012,2013, by the GROMACS development team, led by
* David van der Spoel, Berk Hess, Erik Lindahl, and including many
* others, as listed in the AUTHORS file in the top-level source
* directory and at http://www.gromacs.org.
*
* GROMACS 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.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_LIBGSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_multifit_nlin.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_version.h>
#endif
#include <math.h>
#include "typedefs.h"
#include "smalloc.h"
#include "vec.h"
#include "geminate.h"
#include "gmx_omp.h"
/* The first few sections of this file contain functions that were adopted,
* and to some extent modified, by Erik Marklund (erikm[aT]xray.bmc.uu.se,
* http://folding.bmc.uu.se) from code written by Omer Markovitch (email, url).
* This is also the case with the function eq10v2().
*
* The parts menetioned in the previous paragraph were contributed under the BSD license.
*/
/* This first part is from complex.c which I recieved from Omer Markowitch.
* - Erik Marklund
*
* ------------- from complex.c ------------- */
/* Complexation of a paired number (r,i) */
static gem_complex gem_cmplx(double r, double i)
{
gem_complex value;
value.r = r;
value.i = i;
return value;
}
/* Complexation of a real number, x */
static gem_complex gem_c(double x)
{
gem_complex value;
value.r = x;
value.i = 0;
return value;
}
/* Magnitude of a complex number z */
static double gem_cx_abs(gem_complex z)
{
return (sqrt(z.r*z.r+z.i*z.i));
}
/* Addition of two complex numbers z1 and z2 */
static gem_complex gem_cxadd(gem_complex z1, gem_complex z2)
{
gem_complex value;
value.r = z1.r+z2.r;
value.i = z1.i+z2.i;
return value;
}
/* Addition of a complex number z1 and a real number r */
static gem_complex gem_cxradd(gem_complex z, double r)
{
gem_complex value;
value.r = z.r + r;
value.i = z.i;
return value;
}
/* Subtraction of two complex numbers z1 and z2 */
static gem_complex gem_cxsub(gem_complex z1, gem_complex z2)
{
gem_complex value;
value.r = z1.r-z2.r;
value.i = z1.i-z2.i;
return value;
}
/* Multiplication of two complex numbers z1 and z2 */
static gem_complex gem_cxmul(gem_complex z1, gem_complex z2)
{
gem_complex value;
value.r = z1.r*z2.r-z1.i*z2.i;
value.i = z1.r*z2.i+z1.i*z2.r;
return value;
}
/* Square of a complex number z */
static gem_complex gem_cxsq(gem_complex z)
{
gem_complex value;
value.r = z.r*z.r-z.i*z.i;
value.i = z.r*z.i*2.;
return value;
}
/* multiplication of a complex number z and a real number r */
static gem_complex gem_cxrmul(gem_complex z, double r)
{
gem_complex value;
value.r = z.r*r;
value.i = z.i*r;
return value;
}
/* Division of two complex numbers z1 and z2 */
static gem_complex gem_cxdiv(gem_complex z1, gem_complex z2)
{
gem_complex value;
double num;
num = z2.r*z2.r+z2.i*z2.i;
if (num == 0.)
{
fprintf(stderr, "ERROR in gem_cxdiv function\n");
}
value.r = (z1.r*z2.r+z1.i*z2.i)/num; value.i = (z1.i*z2.r-z1.r*z2.i)/num;
return value;
}
/* division of a complex z number by a real number x */
static gem_complex gem_cxrdiv(gem_complex z, double r)
{
gem_complex value;
value.r = z.r/r;
value.i = z.i/r;
return value;
}
/* division of a real number r by a complex number x */
static gem_complex gem_rxcdiv(double r, gem_complex z)
{
gem_complex value;
double f;
f = r/(z.r*z.r+z.i*z.i);
value.r = f*z.r;
value.i = -f*z.i;
return value;
}
/* Exponential of a complex number-- exp (z)=|exp(z.r)|*{cos(z.i)+I*sin(z.i)}*/
static gem_complex gem_cxdexp(gem_complex z)
{
gem_complex value;
double exp_z_r;
exp_z_r = exp(z.r);
value.r = exp_z_r*cos(z.i);
value.i = exp_z_r*sin(z.i);
return value;
}
/* Logarithm of a complex number -- log(z)=log|z|+I*Arg(z), */
/* where -PI < Arg(z) < PI */
static gem_complex gem_cxlog(gem_complex z)
{
gem_complex value;
double mag2;
mag2 = z.r*z.r+z.i*z.i;
if (mag2 < 0.)
{
fprintf(stderr, "ERROR in gem_cxlog func\n");
}
value.r = log(sqrt(mag2));
if (z.r == 0.)
{
value.i = PI/2.;
if (z.i < 0.)
{
value.i = -value.i;
}
}
else
{
value.i = atan2(z.i, z.r);
}
return value;
}
/* Square root of a complex number z = |z| exp(I*the) -- z^(1/2) */
/* z^(1/2)=|z|^(1/2)*[cos(the/2)+I*sin(the/2)] */
/* where 0 < the < 2*PI */
static gem_complex gem_cxdsqrt(gem_complex z)
{
gem_complex value;
double sq;
sq = gem_cx_abs(z);
value.r = sqrt(fabs((sq+z.r)*0.5)); /* z'.r={|z|*[1+cos(the)]/2}^(1/2) */
value.i = sqrt(fabs((sq-z.r)*0.5)); /* z'.i={|z|*[1-cos(the)]/2}^(1/2) */
if (z.i < 0.)
{
value.r = -value.r;
}
return value;
}
/* Complex power of a complex number z1^z2 */
static gem_complex gem_cxdpow(gem_complex z1, gem_complex z2)
{
gem_complex value;
value = gem_cxdexp(gem_cxmul(gem_cxlog(z1), z2));
return value;
}
/* ------------ end of complex.c ------------ */
/* This next part was derived from cubic.c, also received from Omer Markovitch.
* ------------- from cubic.c ------------- */
/* Solver for a cubic equation: x^3-a*x^2+b*x-c=0 */
static void gem_solve(gem_complex *al, gem_complex *be, gem_complex *gam,
double a, double b, double c)
{
double t1, t2, two_3, temp;
gem_complex ctemp, ct3;
two_3 = pow(2., 1./3.); t1 = -a*a+3.*b; t2 = 2.*a*a*a-9.*a*b+27.*c;
temp = 4.*t1*t1*t1+t2*t2;
ctemp = gem_cmplx(temp, 0.); ctemp = gem_cxadd(gem_cmplx(t2, 0.), gem_cxdsqrt(ctemp));
ct3 = gem_cxdpow(ctemp, gem_cmplx(1./3., 0.));
ctemp = gem_rxcdiv(-two_3*t1/3., ct3);
ctemp = gem_cxadd(ctemp, gem_cxrdiv(ct3, 3.*two_3));
*gam = gem_cxadd(gem_cmplx(a/3., 0.), ctemp);
ctemp = gem_cxmul(gem_cxsq(*gam), gem_cxsq(gem_cxsub(*gam, gem_cmplx(a, 0.))));
ctemp = gem_cxadd(ctemp, gem_cxmul(gem_cmplx(-4.*c, 0.), *gam));
ctemp = gem_cxdiv(gem_cxdsqrt(ctemp), *gam);
*al = gem_cxrmul(gem_cxsub(gem_cxsub(gem_cmplx(a, 0.), *gam), ctemp), 0.5);
*be = gem_cxrmul(gem_cxadd(gem_cxsub(gem_cmplx(a, 0.), *gam), ctemp), 0.5);
}
/* ------------ end of cubic.c ------------ */
/* This next part was derived from cerror.c and rerror.c, also received from Omer Markovitch.
* ------------- from [cr]error.c ------------- */
/************************************************************/
/* Real valued error function and related functions */
/* x, y : real variables */
/* erf(x) : error function */
/* erfc(x) : complementary error function */
/* omega(x) : exp(x*x)*erfc(x) */
/* W(x,y) : exp(-x*x)*omega(x+y)=exp(2*x*y+y^2)*erfc(x+y) */
/************************************************************/
/*---------------------------------------------------------------------------*/
/* Utilzed the series approximation of erf(x) */
/* Relative error=|err(x)|/erf(x)<EPS */
/* Handbook of Mathematical functions, Abramowitz, p 297 */
/* Note: When x>=6 series sum deteriorates -> Asymptotic series used instead */
/*---------------------------------------------------------------------------*/
/* This gives erfc(z) correctly only upto >10-15 */
static double gem_erf(double x)
{
double n, sum, temp, exp2, xm, x2, x4, x6, x8, x10, x12;
temp = x;
sum = temp;
xm = 26.;
x2 = x*x;
x4 = x2*x2;
x6 = x4*x2;
x8 = x6*x2;
x10 = x8*x2;
x12 = x10*x2;
exp2 = exp(-x2);
if (x <= xm)
{
for (n = 1.; n <= 2000.; n += 1.)
{
temp *= 2.*x2/(2.*n+1.);
sum += temp;
if (fabs(temp/sum) < 1.E-16)
{
break;
}
}
if (n >= 2000.)
{
fprintf(stderr, "In Erf calc - iteration exceeds %lg\n", n);
}
sum *= 2./sPI*exp2;
}
else
{
/* from the asymptotic expansion of experfc(x) */
sum = (1. - 0.5/x2 + 0.75/x4
- 1.875/x6 + 6.5625/x8
- 29.53125/x10 + 162.421875/x12)
/ sPI/x;
sum *= exp2; /* now sum is erfc(x) */
sum = -sum+1.;
}
return x >= 0.0 ? sum : -sum;
}
/* Result --> Alex's code for erfc and experfc behaves better than this */
/* complementray error function. Returns 1.-erf(x) */
static double gem_erfc(double x)
{
double t, z, ans;
z = fabs(x);
t = 1.0/(1.0+0.5*z);
ans = t * exp(-z*z - 1.26551223 +
t*(1.00002368 +
t*(0.37409196 +
t*(0.09678418 +
t*(-0.18628806 +
t*(0.27886807 +
t*(-1.13520398 +
t*(1.48851587 +
t*(-0.82215223 +
t*0.17087277)))))))));
return x >= 0.0 ? ans : 2.0-ans;
}
/* omega(x)=exp(x^2)erfc(x) */
static double gem_omega(double x)
{
double xm, ans, xx, x4, x6, x8, x10, x12;
xm = 26;
xx = x*x;
x4 = xx*xx;
x6 = x4*xx;
x8 = x6*xx;
x10 = x8*xx;
x12 = x10*xx;
if (x <= xm)
{
ans = exp(xx)*gem_erfc(x);
}
else
{
/* Asymptotic expansion */
ans = (1. - 0.5/xx + 0.75/x4 - 1.875/x6 + 6.5625/x8 - 29.53125/x10 + 162.421875/x12) / sPI/x;
}
return ans;
}
/*---------------------------------------------------------------------------*/
/* Utilzed the series approximation of erf(z=x+iy) */
/* Relative error=|err(z)|/|erf(z)|<EPS */
/* Handbook of Mathematical functions, Abramowitz, p 299 */
/* comega(z=x+iy)=cexp(z^2)*cerfc(z) */
/*---------------------------------------------------------------------------*/
static gem_complex gem_comega(gem_complex z)
{
gem_complex value;
double x, y;
double sumr, sumi, n, n2, f, temp, temp1;
double x2, y2, cos_2xy, sin_2xy, cosh_2xy, sinh_2xy, cosh_ny, sinh_ny, exp_y2;
x = z.r;
y = z.i;
x2 = x*x;
y2 = y*y;
sumr = 0.;
sumi = 0.;
cos_2xy = cos(2.*x*y);
sin_2xy = sin(2.*x*y);
cosh_2xy = cosh(2.*x*y);
sinh_2xy = sinh(2.*x*y);
exp_y2 = exp(-y2);
for (n = 1.0, temp = 0.; n <= 2000.; n += 1.0)
{
n2 = n*n;
cosh_ny = cosh(n*y);
sinh_ny = sinh(n*y);
f = exp(-n2/4.)/(n2+4.*x2);
/* if(f<1.E-200) break; */
sumr += (2.*x - 2.*x*cosh_ny*cos_2xy + n*sinh_ny*sin_2xy)*f;
sumi += (2.*x*cosh_ny*sin_2xy + n*sinh_ny*cos_2xy)*f;
temp1 = sqrt(sumr*sumr+sumi*sumi);
if (fabs((temp1-temp)/temp1) < 1.E-16)
{
break;
}
temp = temp1;
}
if (n == 2000.)
{
fprintf(stderr, "iteration exceeds %lg\n", n);
}
sumr *= 2./PI;
sumi *= 2./PI;
if (x != 0.)
{
f = 1./2./PI/x;
}
else
{
f = 0.;
}
value.r = gem_omega(x)-(f*(1.-cos_2xy)+sumr);
value.i = -(f*sin_2xy+sumi);
value = gem_cxmul(value, gem_cmplx(exp_y2*cos_2xy, exp_y2*sin_2xy));
return (value);
}
/* ------------ end of [cr]error.c ------------ */
/*_ REVERSIBLE GEMINATE RECOMBINATION
*
* Here are the functions for reversible geminate recombination. */
/* Changes the unit from square cm per s to square Ångström per ps,
* since Omers code uses the latter units while g_mds outputs the former.
* g_hbond expects a diffusion coefficent given in square cm per s. */
static double sqcm_per_s_to_sqA_per_ps (real D)
{
fprintf(stdout, "Diffusion coefficient is %f A^2/ps\n", D*1e4);
return (double)(D*1e4);
}
static double eq10v2(double theoryCt[], double time[], int manytimes,
double ka, double kd, t_gemParams *params)
{
/* Finding the 3 roots */
int i;
double kD, D, r, a, b, c, tsqrt, sumimaginary;
gem_complex
alpha, beta, gamma,
c1, c2, c3, c4,
oma, omb, omc,
part1, part2, part3, part4;
kD = params->kD;
D = params->D;
r = params->sigma;
a = (1.0 + ka/kD) * sqrt(D)/r;
b = kd;
c = kd * sqrt(D)/r;
gem_solve(&alpha, &beta, &gamma, a, b, c);
/* Finding the 3 roots */
sumimaginary = 0;
part1 = gem_cxmul(alpha, gem_cxmul(gem_cxadd(beta, gamma), gem_cxsub(beta, gamma))); /* 1(2+3)(2-3) */
part2 = gem_cxmul(beta, gem_cxmul(gem_cxadd(gamma, alpha), gem_cxsub(gamma, alpha))); /* 2(3+1)(3-1) */
part3 = gem_cxmul(gamma, gem_cxmul(gem_cxadd(alpha, beta), gem_cxsub(alpha, beta))); /* 3(1+2)(1-2) */
part4 = gem_cxmul(gem_cxsub(gamma, alpha), gem_cxmul(gem_cxsub(alpha, beta), gem_cxsub(beta, gamma))); /* (3-1)(1-2)(2-3) */
#pragma omp parallel for \
private(i, tsqrt, oma, omb, omc, c1, c2, c3, c4) \
reduction(+:sumimaginary) \
default(shared) \
schedule(guided)
for (i = 0; i < manytimes; i++)
{
tsqrt = sqrt(time[i]);
oma = gem_comega(gem_cxrmul(alpha, tsqrt));
c1 = gem_cxmul(oma, gem_cxdiv(part1, part4));
omb = gem_comega(gem_cxrmul(beta, tsqrt));
c2 = gem_cxmul(omb, gem_cxdiv(part2, part4));
omc = gem_comega(gem_cxrmul(gamma, tsqrt));
c3 = gem_cxmul(omc, gem_cxdiv(part3, part4));
c4.r = c1.r+c2.r+c3.r;
c4.i = c1.i+c2.i+c3.i;
theoryCt[i] = c4.r;
sumimaginary += c4.i * c4.i;
}
return sumimaginary;
} /* eq10v2 */
/* This returns the real-valued index(!) to an ACF, equidistant on a log scale. */
static double getLogIndex(const int i, const t_gemParams *params)
{
return (exp(((double)(i)) * params->logQuota) -1);
}
extern t_gemParams *init_gemParams(const double sigma, const double D,
const real *t, const int len, const int nFitPoints,
const real begFit, const real endFit,
const real ballistic, const int nBalExp, const gmx_bool bDt)
{
double tDelta;
t_gemParams *p;
snew(p, 1);
/* A few hardcoded things here. For now anyway. */
/* p->ka_min = 0; */
/* p->ka_max = 100; */
/* p->dka = 10; */
/* p->kd_min = 0; */
/* p->kd_max = 2; */
/* p->dkd = 0.2; */
p->ka = 0;
p->kd = 0;
/* p->lsq = -1; */
/* p->lifetime = 0; */
p->sigma = sigma*10; /* Omer uses Å, not nm */
/* p->lsq_old = 99999; */
p->D = sqcm_per_s_to_sqA_per_ps(D);
p->kD = 4*acos(-1.0)*sigma*p->D;
/* Parameters used by calcsquare(). Better to calculate them
* here than in calcsquare every time it's called. */
p->len = len;
/* p->logAfterTime = logAfterTime; */
tDelta = (t[len-1]-t[0]) / len;
if (tDelta <= 0)
{
gmx_fatal(FARGS, "Time between frames is non-positive!");
}
else
{
p->tDelta = tDelta;
}
p->nExpFit = nBalExp;
/* p->nLin = logAfterTime / tDelta; */
p->nFitPoints = nFitPoints;
p->begFit = begFit;
p->endFit = endFit;
p->logQuota = (double)(log(p->len))/(p->nFitPoints-1);
/* if (p->nLin <= 0) { */
/* fprintf(stderr, "Number of data points in the linear regime is non-positive!\n"); */
/* sfree(p); */
/* return NULL; */
/* } */
/* We want the same number of data points in the log regime. Not crucial, but seems like a good idea. */
/* p->logDelta = log(((float)len)/p->nFitPoints) / p->nFitPoints;/\* log(((float)len)/p->nLin) / p->nLin; *\/ */
/* p->logPF = p->nFitPoints*p->nFitPoints/(float)len; /\* p->nLin*p->nLin/(float)len; *\/ */
/* logPF and logDelta are stitched together with the macro GETLOGINDEX defined in geminate.h */
/* p->logMult = pow((float)len, 1.0/nLin);/\* pow(t[len-1]-t[0], 1.0/p->nLin); *\/ */
p->ballistic = ballistic;
return p;
}
/* There was a misunderstanding regarding the fitting. From our
* recent correspondence it appears that Omer's code require
* the ACF data on a log-scale and does not operate on the raw data.
* This needs to be redone in gemFunc_residual() as well as in the
* t_gemParams structure. */
#ifdef HAVE_LIBGSL
static double gemFunc_residual2(const gsl_vector *p, void *data)
{
gemFitData *GD;
int i, iLog, nLin, nFitPoints, nData;
double r, residual2, *ctTheory, *y;
GD = (gemFitData *)data;
nLin = GD->params->nLin;
nFitPoints = GD->params->nFitPoints;
nData = GD->nData;
residual2 = 0;
ctTheory = GD->ctTheory;
y = GD->y;
/* Now, we'd save a lot of time by not calculating eq10v2 for all
* time points, but only those that we sample to calculate the mse.
*/
eq10v2(GD->ctTheory, GD->doubleLogTime /* GD->time */, nFitPoints /* GD->nData */,
gsl_vector_get(p, 0), gsl_vector_get(p, 1),
GD->params);
fixGemACF(GD->ctTheory, nFitPoints);
/* Removing a bunch of points from the log-part. */
#pragma omp parallel for schedule(dynamic) \
firstprivate(nData, ctTheory, y, nFitPoints) \
private (i, iLog, r) \
reduction(+:residual2) \
default(shared)
for (i = 0; i < nFitPoints; i++)
{
iLog = GD->logtime[i];
r = log(ctTheory[i /* iLog */]);
residual2 += sqr(r-log(y[iLog]));
}
residual2 /= nFitPoints; /* Not really necessary for the fitting, but gives more meaning to the returned data. */
/* printf("ka=%3.5f\tkd=%3.5f\trmse=%3.5f\n", gsl_vector_get(p,0), gsl_vector_get(p,1), residual2); */
return residual2;
/* for (i=0; i<nLin; i++) { */
/* /\* Linear part ----------*\/ */
/* r = ctTheory[i]; */
/* residual2 += sqr(r-y[i]); */
/* /\* Log part -------------*\/ */
/* iLog = GETLOGINDEX(i, GD->params); */
/* if (iLog >= nData) */
/* gmx_fatal(FARGS, "log index out of bounds: %i", iLog); */
/* r = ctTheory[iLog]; */
/* residual2 += sqr(r-y[iLog]); */
/* } */
/* residual2 /= GD->n; */
/* return residual2; */
}
#endif
static real* d2r(const double *d, const int nn);
extern real fitGemRecomb(double *ct, double *time, double **ctFit,
const int nData, t_gemParams *params)
{
int nThreads, i, iter, status, maxiter;
real size, d2, tol, *dumpdata;
size_t p, n;
gemFitData *GD;
char *dumpstr, dumpname[128];
/* nmsimplex2 had convergence problems prior to gsl v1.14,
* but it's O(N) instead of O(N) operations, so let's use it if v >= 1.14 */
#ifdef HAVE_LIBGSL
gsl_multimin_fminimizer *s;
gsl_vector *x, *dx; /* parameters and initial step size */
gsl_multimin_function fitFunc;
#ifdef GSL_MAJOR_VERSION
#ifdef GSL_MINOR_VERSION
#if ((GSL_MAJOR_VERSION == 1 && GSL_MINOR_VERSION >= 14) || \
(GSL_MAJOR_VERSION > 1))
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2;
#else
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
#endif /* #if ... */
#endif /* GSL_MINOR_VERSION */
#else
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
#endif /* GSL_MAJOR_VERSION */
fprintf(stdout, "Will fit ka and kd to the ACF according to the reversible geminate recombination model.\n");
#else /* HAVE_LIBGSL */
fprintf(stderr, "Sorry, can't do reversible geminate recombination without gsl. "
"Recompile using --with-gsl.\n");
return -1;
#endif /* HAVE_LIBGSL */
#ifdef HAVE_LIBGSL
#ifdef GMX_OPENMP
nThreads = gmx_omp_get_max_threads();
gmx_omp_set_num_threads(nThreads);
fprintf(stdout, "We will be using %i threads.\n", nThreads);
#endif
iter = 0;
status = 0;
maxiter = 100;
tol = 1e-10;
p = 2; /* Number of parameters to fit. ka and kd. */
n = params->nFitPoints; /* params->nLin*2 */; /* Number of points in the reduced dataset */
if (params->D <= 0)
{
fprintf(stderr, "Fitting of D is not implemented yet. It must be provided on the command line.\n");
return -1;
}
/* if (nData<n) { */
/* fprintf(stderr, "Reduced data set larger than the complete data set!\n"); */
/* n=nData; */
/* } */
snew(dumpdata, nData);
snew(GD, 1);
GD->n = n;
GD->y = ct;
GD->ctTheory = NULL;
snew(GD->ctTheory, nData);
GD->LinLog = NULL;
snew(GD->LinLog, n);
GD->time = time;
GD->ka = 0;
GD->kd = 0;
GD->tDelta = time[1]-time[0];
GD->nData = nData;
GD->params = params;
snew(GD->logtime, params->nFitPoints);
snew(GD->doubleLogTime, params->nFitPoints);
for (i = 0; i < params->nFitPoints; i++)
{
GD->doubleLogTime[i] = (double)(getLogIndex(i, params));
GD->logtime[i] = (int)(GD->doubleLogTime[i]);
GD->doubleLogTime[i] *= GD->tDelta;
if (GD->logtime[i] >= nData)
{
fprintf(stderr, "Ayay. It seems we're indexing out of bounds.\n");
params->nFitPoints = i;
}
}
fitFunc.f = &gemFunc_residual2;
fitFunc.n = 2;
fitFunc.params = (void*)GD;
x = gsl_vector_alloc (fitFunc.n);
dx = gsl_vector_alloc (fitFunc.n);
gsl_vector_set (x, 0, 25);
gsl_vector_set (x, 1, 0.5);
gsl_vector_set (dx, 0, 0.1);
gsl_vector_set (dx, 1, 0.01);
s = gsl_multimin_fminimizer_alloc (T, fitFunc.n);
gsl_multimin_fminimizer_set (s, &fitFunc, x, dx);
gsl_vector_free (x);
gsl_vector_free (dx);
do
{
iter++;
status = gsl_multimin_fminimizer_iterate (s);
if (status != 0)
{
gmx_fatal(FARGS, "Something went wrong in the iteration in minimizer %s:\n \"%s\"\n",
gsl_multimin_fminimizer_name(s), gsl_strerror(status));
}
d2 = gsl_multimin_fminimizer_minimum(s);
size = gsl_multimin_fminimizer_size(s);
params->ka = gsl_vector_get (s->x, 0);
params->kd = gsl_vector_get (s->x, 1);
if (status)
{
fprintf(stderr, "%s\n", gsl_strerror(status));
break;
}
status = gsl_multimin_test_size(size, tol);
if (status == GSL_SUCCESS)
{
fprintf(stdout, "Converged to minimum at\n");
}
printf ("iter %5d: ka = %2.5f kd = %2.5f f() = %7.3f size = %.3f chi2 = %2.5f\n",
iter,
params->ka,
params->kd,
s->fval, size, d2);
if (iter%1 == 0)
{
eq10v2(GD->ctTheory, time, nData, params->ka, params->kd, params);
/* fixGemACF(GD->ctTheory, nFitPoints); */
sprintf(dumpname, "Iter_%i.xvg", iter);
for (i = 0; i < GD->nData; i++)
{
dumpdata[i] = (real)(GD->ctTheory[i]);
if (!gmx_isfinite(dumpdata[i]))
{
gmx_fatal(FARGS, "Non-finite value in acf.");
}
}
dumpN(dumpdata, GD->nData, dumpname);
}
}
while ((status == GSL_CONTINUE) && (iter < maxiter));
/* /\* Calculate the theoretical ACF from the parameters one last time. *\/ */
eq10v2(GD->ctTheory, time, nData, params->ka, params->kd, params);
*ctFit = GD->ctTheory;
sfree(GD);
gsl_multimin_fminimizer_free (s);
return d2;
#endif /* HAVE_LIBGSL */
}
#ifdef HAVE_LIBGSL
static int balFunc_f(const gsl_vector *x, void *data, gsl_vector *f)
{
/* C + sum{ A_i * exp(-B_i * t) }*/
balData *BD;
int n, i, j, nexp;
double *y, *A, *B, C, /* There are the parameters to be optimized. */
t, ct;
BD = (balData *)data;
n = BD->n;
nexp = BD->nexp;
y = BD->y,
snew(A, nexp);
snew(B, nexp);
for (i = 0; i < nexp; i++)
{
A[i] = gsl_vector_get(x, i*2);
B[i] = gsl_vector_get(x, i*2+1);
}
C = gsl_vector_get(x, nexp*2);
for (i = 0; i < n; i++)
{
t = i*BD->tDelta;
ct = 0;
for (j = 0; j < nexp; j++)
{
ct += A[j] * exp(B[j] * t);
}
ct += C;
gsl_vector_set (f, i, ct - y[i]);
}
return GSL_SUCCESS;
}
/* The derivative stored in jacobian form (J)*/
static int balFunc_df(const gsl_vector *params, void *data, gsl_matrix *J)
{
balData *BD;
size_t n, i, j;
double *y, *A, *B, C, /* There are the parameters. */
t;
int nexp;
BD = (balData*)data;
n = BD->n;
y = BD->y;
nexp = BD->nexp;
snew(A, nexp);
snew(B, nexp);
for (i = 0; i < nexp; i++)
{
A[i] = gsl_vector_get(params, i*2);
B[i] = gsl_vector_get(params, i*2+1);
}
C = gsl_vector_get(params, nexp*2);
for (i = 0; i < n; i++)
{
t = i*BD->tDelta;
for (j = 0; j < nexp; j++)
{
gsl_matrix_set (J, i, j*2, exp(B[j]*t)); /* df(t)/dA_j */
gsl_matrix_set (J, i, j*2+1, A[j]*t*exp(B[j]*t)); /* df(t)/dB_j */
}
gsl_matrix_set (J, i, nexp*2, 1); /* df(t)/dC */
}
return GSL_SUCCESS;
}
/* Calculation of the function and its derivative */
static int balFunc_fdf(const gsl_vector *params, void *data,
gsl_vector *f, gsl_matrix *J)
{
balFunc_f(params, data, f);
balFunc_df(params, data, J);
return GSL_SUCCESS;
}
#endif /* HAVE_LIBGSL */
/* Removes the ballistic term from the beginning of the ACF,
* just like in Omer's paper.
*/
extern void takeAwayBallistic(double *ct, double *t, int len, real tMax, int nexp, gmx_bool bDerivative)
{
/* Use nonlinear regression with GSL instead.
* Fit with 4 exponentials and one constant term,
* subtract the fatest exponential. */
int nData, i, status, iter;
balData *BD;
double *guess, /* Initial guess. */
*A, /* The fitted parameters. (A1, B1, A2, B2,... C) */
a[2],
ddt[2];
gmx_bool sorted;
size_t n;
size_t p;
nData = 0;
do
{
nData++;
}
while (t[nData] < tMax+t[0] && nData < len);
p = nexp*2+1; /* Number of parameters. */
#ifdef HAVE_LIBGSL
const gsl_multifit_fdfsolver_type *T
= gsl_multifit_fdfsolver_lmsder;
gsl_multifit_fdfsolver *s; /* The solver itself. */
gsl_multifit_function_fdf fitFunction; /* The function to be fitted. */
gsl_matrix *covar; /* Covariance matrix for the parameters.
* We'll not use the result, though. */
gsl_vector_view theParams;
nData = 0;
do
{
nData++;
}
while (t[nData] < tMax+t[0] && nData < len);
guess = NULL;
n = nData;
snew(guess, p);
snew(A, p);
covar = gsl_matrix_alloc (p, p);
/* Set up an initial gess for the parameters.
* The solver is somewhat sensitive to the initial guess,
* but this worked fine for a TIP3P box with -geminate dd
* EDIT: In fact, this seems like a good starting pont for other watermodels too. */
for (i = 0; i < nexp; i++)
{
guess[i*2] = 0.1;
guess[i*2+1] = -0.5 + (((double)i)/nexp - 0.5)*0.3;
}
guess[nexp * 2] = 0.01;
theParams = gsl_vector_view_array(guess, p);
snew(BD, 1);
BD->n = n;
BD->y = ct;
BD->tDelta = t[1]-t[0];
BD->nexp = nexp;
fitFunction.f = &balFunc_f;
fitFunction.df = &balFunc_df;
fitFunction.fdf = &balFunc_fdf;
fitFunction.n = nData;
fitFunction.p = p;
fitFunction.params = BD;
s = gsl_multifit_fdfsolver_alloc (T, nData, p);
if (s == NULL)
{
gmx_fatal(FARGS, "Could not set up the nonlinear solver.");
}
gsl_multifit_fdfsolver_set(s, &fitFunction, &theParams.vector);
/* \=============================================/ */
iter = 0;
do
{
iter++;
status = gsl_multifit_fdfsolver_iterate (s);
if (status)
{
break;
}
status = gsl_multifit_test_delta (s->dx, s->x, 1e-4, 1e-4);
}
while (iter < 5000 && status == GSL_CONTINUE);
if (iter == 5000)
{
fprintf(stderr, "The non-linear fitting did not converge in 5000 steps.\n"
"Check the quality of the fit!\n");
}
else
{
fprintf(stderr, "Non-linear fitting of ballistic term converged in %d steps.\n\n", (int)iter);
}
for (i = 0; i < nexp; i++)
{
fprintf(stdout, "%c * exp(%c * t) + ", 'A'+(char)i*2, 'B'+(char)i*2);
}
fprintf(stdout, "%c\n", 'A'+(char)nexp*2);
fprintf(stdout, "Here are the actual numbers for A-%c:\n", 'A'+nexp*2);
for (i = 0; i < nexp; i++)
{
A[i*2] = gsl_vector_get(s->x, i*2);
A[i*2+1] = gsl_vector_get(s->x, i*2+1);
fprintf(stdout, " %g*exp(%g * x) +", A[i*2], A[i*2+1]);
}
A[i*2] = gsl_vector_get(s->x, i*2); /* The last and constant term */
fprintf(stdout, " %g\n", A[i*2]);
fflush(stdout);
/* Implement some check for parameter quality */
for (i = 0; i < nexp; i++)
{
if (A[i*2] < 0 || A[i*2] > 1)
{
fprintf(stderr, "WARNING: ----------------------------------\n"
" | A coefficient does not lie within [0,1].\n"
" | This may or may not be a problem.\n"
" | Double check the quality of the fit!\n");
}
if (A[i*2+1] > 0)
{
fprintf(stderr, "WARNING: ----------------------------------\n"
" | One factor in the exponent is positive.\n"
" | This could be a problem if the coefficient\n"
" | is large. Double check the quality of the fit!\n");
}
}
if (A[i*2] < 0 || A[i*2] > 1)
{
fprintf(stderr, "WARNING: ----------------------------------\n"
" | The constant term does not lie within [0,1].\n"
" | This may or may not be a problem.\n"
" | Double check the quality of the fit!\n");
}
/* Sort the terms */
sorted = (nexp > 1) ? FALSE : TRUE;
while (!sorted)
{
sorted = TRUE;
for (i = 0; i < nexp-1; i++)
{
ddt[0] = A[i*2] * A[i*2+1];
ddt[1] = A[i*2+2] * A[i*2+3];
if ((bDerivative && (ddt[0] < 0 && ddt[1] < 0 && ddt[0] > ddt[1])) || /* Compare derivative at t=0... */
(!bDerivative && (A[i*2+1] > A[i*2+3]))) /* Or just the coefficient in the exponent */
{
sorted = FALSE;
a[0] = A[i*2]; /* coefficient */
a[1] = A[i*2+1]; /* parameter in the exponent */
A[i*2] = A[i*2+2];
A[i*2+1] = A[i*2+3];
A[i*2+2] = a[0];
A[i*2+3] = a[1];
}
}
}
/* Subtract the fastest component */
fprintf(stdout, "Fastest component is %g * exp(%g * t)\n"
"Subtracting fastest component from ACF.\n", A[0], A[1]);
for (i = 0; i < len; i++)
{
ct[i] = (ct[i] - A[0] * exp(A[1] * i*BD->tDelta)) / (1-A[0]);
}
sfree(guess);
sfree(A);
gsl_multifit_fdfsolver_free(s);
gsl_matrix_free(covar);
fflush(stdout);
#else
/* We have no gsl. */
fprintf(stderr, "Sorry, can't take away ballistic component without gsl. "
"Recompile using --with-gsl.\n");
return;
#endif /* HAVE_LIBGSL */
}
extern void dumpN(const real *e, const int nn, char *fn)
{
/* For debugging only */
int i;
FILE *f;
char standardName[] = "Nt.xvg";
if (fn == NULL)
{
fn = standardName;
}
f = fopen(fn, "w");
fprintf(f,
"@ type XY\n"
"@ xaxis label \"Frame\"\n"
"@ yaxis label \"N\"\n"
"@ s0 line type 3\n");
for (i = 0; i < nn; i++)
{
fprintf(f, "%-10i %-g\n", i, e[i]);
}
fclose(f);
}
static real* d2r(const double *d, const int nn)
{
real *r;
int i;
snew(r, nn);
for (i = 0; i < nn; i++)
{
r[i] = (real)d[i];
}
return r;
}
static void _patchBad(double *ct, int n, double dy)
{
/* Just do lin. interpolation for now. */
int i;
for (i = 1; i < n; i++)
{
ct[i] = ct[0]+i*dy;
}
}
static void patchBadPart(double *ct, int n)
{
_patchBad(ct, n, (ct[n] - ct[0])/n);
}
static void patchBadTail(double *ct, int n)
{
_patchBad(ct+1, n-1, ct[1]-ct[0]);
}
extern void fixGemACF(double *ct, int len)
{
int i, j, b, e;
gmx_bool bBad;
/* Let's separate two things:
* - identification of bad parts
* - patching of bad parts.
*/
b = 0; /* Start of a bad stretch */
e = 0; /* End of a bad stretch */
bBad = FALSE;
/* An acf of binary data must be one at t=0. */
if (abs(ct[0]-1.0) > 1e-6)
{
ct[0] = 1.0;
fprintf(stderr, "|ct[0]-1.0| = %1.6d. Setting ct[0] to 1.0.\n", abs(ct[0]-1.0));
}
for (i = 0; i < len; i++)
{
#ifdef HAS_ISFINITE
if (isfinite(ct[i]))
#elif defined(HAS__ISFINITE)
if (_isfinite(ct[i]))
#else
if (1)
#endif
{
if (!bBad)
{
/* Still on a good stretch. Proceed.*/
continue;
}
/* Patch up preceding bad stretch. */
if (i == (len-1))
{
/* It's the tail */
if (b <= 1)
{
gmx_fatal(FARGS, "The ACF is mostly NaN or Inf. Aborting.");
}
patchBadTail(&(ct[b-2]), (len-b)+1);
}
e = i;
patchBadPart(&(ct[b-1]), (e-b)+1);
bBad = FALSE;
}
else
{
if (!bBad)
{
b = i;
bBad = TRUE;
}
}
}
}
|
communication.h
|
/*! @brief Flag for checking if this header has already been included. */
#ifndef YGGCOMMUNICATION_H_
#define YGGCOMMUNICATION_H_
#include "../tools.h"
#include "../datatypes/datatypes.h"
#include "CommBase.h"
#include "IPCComm.h"
#include "ZMQComm.h"
#include "ServerComm.h"
#include "ClientComm.h"
#include "AsciiFileComm.h"
#include "AsciiTableComm.h"
#include "DefaultComm.h"
#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */
extern "C" {
#endif
/*! @brief Memory to keep track of comms to clean up at exit. */
static void **vcomms2clean = NULL;
static size_t ncomms2clean = 0;
static size_t clean_registered = 0;
static size_t clean_in_progress = 0;
static size_t clean_called = 0;
#ifdef _OPENMP
#pragma omp threadprivate(clean_in_progress)
#endif
/*! @brief Memory to keep track of global scope comms. */
#ifdef _OPENMP
static size_t global_scope_comm = 1;
#define WITH_GLOBAL_SCOPE(COMM) global_scope_comm = 1; COMM
#pragma omp threadprivate(global_scope_comm)
#else
static size_t global_scope_comm = 0;
#define WITH_GLOBAL_SCOPE(COMM) global_scope_comm = 1; COMM; global_scope_comm = 0
#endif
/*!
@brief Check if EOF should be sent for a comm being used on multiple threads.
@param[in] x const comm_t* Comm to check.
@returns int 1 if EOF has been sent for all but this comm and 0 otherwise.
*/
static
int check_threaded_eof(const comm_t* x) {
int out = 1;
#ifdef _OPENMP
#pragma omp critical (comms)
{
size_t i;
comm_t* icomm = NULL;
int nthreads = 1;
for (i = 0; i < ncomms2clean; i++) {
if ((out == 1) && (vcomms2clean[i] != NULL)) {
icomm = (comm_t*)(vcomms2clean[i]);
if ((strcmp(icomm->name, x->name) == 0)
&& (icomm->thread_id != x->thread_id)) {
nthreads++;
#pragma omp critical (sent_eof)
{
if ((x->sent_eof != NULL) && (x->sent_eof[0] == 0))
out = 0;
}
}
}
}
if (nthreads < omp_get_num_threads())
out = 0; // all threads havn't initialized a comm
}
#endif
return out;
};
/*!
@brief Set the sent_eof flag on the comm.
@param[in] x comm_t* Comm to set the flag for.
*/
static
void set_sent_eof(const comm_t* x) {
#ifdef _OPENMP
#pragma omp critical (sent_eof)
{
#endif
x->sent_eof[0] = 1;
if (x->type == CLIENT_COMM) {
comm_t *req_comm = (comm_t*)(x->handle);
// Don't recurse to prevent block w/ omp critical recursion
req_comm->sent_eof[0] = 1;
}
#ifdef _OPENMP
}
#endif
};
/*!
@brief Retrieve a registered global comm if it exists.
@param[in] const char* name Name that comm might be registered under.
@returns comm_t* Pointer to registered comm. NULL if one does not exist
with the specified name.
*/
static
comm_t* get_global_scope_comm(const char *name) {
comm_t* out = NULL;
#ifdef _OPENMP
#pragma omp critical (comms)
{
#endif
if (global_scope_comm) {
size_t i;
comm_t* icomm = NULL;
int current_thread = get_thread_id();
for (i = 0; i < ncomms2clean; i++) {
if (vcomms2clean[i] != NULL) {
icomm = (comm_t*)(vcomms2clean[i]);
if ((strcmp(icomm->name, name) == 0) && (icomm->thread_id == current_thread)) {
out = icomm;
break;
} else {
const char* YGG_MODEL_NAME = getenv("YGG_MODEL_NAME");
char alt_name[100];
sprintf(alt_name, "%s:%s", YGG_MODEL_NAME, name);
if ((strcmp(icomm->name, alt_name) == 0) && (icomm->thread_id == current_thread)) {
out = icomm;
break;
}
}
}
}
}
#ifdef _OPENMP
}
#endif
return out;
};
// Forward declaration of eof
static
int comm_send_eof(const comm_t *x);
static
int comm_nmsg(const comm_t *x);
/*!
@brief Determine if a channel has a format type associated with it.
@param[in] x comm_t * Pointer to communicator to check.
@returns int 1 if format type, 0 otherwise.
*/
static
int is_comm_format_array_type(const comm_t *x) {
dtype_t *datatype = x->datatype;
return is_dtype_format_array(datatype);
};
/*!
@brief Determine if the current thread can use a comm registered by another.
@param[in] int Thread that created the comm.
@returns int 1 if the current thread can use the comm, 0 otherwise.
*/
static
int thread_can_use(int thread_id) {
int current_thread_id = get_thread_id();
if ((clean_in_progress) && (current_thread_id == 0))
return 1;
if (thread_id == current_thread_id)
return 1;
return 0;
};
/*!
@brief Perform deallocation for type specific communicator.
@param[in] x comm_t * Pointer to communicator to deallocate.
@returns int 1 if there is an error, 0 otherwise.
*/
static
int free_comm_type(comm_t *x) {
comm_type t = x->type;
int ret = 1;
if (!(thread_can_use(x->thread_id))) {
ygglog_error("free_comm_type: Thread is attempting to use a comm it did not initialize");
return ret;
}
if (t == IPC_COMM)
ret = free_ipc_comm(x);
else if (t == ZMQ_COMM)
ret = free_zmq_comm(x);
else if (t == SERVER_COMM)
ret = free_server_comm(x);
else if (t == CLIENT_COMM)
ret = free_client_comm(x);
else if (t == ASCII_FILE_COMM)
ret = free_ascii_file_comm(x);
else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM))
ret = free_ascii_table_comm(x);
else {
ygglog_error("free_comm_type: Unsupported comm_type %d", t);
}
return ret;
};
/*!
@brief Perform deallocation for generic communicator.
@param[in] x comm_t * Pointer to communicator to deallocate.
@returns int 1 if there is an error, 0 otherwise.
*/
static
int free_comm(comm_t *x) {
int ret = 0;
if (x == NULL)
return ret;
ygglog_debug("free_comm(%s)", x->name);
// Send EOF for output comms and then wait for messages to be recv'd
if ((is_send(x->direction)) && (x->valid)) {
if (_ygg_error_flag == 0) {
ygglog_debug("free_comm(%s): Sending EOF", x->name);
comm_send_eof(x);
while (comm_nmsg(x) > 0) {
ygglog_debug("free_comm(%s): draining %d messages",
x->name, comm_nmsg(x));
usleep(YGG_SLEEP_TIME);
}
} else {
ygglog_error("free_comm(%s): Error registered", x->name);
}
}
#ifdef _OPENMP
#pragma omp critical (comms)
{
#endif
ret = free_comm_type(x);
int idx = x->index_in_register;
free_comm_base(x);
if (idx >= 0) {
if (vcomms2clean[idx] != NULL) {
free(vcomms2clean[idx]);
vcomms2clean[idx] = NULL;
}
}
ygglog_debug("free_comm: Finished");
#ifdef _OPENMP
}
#endif
return ret;
};
/*!
@brief Free comms created that were not freed.
*/
static
void clean_comms(void) {
#ifdef _OPENMP
#pragma omp critical (clean)
{
#endif
size_t i;
if (!(clean_called)) {
clean_in_progress = 1;
ygglog_debug("atexit begin");
if (vcomms2clean != NULL) {
for (i = 0; i < ncomms2clean; i++) {
if (vcomms2clean[i] != NULL) {
free_comm((comm_t*)(vcomms2clean[i]));
}
}
}
#ifdef _OPENMP
#pragma omp critical (comms)
{
#endif
if (vcomms2clean != NULL) {
free(vcomms2clean);
vcomms2clean = NULL;
}
ncomms2clean = 0;
ygglog_debug("atexit finished cleaning comms, in final shutdown");
#if defined(ZMQINSTALLED)
// #if defined(_MSC_VER) && defined(ZMQINSTALLED)
ygg_zsys_shutdown();
#endif
if (Py_IsInitialized()) {
Py_Finalize();
}
/* printf(""); */
clean_called = 1;
#ifdef _OPENMP
}
#endif
}
#ifdef _OPENMP
}
#endif
ygglog_debug("atexit done");
if (_ygg_error_flag != 0) {
_exit(_ygg_error_flag);
}
};
/*!
@brief Initialize yggdrasil in a thread-safe way
*/
static inline
int ygg_init() {
int out = 0;
#ifdef _OPENMP
#pragma omp critical (init)
{
#endif
ygglog_debug("ygg_init: clean_registered = %d", clean_registered);
if (clean_registered == 0) {
#if defined(ZMQINSTALLED)
if (!(ygg_zsys_init())) {
out = -1;
}
#endif
if (out == 0) {
ygglog_debug("ygg_init: Registering cleanup");
atexit(clean_comms);
clean_registered = 1;
}
}
#ifdef _OPENMP
}
#endif
return out;
};
/*!
@brief Register a comm so that it can be cleaned up later if not done explicitly.
@param[in] x comm_t* Address of communicator structure that should be
registered.
@returns int -1 if there is an error, 0 otherwise.
*/
static
int register_comm(comm_t *x) {
if (x == NULL) {
return 0;
}
int error_flag = 0;
#ifdef _OPENMP
#pragma omp critical (comms)
{
#endif
if (ygg_init()) {
error_flag = 1;
} else {
void **t_vcomms2clean = (void**)realloc(vcomms2clean, sizeof(void*)*(ncomms2clean + 1));
if (t_vcomms2clean == NULL) {
ygglog_error("register_comm(%s): Failed to realloc the comm list.", x->name);
error_flag = -1;
} else {
vcomms2clean = t_vcomms2clean;
x->index_in_register = (int)ncomms2clean;
vcomms2clean[ncomms2clean++] = (void*)x;
}
}
#ifdef _OPENMP
}
#endif
return error_flag;
};
/*!
@brief Initialize a new communicator based on its type.
@param[in] x comm_t * Pointer to communicator structure initialized with
new_base_comm;
@returns int -1 if the comm could not be initialized.
*/
static
int new_comm_type(comm_t *x) {
comm_type t = x->type;
int flag;
if (t == IPC_COMM)
flag = new_ipc_address(x);
else if (t == ZMQ_COMM)
flag = new_zmq_address(x);
else if (t == SERVER_COMM)
flag = new_server_address(x);
else if (t == CLIENT_COMM)
flag = new_client_address(x);
else if (t == ASCII_FILE_COMM)
flag = new_ascii_file_address(x);
else if (t == ASCII_TABLE_COMM)
flag = new_ascii_table_address(x);
else if (t == ASCII_TABLE_ARRAY_COMM)
flag = new_ascii_table_array_address(x);
else {
ygglog_error("new_comm_type: Unsupported comm_type %d", t);
flag = -1;
}
return flag;
};
/*!
@brief Initialize the communicator based on its type.
@param[in] x comm_t * Pointer to communicator structure initialized with
init_base_comm;
@returns int -1 if the comm could not be initialized.
*/
static
int init_comm_type(comm_t *x) {
comm_type t = x->type;
int flag;
if (t == IPC_COMM)
flag = init_ipc_comm(x);
else if (t == ZMQ_COMM)
flag = init_zmq_comm(x);
else if (t == SERVER_COMM)
flag = init_server_comm(x);
else if (t == CLIENT_COMM)
flag = init_client_comm(x);
else if (t == ASCII_FILE_COMM)
flag = init_ascii_file_comm(x);
else if (t == ASCII_TABLE_COMM)
flag = init_ascii_table_comm(x);
else if (t == ASCII_TABLE_ARRAY_COMM)
flag = init_ascii_table_array_comm(x);
else {
ygglog_error("init_comm_type: Unsupported comm_type %d", t);
flag = -1;
}
ygglog_debug("init_comm_type(%s): Done, flag = %d", x->name, flag);
return flag;
};
/*!
@brief Initialize comm from the address.
@param[in] address char * Address for new comm. If NULL, a new address is
generated.
@param[in] direction Direction that messages will go through the comm.
Values include "recv" and "send".
@param[in] t comm_type Type of comm that should be created.
@param[in] datatype dtype_t* Pointer to data type structure.
@returns comm_t* Pointer to comm structure.
*/
static
comm_t* new_comm(char *address, const char *direction,
const comm_type t, dtype_t* datatype) {
comm_t *ret = new_comm_base(address, direction, t, datatype);
if (ret == NULL) {
ygglog_error("new_comm: Could not initialize base.");
return ret;
}
int flag;
if (address == NULL) {
flag = new_comm_type(ret);
} else {
flag = init_comm_type(ret);
}
if (flag < 0) {
ygglog_error("new_comm: Failed to initialize new comm address.");
ret->valid = 0;
} else {
if (strlen(ret->name) == 0) {
sprintf(ret->name, "temp.%s", ret->address);
}
flag = register_comm(ret);
if (flag < 0) {
ygglog_error("new_comm: Failed to register new comm.");
ret->valid = 0;
}
}
return ret;
};
/*!
@brief Initialize a generic communicator.
The name is used to locate the comm address stored in the associated
environment variable.
@param[in] name Name of environment variable that the queue address is
stored in.
@param[in] direction Direction that messages will go through the comm.
Values include "recv" and "send".
@param[in] t comm_type Type of comm that should be created.
@param[in] datatype dtype_t* Pointer to data type structure.
@returns comm_t* Comm structure.
*/
static
comm_t* init_comm(const char *name, const char *direction,
const comm_type t, dtype_t *datatype) {
ygglog_debug("init_comm: Initializing comm.");
#ifdef _MSC_VER
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
_set_abort_behavior(0,_WRITE_ABORT_MSG);
#endif
comm_t *ret = get_global_scope_comm(name);
if (ret != NULL) {
destroy_dtype(&datatype);
return ret;
}
if ((datatype == NULL) && (strcmp(direction, "send") == 0)) {
datatype = create_dtype_scalar("bytes", 0, "", false);
}
ret = init_comm_base(name, direction, t, datatype);
if (ret == NULL) {
ygglog_error("init_comm(%s): Could not initialize base.", name);
return ret;
}
int flag = init_comm_type(ret);
if (flag < 0) {
ygglog_error("init_comm(%s): Could not initialize comm.", name);
ret->valid = 0;
} else {
flag = register_comm(ret);
if (flag < 0) {
ygglog_error("init_comm(%s): Failed to register new comm.", name);
ret->valid = 0;
}
}
if (ret->valid) {
if (global_scope_comm) {
ret->is_global = 1;
ygglog_debug("init_comm(%s): Global comm!", name);
}
ygglog_debug("init_comm(%s): Initialized comm.", name);
}
return ret;
};
/*!
@brief Convert a format string to a datatype.
@param[in] format_str char* Format string.
@param[in] as_array int If 1, inputs/outputs are processed as arrays.
@returns dtype_t* Pointer to datatype structure.
*/
static
dtype_t* formatstr2datatype(const char *format_str, const int as_array) {
dtype_t* datatype = NULL;
if (format_str != NULL) {
datatype = create_dtype_format(format_str, as_array, false);
}
return datatype;
};
/*!
@brief Initialize a generic communicator using a format string to determine
the type.
The name is used to locate the comm address stored in the associated
environment variable.
@param[in] name Name of environment variable that the queue address is
stored in.
@param[in] direction Direction that messages will go through the comm.
Values include "recv" and "send".
@param[in] t comm_type Type of comm that should be created.
@param[in] format_str char* Format string.
@param[in] as_array int If 1, inputs/outputs are processed as arrays.
@returns comm_t* Pointer to comm structure.
*/
static
comm_t* init_comm_format(const char *name, const char *direction,
const comm_type t, const char *format_str,
const int as_array) {
dtype_t* datatype = formatstr2datatype(format_str, as_array);
comm_t* out = init_comm(name, direction, t, datatype);
if ((format_str != NULL) && (datatype == NULL)) {
ygglog_error("init_comm_format: Failed to create type from format_str.");
if (out != NULL) {
out->valid = 0;
}
}
return out;
};
/*!
@brief Get number of messages in the comm.
@param[in] x comm_t Communicator to check.
@returns int Number of messages.
*/
static
int comm_nmsg(const comm_t *x) {
int ret = -1;
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("comm_nmsg: Invalid comm");
return ret;
}
comm_type t = x->type;
if (t == IPC_COMM)
ret = ipc_comm_nmsg(x);
else if (t == ZMQ_COMM)
ret = zmq_comm_nmsg(x);
else if (t == SERVER_COMM)
ret = server_comm_nmsg(x);
else if (t == CLIENT_COMM)
ret = client_comm_nmsg(x);
else if (t == ASCII_FILE_COMM)
ret = ascii_file_comm_nmsg(x);
else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM))
ret = ascii_table_comm_nmsg(x);
else {
ygglog_error("comm_nmsg: Unsupported comm_type %d", t);
}
return ret;
};
/*!
@brief Send a single message to the comm.
Send a message smaller than YGG_MSG_MAX bytes to an output comm. If the
message is larger, it will not be sent.
@param[in] x comm_t* structure that comm should be sent to.
@param[in] data character pointer to message that should be sent.
@param[in] len size_t length of message to be sent.
@returns int 0 if send succesfull, -1 if send unsuccessful.
*/
static
int comm_send_single(const comm_t *x, const char *data, const size_t len) {
ygglog_debug("Sending %d bytes: '%s'\n", len, data);
int ret = -1;
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("comm_send_single: Invalid comm");
return ret;
}
if (!(thread_can_use(x->thread_id))) {
ygglog_error("comm_send_single: Thread is attempting to use a comm it did not initialize");
return ret;
}
comm_type t = x->type;
if (t == IPC_COMM)
ret = ipc_comm_send(x, data, len);
else if (t == ZMQ_COMM)
ret = zmq_comm_send(x, data, len);
else if (t == SERVER_COMM)
ret = server_comm_send(x, data, len);
else if (t == CLIENT_COMM)
ret = client_comm_send(x, data, len);
else if (t == ASCII_FILE_COMM)
ret = ascii_file_comm_send(x, data, len);
else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM))
ret = ascii_table_comm_send(x, data, len);
else {
ygglog_error("comm_send_single: Unsupported comm_type %d", t);
}
if (ret >= 0) {
time(x->last_send);
/* time_t now; */
/* time(&now); */
/* x->last_send[0] = now; */
}
return ret;
};
/*!
@brief Create header for multipart message.
@param[in] x comm_t* structure that header will be sent to.
@param[in] data const char * Message to be sent.
@param[in] len size_t Size of message body.
@returns comm_head_t Header info that should be sent before the message
body.
*/
static
comm_head_t comm_send_multipart_header(const comm_t *x, const char * data,
const size_t len) {
comm_head_t head = init_header(len, NULL, NULL);
sprintf(head.id, "%d", rand());
char *model_name = getenv("YGG_MODEL_NAME");
if (model_name != NULL) {
strcpy(head.model, model_name);
}
head.multipart = 1;
head.valid = 1;
// Add datatype information to header
if (x->is_file == 0) {
dtype_t *datatype;
if (x->type == CLIENT_COMM) {
comm_t *req_comm = (comm_t*)(x->handle);
datatype = req_comm->datatype;
} else {
datatype = x->datatype;
}
head.dtype = datatype;
}
const comm_t *x0;
if (x->type == SERVER_COMM) {
comm_t **res_comm = (comm_t**)(x->info);
if (res_comm[0] == NULL) {
ygglog_error("comm_send_multipart_header(%s): no response comm registered",
x->name);
head.valid = 0;
return head;
}
x0 = &((*res_comm)[0]);
// Why was this necessary?
strcpy(head.id, x->address);
} else if (x->type == CLIENT_COMM) {
if (!(is_eof(data))) {
head = client_response_header(x, head);
}
x0 = (comm_t*)(x->handle);
} else {
x0 = x;
}
// Get ZMQ header info
if (x0->type == ZMQ_COMM) {
char *reply_address = set_reply_send(x0);
if (reply_address == NULL) {
ygglog_error("comm_send_multipart_header: Could not set reply address.");
head.valid = 0;
return head;
}
strcpy(head.zmq_reply, reply_address);
ygglog_debug("reply_address = %s\n", head.zmq_reply);
}
return head;
};
/*!
@brief Send a large message in multiple parts via a new comm.
@param[in] x comm_t* Structure that message should be sent to.
@param[in] data const char * Message that should be sent.
@param[in] len size_t Size of data.
@returns: int 0 if send successfull, -1 if send unsuccessful.
*/
static
int comm_send_multipart(const comm_t *x, const char *data, const size_t len) {
//char headbuf[YGG_MSG_BUF];
size_t headbuf_len = YGG_MSG_BUF;
int headlen = 0, ret = -1;
comm_t* xmulti = NULL;
int no_type = is_eof(data);
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("comm_send_multipart: Invalid comm");
return ret;
}
// Get header
comm_head_t head = comm_send_multipart_header(x, data, len);
if (head.valid == 0) {
ygglog_error("comm_send_multipart: Invalid header generated.");
return -1;
}
char *headbuf = (char*)malloc(headbuf_len);
if (headbuf == NULL) {
ygglog_error("comm_send_multipart: Failed to malloc headbuf.");
return -1;
}
// Try to send body in header
if (len < (x->maxMsgSize - x->msgBufSize)) {
headlen = format_comm_header(&head, &headbuf, headbuf_len,
x->maxMsgSize - x->msgBufSize,
no_type);
if (headlen < 0) {
ygglog_error("comm_send_multipart: Failed to format header.");
free(headbuf);
return -1;
}
if (((size_t)headlen + len) < (x->maxMsgSize - x->msgBufSize)) {
if (((size_t)headlen + len + 1) > headbuf_len) {
char *t_headbuf = (char*)realloc(headbuf, (size_t)headlen + len + 1);
if (t_headbuf == NULL) {
ygglog_error("comm_send_multipart: Failed to realloc headbuf.");
free(headbuf);
return -1;
}
headbuf = t_headbuf;
headbuf_len = (size_t)headlen + len + 1;
}
head.multipart = 0;
memcpy(headbuf + headlen, data, len);
headlen += (int)len;
headbuf[headlen] = '\0';
}
}
// Get head string
if (head.multipart == 1) {
// Get address for new comm and add to header
xmulti = new_comm(NULL, "send", x->type, NULL);
if ((xmulti == NULL) || (!(xmulti->valid))) {
ygglog_error("comm_send_multipart: Failed to initialize a new comm.");
free(headbuf);
return -1;
}
xmulti->sent_eof[0] = 1;
xmulti->recv_eof[0] = 1;
xmulti->is_work_comm = 1;
strcpy(head.address, xmulti->address);
if (xmulti->type == ZMQ_COMM) {
char *reply_address = set_reply_send(xmulti);
if (reply_address == NULL) {
ygglog_error("comm_send_multipart: Could not set worker reply address.");
return -1;
}
strcpy(head.zmq_reply_worker, reply_address);
ygglog_debug("comm_send_multipart: zmq worker reply address is '%s'",
head.zmq_reply_worker);
}
headlen = format_comm_header(&head, &headbuf, headbuf_len,
x->maxMsgSize - x->msgBufSize,
no_type);
if (headlen < 0) {
ygglog_error("comm_send_multipart: Failed to format header.");
free(headbuf);
if (xmulti != NULL) {
free_comm(xmulti);
}
return -1;
}
}
// Send header
size_t data_in_header = 0;
if ((head.type_in_data) && ((size_t)headlen > (x->maxMsgSize - x->msgBufSize))) {
ret = comm_send_single(x, headbuf, x->maxMsgSize - x->msgBufSize);
data_in_header = headlen - (x->maxMsgSize - x->msgBufSize);
} else {
ret = comm_send_single(x, headbuf, headlen);
}
if (ret < 0) {
ygglog_error("comm_send_multipart: Failed to send header.");
if (xmulti != NULL) {
free_comm(xmulti);
}
free(headbuf);
return -1;
}
if (head.multipart == 0) {
ygglog_debug("comm_send_multipart(%s): %d bytes completed", x->name, head.size);
free(headbuf);
return ret;
}
// Send data stored in header
size_t msgsiz;
size_t prev = headlen - data_in_header;
while (prev < (size_t)headlen) {
if ((headlen - prev) > (xmulti->maxMsgSize - xmulti->msgBufSize)) {
msgsiz = xmulti->maxMsgSize - xmulti->msgBufSize;
} else {
msgsiz = headlen - prev;
}
ret = comm_send_single(xmulti, headbuf + prev, msgsiz);
if (ret < 0) {
ygglog_debug("comm_send_multipart(%s): send of data in header interupted at %d of %d bytes.",
x->name, prev - (headlen - data_in_header), data_in_header);
break;
}
prev += msgsiz;
ygglog_debug("comm_send_multipart(%s): %d of %d bytes sent from data in header",
x->name, prev - (headlen - data_in_header), data_in_header);
}
head.size = head.size - data_in_header;
if (ret < 0) {
ygglog_error("comm_send_multipart: Failed to send data from header.");
if (xmulti != NULL) {
free_comm(xmulti);
}
free(headbuf);
return -1;
}
// Send multipart
prev = 0;
while (prev < head.size) {
if ((head.size - prev) > (xmulti->maxMsgSize - xmulti->msgBufSize)) {
msgsiz = xmulti->maxMsgSize - xmulti->msgBufSize;
} else {
msgsiz = head.size - prev;
}
ret = comm_send_single(xmulti, data + prev, msgsiz);
if (ret < 0) {
ygglog_debug("comm_send_multipart(%s): send interupted at %d of %d bytes.",
x->name, prev, head.size);
break;
}
prev += msgsiz;
ygglog_debug("comm_send_multipart(%s): %d of %d bytes sent",
x->name, prev, head.size);
}
if (ret == 0)
ygglog_debug("comm_send_multipart(%s): %d bytes completed", x->name, head.size);
// Free multipart
if (xmulti != NULL) {
free_comm(xmulti);
}
free(headbuf);
if (ret >= 0)
x->used[0] = 1;
return ret;
};
/*!
@brief Send a message to the comm.
Send a message smaller than YGG_MSG_MAX bytes to an output comm. If the
message is larger, it will not be sent.
@param[in] x comm_t* structure that comm should be sent to.
@param[in] data character pointer to message that should be sent.
@param[in] len size_t length of message to be sent.
@returns int 0 if send succesfull, -1 if send unsuccessful.
*/
static
int comm_send(const comm_t *x, const char *data, const size_t len) {
int ret = -1;
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("comm_send: Invalid comm");
return ret;
}
if (x->sent_eof == NULL) {
ygglog_error("comm_send(%s): sent_eof not initialized.", x->name);
return ret;
}
int sending_eof = 0;
if (is_eof(data)) {
if (x->sent_eof[0]) {
ygglog_debug("comm_send(%s): EOF already sent", x->name);
return ret;
} else if (!(check_threaded_eof(x))) {
ygglog_debug("comm_send(%s): EOF not sent on other threads", x->name);
set_sent_eof(x);
return 0;
} else {
set_sent_eof(x);
sending_eof = 1;
ygglog_debug("comm_send(%s): Sending EOF", x->name);
}
}
if (((len > x->maxMsgSize) && (x->maxMsgSize > 0)) ||
(((x->always_send_header) || (x->used[0] == 0)))) {
ygglog_debug("comm_send(%s): Sending as one or more messages with a header.",
x->name);
ret = comm_send_multipart(x, data, len);
} else {
ygglog_debug("comm_send(%s): Sending as single message without a header.",
x->name);
ret = comm_send_single(x, data, len);
}
if (sending_eof) {
ygglog_debug("comm_send(%s): sent EOF, ret = %d", x->name, ret);
}
if (ret >= 0)
x->used[0] = 1;
return ret;
};
/*!
@brief Send EOF message to the comm.
@param[in] x comm_t structure that message should be sent to.
@returns int 0 if send successfull, -1 otherwise.
*/
static
int comm_send_eof(const comm_t *x) {
int ret = -1;
char buf[100] = YGG_MSG_EOF;
ret = comm_send(x, buf, strlen(buf));
return ret;
};
/*!
@brief Receive a message from an input comm.
Receive a message smaller than YGG_MSG_MAX bytes from an input comm.
@param[in] x comm_t* structure that message should be sent to.
@param[out] data char ** pointer to allocated buffer where the message
should be saved. This should be a malloc'd buffer if allow_realloc is 1.
@param[in] len const size_t length of the allocated message buffer in bytes.
@param[in] allow_realloc const int If 1, the buffer will be realloced if it
is not large enought. Otherwise an error will be returned.
@returns int -1 if message could not be received, otherwise the length of
the received message.
*/
static
int comm_recv_single(comm_t *x, char **data, const size_t len,
const int allow_realloc) {
int ret = -1;
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("comm_recv_single: Invalid comm");
return ret;
}
if (!(thread_can_use(x->thread_id))) {
ygglog_error("comm_recv_single: Thread is attempting to use a comm it did not initialize");
return ret;
}
comm_type t = x->type;
if (t == IPC_COMM)
ret = ipc_comm_recv(x, data, len, allow_realloc);
else if (t == ZMQ_COMM)
ret = zmq_comm_recv(x, data, len, allow_realloc);
else if (t == SERVER_COMM)
ret = server_comm_recv(x, data, len, allow_realloc);
else if (t == CLIENT_COMM)
ret = client_comm_recv(x, data, len, allow_realloc);
else if (t == ASCII_FILE_COMM)
ret = ascii_file_comm_recv(x, data, len, allow_realloc);
else if ((t == ASCII_TABLE_COMM) || (t == ASCII_TABLE_ARRAY_COMM))
ret = ascii_table_comm_recv(x, data, len, allow_realloc);
else {
ygglog_error("comm_recv: Unsupported comm_type %d", t);
}
return ret;
};
/*!
@brief Receive a message in multiple parts.
@param[in] x comm_t* Comm that message should be recieved from.
@param[in] data char ** Pointer to buffer where message should be stored.
@param[in] len size_t Size of data buffer.
@param[in] headlen size_t Size of header in data buffer.
@param[in] allow_realloc int If 1, data will be realloced if the incoming
message is larger than the buffer. Otherwise, an error will be returned.
@returns int -1 if unsucessful, size of message received otherwise.
*/
static
int comm_recv_multipart(comm_t *x, char **data, const size_t len,
const size_t headlen, const int allow_realloc) {
int ret = -1;
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("comm_recv_multipart: Invalid comm");
return ret;
}
usleep(100);
comm_head_t head = parse_comm_header(*data, headlen);
if (!(head.valid)) {
ygglog_error("comm_recv_multipart(%s): Error parsing header.", x->name);
ret = -1;
} else {
// Move body to front of data and return if EOF
memmove(*data, *data + head.bodybeg, head.bodysiz);
(*data)[head.bodysiz] = '\0';
if (is_eof(*data)) {
ygglog_debug("comm_recv_multipart(%s): EOF received.", x->name);
x->recv_eof[0] = 1;
destroy_header(&head);
return -2;
}
// Get datatype information from header on first recv
dtype_t *updtype;
if (x->type == SERVER_COMM) {
comm_t *handle = (comm_t*)(x->handle);
updtype = handle->datatype;
} else {
updtype = x->datatype;
}
if ((x->used[0] == 0) && (x->is_file == 0) && (updtype->obj == NULL) && (head.type_in_data == 0)) {
ygglog_debug("comm_recv_multipart(%s): Updating datatype to '%s'",
x->name, head.dtype->type);
ret = update_dtype(updtype, head.dtype);
if (ret != 0) {
ygglog_error("comm_recv_multipart(%s): Error updating datatype.", x->name);
destroy_header(&head);
return -1;
}
} else if ((x->is_file == 0) && (head.dtype != NULL)) {
ret = update_dtype(updtype, head.dtype);
if (ret != 0) {
ygglog_error("comm_recv_multipart(%s): Error updating existing datatype.", x->name);
destroy_header(&head);
return -1;
}
}
if (head.multipart) {
// Return early if header contained entire message
if (head.size == head.bodysiz) {
x->used[0] = 1;
destroy_header(&head);
return (int)(head.bodysiz);
}
// Get address for new comm
comm_t* xmulti = new_comm(head.address, "recv", x->type, NULL);
if ((xmulti == NULL) || (!(xmulti->valid))) {
ygglog_error("comm_recv_multipart: Failed to initialize a new comm.");
destroy_header(&head);
return -1;
}
xmulti->sent_eof[0] = 1;
xmulti->recv_eof[0] = 1;
xmulti->is_work_comm = 1;
if (xmulti->type == ZMQ_COMM) {
int reply_socket = set_reply_recv(xmulti, head.zmq_reply_worker);
if (reply_socket < 0) {
ygglog_error("comm_recv_multipart: Failed to set worker reply address.");
destroy_header(&head);
return -1;
}
}
// Receive parts of message
size_t prev = head.bodysiz;
size_t msgsiz = 0;
// Reallocate data if necessary
if ((head.size + 1) > len) {
if (allow_realloc) {
char *t_data = (char*)realloc(*data, head.size + 1);
if (t_data == NULL) {
ygglog_error("comm_recv_multipart(%s): Failed to realloc buffer",
x->name);
free(*data);
free_comm(xmulti);
destroy_header(&head);
return -1;
}
*data = t_data;
} else {
ygglog_error("comm_recv_multipart(%s): buffer is not large enough",
x->name);
free_comm(xmulti);
destroy_header(&head);
return -1;
}
}
ret = -1;
char *pos = (*data) + prev;
while (prev < head.size) {
msgsiz = head.size - prev + 1;
ret = comm_recv_single(xmulti, &pos, msgsiz, 0);
if (ret < 0) {
ygglog_debug("comm_recv_multipart(%s): recv interupted at %d of %d bytes.",
x->name, prev, head.size);
break;
}
prev += ret;
pos += ret;
ygglog_debug("comm_recv_multipart(%s): %d of %d bytes received",
x->name, prev, head.size);
}
if ((ret > 0) && (head.type_in_data)) {
ygglog_debug("comm_recv_multipart(%s): Extracting type from data.");
ret = parse_type_in_data(data, prev, &head);
if (ret > 0) {
prev = ret;
ret = update_dtype(updtype, head.dtype);
if (ret != 0) {
ygglog_error("comm_recv_multipart(%s): Error updating existing datatype.", x->name);
destroy_header(&head);
return -1;
} else {
ret = (int)prev;
}
}
}
if (ret > 0) {
ygglog_debug("comm_recv_multipart(%s): %d bytes completed", x->name, prev);
ret = (int)prev;
}
free_comm(xmulti);
} else {
ret = (int)(head.bodysiz);
}
}
if (ret >= 0)
x->used[0] = 1;
destroy_header(&head);
return ret;
};
/*!
@brief Receive a message from an input comm.
An error will be returned if the buffer is not large enough.
@param[in] x comm_t* structure that message should be sent to.
@param[out] data character pointer to allocated buffer where the
message should be saved.
@param[in] len const size_t length of the allocated message buffer in bytes.
@returns int -1 if message could not be received and -2 if EOF is received.
Length of the received message otherwise.
*/
static
int comm_recv(comm_t *x, char *data, const size_t len) {
int ret = comm_recv_single(x, &data, len, 0);
if (ret > 0) {
if (is_eof(data)) {
ygglog_debug("comm_recv(%s): EOF received.", x->name);
x->recv_eof[0] = 1;
ret = -2;
} else {
ret = comm_recv_multipart(x, &data, len, ret, 0);
}
} else {
ygglog_error("comm_recv_realloc(%s): Failed to receive header or message.",
x->name);
}
return ret;
};
/*!
@brief Receive a message from an input comm, reallocating as necessary.
@param[in] x comm_t* structure that message should be sent to.
@param[out] data character pointer to pointer to allocated buffer where the
message should be saved.
@param[in] len const size_t length of the allocated message buffer in bytes.
@returns int -1 if message could not be received and -2 if EOF is received.
Length of the received message otherwise.
*/
static
int comm_recv_realloc(comm_t *x, char **data, const size_t len) {
int ret = comm_recv_single(x, data, len, 1);
if (ret > 0) {
if (is_eof(*data)) {
ygglog_debug("comm_recv_realloc(%s): EOF received.", x->name);
x->recv_eof[0] = 1;
ret = -2;
} else {
ret = comm_recv_multipart(x, data, len, ret, 1);
}
} else {
ygglog_error("comm_recv_realloc(%s): Failed to receive header or message.",
x->name);
}
return ret;
};
/*! @brief alias for comm_send. */
static
int comm_send_nolimit(const comm_t *x, const char *data, const size_t len) {
return comm_send(x, data, len);
};
/*!
@brief Send EOF message to the comm.
@param[in] x comm_t* structure that message should be sent to.
@returns int 0 if send successfull, -1 otherwise.
*/
static
int comm_send_nolimit_eof(const comm_t *x) {
int ret = -1;
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("comm_send_nolimit_eof: Invalid comm");
return ret;
}
if (x->sent_eof == NULL) {
ygglog_error("comm_send_nolimit_eof(%s): sent_eof not initialized.", x->name);
return ret;
}
if (x->sent_eof[0] == 0) {
char buf[2048] = YGG_MSG_EOF;
ret = comm_send_nolimit(x, buf, strlen(buf));
x->sent_eof[0] = 1;
} else {
ygglog_debug("comm_send_nolimit_eof(%s): EOF already sent", x->name);
}
return ret;
};
/*!
@brief Receive a large message from an input comm.
Receive a message larger than YGG_MSG_MAX bytes from an input comm by
receiving it in parts. This expects the first message to be the size of
the total message.
@param[in] x comm_t structure that message should be sent to.
@param[out] data character pointer to pointer for allocated buffer where the
message should be stored. A pointer to a pointer is used so that the buffer
may be reallocated as necessary for the incoming message.
@param[in] len size_t length of the initial allocated message buffer in bytes.
@returns int -1 if message could not be received and -2 if EOF is received.
Length of the received message otherwise.
*/
static
int comm_recv_nolimit(comm_t *x, char **data, const size_t len) {
return comm_recv_realloc(x, data, len);
};
/*!
@brief Send arguments as a small formatted message to an output comm.
Use the format string to create a message from the input arguments that
is then sent to the specified output comm. If the message is larger than
YGG_MSG_MAX or cannot be encoded, it will not be sent.
@param[in] x comm_t* structure for comm that message should be sent to.
@param[in] nargs size_t Number of arguments in the variable argument list.
@param[in] ap va_list arguments to be formatted into a message using sprintf.
@returns int Number of arguments formatted if send succesfull, -1 if send
unsuccessful.
*/
static
int vcommSend(const comm_t *x, size_t nargs, va_list_t ap) {
ygglog_debug("vcommSend: Formatting %lu arguments.", nargs);
int ret = -1;
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("vcommSend: Invalid comm");
return ret;
}
size_t buf_siz = YGG_MSG_BUF;
// char *buf = NULL;
char *buf = (char*)malloc(buf_siz);
if (buf == NULL) {
ygglog_error("vcommSend(%s): Failed to alloc buffer", x->name);
return -1;
}
dtype_t *datatype = x->datatype;
if (x->type == CLIENT_COMM) {
comm_t *handle = (comm_t*)(x->handle);
datatype = handle->datatype;
}
// Update datatype if not yet set and object being sent includes type
if (update_dtype_from_generic_ap(datatype, nargs, ap) < 0) {
return -1;
}
size_t nargs_orig = nargs;
ret = serialize_dtype(datatype, &buf, &buf_siz, 1, &nargs, ap);
if (ret < 0) {
ygglog_error("vcommSend(%s): serialization error", x->name);
free(buf);
return -1;
}
ret = comm_send(x, buf, ret);
ygglog_debug("vcommSend(%s): comm_send returns %d, nargs (remaining) = %d",
x->name, ret, nargs);
free(buf);
if (ret < 0) {
return ret;
} else {
return (int)(nargs_orig - nargs);
}
};
/*!
@brief Send arguments as a formatted message to an output comm.
Use the format string to create a message from the input arguments that
is then sent to the specified output comm.
@param[in] x comm_t structure for comm that message should be sent to.
@param[in] nargs size_t Number of variable arguments provided.
@param[in] ... Arguments to be formatted into a message using sprintf.
@returns int Number of arguments formatted if send succesfull, -1 if send
unsuccessful.
*/
static
int ncommSend(const comm_t *x, size_t nargs, ...) {
va_list_t ap = init_va_list();
va_start(ap.va, nargs);
ygglog_debug("ncommSend: nargs = %d", nargs);
int ret = vcommSend(x, nargs, ap);
va_end(ap.va);
return ret;
};
#define commSend(x, ...) ncommSend(x, COUNT_VARARGS(__VA_ARGS__), __VA_ARGS__)
/*!
@brief Assign arguments by receiving and parsing a message from an input comm.
Receive a message smaller than YGG_MSG_MAX bytes from an input comm and parse
it using the associated format string.
@param[in] x comm_t structure for comm that message should be sent to.
@param[in] allow_realloc int If 1, variables being filled are assumed to be
pointers to pointers for heap memory. If 0, variables are assumed to be pointers
to stack memory. If allow_realloc is set to 1, but stack variables are passed,
a segfault can occur.
@param[in] nargs size_t Number of arguments in the variable argument list.
@param[out] ap va_list arguments that should be assigned by parsing the
received message using sscanf. As these are being assigned, they should be
pointers to memory that has already been allocated.
@returns int -1 if message could not be received or could not be parsed.
Length of the received message if message was received and parsed. -2 is
returned if EOF is received.
*/
static
int vcommRecv(comm_t *x, const int allow_realloc, size_t nargs, va_list_t ap) {
int ret = -1;
ygglog_debug("vcommRecv: Parsing %lu arguments.", nargs);
if ((x == NULL) || (x->valid == 0)) {
ygglog_error("vcommRecv: Invalid comm");
return ret;
}
// Receive message
size_t buf_siz = YGG_MSG_BUF;
/* char *buf = NULL; */
char *buf = (char*)malloc(buf_siz);
if (buf == NULL) {
ygglog_error("vcommRecv(%s): Failed to alloc buffer", x->name);
return -1;
}
ret = comm_recv_nolimit(x, &buf, buf_siz);
if (ret < 0) {
// ygglog_error("vcommRecv(%s): Error receiving.", x->name);
free(buf);
return ret;
}
ygglog_debug("vcommRecv(%s): comm_recv returns %d: %.10s...", x->name, ret, buf);
// Deserialize message
dtype_t *datatype = x->datatype;
if (x->type == SERVER_COMM) {
comm_t *handle = (comm_t*)(x->handle);
datatype = handle->datatype;
}
ret = deserialize_dtype(datatype, buf, ret, allow_realloc, &nargs, ap);
if (ret < 0) {
ygglog_error("vcommRecv(%s): error deserializing message (ret=%d)",
x->name, ret);
free(buf);
return -1;
}
ygglog_debug("vcommRecv(%s): deserialize_format returns %d", x->name, ret);
free(buf);
return ret;
};
/*!
@brief Assign arguments by receiving and parsing a message from an input comm.
Receive a message from an input comm and parse it using the associated type.
@param[in] x comm_t* structure for comm that message should be sent to.
@param[in] allow_realloc int If 1, variables being filled are assumed to be
pointers to pointers for heap memory. If 0, variables are assumed to be pointers
to stack memory. If allow_realloc is set to 1, but stack variables are passed,
a segfault can occur.
@param[in] nargs size_t Number of variable arguments provided.
@param[out] ... arguments that should be assigned by parsing the
received message using sscanf. As these are being assigned, they should be
pointers to memory that has already been allocated.
@returns int -1 if message could not be received or could not be parsed.
Length of the received message if message was received and parsed. -2 is
returned if EOF is received.
*/
static
int ncommRecv(comm_t *x, const int allow_realloc, size_t nargs, ...) {
va_list_t ap = init_va_list();
va_start(ap.va, nargs);
ygglog_debug("ncommRecv: nargs = %d", nargs);
int ret = vcommRecv(x, allow_realloc, nargs, ap);
va_end(ap.va);
return ret;
};
#define commRecvStack(x, ...) ncommRecv(x, 0, COUNT_VARARGS(__VA_ARGS__), __VA_ARGS__)
#define commRecvHeap(x, ...) ncommRecv(x, 1, COUNT_VARARGS(__VA_ARGS__), __VA_ARGS__)
#define commRecv commRecvStack
#define commRecvRealloc commRecvHeap
#define vcommSend_nolimit vcommSend
#define vcommRecv_nolimit vcommRecv
#ifdef __cplusplus /* If this is a C++ compiler, end C linkage */
}
#endif
#endif /*YGGCOMMUNICATION_H_*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.