source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
openmp_bucket_sort.c | #include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <inttypes.h>
/* bucket sort using multiple threads
first argument - problem size
second argument - number of buckets
third argument - number of threads */
int main (int argc, char *argv[])
{
uint32_t seed = (unsigned int)time(NULL);
srand (seed);
int N = atoi(argv[1]);
//int buckets_per_thread = atoi(argv[2]);
int threads_count;
int buckets_count;
double *tab;
double **buckets;
int *bucket_sizes;
double start;
double end;
omp_set_num_threads(atoi(argv[3]));
#pragma omp parallel
{
int i;
#pragma omp single
{
threads_count = omp_get_num_threads();
buckets_count = atoi(argv[2]);
tab = malloc(sizeof(double)*N);
buckets = malloc(sizeof(double*) * buckets_count);
bucket_sizes = malloc(sizeof(int) * buckets_count);
printf("Threads: %d, Buckets: %d\n ", threads_count, buckets_count);
for (i = 0; i < buckets_count; i++)
{
buckets[i] = malloc(sizeof(double) * N);
bucket_sizes[i] = 0;
}
for (i = 0; i < N; i++)
tab[i] = ((double)rand()/(double)(RAND_MAX));
start = omp_get_wtime();
}
#pragma omp for schedule(static)
for (i = 0; i < buckets_count; i++)
{
//printf(" - filling %d by %d\n", i, omp_get_thread_num());
int j;
for (j = 0; j < N; j++)
{
int bucket_num = (int)(tab[j]*buckets_count);
if (bucket_num == i)
buckets[bucket_num][bucket_sizes[bucket_num]++] = tab[j];
}
}
#pragma omp for schedule(static)
for (i = 0; i < buckets_count; i++)
{
//printf(" - sorting %d by %d\n", i, omp_get_thread_num());
int bucket_start_index = 0;
int j, k;
for (j = 0; j < i; j++)
bucket_start_index += bucket_sizes[j];
for (j = 0; j < bucket_sizes[i]; j++)
{
for (k = 0; k < bucket_sizes[i] - 1; k++)
{
if (buckets[i][k] > buckets[i][k + 1])
{
double tmp = buckets[i][k];
buckets[i][k] = buckets[i][k + 1];
buckets[i][k + 1] = tmp;
}
}
}
for (j = 0; j < bucket_sizes[i]; j++)
tab[bucket_start_index + j] = buckets[i][j];
}
#pragma omp single
{
end = omp_get_wtime();
free(tab);
for (i = 0; i < buckets_count; i++)
{
free(buckets[i]);
}
free(buckets);
printf(" - total time of sorting: %f\n", end-start);
}
}
return 0;
}
|
app.c | /**
* Christina Giannoula
* cgiannoula: christina.giann@gmail.com
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <dpu.h>
#include <dpu_log.h>
#include <unistd.h>
#include <getopt.h>
#include <assert.h>
#include <math.h>
#include <omp.h>
#include "../support/common.h"
#include "../support/matrix.h"
#include "../support/params.h"
#include "../support/partition.h"
#include "../support/timer.h"
#include "../support/utils.h"
// Define the DPU Binary path as DPU_BINARY here.
#ifndef DPU_BINARY
#define DPU_BINARY "./bin/spmv_dpu"
#endif
#define DPU_CAPACITY (64 << 20) // A DPU's capacity is 64 MB
/*
* Main Structures:
* 1. Matrices
* 2. Input vector
* 3. Output vector
* 4. Help structures for data partitioning
*/
static struct DCSRMatrix* A;
static struct COOMatrix* B;
static val_dt* x;
static val_dt* y;
static struct partition_info_t *part_info;
/**
* @brief Specific information for each DPU
*/
struct dpu_info_t {
uint32_t rows_per_dpu;
uint32_t rows_per_dpu_pad;
uint32_t prev_rows_dpu;
uint32_t prev_nnz_dpu;
uint32_t nnz;
uint32_t nnz_pad;
uint32_t ptr_offset;
};
struct dpu_info_t *dpu_info;
/**
* @brief find the dpus_per_vert_partition
* @param factor n to create partitions
* @param vertical_partitions
* @param/return horz_partitions
*/
void find_partitions(uint32_t n, uint32_t *horz_partitions, uint32_t vert_partitions) {
uint32_t dpus_per_vert_partition = n / vert_partitions;
*horz_partitions = dpus_per_vert_partition;
}
/**
* @brief initialize input vector
* @param pointer to input vector and vector size
*/
void init_vector(val_dt* vec, uint32_t size) {
for(unsigned int i = 0; i < size; ++i) {
vec[i] = (val_dt) (i%4+1);
}
}
/**
* @brief compute output in the host CPU
*/
static void spmv_host(val_dt* y, struct DCSRMatrix *A, val_dt* x) {
uint64_t total_nnzs = 0;
for (uint32_t r = 0; r < A->horz_partitions; r++) {
for (uint32_t c = 0; c < A->vert_partitions; c++) {
for(uint32_t rowIndx = 0; rowIndx < A->tile_height; ++rowIndx) {
val_dt sum = 0;
uint32_t ptr_offset = (r * A->vert_partitions + c) * (A->tile_height + 1);
uint32_t row_offset = r * A->tile_height;
uint32_t col_offset = c * A->tile_width;
for(uint32_t n = A->drowptr[ptr_offset + rowIndx]; n < A->drowptr[ptr_offset + rowIndx + 1]; n++) {
uint32_t colIndx = A->dcolind[total_nnzs];
val_dt value = A->dval[total_nnzs++];
sum += x[col_offset + colIndx] * value;
}
y[row_offset + rowIndx] += sum;
}
}
}
}
/**
* @brief main of the host application
*/
int main(int argc, char **argv) {
struct Params p = input_params(argc, argv);
struct dpu_set_t dpu_set, dpu;
uint32_t nr_of_dpus;
// Allocate DPUs and load binary
DPU_ASSERT(dpu_alloc(NR_DPUS, NULL, &dpu_set));
DPU_ASSERT(dpu_load(dpu_set, DPU_BINARY, NULL));
DPU_ASSERT(dpu_get_nr_dpus(dpu_set, &nr_of_dpus));
printf("[INFO] Allocated %d DPU(s)\n", nr_of_dpus);
printf("[INFO] Allocated %d TASKLET(s) per DPU\n", NR_TASKLETS);
unsigned int i;
// Initialize input data
B = readCOOMatrix(p.fileName);
sortCOOMatrix(B);
uint32_t horz_partitions = 0;
uint32_t vert_partitions = p.vert_partitions;
find_partitions(nr_of_dpus, &horz_partitions, p.vert_partitions);
printf("[INFO] %dx%d Matrix Partitioning\n\n", horz_partitions, vert_partitions);
A = coo2dcsr(B, horz_partitions, vert_partitions);
freeCOOMatrix(B);
// Initialize partition data
part_info = partition_init(nr_of_dpus, NR_TASKLETS);
// Initialize help data - Padding needed
uint32_t ncols_pad = A->vert_partitions * A->tile_width;
uint32_t tile_width_pad = A->tile_width;
uint32_t nrows_pad = A->horz_partitions * A->tile_height;
if (ncols_pad % (8 / byte_dt) != 0)
ncols_pad = ncols_pad + ((8 / byte_dt) - (ncols_pad % (8 / byte_dt)));
if (tile_width_pad % (8 / byte_dt) != 0)
tile_width_pad = tile_width_pad + ((8 / byte_dt) - (tile_width_pad % (8 / byte_dt)));
if (nrows_pad % (8 / byte_dt) != 0)
nrows_pad = nrows_pad + ((8 / byte_dt) - (nrows_pad % (8 / byte_dt)));
// Allocate input vector
x = (val_dt *) malloc(ncols_pad * sizeof(val_dt));
// Initialize input vector with arbitrary data
init_vector(x, ncols_pad);
// Initialize help data
dpu_info = (struct dpu_info_t *) malloc(nr_of_dpus * sizeof(struct dpu_info_t));
dpu_arguments_t *input_args = (dpu_arguments_t *) malloc(nr_of_dpus * sizeof(dpu_arguments_t));
// Max limits for parallel transfers
uint64_t max_rows_per_dpu = 0;
uint64_t max_nnz_ind_per_dpu = 0;
uint64_t max_nnz_val_per_dpu = 0;
uint64_t max_rows_per_tasklet = 0;
// Timer for measurements
Timer timer;
uint64_t total_nnzs = 0;
i = 0;
DPU_FOREACH(dpu_set, dpu, i) {
// Find padding for rows and non-zero elements needed for CPU-DPU transfers
uint32_t tile_horz_indx = i / A->vert_partitions;
uint32_t tile_vert_indx = i % A->vert_partitions;
uint32_t rows_per_dpu = A->tile_height;
uint32_t prev_rows_dpu = tile_horz_indx * A->tile_height;
// Pad data to be transfered
uint32_t rows_per_dpu_pad = rows_per_dpu + 1;
if (rows_per_dpu_pad % (8 / byte_dt) != 0)
rows_per_dpu_pad += ((8 / byte_dt) - (rows_per_dpu_pad % (8 / byte_dt)));
#if INT64 || FP64
if (rows_per_dpu_pad % 2 == 1)
rows_per_dpu_pad++;
#endif
if (rows_per_dpu_pad > max_rows_per_dpu)
max_rows_per_dpu = rows_per_dpu_pad;
unsigned int nnz, nnz_ind_pad, nnz_val_pad;
nnz = A->nnzs_per_partition[i];
if (nnz % 2 != 0)
nnz_ind_pad = nnz + 1;
else
nnz_ind_pad = nnz;
if (nnz % (8 / byte_dt) != 0)
nnz_val_pad = nnz + ((8 / byte_dt) - (nnz % (8 / byte_dt)));
else
nnz_val_pad = nnz;
#if INT64 || FP64
if (nnz_ind_pad % 2 == 1)
nnz_ind_pad++;
if (nnz_val_pad % 2 == 1)
nnz_val_pad++;
#endif
if (nnz_ind_pad > max_nnz_ind_per_dpu)
max_nnz_ind_per_dpu = nnz_ind_pad;
if (nnz_val_pad > max_nnz_val_per_dpu)
max_nnz_val_per_dpu = nnz_val_pad;
uint32_t prev_nnz_dpu = total_nnzs;
total_nnzs += nnz;
// Keep information per DPU
dpu_info[i].rows_per_dpu = rows_per_dpu;
dpu_info[i].prev_rows_dpu = prev_rows_dpu;
dpu_info[i].prev_nnz_dpu = prev_nnz_dpu;
dpu_info[i].nnz = nnz;
dpu_info[i].nnz_pad = nnz_ind_pad;
dpu_info[i].ptr_offset = (tile_horz_indx * A->vert_partitions + tile_vert_indx) * (A->tile_height + 1);
// Find input arguments per DPU
input_args[i].nrows = rows_per_dpu;
input_args[i].tcols = tile_width_pad;
#if BLNC_TSKLT_ROW
// Load-balance rows across tasklets
partition_tsklt_by_row(A, part_info, i, rows_per_dpu, NR_TASKLETS);
#else
// Load-balance nnzs across tasklets
partition_tsklt_by_nnz(A, part_info, i, nnz, (tile_horz_indx * A->vert_partitions + tile_vert_indx) * (A->tile_height + 1), NR_TASKLETS);
#endif
uint32_t t;
for (t = 0; t < NR_TASKLETS; t++) {
// Find input arguments per tasklet
input_args[i].start_row[t] = part_info->row_split_tasklet[t];
input_args[i].rows_per_tasklet[t] = part_info->row_split_tasklet[t+1] - part_info->row_split_tasklet[t];
if (input_args[i].rows_per_tasklet[t] > max_rows_per_tasklet)
max_rows_per_tasklet = input_args[i].rows_per_tasklet[t];
}
}
assert(A->nnz == total_nnzs && "wrong balancing");
// Initializations for parallel transfers with padding needed
if (max_rows_per_dpu % 2 != 0)
max_rows_per_dpu++;
if (max_rows_per_dpu % (8 / byte_dt) != 0)
max_rows_per_dpu += ((8 / byte_dt) - (max_rows_per_dpu % (8 / byte_dt)));
if (max_nnz_ind_per_dpu % 2 != 0)
max_nnz_ind_per_dpu++;
if (max_nnz_val_per_dpu % (8 / byte_dt) != 0)
max_nnz_val_per_dpu += ((8 / byte_dt) - (max_nnz_val_per_dpu % (8 / byte_dt)));
if (max_rows_per_tasklet % (8 / byte_dt) != 0)
max_rows_per_tasklet += ((8 / byte_dt) - (max_rows_per_tasklet % (8 / byte_dt)));
// Re-allocations for padding needed
A->drowptr = (uint32_t *) realloc(A->drowptr, (max_rows_per_dpu * (uint64_t) nr_of_dpus * sizeof(uint32_t)));
A->dcolind = (uint32_t *) realloc(A->dcolind, (max_nnz_ind_per_dpu * nr_of_dpus * sizeof(uint32_t)));
A->dval = (val_dt *) realloc(A->dval, (max_nnz_val_per_dpu * nr_of_dpus * sizeof(val_dt)));
y = (val_dt *) malloc((uint64_t) ((uint64_t) nr_of_dpus * (uint64_t) NR_TASKLETS * (uint64_t) max_rows_per_tasklet) * (uint64_t) sizeof(val_dt));
// Count total number of bytes to be transfered in MRAM of DPU
unsigned long int total_bytes;
total_bytes = ((max_rows_per_dpu) * sizeof(uint32_t)) + (max_nnz_ind_per_dpu * sizeof(uint32_t)) + (max_nnz_val_per_dpu * sizeof(val_dt)) + (tile_width_pad * sizeof(val_dt)) + (max_rows_per_dpu * sizeof(val_dt));
assert(total_bytes <= DPU_CAPACITY && "Bytes needed exceeded MRAM size");
// Copy input arguments to DPUs
i = 0;
DPU_FOREACH(dpu_set, dpu, i) {
input_args[i].max_rows = max_rows_per_dpu;
input_args[i].max_nnz_ind = max_nnz_ind_per_dpu;
DPU_ASSERT(dpu_prepare_xfer(dpu, input_args + i));
}
DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, "DPU_INPUT_ARGUMENTS", 0, sizeof(dpu_arguments_t), DPU_XFER_DEFAULT));
// Copy input matrix to DPUs
startTimer(&timer, 0);
// Copy Rowptr
i = 0;
DPU_FOREACH(dpu_set, dpu, i) {
DPU_ASSERT(dpu_prepare_xfer(dpu, A->drowptr + dpu_info[i].ptr_offset));
}
DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, (max_rows_per_dpu * sizeof(val_dt) + tile_width_pad * sizeof(val_dt)), max_rows_per_dpu * sizeof(uint32_t), DPU_XFER_DEFAULT));
// Copy Colind
i = 0;
DPU_FOREACH(dpu_set, dpu, i) {
DPU_ASSERT(dpu_prepare_xfer(dpu, A->dcolind + dpu_info[i].prev_nnz_dpu));
}
DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_rows_per_dpu * sizeof(val_dt) + tile_width_pad * sizeof(val_dt) + max_rows_per_dpu * sizeof(uint32_t), max_nnz_ind_per_dpu * sizeof(uint32_t), DPU_XFER_DEFAULT));
// Copy Values
i = 0;
DPU_FOREACH(dpu_set, dpu, i) {
DPU_ASSERT(dpu_prepare_xfer(dpu, A->dval + dpu_info[i].prev_nnz_dpu));
}
DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_rows_per_dpu * sizeof(val_dt) + tile_width_pad * sizeof(val_dt) + max_rows_per_dpu * sizeof(uint32_t) + max_nnz_ind_per_dpu * sizeof(uint32_t), max_nnz_val_per_dpu * sizeof(val_dt), DPU_XFER_DEFAULT));
stopTimer(&timer, 0);
// Copy input vector to DPUs
startTimer(&timer, 1);
i = 0;
DPU_FOREACH(dpu_set, dpu, i) {
uint32_t tile_vert_indx = i % A->vert_partitions;
DPU_ASSERT(dpu_prepare_xfer(dpu, x + tile_vert_indx * A->tile_width));
}
DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_rows_per_dpu * sizeof(val_dt), tile_width_pad * sizeof(val_dt), DPU_XFER_DEFAULT));
stopTimer(&timer, 1);
// Run kernel on DPUs
startTimer(&timer, 2);
DPU_ASSERT(dpu_launch(dpu_set, DPU_SYNCHRONOUS));
stopTimer(&timer, 2);
#if LOG
// Display DPU Log (default: disabled)
DPU_FOREACH(dpu_set, dpu) {
DPU_ASSERT(dpulog_read_for_dpu(dpu.dpu, stdout));
}
#endif
// Retrieve results for output vector from DPUs
startTimer(&timer, 3);
i = 0;
DPU_FOREACH(dpu_set, dpu, i) {
DPU_ASSERT(dpu_prepare_xfer(dpu, y + (i * max_rows_per_dpu)));
}
DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_FROM_DPU, DPU_MRAM_HEAP_POINTER_NAME, 0, max_rows_per_dpu * sizeof(val_dt), DPU_XFER_DEFAULT));
stopTimer(&timer, 3);
// Merge partial results to the host CPU
startTimer(&timer, 4);
uint32_t r, c, t;
#pragma omp parallel for num_threads(p.nthreads) shared(A, y, max_rows_per_dpu) private(r,c,t) collapse(2)
for (r = 0; r < A->horz_partitions; r++) {
for (t = 0; t < A->tile_height; t++) {
for (c = 1; c < A->vert_partitions; c++) {
y[r * A->vert_partitions * max_rows_per_dpu + t] += y[r * A->vert_partitions * max_rows_per_dpu + c * max_rows_per_dpu + t];
}
}
}
stopTimer(&timer, 4);
// Print timing results
printf("\n");
printf("Load Matrix ");
printTimer(&timer, 0);
printf("Load Input Vector ");
printTimer(&timer, 1);
printf("Kernel ");
printTimer(&timer, 2);
printf("Retrieve Output Vector ");
printTimer(&timer, 3);
printf("Merge Partial Results ");
printTimer(&timer, 4);
printf("\n\n");
#if CHECK_CORR
// Check output
val_dt *y_host = (val_dt *) calloc(nrows_pad, sizeof(val_dt));
spmv_host(y_host, A, x);
bool status = true;
i = 0;
for (uint32_t r = 0; r < A->horz_partitions; r++) {
for (uint32_t t = 0; t < A->tile_height; t++) {
if((r * A->tile_height + t < A->nrows) && y_host[i] != y[r * A->vert_partitions * max_rows_per_dpu + t]) {
status = false;
}
i++;
}
}
if (status) {
printf("[" ANSI_COLOR_GREEN "OK" ANSI_COLOR_RESET "] Outputs are equal\n");
} else {
printf("[" ANSI_COLOR_RED "ERROR" ANSI_COLOR_RESET "] Outputs differ!\n");
}
free(y_host);
#endif
// Deallocation
freeDCSRMatrix(A);
free(x);
free(y);
partition_free(part_info);
DPU_ASSERT(dpu_free(dpu_set));
return 0;
}
|
chunk_gomp.c | /******************************************************************************
* FILE: omp_workshare1.c
* DESCRIPTION:
* OpenMP Example - Loop Work-sharing - C/C++ Version
* In this example, the iterations of a loop are scheduled dynamically
* across the team of threads. A thread will perform CHUNK iterations
* at a time before being scheduled for the next CHUNK of work.
* AUTHOR: Blaise Barney 5/99
* LAST REVISED: 04/06/05
******************************************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define CHUNKSIZE 10
#define N 100
int main (int argc, char *argv[]) {
int nthreads, tid, i, chunk;
float a[N], b[N], c[N];
/* Some initializations */
for (i=0; i < N; i++)
a[i] = b[i] = i * 1.0;
chunk = CHUNKSIZE;
#pragma omp parallel shared(a,b,c,nthreads,chunk) private(i,tid)
{
tid = omp_get_thread_num();
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
printf("Thread %d starting...\n",tid);
#pragma omp for schedule(dynamic,chunk)
for (i=0; i<N; i++)
{
c[i] = a[i] + b[i];
printf("Thread %d: c[%d]= %f\n",tid,i,c[i]);
}
} /* end of parallel section */
}
|
dynamic_not_enough_threads.c | // RUN: %libomp-compile && env OMP_THREAD_LIMIT=2 %libomp-run | FileCheck %s
// REQUIRES: ompt
#include "callback.h"
int main()
{
omp_set_dynamic(1);
#pragma omp parallel num_threads(4)
{
print_ids(0);
print_ids(1);
}
print_fuzzy_address(1);
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_thread_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_thread_end'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_end'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task'
//team-size of 1-4 is expected
// CHECK: 0: NULL_POINTER=[[NULL:.*$]]
// make sure initial data pointers are null
// CHECK-NOT: 0: parallel_data initially not null
// CHECK-NOT: 0: task_data initially not null
// CHECK-NOT: 0: thread_data initially not null
// CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin: parent_task_id=[[PARENT_TASK_ID:[0-9]+]], parent_task_frame.exit=[[NULL]], parent_task_frame.reenter={{0x[0-f]+}}, parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=4, codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}}, invoker=[[PARALLEL_INVOKER:[0-9]+]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID:[0-9]+]], team_size={{[1-4]}}
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: task level 1: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]], task_id=[[PARENT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_end: parallel_id=[[PARALLEL_ID]], task_id=[[PARENT_TASK_ID]], invoker=[[PARALLEL_INVOKER]]
// CHECK: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]]
return 0;
}
|
omp_simd_lastprivate.c | //Variable examples of using simd directives
void foo (int n, double *a, double* b)
{
for (int i=0; i<n; i++)
a[i]=b[i];
}
void foo2 (int n, double *a, double* b)
{
for (int i=0; i<n; i++)
a[i]=b[i];
}
void foo3 (int n, double *a, double* b)
{
int j=0;
for (int i=0; i<n; i++,j++)
{
a[i]=b[i]+j;
}
}
void foo32 (int n, double *a, double* b)
{
int j=0, k=0;
for (int i=0; i<n; i++,j++,k++)
{
a[i]=b[i]+j+k;
}
}
void foo33 (int n, double *a, double* b)
{
int j=0, k=0;
for (int i=0; i<n; i++,j++,k++)
{
a[i]=b[i]+j+k;
}
}
void fooAligned (int n, double *a, double* b)
{
int j=0, k=0;
for (int i=0; i<n; i++,j++,k++)
{
a[i]=b[i]+j+k;
}
}
void fooAligned2 (int n, double *a, double* b)
{
int j=0, k=0;
for (int i=0; i<n; i++,j++,k++)
{
a[i]=b[i]+j+k;
}
}
double work( double *a, double *b, int n )
{
int i;
double tmp, sum;
sum = 0.0;
for (i = 0; i < n; i++) {
tmp = a[i] + b[i];
sum += tmp;
}
return sum;
}
#define N 45
int a[N], b[N], c[N];
void foo4(int i, double* P)
{
int j;
#pragma omp simd lastprivate(j)
for (i = 0; i < 999; ++i) {
j = P[i];
}
}
void work2( double **a, double **b, double **c, int n )
{
int i, j;
double tmp;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
tmp = a[i][j] + b[i][j];
c[i][j] = tmp;
}
}
}
void work3( double **a, double **b, double **c, int n )
{
int i, j;
double tmp;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
tmp = a[i][j] + b[i][j];
c[i][j] = tmp;
}
}
}
// declare simd can show up several times!
float bar(int * p) {
*p = *p +10;
return *p;
}
// declare simd can show up several times!
float bar2(int * p) {
*p = *p +10;
return *p;
}
|
Example_target_struct_map.1.c | /*
* @@name: target_struct_map.1c
* @@type: C
* @@compilable: yes
* @@linkable: yes
* @@expect: success
* @@version: omp_5.0
*/
#include <stdio.h>
#include <stdlib.h>
#define N 100
#define BAZILLION 2000000
struct foo {
char buffera[BAZILLION];
char bufferb[BAZILLION];
float x;
float a, b;
float *p;
};
#pragma omp declare target
void saxpyfun(struct foo *S)
{
int i;
for(i=0; i<N; i++)
S->p[i] = S->p[i]*S->a + S->b;
}
#pragma omp end declare target
int main()
{
struct foo S;
int i;
S.a = 2.0;
S.b = 4.0;
S.p = (float *)malloc(sizeof(float)*N);
for(i=0; i<N; i++) S.p[i] = i;
#pragma omp target map(alloc:S.p) map(S.p[:N]) map(to:S.a, S.b)
saxpyfun(&S);
printf(" %4.0f %4.0f\n", S.p[0], S.p[N-1]);
// 4 202 <- output
return 0;
}
|
Example_udr.1.c | /*
* @@name: udr.1.c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_4.0
*/
#include <stdio.h>
#include <limits.h>
struct point {
int x;
int y;
};
void minproc ( struct point *out, struct point *in )
{
if ( in->x < out->x ) out->x = in->x;
if ( in->y < out->y ) out->y = in->y;
}
void maxproc ( struct point *out, struct point *in )
{
if ( in->x > out->x ) out->x = in->x;
if ( in->y > out->y ) out->y = in->y;
}
#pragma omp declare reduction(min : struct point : \
minproc(&omp_out, &omp_in)) \
initializer( omp_priv = { INT_MAX, INT_MAX } )
#pragma omp declare reduction(max : struct point : \
maxproc(&omp_out, &omp_in)) \
initializer( omp_priv = { 0, 0 } )
void find_enclosing_rectangle ( int n, struct point points[] )
{
struct point minp = { INT_MAX, INT_MAX }, maxp = {0,0};
int i;
#pragma omp parallel for reduction(min:minp) reduction(max:maxp)
for ( i = 0; i < n; i++ ) {
minproc(&minp, &points[i]);
maxproc(&maxp, &points[i]);
}
printf("min = (%d, %d)\n", minp.x, minp.y);
printf("max = (%d, %d)\n", maxp.x, maxp.y);
}
|
nested.c | // RUN: %libomp-compile && env OMP_DISPLAY_AFFINITY=true OMP_PLACES=threads OMP_PROC_BIND=spread,close %libomp-run | %python %S/check.py -c 'CHECK' %s
// REQUIRES: affinity
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main(int argc, char** argv) {
omp_set_affinity_format("TESTER: tl:%L at:%a tn:%n nt:%N");
omp_set_nested(1);
#pragma omp parallel num_threads(4)
{
#pragma omp parallel num_threads(3)
{ }
}
return 0;
}
// CHECK: num_threads=4 TESTER: tl:1 at:0 tn:[0-3] nt:4
// CHECK: num_threads=3 TESTER: tl:2 at:[0-3] tn:[0-2] nt:3
// CHECK: num_threads=3 TESTER: tl:2 at:[0-3] tn:[0-2] nt:3
// CHECK: num_threads=3 TESTER: tl:2 at:[0-3] tn:[0-2] nt:3
// CHECK: num_threads=3 TESTER: tl:2 at:[0-3] tn:[0-2] nt:3
|
matrix_op-inl.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2015 by Contributors
* \file matrix_op-inl.h
* \brief Function definition of matrix related operators
*/
#ifndef MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_
#define MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_
#include <mxnet/operator_util.h>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <type_traits>
#include "../mshadow_op.h"
#include "../elemwise_op_common.h"
#include "../channel_op_common.h"
#include "../mxnet_op.h"
#include "broadcast_reduce_op.h"
#include "./init_op.h"
#include "../../common/static_array.h"
#include "./slice-inl.h"
#if MXNET_USE_CUDA
#include <thrust/device_vector.h>
#endif
#ifdef __CUDACC__
#include "./pseudo2DTranspose_op-inl.cuh"
#endif
namespace mxnet {
namespace op {
struct ReshapeParam : public dmlc::Parameter<ReshapeParam> {
mxnet::TShape target_shape;
bool keep_highest;
mxnet::Tuple<int> shape;
bool reverse;
DMLC_DECLARE_PARAMETER(ReshapeParam) {
DMLC_DECLARE_FIELD(shape)
.set_default(mxnet::Tuple<int>())
.describe("The target shape");
DMLC_DECLARE_FIELD(reverse)
.set_default(false)
.describe("If true then the special values are inferred from right to left");
DMLC_DECLARE_FIELD(target_shape)
.set_default(mxnet::TShape(0, -1))
.describe("(Deprecated! Use ``shape`` instead.) "
"Target new shape. One and only one dim can be 0, "
"in which case it will be inferred from the rest of dims");
DMLC_DECLARE_FIELD(keep_highest).set_default(false)
.describe("(Deprecated! Use ``shape`` instead.) Whether keep the highest dim unchanged."
"If set to true, then the first dim in target_shape is ignored,"
"and always fixed as input");
}
bool operator==(const ReshapeParam &other) const {
return this->target_shape == other.target_shape &&
this->keep_highest == other.keep_highest &&
this->shape == other.shape &&
this->reverse == other.reverse;
}
};
template<typename IType>
inline mxnet::TShape InferReshapeShape(const mxnet::Tuple<IType>& shape,
const mxnet::TShape& dshape, bool reverse) {
std::vector<IType> dshape_vec;
std::vector<IType> param_shape_vec(shape.begin(), shape.end());
for (int i = 0; i < dshape.ndim(); ++i) {
dshape_vec.push_back(dshape[i]);
}
std::vector<IType> tmp;
size_t src_idx = 0;
int inf_idx = -1;
if (reverse) {
std::reverse(dshape_vec.begin(), dshape_vec.end());
std::reverse(param_shape_vec.begin(), param_shape_vec.end());
}
auto dshape_len = dshape_vec.size();
auto params_len = param_shape_vec.size();
for (size_t i = 0; i < params_len; ++i) {
IType proposed_dim = param_shape_vec[i];
if (proposed_dim == 0) {
// keep same
CHECK_LT(src_idx, dshape_len);
tmp.push_back(dshape_vec[src_idx++]);
} else if (proposed_dim == -1) {
// infer
CHECK_LT(inf_idx, 0) << "One and only one dim can be inferred";
inf_idx = i;
tmp.push_back(1);
src_idx++;
} else if (proposed_dim == -2) {
// copy all remaining dims from source
while (src_idx < dshape_len) {
const int dn = dshape_vec[src_idx++];
tmp.push_back(dn);
}
} else if (proposed_dim == -3) {
// merge two dims from source
CHECK_LT(src_idx, dshape_len-1);
const int d1 = dshape_vec[src_idx++];
const int d2 = dshape_vec[src_idx++];
if (!mxnet::dim_size_is_known(d1) || !mxnet::dim_size_is_known(d2)) {
tmp.push_back(-1);
} else {
tmp.push_back(d1 * d2);
}
} else if (proposed_dim == -4) {
// split the source dim s into two dims
// read the left dim and then the right dim (either can be -1)
CHECK_LT(i + 2, params_len);
CHECK_LT(src_idx, dshape_len);
const int d0 = dshape_vec[src_idx++];
IType d1 = param_shape_vec[++i];
IType d2 = param_shape_vec[++i];
CHECK(d1 != -1 || d2 != -1) << "Split dims cannot both be -1.";
if (d1 == -1 && d0 >= 0) d1 = d0 / d2; // d0 must be known to do this
if (d2 == -1 && d0 >= 0) d2 = d0 / d1; // d0 must be known to do this
CHECK(d1 * d2 == static_cast<IType>(d0) || static_cast<IType>(d0) == IType(-1)) <<
"Split dims " << d1 << ", " << d2 << " do not divide original dim " << d0;
tmp.push_back(d1);
tmp.push_back(d2);
} else {
// greater than 0, new shape
tmp.push_back(proposed_dim);
src_idx++;
}
}
if (inf_idx >= 0) {
if (shape_is_known(dshape)) {
IType new_size = 1;
for (IType x : tmp) new_size *= x;
tmp[inf_idx] = dshape.Size() / new_size;
} else {
tmp[inf_idx] = -1;
}
}
if (reverse) {
std::reverse(param_shape_vec.begin(), param_shape_vec.end());
std::reverse(dshape_vec.begin(), dshape_vec.end());
std::reverse(tmp.begin(), tmp.end());
}
mxnet::TShape oshape(tmp.begin(), tmp.end());
return oshape;
}
inline bool ReverseReshapeInferShape(mxnet::TShape *in, const mxnet::TShape& out) {
if (shape_is_known(*in) && shape_is_known(out)) {
return true;
} else if (!shape_is_known(out)) {
return false;
} else {
int zero_axis = -1;
int known_dim_size_prod = 1;
for (int i = 0; i < in->ndim(); i++) {
if (!mxnet::dim_size_is_known(*in, i)) {
if (zero_axis != -1)
return false; // more than 1 zero found.
else
zero_axis = i;
} else {
known_dim_size_prod *= (*in)[i];
}
}
(*in)[zero_axis] = out.Size() / known_dim_size_prod;
return true;
}
}
inline bool ReshapeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const ReshapeParam& param_ = nnvm::get<ReshapeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]";
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape &dshape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(dshape)) return false;
mxnet::TShape oshape;
if (param_.shape.ndim() != 0) {
oshape = InferReshapeShape(param_.shape, dshape, param_.reverse);
} else if (param_.target_shape.ndim() != -1) {
LOG(INFO) << "Using target_shape will be deprecated.";
oshape = param_.target_shape;
int neg_count = 0;
index_t inf_idx = 0;
index_t start_idx = param_.keep_highest ? 1 : 0;
if (param_.keep_highest) {
oshape[0] = dshape[0];
}
for (int i = start_idx; i < oshape.ndim(); ++i) {
if (oshape[i] == 0) {
neg_count++;
inf_idx = i;
}
}
if (neg_count == 1) {
oshape[inf_idx] = 1;
oshape[inf_idx] = dshape.Size() / oshape.Size();
}
} else {
return shape_is_known((*out_attrs)[0])
&& ReverseReshapeInferShape(&(*in_attrs)[0], (*out_attrs)[0]);
}
ReverseReshapeInferShape(&dshape, oshape);
#if 0
CHECK_EQ(oshape.Size(), dshape.Size())
<< "Target shape size is different to source. "
<< "Target: " << oshape
<< "\nSource: " << dshape;
#endif
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return ReverseReshapeInferShape(&(*in_attrs)[0], (*out_attrs)[0]);
}
inline bool FlattenShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]";
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape &dshape = (*in_attrs)[0];
if (!shape_is_known(dshape)) return false;
size_t target_dim = 1;
for (int i = 1; i < dshape.ndim(); ++i) {
target_dim *= dshape[i];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mshadow::Shape2(dshape[0], target_dim));
return true;
}
struct TransposeParam : public dmlc::Parameter<TransposeParam> {
mxnet::TShape axes;
DMLC_DECLARE_PARAMETER(TransposeParam) {
DMLC_DECLARE_FIELD(axes).set_default(mxnet::TShape(0, -1))
.describe("Target axis order. By default the axes will be inverted.");
}
bool operator==(const TransposeParam &other) const {
return this->axes == other.axes;
}
};
/*!
* \brief This function performs transpose operation on a 2D matrix by utilizing the L1 cache
* \param in input tensor
* \param out output tensor
* \param row shape of dim 0 of input
* \param col shape of dim 1 of input
* \tparam DType Data type
* \tparam is_addto
*/
template<typename DType, bool is_addto>
MSHADOW_XINLINE void Transpose2D(const DType *in, DType *out, index_t row, index_t col) {
// ensure cache line hits and prevent cache miss for any configuration
// L1 cache size to be utilized = 32kb = 2^15
// Largest size of a single unit of any dtype <= 8 byte = 2^3
// Number of elements - (2^15/2^3) = 2^12
// Block-size - 2^6 v 2^6 (64 v 64)
// But we could leverage unrolling of for loops (for parallelization)
// Block-size - 2^5 v 2^5 (32 v 32) with potential 4 pragma for loop unrolled
// blocksize * blocksize * num_threads = cache_size / dtype_size
// Instead of explicit unroll, let compiler figure out optimal unroll factor
const index_t blocksize = 32;
// collapse 2 parallelizes 2 for loops
// inner 2 for loops aren't parallelized to prevent cache miss
// Microsoft Visual C++ compiler does not support omp collapse
#ifdef _MSC_VER
#pragma omp parallel for
#else
#pragma omp parallel for collapse(2)
#endif // _MSC_VER
for (index_t i = 0; i < row; i += blocksize) {
for (index_t j = 0; j < col; j += blocksize) {
// transpose the block
for (index_t a = j; (a < blocksize + j) && (a < col); ++a) {
for (index_t b = i; (b < blocksize + i) && (b < row); ++b) {
if (!is_addto) {
out[a * row + b] = in[b * col + a];
} else {
out[a * row + b] += in[b * col + a];
}
}
}
}
}
}
inline bool IsIdentityTranspose(const TShape& axes) {
for (dim_t i = 0; i < axes.ndim(); i++) {
if (axes[i] != i) return false;
}
return true;
}
template<typename xpu, bool is_addto = false>
bool TransposeCommonImpl(RunContext ctx,
const TBlob& src,
const TBlob& ret,
const mxnet::TShape& axes) {
// return true when running successfully, otherwise false
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(src.type_flag_, ret.type_flag_);
// zero-size tensor, no need to compute
if (src.shape_.Size() == 0U) return true;
Stream<xpu> *s = ctx.get_stream<xpu>();
#ifdef __CUDACC__
// This transpose can be used only if there exist n and m such that:
// params = (0, ..., n-1, n+m, ..., params.size, n, ..., n+m-1)
// Example: (0, 2, 3, 1) or (0, 3, 1, 2), but not (0, 2, 1, 3).
if (isPseudo2DTranspose(axes)) {
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
transpose_pseudo2D<DType, is_addto>(ret, src, axes, s);
});
return true;
}
#endif
// Special handle the identity case
if (IsIdentityTranspose(axes)) {
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
Tensor<xpu, 1, DType> in = src.get_with_shape<xpu, 1, DType>(mshadow::Shape1(src.Size()), s);
Tensor<xpu, 1, DType> out = ret.get_with_shape<xpu, 1, DType>(mshadow::Shape1(ret.Size()), s);
if (!is_addto) {
// Use memcpy to accelerate the speed
Copy(out, in, s);
} else {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, kAddTo>, xpu>::Launch(
s, ret.Size(), out.dptr_, in.dptr_);
}
});
return true;
}
// Handle the general transpose case
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
switch (axes.ndim()) {
case 2: {
Tensor<xpu, 2, DType> in = src.get<xpu, 2, DType>(s);
Tensor<xpu, 2, DType> out = ret.get<xpu, 2, DType>(s);
if (ctx.get_ctx().dev_mask() == cpu::kDevMask) {
Transpose2D<DType, is_addto>(in.dptr_, out.dptr_, in.shape_[0], in.shape_[1]);
} else {
LOG(FATAL) << "Not Implemented. We should never reach here because the 2D case "
"in GPU has been covered by transpose_pseudo2D."
" Report an issue in Github.";
}
break;
}
case 3: {
Tensor<xpu, 3, DType> in = src.get<xpu, 3, DType>(s);
Tensor<xpu, 3, DType> out = ret.get<xpu, 3, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<3>());
} else {
out += transpose(in, axes.get<3>());
}
break;
}
case 4: {
Tensor<xpu, 4, DType> in = src.get<xpu, 4, DType>(s);
Tensor<xpu, 4, DType> out = ret.get<xpu, 4, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<4>());
} else {
out += transpose(in, axes.get<4>());
}
break;
}
case 5: {
Tensor<xpu, 5, DType> in = src.get<xpu, 5, DType>(s);
Tensor<xpu, 5, DType> out = ret.get<xpu, 5, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<5>());
} else {
out += transpose(in, axes.get<5>());
}
break;
}
case 6: {
Tensor<xpu, 6, DType> in = src.get<xpu, 6, DType>(s);
Tensor<xpu, 6, DType> out = ret.get<xpu, 6, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<6>());
} else {
out += transpose(in, axes.get<6>());
}
break;
}
default:
// return false when dimensions > 6
return false;
break;
}
});
return true;
}
template<typename xpu, bool is_addto = false>
void TransposeImpl(RunContext ctx,
const TBlob& src,
const TBlob& ret,
const mxnet::TShape& axes) {
CHECK_LE(axes.ndim(), 6) << "TransposeImpl supports at most 6 dimensions";
CHECK((TransposeCommonImpl<xpu, is_addto>(ctx, src, ret, axes))) <<
"Failed to execute TransposeImpl Operator";
}
template <bool is_addto>
struct TransposeExKernel {
/*!
* \brief
* \param tid global thread id
* \param out_data output data
* \param in_data input data
* \param strides input strides and output strides
* \param ndim the number of dimension
*/
template <typename DType>
MSHADOW_XINLINE static void Map(int tid,
DType *out_data,
const DType *in_data,
const dim_t *strides,
const int ndim
) {
// tid is the index of input data
const dim_t* const out_strides = strides + ndim;
int k = tid;
int out_id = 0;
for (int i = 0; i < ndim; ++i) {
out_id += (k / strides[i]) * out_strides[i];
k %= strides[i];
}
if (is_addto)
out_data[out_id] += in_data[tid];
else
out_data[out_id] = in_data[tid];
}
};
template<typename xpu, bool is_addto = false>
void TransposeExImpl(RunContext ctx,
const TBlob& src,
const TBlob& ret,
const mxnet::TShape& axes,
mshadow::Tensor<xpu, 1, dim_t>& strides_xpu
) {
/*
* If ndim <= 6, it is not necessary to allocate any space for `strides_xpu`
* If ndim > 6, `strides_xpu` should be allocated `ndim * 2` elements
*/
using namespace mshadow;
using namespace mshadow::expr;
if (TransposeCommonImpl<xpu, is_addto>(ctx, src, ret, axes)) return;
CHECK_GT(axes.ndim(), 6) <<
"Failed to execute TransposeExImpl when axes.ndim() <= 6";
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
CHECK_EQ(strides_xpu.MSize(), axes.ndim() * 2) << \
"If ndim > 6, `strides_xpu` should be allocated `ndim * 2` elements";
const mxnet::TShape &in_shape = src.shape_;
// strides: in_strides and out_strides
const int ndim = axes.ndim();
std::vector<dim_t> strides(ndim * 2);
// compute in_strides
strides[ndim - 1] = 1;
for (int i = ndim - 2; i >= 0; --i) {
strides[i] = strides[i + 1] * in_shape[i + 1];
}
// compute out_strides
std::vector<dim_t> tmp_strides(ndim);
tmp_strides[ndim - 1] = 1;
for (int i = ndim - 2; i >= 0; --i) {
tmp_strides[i] = tmp_strides[i + 1] * in_shape[axes[i + 1]];
}
// reorder tmp_strides to out_strides
dim_t * const out_strides = &strides[ndim];
for (int i = 0; i < ndim; ++i) {
out_strides[axes[i]] = tmp_strides[i];
}
Shape<1> strides_shape;
strides_shape[0] = ndim * 2;
Tensor<cpu, 1, dim_t> strides_cpu(strides.data(), strides_shape);
// copy arguments into xpu context
Copy(strides_xpu, strides_cpu, s);
const DType *in = src.dptr<DType>();
DType *out = ret.dptr<DType>();
if (is_addto) {
mxnet_op::Kernel<TransposeExKernel<true>, xpu>::Launch(s,
in_shape.Size(), out, in, strides_xpu.dptr_, ndim);
} else {
mxnet_op::Kernel<TransposeExKernel<false>, xpu>::Launch(s,
in_shape.Size(), out, in, strides_xpu.dptr_, ndim);
}
});
}
template<typename xpu>
mshadow::Tensor<xpu, 1, dim_t> GetTransposeExWorkspace(
const OpContext& ctx,
const mxnet::TShape& axes
) {
if (axes.ndim() > 6) {
// allocate workspace when axes.ndim() > 6
mshadow::Shape<1> strides_shape;
strides_shape[0] = axes.ndim() * 2;
return ctx.requested[0].get_space_typed<xpu, 1, dim_t>(
strides_shape, ctx.get_stream<xpu>());
}
return {};
}
// matrix transpose
template<typename xpu>
void Transpose(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
if (req[0] == kNullOp) {
return;
}
const TransposeParam& param = nnvm::get<TransposeParam>(attrs.parsed);
CHECK(req[0] == kWriteTo || req[0] == kAddTo)
<< "Transpose only supports kNullOp, kWriteTo and kAddTo";
mxnet::TShape axes;
if (param.axes.ndim() == 0) {
axes = mxnet::TShape(inputs[0].ndim(), -1);
for (int i = 0; i < axes.ndim(); ++i) {
axes[i] = axes.ndim() - 1 - i;
}
} else {
axes = common::CanonicalizeAxes(param.axes);
}
mshadow::Tensor<xpu, 1, dim_t> workspace =
GetTransposeExWorkspace<xpu>(ctx, axes);
if (req[0] == kAddTo) {
TransposeExImpl<xpu, true>(ctx.run_ctx, inputs[0], outputs[0],
axes, workspace);
} else {
TransposeExImpl<xpu, false>(ctx.run_ctx, inputs[0], outputs[0],
axes, workspace);
}
}
inline bool TransposeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const TransposeParam& param = nnvm::get<TransposeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& shp = (*in_attrs)[0];
mxnet::TShape& out_shp = (*out_attrs)[0];
if (!mxnet::ndim_is_known(shp) && !mxnet::ndim_is_known(out_shp))
return false; // none of the shapes is known
if (out_shp.ndim() >= 0 && shp.ndim() >= 0)
CHECK_EQ(out_shp.ndim(), shp.ndim());
mxnet::TShape get(std::max(shp.ndim(), out_shp.ndim()), -1);
mxnet::TShape ret(std::max(shp.ndim(), out_shp.ndim()), -1);
if (param.axes.ndim() == 0) {
for (int i = 0; i < shp.ndim(); ++i) {
ret[i] = shp[shp.ndim()-1-i];
}
for (int i = 0; i < out_shp.ndim(); ++i) {
get[shp.ndim()-1-i] = out_shp[i];
}
} else {
CHECK_EQ(std::max(shp.ndim(), out_shp.ndim()), param.axes.ndim());
for (int i = 0; i < shp.ndim(); ++i) {
CHECK(param.axes[i] < static_cast<int64_t>(shp.ndim()));
ret[i] = shp[param.axes[i]];
}
for (int i = 0; i < out_shp.ndim(); ++i) {
get[param.axes[i]] = out_shp[i];
}
}
SHAPE_ASSIGN_CHECK(*in_attrs, 0, get);
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ret);
return shape_is_known(ret);
}
struct ExpandDimParam : public dmlc::Parameter<ExpandDimParam> {
int axis;
DMLC_DECLARE_PARAMETER(ExpandDimParam) {
DMLC_DECLARE_FIELD(axis)
.describe("Position where new axis is to be inserted. Suppose that "
"the input `NDArray`'s dimension is `ndim`, the range of "
"the inserted axis is `[-ndim, ndim]`");
}
bool operator==(const ExpandDimParam &other) const {
return this->axis == other.axis;
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream axis_s;
axis_s << axis;
(*dict)["axis"] = axis_s.str();
}
};
inline bool ExpandDimShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const ExpandDimParam& param = nnvm::get<ExpandDimParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& ishape = (*in_attrs)[0];
mxnet::TShape& oshape = (*out_attrs)[0];
if (!mxnet::ndim_is_known(ishape) && !mxnet::ndim_is_known(oshape)) {
return false;
}
int indim = ishape.ndim();
bool unknown_ishape = false;
if (-1 == indim) {
indim = oshape.ndim() - 1;
unknown_ishape = true;
}
int axis = param.axis;
if (axis < 0) {
axis += indim + 1;
}
CHECK(axis >= 0 && axis <= indim)
<< "axis must be in the range [" << -indim << ", " << indim << "] ("
<< param.axis << " provided)";
mxnet::TShape ret(indim + 1, -1);
for (int i = 0; i < axis; ++i) {
ret[i] = (unknown_ishape? -1 : ishape[i]);
}
ret[axis] = 1;
for (int i = axis+1; i < indim+1; ++i) {
ret[i] = (unknown_ishape? -1 : ishape[i-1]);
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ret);
ret = mxnet::TShape(indim, -1);
for (int i = 0; i < axis; ++i) ret[i] = oshape[i];
for (int i = axis+1; i < indim+1; ++i) ret[i-1] = oshape[i];
SHAPE_ASSIGN_CHECK(*in_attrs, 0, ret);
return shape_is_known(in_attrs->at(0)) && shape_is_known(out_attrs->at(0));
}
// Currently MKLDNN only supports step = 1 or step has no value
inline bool SupportMKLDNNSlice(const SliceParam& param) {
if (param.step.ndim() == 0U) return true;
for (int i = 0; i < param.step.ndim(); ++i) {
if (param.step[i].has_value() && param.step[i].value() != 1)
return false;
}
return true;
}
inline bool SliceForwardInferStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1);
CHECK_EQ(out_attrs->size(), 1);
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
const auto& in_stype = in_attrs->at(0);
auto& out_stype = out_attrs->at(0);
bool dispatched = false;
const auto dispatch_ex = DispatchMode::kFComputeEx;
// If step = 1, no need to fallback; otherwise fallback to dense
bool trivial_step = false;
if (param.step.ndim() == 0U) {
trivial_step = true;
} else if (param.step.ndim() == 1U
&& (!param.step[0].has_value() || param.step[0].value() == 1)) {
trivial_step = true;
}
if (in_stype == kDefaultStorage) {
#if MXNET_USE_MKLDNN == 1
if (dev_mask == Context::kCPU && MKLDNNEnvSet()
&& SupportMKLDNNSlice(param)) {
dispatched = storage_type_assign(&out_stype, kDefaultStorage,
dispatch_mode, dispatch_ex);
}
#endif
if (!dispatched) {
dispatched = storage_type_assign(&out_stype, kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
}
if (!dispatched && in_stype == kCSRStorage && trivial_step) {
dispatched = storage_type_assign(&out_stype, kCSRStorage,
dispatch_mode, dispatch_ex);
}
if (!dispatched) {
dispatched = dispatch_fallback(out_attrs, dispatch_mode);
}
return dispatched;
}
// slice the indptr of a csr
struct SliceCsrIndPtr {
template<typename IType>
MSHADOW_XINLINE static void Map(int i, IType* out, const IType* in, const IType* base) {
KERNEL_ASSIGN(out[i], kWriteTo, in[i] - *base);
}
};
/*
* a wrapper to launch SliceCsrIndPtr kernel.
* slice [src[begin] .. src[end]) and store in dst[0, end - begin)
*/
template<typename xpu, typename IType>
void SliceCsrIndPtrImpl(const int begin, const int end, RunContext ctx,
const IType* src, IType* dst) {
using namespace mshadow;
using namespace mxnet_op;
Stream<xpu> *s = ctx.get_stream<xpu>();
int indptr_len = end - begin + 1;
Kernel<SliceCsrIndPtr, xpu>::Launch(s, indptr_len, dst, src + begin, src + begin);
}
/*
* Slice a CSR NDArray for first dimension
*/
template<typename xpu>
void SliceDimOneCsrImpl(const mxnet::TShape &begin, const mxnet::TShape &end, const OpContext& ctx,
const NDArray &in, const NDArray &out) {
using namespace mshadow;
using namespace mxnet_op;
using namespace csr;
nnvm::dim_t begin_row = begin[0];
nnvm::dim_t end_row = end[0];
nnvm::dim_t indptr_len = end_row - begin_row + 1;
out.CheckAndAllocAuxData(kIndPtr, Shape1(indptr_len));
// assume idx indptr share the same type
MSHADOW_IDX_TYPE_SWITCH(in.aux_type(kIndPtr), RType, {
MSHADOW_IDX_TYPE_SWITCH(in.aux_type(kIdx), IType, {
MSHADOW_TYPE_SWITCH(in.dtype(), DType, {
RType* in_indptr = in.aux_data(kIndPtr).dptr<RType>();
RType* out_indptr = out.aux_data(kIndPtr).dptr<RType>();
SliceCsrIndPtrImpl<xpu, RType>(begin_row, end_row, ctx.run_ctx, in_indptr, out_indptr);
Stream<xpu> *s = ctx.get_stream<xpu>();
RType nnz = 0;
mshadow::Copy(Tensor<cpu, 1, RType>(&nnz, Shape1(1)),
Tensor<xpu, 1, RType>(out_indptr + indptr_len - 1, Shape1(1), s));
// return csr zeros if nnz = 0
if (nnz == 0) {
out.set_aux_shape(kIdx, Shape1(0));
return;
}
// copy indices and values
out.CheckAndAllocAuxData(kIdx, Shape1(nnz));
out.CheckAndAllocData(Shape1(nnz));
IType* in_idx = in.aux_data(kIdx).dptr<IType>();
IType* out_idx = out.aux_data(kIdx).dptr<IType>();
DType* in_data = in.data().dptr<DType>();
DType* out_data = out.data().dptr<DType>();
RType offset = 0;
mshadow::Copy(Tensor<cpu, 1, RType>(&offset, Shape1(1)),
Tensor<xpu, 1, RType>(in_indptr + begin_row, Shape1(1), s));
mshadow::Copy(Tensor<xpu, 1, IType>(out_idx, Shape1(nnz), s),
Tensor<xpu, 1, IType>(in_idx + offset, Shape1(nnz), s), s);
mshadow::Copy(Tensor<xpu, 1, DType>(out_data, Shape1(nnz), s),
Tensor<xpu, 1, DType>(in_data + offset, Shape1(nnz), s), s);
});
});
});
}
/*!
* \brief slice a CSRNDArray for two dimensions
*/
struct SliceDimTwoCsrAssign {
/*!
* \brief This function slices a CSRNDArray on axis one between begin_col and end_col
* \param i loop index
* \param out_idx output csr ndarray column indices
* \param out_data output csr ndarray data
* \param out_indptr output csr ndarray row index pointer
* \param in_idx input csr ndarray column indices
* \param in_data input csr ndarray data
* \param in_indptr input csr ndarray row index pointer
* \param begin_col begin column indice
* \param end_col end column indice
*/
template<typename IType, typename RType, typename DType>
MSHADOW_XINLINE static void Map(int i,
IType* out_idx, DType* out_data,
const RType* out_indptr,
const IType* in_idx, const DType* in_data,
const RType* in_indptr,
const int begin_col, const int end_col) {
RType ind = out_indptr[i];
for (RType j = in_indptr[i]; j < in_indptr[i+1]; j++) {
// indices of CSRNDArray are in ascending order per row
if (in_idx[j] >= end_col) {
break;
} else if (in_idx[j] >= begin_col) {
out_idx[ind] = in_idx[j] - begin_col;
out_data[ind] = in_data[j];
ind++;
}
}
}
};
/*
* Slice a CSR NDArray for two dimensions
*/
template<typename xpu>
void SliceDimTwoCsrImpl(const mxnet::TShape &begin, const mxnet::TShape &end, const OpContext& ctx,
const NDArray &in, const NDArray &out);
template<typename xpu>
void SliceCsrImpl(const SliceParam ¶m, const OpContext& ctx,
const NDArray &in, OpReqType req, const NDArray &out) {
if (req == kNullOp) return;
CHECK_NE(req, kAddTo) << "kAddTo for Slice on CSR input is not supported";
CHECK_NE(req, kWriteInplace) << "kWriteInplace for Slice on CSR input is not supported";
const mxnet::TShape ishape = in.shape();
const mxnet::TShape oshape = out.shape();
int N = ishape.ndim();
mxnet::TShape begin(N, -1), end(N, -1);
for (int i = 0; i < N; ++i) {
int s = 0;
if (i < param.begin.ndim() && param.begin[i]) {
s = *param.begin[i];
if (s < 0) s += ishape[i];
}
begin[i] = s;
end[i] = s + oshape[i];
}
switch (N) {
case 1: {
SliceDimOneCsrImpl<xpu>(begin, end, ctx, in, out);
break;
}
case 2: {
SliceDimTwoCsrImpl<xpu>(begin, end, ctx, in, out);
break;
}
default:
LOG(FATAL) << "CSR is only for 2-D shape";
break;
}
}
template<typename xpu>
void SliceEx(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CHECK_EQ(inputs.size(), 1);
CHECK_EQ(outputs.size(), 1);
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
auto in_stype = inputs[0].storage_type();
if (in_stype == kCSRStorage) {
SliceCsrImpl<xpu>(param, ctx, inputs[0], req[0], outputs[0]);
} else {
LOG(FATAL) << "Slice not implemented for storage type" << in_stype;
}
}
template<int ndim>
inline bool GetIndexRange(const mxnet::TShape& dshape,
const mxnet::Tuple<dmlc::optional<index_t>>& param_begin,
const mxnet::Tuple<dmlc::optional<index_t>>& param_end,
const mxnet::Tuple<dmlc::optional<index_t>>& param_step,
common::StaticArray<index_t, ndim>* begin,
common::StaticArray<index_t, ndim>* end,
common::StaticArray<index_t, ndim>* step) {
// Function returns false if output is zero-sized, true otherwise.
bool zero_size_shape = false;
CHECK_NE(dshape.ndim(), 0U);
CHECK_LE(param_begin.ndim(), dshape.ndim())
<< "Slicing axis exceeds data dimensions";
CHECK_LE(param_end.ndim(), dshape.ndim())
<< "Slicing axis exceeds data dimensions";
CHECK_EQ(param_begin.ndim(), param_end.ndim())
<< "begin and end must have the same length";
CHECK_EQ(ndim, dshape.ndim())
<< "Static array size=" << ndim
<< " is not equal to data shape ndim=" << dshape.ndim();
if (param_step.ndim() > 0) {
CHECK_EQ(param_step.ndim(), param_begin.ndim())
<< "step and begin must have the same length";
}
for (int i = 0; i < param_begin.ndim(); ++i) {
index_t s = param_step.ndim() > 0 && param_step[i].has_value() ? param_step[i].value() : 1;
CHECK_NE(s, 0) << "slice op step[" << i << "] cannot be 0";
index_t b = 0, e = 0;
const index_t len = dshape[i];
if (len > 0) {
b = param_begin[i].has_value() ? param_begin[i].value() : (s < 0 ? len - 1 : 0);
e = param_end[i].has_value() ? param_end[i].value() : (s < 0 ? -1 : len);
if (b < 0) {
b += len;
}
if (e < 0 && param_end[i].has_value()) {
e += len;
}
// move the begin and end to correct position for calculating dim size
b = (b < 0 && s > 0) ? 0 : b;
b = (b > len - 1 && s < 0) ? len - 1 : b;
// if the start value lead to empty tensor under step s, use -1 for indication
b = (b < 0 || b > len - 1) ? -1 : b;
e = e > -1 ? e : -1;
e = e > len ? len : e;
} else if (len == 0) {
b = 0;
e = 0;
}
(*begin)[i] = b;
(*end)[i] = e;
(*step)[i] = s;
// checking begin==end
if (b == e) {
zero_size_shape = true;
}
}
for (int i = param_begin.ndim(); i < dshape.ndim(); ++i) {
(*begin)[i] = 0;
(*end)[i] = dshape[i];
(*step)[i] = 1;
}
return zero_size_shape;
}
inline void SetSliceOpOutputDimSize(const mxnet::TShape& dshape,
const index_t i, const index_t b,
const index_t e, const index_t s,
mxnet::TShape* oshape) {
if (!mxnet::dim_size_is_known(dshape, i)) {
(*oshape)[i] = -1;
return;
}
if (e != b && b >= 0) {
if (s > 0) {
(*oshape)[i] = e > b ? (e - b - 1) / s + 1 : 0;
} else {
(*oshape)[i] = e < b ? (b - e - 1) / (-s) + 1 : 0;
}
} else {
(*oshape)[i] = 0;
}
}
inline bool SliceOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(dshape)) return false;
CHECK_GT(dshape.ndim(), 0) << "slice only works for ndim > 0";
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
mxnet::TShape oshape = dshape;
MXNET_NDIM_SWITCH(dshape.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(dshape, param.begin, param.end, param.step, &begin, &end, &step);
for (int i = 0; i < param.begin.ndim(); ++i) {
const index_t b = begin[i], e = end[i], s = step[i];
SetSliceOpOutputDimSize(dshape, i, b, e, s, &oshape);
}
})
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return shape_is_known(dshape) && shape_is_known(oshape);
}
template<int ndim, int req, typename xpu>
struct slice_forward;
template<int ndim, int req>
struct slice_forward<ndim, req, gpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* data,
const mshadow::Shape<ndim> dshape,
const mshadow::Shape<ndim> oshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = dshape[ndim-1];
const index_t out_last_dim_size = oshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
const index_t j = i % out_last_dim_size;
index_t irow = 0; // row id of flattend 2D data
index_t stride = 1;
index_t idx = i / out_last_dim_size;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % oshape[k]) * step[k] + begin[k]);
idx /= oshape[k];
stride *= dshape[k];
}
KERNEL_ASSIGN(out[i], req,
data[irow * data_last_dim_size + j * step_last_dim + begin_last_dim]);
}
};
template<int ndim, int req>
struct slice_forward<ndim, req, cpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* data,
const mshadow::Shape<ndim> dshape,
const mshadow::Shape<ndim> oshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = dshape[ndim-1];
const index_t out_last_dim_size = oshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
index_t out_offset = i * out_last_dim_size;
for (index_t j = 0; j < out_last_dim_size; ++j) {
index_t irow = 0; // row id of flattend 2D data
index_t stride = 1;
index_t idx = i;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % oshape[k]) * step[k] + begin[k]);
idx /= oshape[k];
stride *= dshape[k];
}
KERNEL_ASSIGN(out[out_offset++], req,
data[irow * data_last_dim_size + j * step_last_dim + begin_last_dim]);
}
}
};
template<typename xpu>
void SliceOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
if (req[0] == kNullOp) return;
using namespace mshadow;
Stream<xpu>* s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& out = outputs[0];
if (out.Size() == 0) return;
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(data.shape_, param.begin, param.end, param.step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH_WITH_BOOL(out.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
size_t num_threads = out.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= out.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_forward<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
out.dptr<DType>(), data.dptr<DType>(),
data.shape_.get<ndim>(), out.shape_.get<ndim>(), begin, step);
})
})
})
}
template<int ndim, int req, typename xpu>
struct slice_assign;
template<int ndim, int req>
struct slice_assign<ndim, req, cpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* val,
const mshadow::Shape<ndim> oshape,
const mshadow::Shape<ndim> vshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = oshape[ndim-1];
const index_t out_last_dim_size = vshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
index_t offset = i * out_last_dim_size;
for (index_t j = 0; j < out_last_dim_size; ++j) {
index_t irow = 0; // row id of flattend 2D out
index_t stride = 1;
index_t idx = i;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % vshape[k]) * step[k] + begin[k]);
idx /= vshape[k];
stride *= oshape[k];
}
KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim],
req, val[offset++]);
}
}
};
template<int ndim, int req>
struct slice_assign<ndim, req, gpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* val,
const mshadow::Shape<ndim> oshape,
const mshadow::Shape<ndim> vshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = oshape[ndim-1];
const index_t out_last_dim_size = vshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
const index_t j = i % out_last_dim_size;
index_t irow = 0; // row id of flattend 2D out
index_t stride = 1;
index_t idx = i / out_last_dim_size;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % vshape[k]) * step[k] + begin[k]);
idx /= vshape[k];
stride *= oshape[k];
}
KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim],
req, val[i]);
}
};
template<typename xpu>
void SliceOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
if (req[0] == kNullOp) return;
using namespace mshadow;
Stream<xpu>* s = ctx.get_stream<xpu>();
const TBlob& ograd = inputs[0];
const TBlob& igrad = outputs[0];
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
if (req[0] == kWriteTo) {
Fill(s, igrad, req[0], 0);
} else if (req[0] == kWriteInplace) {
LOG(FATAL) << "_slice_backward does not support kWriteInplace";
}
if (ograd.Size() == 0) return;
MXNET_NDIM_SWITCH(ograd.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(igrad.shape_, param.begin, param.end, param.step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH(ograd.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
int num_threads = ograd.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= ograd.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
igrad.dptr<DType>(), ograd.dptr<DType>(),
igrad.shape_.get<ndim>(), ograd.shape_.get<ndim>(), begin, step);
})
})
})
}
inline bool SliceAssignOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 2U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(dshape)) return false;
mxnet::TShape vshape = dshape; // vshape is the value shape on the right hand side
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
MXNET_NDIM_SWITCH(dshape.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(dshape, param.begin, param.end, param.step, &begin, &end, &step);
for (int i = 0; i < param.begin.ndim(); ++i) {
const index_t b = begin[i], e = end[i], s = step[i];
SetSliceOpOutputDimSize(dshape, i, b, e, s, &vshape);
}
})
SHAPE_ASSIGN_CHECK(*in_attrs, 1, vshape);
SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape);
return true;
}
template<typename xpu>
void SliceAssignOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
CHECK_EQ(inputs.size(), 2U); // data[index] = val, data and val are two inputs
CHECK_EQ(outputs.size(), 1U);
if (req[0] == kNullOp) return;
Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& val = inputs[1];
const TBlob& out = outputs[0];
if (req[0] == kWriteTo) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Tensor<xpu, 1, DType> in = inputs[0].FlatTo1D<xpu, DType>(s);
Tensor<xpu, 1, DType> out = outputs[0].FlatTo1D<xpu, DType>(s);
Copy(out, in, s);
});
} else if (req[0] != kWriteInplace) {
LOG(FATAL) << "_slice_assign only supports kWriteTo and kWriteInplace";
}
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
bool zero_size_shape = GetIndexRange(data.shape_, param.begin, param.end, param.step,
&begin, &end, &step);
if (zero_size_shape) {
return; // slice_assign of zero-sized subspace needs no operation.
}
MSHADOW_TYPE_SWITCH(out.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
index_t num_threads = val.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= val.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
out.dptr<DType>(), val.dptr<DType>(),
out.shape_.get<ndim>(), val.shape_.get<ndim>(), begin, step);
})
})
})
}
struct SliceAssignScalarParam : public dmlc::Parameter<SliceAssignScalarParam> {
double scalar;
mxnet::Tuple<dmlc::optional<index_t>> begin, end;
mxnet::Tuple<dmlc::optional<index_t>> step;
DMLC_DECLARE_PARAMETER(SliceAssignScalarParam) {
DMLC_DECLARE_FIELD(scalar)
.set_default(0)
.describe("The scalar value for assignment.");
DMLC_DECLARE_FIELD(begin)
.describe("starting indices for the slice operation, supports negative indices.");
DMLC_DECLARE_FIELD(end)
.describe("ending indices for the slice operation, supports negative indices.");
DMLC_DECLARE_FIELD(step)
.set_default(mxnet::Tuple<dmlc::optional<index_t>>())
.describe("step for the slice operation, supports negative values.");
}
};
inline bool SliceAssignScalarOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = (*in_attrs)[0];
if (!shape_is_known(dshape)) return false;
SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape);
return true;
}
template<int ndim>
struct slice_assign_scalar {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType val,
const OpReqType req,
const mshadow::Shape<ndim> oshape,
const mshadow::Shape<ndim> vshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = oshape[ndim-1];
const index_t out_last_dim_size = vshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
for (index_t j = 0; j < out_last_dim_size; ++j) {
index_t irow = 0; // row id of flattend 2D out
index_t stride = 1;
index_t idx = i;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % vshape[k]) * step[k] + begin[k]);
idx /= vshape[k];
stride *= oshape[k];
}
KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim], req, val);
}
}
};
template<typename xpu>
void SliceAssignScalarOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
using namespace mshadow;
Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& out = outputs[0];
if (req[0] == kWriteTo) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Tensor<xpu, 1, DType> in = inputs[0].FlatTo1D<xpu, DType>(s);
Tensor<xpu, 1, DType> out = outputs[0].FlatTo1D<xpu, DType>(s);
Copy(out, in, s);
});
} else if (req[0] != kWriteInplace) {
LOG(FATAL) << "_crop_assign_scalar only supports kWriteTo and kWriteInplace";
}
mxnet::TShape vshape = data.shape_;
const SliceAssignScalarParam& param = nnvm::get<SliceAssignScalarParam>(attrs.parsed);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
bool zero_size_shape = GetIndexRange(data.shape_, param.begin, param.end, param.step,
&begin, &end, &step);
if (zero_size_shape) {
return; // slice_assign of zero-sized subspaced needs no operation.
}
for (index_t i = 0; i < param.begin.ndim(); ++i) {
const index_t b = begin[i], e = end[i], s = step[i];
SetSliceOpOutputDimSize(data.shape_, i, b, e, s, &vshape);
}
MSHADOW_TYPE_SWITCH_WITH_BOOL(out.type_flag_, DType, {
mxnet_op::Kernel<slice_assign_scalar<ndim>, xpu>::Launch(s, vshape.FlatTo2D()[0],
out.dptr<DType>(), static_cast<DType>(param.scalar), req[0],
out.shape_.get<ndim>(), vshape.get<ndim>(), begin, step);
})
})
}
struct SliceAxisParam : public dmlc::Parameter<SliceAxisParam> {
int axis;
index_t begin;
dmlc::optional<index_t> end;
DMLC_DECLARE_PARAMETER(SliceAxisParam) {
DMLC_DECLARE_FIELD(axis)
.describe("Axis along which to be sliced, supports negative indexes.");
DMLC_DECLARE_FIELD(begin)
.describe("The beginning index along the axis to be sliced, "
" supports negative indexes.");
DMLC_DECLARE_FIELD(end)
.describe("The ending index along the axis to be sliced, "
" supports negative indexes.");
}
};
inline void GetSliceAxisParams(const SliceAxisParam& param, const mxnet::TShape& ishape,
int* axis, index_t* begin, index_t* end) {
*axis = param.axis;
if (*axis < 0) {
*axis += ishape.ndim();
}
CHECK(*axis < ishape.ndim() && *axis >= 0) <<
"Transformed axis must be smaller than the source ndim and larger than zero! Recieved axis=" <<
param.axis << ", src_ndim=" << ishape.ndim() << ", transformed axis=" << *axis;
index_t axis_size = static_cast<index_t>(ishape[*axis]);
*begin = param.begin;
*end = -1;
if (*begin < 0) {
*begin += axis_size;
}
if (axis_size > 0) {
if (!static_cast<bool>(param.end)) {
*end = axis_size;
} else {
*end = param.end.value();
if (*end < 0) {
*end += axis_size;
}
}
CHECK(*end <= axis_size) << "Invalid end for end=" << *end << " as axis_size is " << axis_size;
CHECK((*begin < *end))
<< "Invalid begin, end, get begin=" << param.begin << ", end=" << param.end;
} else {
*begin = 0;
*end = 0;
}
CHECK(*end >= 0)
<< "Invalid begin, end, get begin=" << param.begin << ", end=" << param.end;
CHECK(*begin >= 0) << "Invalid begin for begin=" << param.begin;
}
inline bool SliceAxisShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& ishape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(ishape)) return false;
int axis;
index_t begin, end;
GetSliceAxisParams(param, ishape, &axis, &begin, &end);
if (!mxnet::dim_size_is_known(ishape, axis)) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ishape);
return false;
}
mxnet::TShape shape(ishape.ndim(), -1);
for (int i = 0; i < ishape.ndim(); ++i) {
if (i == axis) {
shape[i] = static_cast<index_t>(end - begin);
} else {
shape[i] = ishape[i];
}
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
return shape_is_known(shape);
}
template<typename xpu>
void SliceAxis(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow::expr;
const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
int axis;
index_t begin, end;
GetSliceAxisParams(param, inputs[0].shape_, &axis, &begin, &end);
int ndim = outputs[0].ndim();
if (axis + 1 == ndim) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 2, DType> in =
inputs[0].FlatTo2D<xpu, DType>(s);
mshadow::Tensor<xpu, 2, DType> out =
outputs[0].FlatTo2D<xpu, DType>(s);
ASSIGN_DISPATCH(out, req[0], slice<1>(in, begin, end));
});
} else {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 3, DType> in =
inputs[0].FlatTo3D<xpu, DType>(axis, s);
mshadow::Tensor<xpu, 3, DType> out =
outputs[0].FlatTo3D<xpu, DType>(axis, s);
ASSIGN_DISPATCH(out, req[0], slice<1>(in, begin, end));
});
}
}
// Backward pass of broadcast over the given axis
template<typename xpu>
void SliceAxisGrad_(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
if (outputs[0].shape_.Size() == 0) {
return;
}
const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed);
using namespace mshadow::op;
using namespace mshadow::expr;
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
int axis;
index_t begin, end;
GetSliceAxisParams(param, outputs[0].shape_, &axis, &begin, &end);
int ndim = outputs[0].shape_.ndim();
if (axis + 1 == ndim) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 2, DType> ograd =
inputs[0].FlatTo2D<xpu, DType>(s);
mshadow::Tensor<xpu, 2, DType> igrad =
outputs[0].FlatTo2D<xpu, DType>(s);
if (req[0] == kAddTo) {
slice<1>(igrad, begin, end) += F<identity>(ograd);
} else if (req[0] == kWriteTo) {
igrad = 0.0f;
slice<1>(igrad, begin, end) = F<identity>(ograd);
} else {
CHECK_EQ(req[0], kNullOp);
}
});
} else {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 3, DType> ograd =
inputs[0].FlatTo3D<xpu, DType>(axis, s);
mshadow::Tensor<xpu, 3, DType> igrad =
outputs[0].FlatTo3D<xpu, DType>(axis, s);
if (req[0] == kAddTo) {
slice<1>(igrad, begin, end) += F<identity>(ograd);
} else if (req[0] == kWriteTo) {
igrad = 0.0f;
slice<1>(igrad, begin, end) = F<identity>(ograd);
} else {
CHECK_EQ(req[0], kNullOp);
}
});
}
}
struct SliceLikeParam : public dmlc::Parameter<SliceLikeParam> {
mxnet::Tuple<int> axes;
DMLC_DECLARE_PARAMETER(SliceLikeParam) {
DMLC_DECLARE_FIELD(axes).set_default(mxnet::Tuple<int>())
.describe("List of axes on which input data will be sliced according to the "
"corresponding size of the second input. By default will slice on "
"all axes. Negative axes are supported.");
}
};
inline bool SliceLikeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 2U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& ishape = (*in_attrs)[0];
mxnet::TShape& from_shape = (*in_attrs)[1];
if (!mxnet::ndim_is_known(ishape) || !mxnet::ndim_is_known(from_shape)) {
return false;
}
if (param.axes.ndim() == 0) {
CHECK_EQ(ishape.ndim(), from_shape.ndim())
<< "By default slice_axis performs slice on all axes, but ndim mismatch "
"for inputs: " << ishape.ndim() << " vs. " << from_shape.ndim();
for (int i = 0; i < ishape.ndim(); ++i) {
CHECK_GE(ishape[i], from_shape[i])
<< "Slice axis " << i << " with size " << from_shape[i]
<< "exceeds limit of input with size " << ishape[i];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, from_shape);
} else {
mxnet::TShape shape(ishape);
for (int i = 0; i < param.axes.ndim(); ++i) {
int axis = param.axes[i];
if (axis < 0) {
axis += ishape.ndim();
}
CHECK_GE(axis, 0)
<< "Slice axis: " << param.axes[i] << " too small";
CHECK_GT(ishape.ndim(), axis)
<< "Slice axis: " << axis << " exceeds first input: " << ishape.ndim();
CHECK_GT(from_shape.ndim(), axis)
<< "Slice axis: " << axis << " exceeds second input: " << from_shape.ndim();
shape[axis] = from_shape[axis];
CHECK_GE(ishape[axis], from_shape[axis])
<< "Slice axis " << axis << " with size " << from_shape[axis]
<< "exceeds limit of input with size " << ishape[axis];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
}
return true;
}
inline void SliceLikeInferRanges(const mxnet::TShape& dshape,
const mxnet::TShape& fshape,
const mxnet::Tuple<int>& axes,
mxnet::Tuple<dmlc::optional<index_t>>* param_begin,
mxnet::Tuple<dmlc::optional<index_t>>* param_end,
mxnet::Tuple<dmlc::optional<index_t>>* param_step) {
std::vector<dmlc::optional<index_t>> pb(dshape.ndim());
std::vector<dmlc::optional<index_t>> pe(dshape.ndim());
std::vector<dmlc::optional<index_t>> ps(dshape.ndim());
if (axes.ndim() == 0) {
for (int i = 0; i < dshape.ndim(); ++i) {
pb[i] = 0;
pe[i] = fshape[i];
ps[i] = 1;
}
} else {
for (int i = 0; i < axes.ndim(); ++i) {
int axis = axes[i];
if (axis < 0) {
axis += dshape.ndim();
}
CHECK_GE(axis, 0)
<< "Slice axis: " << axes[i] << " too small";
CHECK_LT(axis, dshape.ndim())
<< "Slice axis: " << axis << " exceeds first input: " << dshape.ndim();
CHECK_LT(axis, fshape.ndim())
<< "Slice axis: " << axis << " exceeds first input: " << fshape.ndim();
pb[axis] = 0;
pe[axis] = fshape[axis];
ps[axis] = 1;
}
}
*param_begin = mxnet::Tuple<dmlc::optional<index_t>>(pb.begin(), pb.end());
*param_end = mxnet::Tuple<dmlc::optional<index_t>>(pe.begin(), pe.end());
*param_step = mxnet::Tuple<dmlc::optional<index_t>>(ps.begin(), ps.end());
}
template<typename xpu>
void SliceLikeForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
using namespace mshadow::expr;
const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& out = outputs[0];
const mxnet::TShape& ishape = data.shape_;
const mxnet::TShape& from_shape = inputs[1].shape_;
mxnet::Tuple<dmlc::optional<index_t>> param_begin;
mxnet::Tuple<dmlc::optional<index_t>> param_end;
mxnet::Tuple<dmlc::optional<index_t>> param_step;
SliceLikeInferRanges(ishape, from_shape, param.axes, ¶m_begin, ¶m_end, ¶m_step);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(data.shape_, param_begin, param_end, param_step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH(out.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
int num_threads = out.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= out.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_forward<ndim, Req, xpu>, xpu>::Launch(s,
num_threads, out.dptr<DType>(), data.dptr<DType>(),
data.shape_.get<ndim>(), out.shape_.get<ndim>(), begin, step);
})
})
})
}
template<typename xpu>
void SliceLikeBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 2U);
CHECK_EQ(req.size(), 2U);
using namespace mshadow;
Stream<xpu>* s = ctx.get_stream<xpu>();
if (req[1] != kNullOp && req[1] != kAddTo) {
Fill(s, outputs[1], req[1], 0); // Second input not relavant to gradients.
}
if (req[0] == kNullOp) return;
const TBlob& ograd = inputs[0];
const TBlob& igrad = outputs[0];
const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed);
if (req[0] == kWriteTo) {
Fill(s, igrad, req[0], 0);
} else if (req[0] == kWriteInplace) {
LOG(FATAL) << "_slice_like_backward does not support kWriteInplace";
}
const mxnet::TShape& ishape = ograd.shape_;
const mxnet::TShape& from_shape = outputs[1].shape_;
mxnet::Tuple<dmlc::optional<index_t>> param_begin;
mxnet::Tuple<dmlc::optional<index_t>> param_end;
mxnet::Tuple<dmlc::optional<index_t>> param_step;
SliceLikeInferRanges(ishape, from_shape, param.axes, ¶m_begin, ¶m_end, ¶m_step);
MXNET_NDIM_SWITCH(ograd.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(ograd.shape_, param_begin, param_end, param_step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH(ograd.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
int num_threads = ograd.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= ograd.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
igrad.dptr<DType>(), ograd.dptr<DType>(),
igrad.shape_.get<ndim>(), ograd.shape_.get<ndim>(), begin, step);
})
})
})
}
struct ClipParam : public dmlc::Parameter<ClipParam> {
real_t a_min, a_max;
DMLC_DECLARE_PARAMETER(ClipParam) {
DMLC_DECLARE_FIELD(a_min)
.describe("Minimum value");
DMLC_DECLARE_FIELD(a_max)
.describe("Maximum value");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream a_min_s, a_max_s;
a_min_s << a_min;
a_max_s << a_max;
(*dict)["a_min"] = a_min_s.str();
(*dict)["a_max"] = a_max_s.str();
}
};
struct clip {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* datas,
const float a_min, const float a_max) {
DType data = datas[i];
if (data > a_max) {
out[i] = a_max;
} else if (data < a_min) {
out[i] = a_min;
} else {
out[i] = data;
}
}
};
struct clip_grad {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* grad, const DType* datas,
const float a_min, const float a_max) {
DType data = datas[i];
if (data > a_max) {
out[i] = 0;
} else if (data < a_min) {
out[i] = 0;
} else {
out[i] = grad[i];
}
}
};
template<typename xpu>
void Clip(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
const ClipParam& param = nnvm::get<ClipParam>(attrs.parsed);
CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_);
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mxnet_op::Kernel<mxnet::op::clip, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(),
param.a_min, param.a_max);
});
}
template<typename xpu>
void ClipEx(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CHECK_EQ(inputs[0].dtype(), outputs[0].dtype());
CHECK_EQ(inputs[0].storage_type(), outputs[0].storage_type());
CHECK_NE(inputs[0].storage_type(), kDefaultStorage);
UnaryOp::MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Clip<xpu>);
}
template<typename xpu>
void ClipGrad_(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mxnet_op;
const ClipParam& param = nnvm::get<ClipParam>(attrs.parsed);
CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_);
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Kernel<clip_grad, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<DType>(), param.a_min, param.a_max);
});
}
/*!
* \brief The parameters of the repeat operator include
* the number of repeating time and axis (optional).
* The parameters will be later used to deduce the
* output ndarray shape in bool RepeatShape() function.
*/
struct RepeatParam : public dmlc::Parameter<RepeatParam> {
int repeats = 1;
dmlc::optional<int> axis;
DMLC_DECLARE_PARAMETER(RepeatParam) {
DMLC_DECLARE_FIELD(repeats)
.describe("The number of repetitions for each element.");
DMLC_DECLARE_FIELD(axis)
.set_default(dmlc::optional<int>())
.describe("The axis along which to repeat values."
" The negative numbers are interpreted counting from the backward."
" By default, use the flattened input array,"
" and return a flat output array.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream repeats_s, axis_s;
repeats_s << repeats;
axis_s << axis;
(*dict)["repeats"] = repeats_s.str();
(*dict)["axis"] = axis_s.str();
}
};
/*!
* \brief Helper function for getting user input params for the operator repeat.
* Sanity check the user input values.
*/
inline void GetRepeatParams(const RepeatParam& param, const mxnet::TShape& ishape,
int* repeats, dmlc::optional<int>* axisOpt) {
*repeats = param.repeats;
CHECK_GE(*repeats, 0) << "repeats cannot be a negative number";
*axisOpt = param.axis;
if (static_cast<bool>(*axisOpt)) {
int ndims = ishape.ndim();
int axis = axisOpt->value();
if (axis < 0) {
axis += ndims;
}
CHECK(axis >= 0 && axis < ndims) << "axis = " << axisOpt->value() << " out of bounds";
}
}
inline bool RepeatOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& ishape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(ishape)) {
return false;
}
int repeats = 0;
dmlc::optional<int> axisOpt;
GetRepeatParams(param, ishape, &repeats, &axisOpt);
// If 0 repeats, return an empty 1-dim, 0-size array
if (0 == repeats) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape(1, 0));
return true;
}
// If repeats > 0, multiply the size of the corresponding axis by repeats
if (static_cast<bool>(axisOpt)) {
int ndims = ishape.ndim();
int axis = axisOpt.value();
if (axis < 0) {
axis += ndims;
}
mxnet::TShape shape(ishape.ndim(), -1);
for (int i = 0; i < ishape.ndim(); ++i) {
if (i == axis) {
shape[i] = repeats * ishape[i];
} else {
shape[i] = ishape[i];
}
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
} else { // If axis is not input by user, return a flat 1D array of size = in.size*repeats
mxnet::TShape shape(1, ishape.Size() * repeats);
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
}
return shape_is_known(out_attrs->at(0));
}
inline bool RepeatOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
if ((*in_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]);
} else if ((*out_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]);
}
return true;
}
/*!
* \brief Reshape the input and output tensors for
* using broadcast_to to achieve the funcitonality
* of operator repeat.
* \return a pair of mxnet::TShape's, first is the reshaped
* input shape, second is the reshaped output shape.
*/
inline std::pair<mxnet::TShape, mxnet::TShape> ReshapeInputOutputForRepeatOp(
const mxnet::TShape& ishape,
const dmlc::optional<int>& axisOpt,
const int repeats) {
if (static_cast<bool>(axisOpt)) {
int axis = axisOpt.value();
int ndim = ishape.ndim();
if (axis < 0) {
axis += ndim;
}
CHECK(axis >= 0 && axis < ishape.ndim()) << "Invalid input of axis";
// reshape the input tensor by adding a dim at the (axis+1)-th dim
mxnet::TShape rshape(ishape.ndim()+1, 1);
// the shape we want to broadcast to
mxnet::TShape bshape(rshape.ndim(), 1);
int i = 0;
while (i <= axis) {
rshape[i] = bshape[i] = ishape[i];
++i;
}
rshape[i] = 1;
bshape[i] = repeats;
while (i < ishape.ndim()) {
rshape[i+1] = ishape[i];
bshape[i+1] = ishape[i];
++i;
}
return std::make_pair(rshape, bshape);
} else {
// axis is not input by user
// reshape the tensor into shape (ishape.Size(), 1)
// then add one dim at axis = 1 and broadcast to
// shape (ishape.Size(), repeats)
mxnet::TShape rshape(2, 1);
rshape[0] = ishape.Size();
rshape[1] = 1;
mxnet::TShape bshape(2, 1);
bshape[0] = rshape[0];
bshape[1] = repeats;
return std::make_pair(rshape, bshape);
}
}
template<typename xpu>
void RepeatOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
const TBlob& iTBlob = inputs[0];
const mxnet::TShape& ishape = iTBlob.shape_;
if (!shape_is_known(ishape)) return;
int repeats = 0;
dmlc::optional<int> axisOpt;
const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed);
GetRepeatParams(param, ishape, &repeats, &axisOpt);
if (0 == repeats) return;
std::pair<mxnet::TShape, mxnet::TShape> rshapes = \
ReshapeInputOutputForRepeatOp(ishape, axisOpt, repeats);
// reshaped input tblob
TBlob iblob(inputs[0].dptr_, rshapes.first, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
// reshaped output tblob
TBlob oblob(outputs[0].dptr_, rshapes.second, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
BroadcastCompute<xpu>(attrs, ctx, newInputs, req, newOutputs);
}
/*!
* \brief Compute the gradient of the loss function
* with respect to the input of the operator.
* Backpropagation is employed to implement the
* chain rule.
* \param inputs the gradient of the loss function
* with respect to the outputs of the operator
* \param outputs the gradient of the loss function
* with respect to the inputs of the operator
*/
template<typename xpu>
void RepeatOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
const mxnet::TShape& oshape = outputs[0].shape_;
if (!shape_is_known(oshape)) return;
int repeats = 0;
dmlc::optional<int> axisOpt;
const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed);
GetRepeatParams(param, oshape, &repeats, &axisOpt);
if (0 == repeats) return;
std::pair<mxnet::TShape, mxnet::TShape> rshapes =
ReshapeInputOutputForRepeatOp(oshape, axisOpt, repeats);
// reshaped output grad tblob
TBlob oblob(outputs[0].dptr_, rshapes.first, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
// reshaped input grad tblob
TBlob iblob(inputs[0].dptr_, rshapes.second, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
ReduceAxesComputeImpl<xpu, mshadow::red::sum, false, false>(
ctx, newInputs, req, newOutputs, rshapes.first);
}
struct TileParam : public dmlc::Parameter<TileParam> {
mxnet::Tuple<int> reps;
DMLC_DECLARE_PARAMETER(TileParam) {
DMLC_DECLARE_FIELD(reps)
.describe("The number of times for repeating the tensor a. Each dim size of reps"
" must be a positive integer."
" If reps has length d, the result will have dimension of max(d, a.ndim);"
" If a.ndim < d, a is promoted to be d-dimensional by prepending new axes."
" If a.ndim > d, reps is promoted to a.ndim by pre-pending 1's to it.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream reps_s;
reps_s << reps;
(*dict)["reps"] = reps_s.str();
}
};
inline bool TileOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const TileParam& param = nnvm::get<TileParam>(attrs.parsed);
const mxnet::TShape& ishape = (*in_attrs)[0];
if (!shape_is_known(ishape)) {
return false;
}
const mxnet::Tuple<int>& reps = param.reps;
// If reps is empty, return a identical input array
if (reps.ndim() == 0) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ishape);
return true;
}
mxnet::TShape oshape(std::max(ishape.ndim(), reps.ndim()), -1);
int i1 = ishape.ndim() - 1;
int i2 = reps.ndim() - 1;
for (int i = oshape.ndim() - 1; i >= 0; --i) {
if (i1 >= 0 && i2 >= 0) {
oshape[i] = ishape[i1--] * reps[i2--];
} else if (i1 >= 0) {
oshape[i] = ishape[i1--];
} else if (i2 >= 0) {
oshape[i] = reps[i2--];
}
}
// If reps contains 0s, oshape is a zero-size shape.
// Need to distinguish between np_shape mode and legacy mode.
if (!Imperative::Get()->is_np_shape()) {
common::ConvertToNumpyShape(&oshape);
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return shape_is_known(oshape);
}
inline bool TileOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
if ((*in_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]);
} else if ((*out_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]);
}
return true;
}
/*!
* \brief Reshape the input and output tensors for
* using broadcast_to to achieve the functionality
* of operator tile.
* \return a pair of mxnet::TShape's, first is the reshaped
* input shape, second is the reshaped output shape.
*/
inline std::pair<mxnet::TShape, mxnet::TShape> ReshapeInputOutputForTileOp(
const mxnet::TShape& ishape,
const mxnet::Tuple<int>& reps) {
if (reps.ndim() == 0) {
return std::make_pair(ishape, ishape);
}
// The shape we want to broadcast to
mxnet::TShape bshape(std::max(ishape.ndim(), reps.ndim()) * 2, 1);
// The shape of the input tensor after adding new axes before each dim
mxnet::TShape rshape(bshape.ndim(), 1);
int i1 = ishape.ndim() - 1;
int i2 = reps.ndim() - 1;
for (int i = bshape.ndim() - 1; i >= 0; --i) {
if (0 == (i & 1)) {
bshape[i] = (i2 >= 0? reps[i2--] : 1);
rshape[i] = 1;
} else {
rshape[i] = bshape[i] = (i1 >= 0? ishape[i1--] : 1);
}
}
return std::make_pair(rshape, bshape);
}
/*!
* \brief Implementation of tiling the input tensor a based
* on the user-input shape, reps.
* If a.ndim < reps.ndim, new axes are pre-pended to a. For example,
* the input tensor has shape (3,), and the reps is (2, 4); the input
* tensor would be reshaped to (1, 3).
* If a.ndim > reps.ndim, pre-pending 1's to reps. For example,
* the input tensor has shape (2, 3, 4, 5), and reps is (2, 2);
* the reps would be changed to (1, 1, 2, 2).
* Suppose we have a.ndim = reps.ndim now. To achieve tiling,
* we utilize the operator broadcast_to. For example, for a tensor
* of shape (2, 3, 4, 5) and reps (2, 8, 9, 3), we first reshape
* the tensor to the shape (1, 2, 1, 3, 1, 4, 1, 5) by adding
* one axis before each dimension. Then, we want to broadcast
* the new tensor to shape (2, 2, 8, 3, 9, 4, 3, 5). The final
* output tensor would have shape (2*2, 8*3, 9*4, 3*5).
*/
template<typename xpu>
void TileOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
if (inputs[0].Size() == 0) return;
const mxnet::TShape& ishape = inputs[0].shape_;
const mxnet::Tuple<int>& reps = nnvm::get<TileParam>(attrs.parsed).reps;
// If any one of the number in reps is zero, return immediately
for (int i = 0; i < reps.ndim(); ++i) {
if (0 == reps[i]) return;
}
std::pair<mxnet::TShape, mxnet::TShape> rshapes = ReshapeInputOutputForTileOp(ishape, reps);
// reshaped input tblob
TBlob iblob(inputs[0].dptr_, rshapes.first, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
// reshaped output tblob
TBlob oblob(outputs[0].dptr_, rshapes.second, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
BroadcastCompute<xpu>(attrs, ctx, newInputs, req, newOutputs);
}
/*!
* \brief Compute the gradient of the loss function
* with respect to the input of the operator.
* Backpropagation is employed to implement the
* chain rule.
* \param inputs the gradient of the loss function
* with respect to the outputs of the operator
* \param outputs the gradient of the loss function
* with respect to the inputs of the operator
*/
template<typename xpu>
void TileOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
if (inputs[0].Size() == 0) return;
const mxnet::TShape& oshape = outputs[0].shape_;
const mxnet::Tuple<int>& reps = nnvm::get<TileParam>(attrs.parsed).reps;
// If any one of the number in reps is zero, return immediately
for (int i = 0; i < reps.ndim(); ++i) {
if (0 == reps[i]) return;
}
std::pair<mxnet::TShape, mxnet::TShape> rshapes = ReshapeInputOutputForTileOp(oshape, reps);
// reshaped output grad tblob
TBlob oblob(outputs[0].dptr_, rshapes.first, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
// reshaped input grad tblob
TBlob iblob(inputs[0].dptr_, rshapes.second, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
ReduceAxesComputeImpl<xpu, mshadow::red::sum, false, false>(
ctx, newInputs, req, newOutputs, rshapes.first);
}
struct ReverseParam : public dmlc::Parameter<ReverseParam> {
mxnet::Tuple<int> axis;
DMLC_DECLARE_PARAMETER(ReverseParam) {
DMLC_DECLARE_FIELD(axis)
.describe("The axis which to reverse elements.");
}
};
#define REVERSE_MAX_DIM 10U
struct reverse {
MSHADOW_XINLINE static index_t ReverseIndex(index_t idx,
index_t nreversedim,
const index_t * stride_,
const index_t * trailing_) {
index_t outputIndex = idx;
for (index_t i = 0; i < nreversedim; ++i) {
const index_t low = outputIndex % trailing_[i];
index_t high = outputIndex / trailing_[i];
const index_t x = high%stride_[i];
high /= stride_[i];
outputIndex = (high*stride_[i] + stride_[i] - 1 - x)*trailing_[i] + low;
}
return outputIndex;
}
#ifdef __CUDACC__
template<typename DType>
__device__ static void Map(index_t index, index_t nreversedim, const DType *src, DType *dst,
const index_t * stride_,
const index_t * trailing_) {
__shared__ index_t stride_share[REVERSE_MAX_DIM];
__shared__ index_t trailing_share[REVERSE_MAX_DIM];
if (threadIdx.x < REVERSE_MAX_DIM) {
stride_share[threadIdx.x] = stride_[threadIdx.x];
trailing_share[threadIdx.x] = trailing_[threadIdx.x];
}
__syncthreads();
index_t new_idx = ReverseIndex(index, nreversedim, stride_share, trailing_share);
dst[new_idx] = src[index];
}
#else
template<typename DType>
MSHADOW_XINLINE static void Map(index_t index, index_t nreversedim, const DType *src, DType *dst,
const index_t * stride_,
const index_t * trailing_) {
index_t new_idx = ReverseIndex(index, nreversedim, stride_, trailing_);
dst[new_idx] = src[index];
}
#endif
};
template<typename xpu>
void ReverseOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mxnet_op;
const ReverseParam& param = nnvm::get<ReverseParam>(attrs.parsed);
CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_);
CHECK_LT(param.axis.ndim(), REVERSE_MAX_DIM);
Stream<xpu> *s = ctx.get_stream<xpu>();
const mxnet::TShape& ishape = inputs[0].shape_;
std::vector<index_t> stride_(param.axis.ndim());
std::vector<index_t> trailing_(param.axis.ndim());
index_t reverse_index = 0;
for (int axis : param.axis) {
CHECK_LT(axis, ishape.ndim());
stride_[reverse_index] = ishape[axis];
trailing_[reverse_index] = 1;
for (int i2 = axis + 1; i2 < ishape.ndim(); ++i2) {
trailing_[reverse_index] *= ishape[i2];
}
reverse_index++;
}
#ifdef __CUDACC__
mshadow::Tensor<xpu, 1, uint8_t> workspace =
ctx.requested[0].get_space_typed<xpu, 1, uint8_t>(
mshadow::Shape1(reverse_index * sizeof(index_t) * 2), s);
auto stride_workspace = workspace.dptr_;
auto trailing_workspace = workspace.dptr_ + reverse_index * sizeof(index_t);
cudaMemcpyAsync(stride_workspace, thrust::raw_pointer_cast(stride_.data()),
stride_.size() * sizeof(index_t),
cudaMemcpyHostToDevice, mshadow::Stream<gpu>::GetStream(s));
cudaMemcpyAsync(trailing_workspace, thrust::raw_pointer_cast(trailing_.data()),
trailing_.size() * sizeof(index_t),
cudaMemcpyHostToDevice, mshadow::Stream<gpu>::GetStream(s));
#endif
#ifdef __CUDACC__
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Kernel<reverse, xpu>::Launch(s, inputs[0].Size(), reverse_index,
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
reinterpret_cast<index_t*>(stride_workspace), reinterpret_cast<index_t*>(trailing_workspace));
});
#else
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Kernel<reverse, xpu>::Launch(s, inputs[0].Size(), reverse_index,
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
stride_.data(), trailing_.data());
});
#endif
}
struct StackParam : public dmlc::Parameter<StackParam> {
int axis;
int num_args;
DMLC_DECLARE_PARAMETER(StackParam) {
DMLC_DECLARE_FIELD(axis)
.set_default(0)
.describe("The axis in the result array along which the input arrays are stacked.");
DMLC_DECLARE_FIELD(num_args).set_lower_bound(1)
.describe("Number of inputs to be stacked.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream axis_s, num_args_s;
axis_s << axis;
num_args_s << num_args;
(*dict)["axis"] = axis_s.str();
(*dict)["num_args"] = num_args_s.str();
}
};
inline bool StackOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const StackParam& param = dmlc::get<StackParam>(attrs.parsed);
mxnet::TShape dshape;
for (const mxnet::TShape& i : (*in_attrs)) {
shape_assign(&dshape, i);
}
if (!shape_is_known(dshape)) return false;
mxnet::TShape oshape(dshape.ndim() + 1, -1);
int axis = CheckAxis(param.axis, oshape.ndim());
for (int i = 0; i < axis; ++i) {
oshape[i] = dshape[i];
}
oshape[axis] = param.num_args;
for (index_t i = axis + 1; i < oshape.ndim(); ++i) {
oshape[i] = dshape[i-1];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return shape_is_known(oshape);
}
template<typename xpu>
void StackOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mshadow::expr;
const StackParam& param = dmlc::get<StackParam>(attrs.parsed);
int axis = CheckAxis(param.axis, outputs[0].ndim());
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH_WITH_BOOL(outputs[0].type_flag_, DType, {
std::vector<Tensor<xpu, 3, DType> > data(inputs.size());
Tensor<xpu, 3, DType> out;
size_t leading = 1, trailing = 1;
for (int i = 0; i < axis; ++i) {
leading *= outputs[0].shape_[i];
}
for (int i = axis + 1; i < outputs[0].ndim(); ++i) {
trailing *= outputs[0].shape_[i];
}
size_t mid = outputs[0].shape_[axis];
Shape<3> oshape = Shape3(leading, mid, trailing);
out = outputs[0].get_with_shape<xpu, 3, DType>(oshape, s);
for (size_t i = 0; i < inputs.size(); ++i) {
Shape<3> dshape = Shape3(leading, 1, trailing);
data[i] = inputs[i].get_with_shape<xpu, 3, DType>(dshape, s);
}
Concatenate(data, &out, 1, req[0]);
})
}
template<typename xpu>
void StackOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mshadow::expr;
const StackParam& param = dmlc::get<StackParam>(attrs.parsed);
int axis = CheckAxis(param.axis, inputs[0].ndim());
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH_WITH_BOOL(inputs[0].type_flag_, DType, {
std::vector<Tensor<xpu, 3, DType> > grad_in(outputs.size());
Tensor<xpu, 3, DType> grad;
size_t leading = 1, trailing = 1;
for (int i = 0; i < axis; ++i) {
leading *= inputs[0].shape_[i];
}
for (int i = axis + 1; i < inputs[0].ndim(); ++i) {
trailing *= inputs[0].shape_[i];
}
size_t mid = inputs[0].shape_[axis];
Shape<3> oshape = Shape3(leading, mid, trailing);
grad = inputs[0].get_with_shape<xpu, 3, DType>(oshape, s);
for (size_t i = 0; i < outputs.size(); ++i) {
Shape<3> dshape = Shape3(leading, 1, trailing);
grad_in[i] = outputs[i].get_with_shape<xpu, 3, DType>(dshape, s);
}
Split(grad, &grad_in, 1, req);
})
}
struct SqueezeParam : public dmlc::Parameter<SqueezeParam> {
dmlc::optional<mxnet::Tuple<int>> axis;
DMLC_DECLARE_PARAMETER(SqueezeParam) {
DMLC_DECLARE_FIELD(axis)
.set_default(dmlc::optional<mxnet::Tuple<int>>())
.describe("Selects a subset of the single-dimensional entries in the shape."
" If an axis is selected with shape entry greater than one, an error is raised.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream axis_s;
axis_s << axis;
(*dict)["axis"] = axis_s.str();
}
};
// Given a shape that may have dim size equal to 0,
// move all the zeros to the last of the shape array
// and keep the relative order of the non-zero values.
// Returns the new shape size after moving all zeros to the end.
inline size_t SqueezeShapeHelper(mxnet::TShape* shape) {
CHECK(shape != nullptr);
size_t count = 0;
for (int i = 0; i < shape->ndim(); ++i) {
if ((*shape)[i] == -1) {
++count;
} else {
std::swap((*shape)[i], (*shape)[i-count]);
}
}
return shape->ndim() - count;
}
inline bool SqueezeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const SqueezeParam& param = nnvm::get<SqueezeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]";
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = in_attrs->at(0);
const int dndim = dshape.ndim();
if (!shape_is_known(dshape)) return false;
mxnet::TShape oshape = dshape;
if (param.axis.has_value()) {
// preprocess axis
mxnet::Tuple<int> axes = param.axis.value();
for (int i = 0; i < axes.ndim(); ++i) {
if (axes[i] < 0) {
axes[i] += dndim;
CHECK_GE(axes[i], 0)
<< "axis " << axes[i] - dndim << " is out of bounds for array of dimension " << dndim;
}
CHECK_LT(axes[i], dndim)
<< "axis " << axes[i] << " is out of bounds for array of dimension " << dndim;
CHECK_EQ(dshape[axes[i]], 1)
<< "cannot select an axis to squeeze out which has size="
<< dshape[axes[i]] << " not equal to one";
CHECK_NE(oshape[axes[i]], -1) << "duplicate value in axis";
oshape[axes[i]] = -1;
}
} else {
for (int i = 0; i < oshape.ndim(); ++i) {
if (oshape[i] == 1) oshape[i] = -1;
}
}
size_t oshape_size = SqueezeShapeHelper(&oshape);
if (oshape_size == 0) { // corner case when dshape is (1, 1, 1, 1)
oshape[0] = 1;
oshape_size = 1;
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape(oshape.data(), oshape.data()+oshape_size));
return true;
}
struct DepthToSpaceParam : public dmlc::Parameter<DepthToSpaceParam> {
int block_size;
DMLC_DECLARE_PARAMETER(DepthToSpaceParam) {
DMLC_DECLARE_FIELD(block_size)
.describe("Blocks of [block_size. block_size] are moved");
}
};
inline bool DepthToSpaceOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
CHECK_EQ(in_attrs->at(0).ndim(), 4) << "Operation Depth To Space requires exactly 4D tensor";
mxnet::TShape expected_out(4, -1);
mxnet::TShape& in_shape = in_attrs->at(0);
if (!mxnet::ndim_is_known(in_shape)) {
return false;
}
int block = param.block_size;
CHECK_NE(block, 0) << "block_size must be a positive integer value";
CHECK_NE(in_shape[1], 0) << "Depth dimension:1 cannot be 0";
CHECK_EQ(in_shape[1] % (block * block), 0)
<< "Cannot perform Depth To Space operation on the specified tensor."
" Dimension:1(depth dimension) should be a multiple of 'block^2'";
CHECK_NE(in_shape[0], 0)
<< "Operation requires a 4D tensor. Size of dimension:0 cannot be 0";
CHECK_NE(in_shape[2], 0)
<< "Operation requires a 4D tensor. Size of dimension:2 cannot be 0";
CHECK_NE(in_shape[3], 0)
<< "Operation requires a 4D tensor. Size of dimension:3 cannot be 0";
expected_out[0] = in_shape[0];
expected_out[1] = in_shape[1] / (block * block);
int i = 2;
while (i < expected_out.ndim()) {
expected_out[i] = in_shape[i] * block;
++i;
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, expected_out);
return shape_is_known(expected_out);
}
inline bool DepthToSpaceOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0));
TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0));
return out_attrs->at(0) != -1;
}
/*!
* \brief This function updates the value of input index from where the data element
* needs to be fetched and written out to the ith location in output tensor
* \param index_position index within offset array to get offset of given dimension
* \param dim_size size of current dimension
* \param idx output tensor index
* \param inp_index index within input tensor from where value is retrieved
* \param offset_arr array containing the linear offset of input tensor
*/
MSHADOW_XINLINE void update_index(index_t index_position, index_t dim_size, index_t *idx,
index_t *inp_index, const index_t* offset_arr) {
index_t next_idx_val = *idx / dim_size;
*inp_index += (*idx - next_idx_val * dim_size) * offset_arr[index_position];
*idx = next_idx_val;
}
/*!
* \brief This function performs the tensor transpose (0, 1, 2, 3, 4, 5) ->
* (0, 3, 4, 1, 5, 2) by computing linear index within input tensor to be mapped
* to the ith index of output tensor
* \param i tensor index
* \param out_data output tensor
* \param in_data input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size array containing the size of each dimension of input tensor
* \param offset_arr array containing the linear offset of input tensor
*/
template<int req>
struct depth_to_space_forward {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out_data, const DType* in_data,
const int block, const index_t* size, const index_t* offset_arr) {
index_t inp_index = 0, idx = i, dim_size;
dim_size = block;
update_index(2, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[3];
update_index(5, dim_size, &idx, &inp_index, offset_arr);
dim_size = block;
update_index(1, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[2];
update_index(4, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[1] / (block * block);
update_index(3, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[0];
update_index(0, dim_size, &idx, &inp_index, offset_arr);
KERNEL_ASSIGN(out_data[i], req, in_data[inp_index]);
}
};
/*!
* \brief This function calculates the linear offset for each dimension of
* input tensor and stores them in an array, which is later used in
* performing depth_to_space operation
* \param i global thread id
* \param offset_arr array to be populated with offset values
* \param size array to be populated with size of each dimension of input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size0 size of Dim 0 of input tensor
* \param size1 size of Dim 1 of input tensor
* \param size2 size of Dim 2 of input tensor
* \param size3 size of Dim 3 of input tensor
*/
template<int req>
struct compute_offset_for_depth_to_space {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* offset_arr, DType* size, const int block,
const index_t size0, const index_t size1, const index_t size2,
const index_t size3) {
size[0] = size0;
size[1] = size1;
size[2] = size2;
size[3] = size3;
offset_arr[5] = 1;
offset_arr[4] = offset_arr[5] * size[3];
offset_arr[3] = offset_arr[4] * size[2];
offset_arr[2] = offset_arr[3] * size[1] / (block * block);
offset_arr[1] = offset_arr[2] * block;
offset_arr[0] = offset_arr[1] * block;
}
};
template<typename xpu>
void DepthToSpaceOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& in_data = inputs[0];
const TBlob& out_data = outputs[0];
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
using namespace mxnet_op;
int block = param.block_size;
mshadow::Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(mshadow::Shape1(sizeof(index_t) * 10), s);
char* workspace_curr_ptr = workspace.dptr_;
index_t* offset_arr = reinterpret_cast<index_t*>(workspace_curr_ptr);
index_t* size = reinterpret_cast<index_t*>(workspace_curr_ptr + sizeof(index_t) * 6);
MSHADOW_TYPE_SWITCH(out_data.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
Kernel<compute_offset_for_depth_to_space<req_type>, xpu>::Launch(
s, 1, offset_arr, size, block, in_data.shape_[0], in_data.shape_[1],
in_data.shape_[2], in_data.shape_[3]);
Kernel<depth_to_space_forward<req_type>, xpu>::Launch(
s, out_data.Size(), out_data.dptr<DType>(), in_data.dptr<DType>(),
block, size, offset_arr);
});
});
}
inline bool SpaceToDepthOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
CHECK_EQ(in_attrs->at(0).ndim(), 4) << "Operation Space To Depth requires exactly 4D tensor";
mxnet::TShape expected_out(in_attrs->at(0).ndim(), -1);
mxnet::TShape& in_shape = in_attrs->at(0);
if (!mxnet::ndim_is_known(in_shape)) {
return false;
}
int block = param.block_size;
CHECK_NE(block, 0) << "block_size must be a positive integer value";
CHECK_NE(in_shape[0], 0)
<< "Operation requires a 4D tensor. Size of dimension:0 cannot be 0";
CHECK_NE(in_shape[1], 0) << "Depth dimension:1 cannot be 0";
CHECK_NE(in_shape[2], 0)
<< "Operation requires a 4D tensor. Size of dimension:2 cannot be 0";
CHECK_EQ(in_shape[2] % block, 0)
<< "Cannot perform Depth To Space operation on the specified tensor."
" Dimension:2(1st Space dimension) should be a multiple of 'block' ";
CHECK_NE(in_shape[3], 0)
<< "Operation requires a 4D tensor. Size of dimension:3 cannot be 0";
CHECK_EQ(in_shape[3] % block, 0)
<< "Cannot perform Depth To Space operation on the specified tensor."
" Dimension:3(2nd space dimension) should be a multiple of 'block' ";
expected_out[0] = in_shape[0];
expected_out[1] = in_shape[1] * block * block;
int i = 2;
while (i < expected_out.ndim()) {
expected_out[i] = in_shape[i] / block;
++i;
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, expected_out);
return shape_is_known(expected_out);
}
inline bool SpaceToDepthOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0));
TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0));
return out_attrs->at(0) != -1;
}
/*!
* \brief This function preforms the tensor transpose (0, 1, 2, 3, 4, 5) ->
* (0, 3, 5, 1, 2, 4) by computing linear index within input tensor to be mapped
* to the ith index of output tensor
* \param i tensor index
* \param out_data output tensor
* \param in_data input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size array containing the size of each dimension of input tensor
* \param offset_arr array containing the linear offset of input tensor
*/
template<int req>
struct space_to_depth_forward {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out_data, const DType* in_data, const int block,
const index_t* size, const index_t* offset_arr) {
index_t inp_index = 0, idx = i, dim_size;
dim_size = size[3] / block;
update_index(4, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[2] / block;
update_index(2, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[1];
update_index(1, dim_size, &idx, &inp_index, offset_arr);
dim_size = block;
update_index(5, dim_size, &idx, &inp_index, offset_arr);
dim_size = block;
update_index(3, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[0];
update_index(0, dim_size, &idx, &inp_index, offset_arr);
KERNEL_ASSIGN(out_data[i], req, in_data[inp_index]);
}
};
/*!
* \brief This function calculates the linear offset for each dimension of
* input tensor and stores them in an array, which is later used in
* performing space_to_depth operation
* \param i global thread id
* \param offset_arr array to be populated with offset values
* \param size array to be populated with size of each dimension of input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size0 size of Dim 0 of input tensor
* \param size1 size of Dim 1 of input tensor
* \param size2 size of Dim 2 of input tensor
* \param size3 size of Dim 3 of input tensor
*/
template<int req>
struct compute_offset_for_space_to_depth {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* offset_arr, DType* size, const int block,
const index_t size0, const index_t size1,
const index_t size2, const index_t size3) {
size[0] = size0;
size[1] = size1;
size[2] = size2;
size[3] = size3;
offset_arr[5] = 1;
offset_arr[4] = offset_arr[5] * block;
offset_arr[3] = offset_arr[4] * size[3] / block;
offset_arr[2] = offset_arr[3] * block;
offset_arr[1] = offset_arr[2] * size[2] / block;
offset_arr[0] = offset_arr[1] * size[1];
}
};
template<typename xpu>
void SpaceToDepthOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& in_data = inputs[0];
const TBlob& out_data = outputs[0];
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
using namespace mxnet_op;
int block = param.block_size;
mshadow::Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(mshadow::Shape1(sizeof(index_t) * 10), s);
char* workspace_curr_ptr = workspace.dptr_;
index_t* offset_arr = reinterpret_cast<index_t*>(workspace_curr_ptr);
index_t* size = reinterpret_cast<index_t*>(workspace_curr_ptr + sizeof(index_t) * 6);
MSHADOW_TYPE_SWITCH(out_data.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
Kernel<compute_offset_for_space_to_depth<req_type>, xpu>::Launch(
s, 1, offset_arr, size, block, in_data.shape_[0], in_data.shape_[1],
in_data.shape_[2], in_data.shape_[3]);
Kernel<space_to_depth_forward<req_type>, xpu>::Launch(
s, out_data.Size(), out_data.dptr<DType>(), in_data.dptr<DType>(),
block, size, offset_arr);
});
});
}
namespace split_enum {
enum SplitOpInputs {kData};
} // namespace split_enum
struct SplitParam : public dmlc::Parameter<SplitParam> {
mxnet::TShape indices;
int axis;
bool squeeze_axis;
int sections;
DMLC_DECLARE_PARAMETER(SplitParam) {
DMLC_DECLARE_FIELD(indices)
.describe("Indices of splits. The elements should denote the boundaries of at which split"
" is performed along the `axis`.");
DMLC_DECLARE_FIELD(axis).set_default(1)
.describe("Axis along which to split.");
DMLC_DECLARE_FIELD(squeeze_axis).set_default(0)
.describe("If true, Removes the axis with length 1 from the shapes of the output arrays."
" **Note** that setting `squeeze_axis` to ``true`` removes axis with length 1"
" only along the `axis` which it is split."
" Also `squeeze_axis` can be set to ``true``"
" only if ``input.shape[axis] == num_outputs``.");
DMLC_DECLARE_FIELD(sections).set_default(0)
.describe("Number of sections if equally splitted. Default to 0 which means split by indices.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream indices_s, axis_s, squeeze_axis_s, sections_s;
indices_s << indices;
axis_s << axis;
squeeze_axis_s << squeeze_axis;
sections_s << sections;
(*dict)["indices"] = indices_s.str();
(*dict)["axis"] = axis_s.str();
(*dict)["squeeze_axis"] = squeeze_axis_s.str();
(*dict)["sections"] = sections_s.str();
}
}; // struct SplitParam
inline mxnet::TShape GetSplitIndices(const mxnet::TShape& ishape, int axis, int sections) {
mxnet::TShape indices(sections+1, -1);
indices[0] = 0;
int64_t section_size_b = (int64_t) (ishape[axis] / sections);
int64_t section_size_a = section_size_b + 1;
int section_a = ishape[axis] % sections;
for (int i = 0; i < sections; ++i) {
if ( i < section_a ) {
indices[i+1] = section_size_a * (i + 1);
} else {
indices[i+1] = section_size_b + indices[i];
}
}
return indices;
}
inline bool SplitOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
int dtype = (*in_attrs)[0];
CHECK_NE(dtype, -1) << "First input must have specified type";
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
out_attrs->clear();
int num_outputs = (param.sections > 0) ? param.sections : param.indices.ndim();
for (int i = 0; i < num_outputs; ++i) {
out_attrs->push_back(dtype);
}
return true;
}
inline bool SplitOpShapeImpl(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs,
const int real_axis) {
using namespace mshadow;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
mxnet::TShape dshape = in_attrs->at(split_enum::kData);
mxnet::TShape ishape = in_attrs->at(split_enum::kData);
const mxnet::TShape indices =
(param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices;
int num_outputs = (param.sections > 0) ? indices.ndim() - 1 : indices.ndim();
// Pre-compute squeezed output shape for future usage
mxnet::TShape squeezed_dshape = dshape;
for (int d = real_axis; d < squeezed_dshape.ndim() - 1; ++d) {
squeezed_dshape[d] = squeezed_dshape[d+1];
}
squeezed_dshape = mxnet::TShape(&squeezed_dshape[0], &squeezed_dshape[squeezed_dshape.ndim()-1]);
// Assign shape to every output
for (int i = 0; i < num_outputs; ++i) {
index_t start = indices[i];
index_t end = (i < num_outputs - 1) ? indices[i + 1] : ishape[real_axis];
if (ishape[real_axis] == 0U) {
end = start;
} else {
CHECK(start <= end)
<< "start " << start << " is not less than end " << end << "for subarray " << i;
CHECK(end <= ishape[real_axis])
<< "end " << end << " is no less than the size of the axis " << ishape[real_axis];
}
dshape[real_axis] = (end - start);
if (param.squeeze_axis) {
CHECK_EQ(end - start, 1U) << "expected axis size of 1 but got " << end - start;
SHAPE_ASSIGN_CHECK(*out_attrs, i, squeezed_dshape);
} else {
SHAPE_ASSIGN_CHECK(*out_attrs, i, dshape);
}
}
mxnet::TShape back_calculate_dshape = ishape;
back_calculate_dshape[real_axis] = 0;
for (int d = 0; d < real_axis; ++d) {
back_calculate_dshape[d] = (*out_attrs)[0][d];
}
if (param.squeeze_axis) {
back_calculate_dshape[real_axis] = num_outputs;
} else {
for (int i = 0; i < num_outputs; ++i) {
back_calculate_dshape[real_axis] += (*out_attrs)[i][real_axis];
}
}
for (int d = real_axis + 1; d < ishape.ndim(); ++d) {
if (param.squeeze_axis) {
back_calculate_dshape[d] = (*out_attrs)[0][d - 1];
} else {
back_calculate_dshape[d] = (*out_attrs)[0][d];
}
}
SHAPE_ASSIGN_CHECK(*in_attrs, split_enum::kData, back_calculate_dshape);
return true;
}
inline bool SplitOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
using namespace mshadow;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
mxnet::TShape dshape = in_attrs->at(split_enum::kData);
if (!mxnet::ndim_is_known(dshape)) return false;
if (param.axis >= 0) {
CHECK_LT(param.axis, dshape.ndim());
} else {
CHECK_LT(param.axis + dshape.ndim(), dshape.ndim());
}
int real_axis = param.axis;
if (real_axis < 0) {
real_axis += dshape.ndim();
}
return SplitOpShapeImpl(attrs, in_attrs, out_attrs, real_axis);
}
struct SplitKernel {
/*!
* \brief Map function for forward split_v2 operator
* \param i global thread id
* \param in_data ptr to input buffer
* \param out_data ptr to ptr of outputs buffer
* \param indices ptr to indices buffer
* \param num_sections # of sections after split
* \param axis_size size of axis to be splitted on
* \param trailing_size step size within the data buffer of the axis to be splitted on
*/
template<typename DType>
static MSHADOW_XINLINE void Map(size_t i,
const DType *in_data, DType** out_data, const size_t* indices,
const size_t num_sections, const size_t axis_size,
const size_t trailing_size) {
size_t idx = i / trailing_size % axis_size;
size_t target = 0;
for (size_t section = 0;
section < num_sections && indices[section] <= idx;
target = section++) {}
DType* target_data = out_data[target];
const size_t mid_idx = idx - indices[target];
const size_t head_idx = i / (trailing_size * axis_size);
const size_t tail_idx = i % trailing_size;
const size_t section_size = indices[target + 1] - indices[target];
const size_t target_idx =
head_idx * trailing_size * section_size + mid_idx * trailing_size + tail_idx;
target_data[target_idx] = in_data[i];
}
};
struct ConcatenateKernel {
/*!
* \brief Map function for backward split_v2 operator
* \param i global thread id
* \param out_grad ptr to ptr of out grads buffer
* \param in_grad ptr to input grad buffer
* \param indices ptr to indices buffer
* \param num_sections # of sections after split
* \param axis_size size of axis to be splitted on
* \param trailing_size step size within the data buffer of the axis to be splitted on
*/
template<typename DType>
static MSHADOW_XINLINE void Map(size_t i,
DType** out_grad, DType* in_grad, const size_t* indices,
const size_t num_sections, const size_t axis_size,
const size_t trailing_size) {
size_t idx = i / trailing_size % axis_size;
size_t src = 0;
for (size_t section = 0;
section < num_sections && indices[section] <= idx;
src = section++) {}
DType* src_grad = out_grad[src];
const size_t mid_idx = idx - indices[src];
const size_t head_idx = i / (trailing_size * axis_size);
const size_t tail_idx = i % trailing_size;
const size_t section_size = indices[src + 1] - indices[src];
const size_t src_idx =
head_idx * trailing_size * section_size + mid_idx * trailing_size + tail_idx;
in_grad[i] = src_grad[src_idx];
}
};
template<typename xpu>
inline void SplitOpForwardImpl(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs,
const int real_axis) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& input_data = inputs[split_enum::kData];
size_t leading = 1, trailing = 1;
CHECK_LT(real_axis, input_data.ndim());
size_t mid = input_data.shape_[real_axis];
for (int i = 0; i < real_axis; ++i) {
leading *= input_data.shape_[i];
}
for (int i = real_axis + 1; i < input_data.ndim(); ++i) {
trailing *= input_data.shape_[i];
}
size_t workspace_size = 0;
const mxnet::TShape& ishape = input_data.shape_;
const mxnet::TShape split_pts =
(param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices;
std::vector<size_t> indices;
for (const auto& section : split_pts) {
indices.push_back(section);
}
if (param.sections == 0) {
indices.push_back(ishape[real_axis]);
}
workspace_size += indices.size() * sizeof(size_t);
MSHADOW_TYPE_SWITCH(input_data.type_flag_, DType, {
std::vector<DType*> output_data;
for (const TBlob& data : outputs) {
output_data.push_back(data.dptr<DType>());
}
workspace_size += output_data.size() * sizeof(DType*);
Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(Shape1(workspace_size), s);
Tensor<cpu, 1, size_t> indices_cpu_tensor(indices.data(), Shape1(indices.size()));
Tensor<xpu, 1, size_t> indices_xpu_tensor(
reinterpret_cast<size_t*>(workspace.dptr_), Shape1(indices.size()));
Tensor<cpu, 1, DType*> ptrs_cpu_tensor(output_data.data(), Shape1(output_data.size()));
Tensor<xpu, 1, DType*> ptrs_xpu_tensor(
reinterpret_cast<DType**>(workspace.dptr_ + indices.size() * sizeof(size_t)),
Shape1(output_data.size()));
mshadow::Copy(indices_xpu_tensor, indices_cpu_tensor, s);
mshadow::Copy(ptrs_xpu_tensor, ptrs_cpu_tensor, s);
Kernel<SplitKernel, xpu>::Launch(
s, input_data.Size(), input_data.dptr<DType>(), ptrs_xpu_tensor.dptr_,
indices_xpu_tensor.dptr_, indices.size() - 1, mid, trailing);
});
}
template<typename xpu>
inline void SplitOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), (param.sections > 0) ? param.sections : param.indices.ndim());
const TBlob& input_data = inputs[split_enum::kData];
int real_axis = param.axis;
if (real_axis < 0) {
real_axis += input_data.ndim();
}
SplitOpForwardImpl<xpu>(attrs, ctx, inputs, req, outputs, real_axis);
}
template<typename xpu>
inline void SplitOpBackwardImpl(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs,
const int real_axis) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
Stream<xpu> *s = ctx.get_stream<xpu>();
TBlob input_grad = outputs[split_enum::kData];
size_t leading = 1, trailing = 1;
CHECK_LT(real_axis, input_grad.ndim());
size_t mid = input_grad.shape_[real_axis];
for (int i = 0; i < real_axis; ++i) {
leading *= input_grad.shape_[i];
}
for (int i = real_axis + 1; i < input_grad.ndim(); ++i) {
trailing *= input_grad.shape_[i];
}
size_t workspace_size = 0;
const mxnet::TShape& ishape = input_grad.shape_;
const mxnet::TShape split_pts =
(param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices;
std::vector<size_t> indices;
for (const auto& section : split_pts) {
indices.push_back(section);
}
if (param.sections == 0) {
indices.push_back(ishape[real_axis]);
}
workspace_size += indices.size() * sizeof(size_t);
MSHADOW_TYPE_SWITCH(input_grad.type_flag_, DType, {
std::vector<DType*> out_grads;
for (const TBlob& output_grad : inputs) {
out_grads.push_back(output_grad.dptr<DType>());
}
workspace_size += out_grads.size() * sizeof(DType*);
Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(Shape1(workspace_size), s);
Tensor<cpu, 1, size_t> indices_cpu_tensor(indices.data(), Shape1(indices.size()));
Tensor<xpu, 1, size_t> indices_xpu_tensor(
reinterpret_cast<size_t*>(workspace.dptr_), Shape1(indices.size()));
Tensor<cpu, 1, DType*> ptrs_cpu_tensor(out_grads.data(), Shape1(inputs.size()));
Tensor<xpu, 1, DType*> ptrs_xpu_tensor(
reinterpret_cast<DType**>(workspace.dptr_ + indices.size() * sizeof(size_t)),
Shape1(inputs.size()));
mshadow::Copy(indices_xpu_tensor, indices_cpu_tensor, s);
mshadow::Copy(ptrs_xpu_tensor, ptrs_cpu_tensor, s);
Kernel<ConcatenateKernel, xpu>::Launch(
s, input_grad.Size(), ptrs_xpu_tensor.dptr_, input_grad.dptr<DType>(),
indices_xpu_tensor.dptr_, indices.size() - 1, mid, trailing);
});
}
template<typename xpu>
inline void SplitOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
CHECK_EQ(inputs.size(), (param.sections > 0) ? param.sections : param.indices.ndim())
<< "out grad vector size mush match the output size";
CHECK_EQ(outputs.size(), 1U);
int real_axis = param.axis;
if (real_axis < 0) {
real_axis += outputs[split_enum::kData].ndim();
}
SplitOpBackwardImpl<xpu>(attrs, ctx, inputs, req, outputs, real_axis);
}
inline uint32_t SplitNumOutputs(const NodeAttrs& attrs) {
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
return (param.sections > 0) ? param.sections : param.indices.ndim();
}
} // namespace op
} // namespace mxnet
namespace std {
template<>
struct hash<mxnet::op::TransposeParam> {
size_t operator()(const mxnet::op::TransposeParam& val) {
size_t ret = 0;
ret = dmlc::HashCombine(ret, val.axes);
return ret;
}
};
template<>
struct hash<mxnet::op::ReshapeParam> {
size_t operator()(const mxnet::op::ReshapeParam& val) {
size_t ret = 0;
ret = dmlc::HashCombine(ret, val.target_shape);
ret = dmlc::HashCombine(ret, val.keep_highest);
ret = dmlc::HashCombine(ret, val.shape);
ret = dmlc::HashCombine(ret, val.reverse);
return ret;
}
};
template<>
struct hash<mxnet::op::ExpandDimParam> {
size_t operator()(const mxnet::op::ExpandDimParam& val) {
size_t ret = 0;
ret = dmlc::HashCombine(ret, val.axis);
return ret;
}
};
} // namespace std
#endif // MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_
|
SparseProduct.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
/// #include "InputOutput.h"
#include "ScalarVectors.h"
#include "hb_io.h"
#include "SparseProduct.h"
/*********************************************************************************/
// This routine creates a sparseMatrix from the next parameters
// * numR defines the number of rows
// * numC defines the number of columns
// * numE defines the number of nonzero elements
// * msr indicates if the MSR is the format used to the sparse matrix
// If msr is actived, numE doesn't include the diagonal elements
// The parameter index indicates if 0-indexing or 1-indexing is used.
void CreateSparseMatrix (ptr_SparseMatrix p_spr, int index, int numR, int numC, int numE, int msr) {
// printf (" index = %d , numR = %d , numC = %d , numE = %d\n", index, numR, numC, numE);
// The scalar components of the structure are initiated
p_spr->dim1 = numR; p_spr->dim2 = numC;
// Only one malloc is made for the vectors of indices
CreateInts (&(p_spr->vptr), numE+numR+1);
// The first component of the vectors depends on the used format
*(p_spr->vptr) = ((msr)? (numR+1): 0) + index;
p_spr->vpos = p_spr->vptr + ((msr)? 0: (numR+1));
// The number of nonzero elements depends on the format used
CreateDoubles (&(p_spr->vval), numE+(numR+1)*msr);
}
// This routine liberates the memory related to matrix spr
void RemoveSparseMatrix (ptr_SparseMatrix spr) {
// First the scalar are initiated
spr->dim1 = -1; spr->dim2 = -1;
// The vectors are liberated
RemoveInts (&(spr->vptr)); RemoveDoubles (&(spr->vval));
}
/*********************************************************************************/
// This routine creates de sparse matrix dst from the symmetric matrix spr.
// The parameters indexS and indexD indicate, respectivaly, if 0-indexing or 1-indexing is used
// to store the sparse matrices.
void DesymmetrizeSparseMatrices (SparseMatrix src, int indexS, ptr_SparseMatrix dst, int indexD) {
int n = src.dim1, nnz = 0;
int *sizes = NULL;
int *pp1 = NULL, *pp2 = NULL, *pp3 = NULL, *pp4 = NULL, *pp5 = NULL;
int i, j, dim, indexDS = indexD - indexS;
double *pd3 = NULL, *pd4 = NULL;
// The vector sizes is created and initiated
CreateInts (&sizes, n); InitInts (sizes, n, 0, 0);
// This loop counts the number of elements in each row
pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS;
pp2 = pp1 + 1 ; pp4 = sizes - indexS;
for (i=indexS; i<(n+indexS); i++) {
// The size of the corresponding row is accumulated
dim = (*pp2 - *pp1); pp4[i] += dim;
// Now each component of the row is analyzed
for (j=0; j<dim; j++) {
// The nondiagonals elements define another element in the graph
if (*pp3 != i) pp4[*pp3]++;
pp3++;
}
pp1 = pp2++;
}
// Compute the number of nonzeros of the new sparse matrix
nnz = AddInts (sizes, n);
// Create the new sparse matrix
CreateSparseMatrix (dst, indexD, n, n, nnz, 0);
// Fill the vector of pointers
CopyInts (sizes, (dst->vptr) + 1, n);
dst->vptr[0] = indexD; TransformLengthtoHeader (dst->vptr, n);
// The vector sizes is initiated with the beginning of each row
CopyInts (dst->vptr, sizes, n);
// This loop fills the contents of vector vpos
pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS;
pp2 = pp1 + 1 ; pp4 = dst->vpos - indexD; pp5 = sizes - indexS;
pd3 = src.vval + *pp1 - indexS; pd4 = dst->vval - indexD;
for (i=indexS; i<(n+indexS); i++) {
dim = (*pp2 - *pp1);
for (j=0; j<dim; j++) {
// The elements in the i-th row
pp4[pp5[i] ] = *pp3+indexDS;
pd4[pp5[i]++] = *pd3;
if (*pp3 != i) {
// The nondiagonals elements define another element in the graph
pp4[pp5[*pp3] ] = i+indexDS;
pd4[pp5[*pp3]++] = *pd3;
}
pp3++; pd3++;
}
pp1 = pp2++;
}
// The memory related to the vector sizes is liberated
RemoveInts (&sizes);
}
/*********************************************************************************/
// This routine creates de sparse matrix dst from the matrix spr.
// The parameters indexS and indexD indicate, respectivaly, if 0-indexing or 1-indexing is used
// to store the sparse matrices.
void TransposeSparseMatrices (SparseMatrix src, int indexS, ptr_SparseMatrix dst, int indexD) {
int n = src.dim1, nnz = 0;
int *sizes = NULL;
int *pp1 = NULL, *pp2 = NULL, *pp3 = NULL, *pp4 = NULL, *pp5 = NULL;
int i, j, dim, indexDS = indexD - indexS;
double *pd3 = NULL, *pd4 = NULL;
// The vector sizes is created and initiated
CreateInts (&sizes, n); InitInts (sizes, n, 0, 0);
// This loop counts the number of elements in each row
pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS;
pp2 = pp1 + 1 ; pp4 = sizes - indexS;
for (i=indexS; i<(n+indexS); i++) {
// The size of the corresponding row is accumulated
dim = (*pp2 - *pp1);
// Now each component of the row is analyzed
for (j=0; j<dim; j++) {
pp4[*pp3]++;
pp3++;
}
pp1 = pp2++;
}
// Compute the number of nonzeros of the new sparse matrix
nnz = AddInts (sizes, n);
// Create the new sparse matrix
CreateSparseMatrix (dst, indexD, n, n, nnz, 0);
// Fill the vector of pointers
CopyInts (sizes, (dst->vptr) + 1, n);
dst->vptr[0] = indexD; TransformLengthtoHeader (dst->vptr, n);
// The vector sizes is initiated with the beginning of each row
CopyInts (dst->vptr, sizes, n);
// This loop fills the contents of vector vpos
pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS;
pp2 = pp1 + 1 ; pp4 = dst->vpos - indexD; pp5 = sizes - indexS;
pd3 = src.vval + *pp1 - indexS; pd4 = dst->vval - indexD;
for (i=indexS; i<(n+indexS); i++) {
dim = (*pp2 - *pp1);
for (j=0; j<dim; j++) {
// The elements in the i-th column
pp4[pp5[*pp3] ] = i+indexDS;
pd4[pp5[*pp3]++] = *pd3;
pp3++; pd3++;
}
pp1 = pp2++;
}
// The memory related to the vector sizes is liberated
RemoveInts (&sizes);
}
/*********************************************************************************/
int ReadMatrixHB (char *filename, ptr_SparseMatrix p_spr) {
int *colptr = NULL;
double *exact = NULL;
double *guess = NULL;
int indcrd;
char *indfmt = NULL;
FILE *input;
char *key = NULL;
char *mxtype = NULL;
int ncol;
int neltvl;
int nnzero;
int nrhs;
int nrhsix;
int nrow;
int ptrcrd;
char *ptrfmt = NULL;
int rhscrd;
char *rhsfmt = NULL;
int *rhsind = NULL;
int *rhsptr = NULL;
char *rhstyp = NULL;
double *rhsval = NULL;
double *rhsvec = NULL;
int *rowind = NULL;
char *title = NULL;
int totcrd;
int valcrd;
char *valfmt = NULL;
double *values = NULL;
printf ("\nTEST09\n");
printf (" HB_FILE_READ reads all the data in an HB file.\n");
printf (" HB_FILE_MODULE is the module that stores the data.\n");
input = fopen (filename, "r");
if ( !input ) {
printf ("\n TEST09 - Warning!\n Error opening the file %s .\n", filename);
return -1;
}
hb_file_read ( input, &title, &key, &totcrd, &ptrcrd, &indcrd,
&valcrd, &rhscrd, &mxtype, &nrow, &ncol, &nnzero, &neltvl,
&ptrfmt, &indfmt, &valfmt, &rhsfmt, &rhstyp, &nrhs, &nrhsix,
&colptr, &rowind, &values, &rhsval, &rhsptr, &rhsind, &rhsvec,
&guess, &exact );
fclose (input);
// Conversion Fortran to C
CopyShiftInts (colptr, colptr, nrow+1, -1);
CopyShiftInts (rowind, rowind, nnzero, -1);
// Data assignment
p_spr->dim1 = nrow ; p_spr->dim2 = ncol ;
p_spr->vptr = colptr; p_spr->vpos = rowind; p_spr->vval = values;
// Memory liberation
free (exact ); free (guess ); free (indfmt);
free (key ); free (mxtype); free (ptrfmt);
free (rhsfmt); free (rhsind); free (rhsptr);
free (rhstyp); free (rhsval); free (rhsvec);
free (title ); free (valfmt);
return 0;
}
/*********************************************************************************/
// This routine computes the product { res += spr * vec }.
// The parameter index indicates if 0-indexing or 1-indexing is used,
void ProdSparseMatrixVector2 (SparseMatrix spr, int index, double *vec, double *res) {
int i, j;
int *pp1 = spr.vptr, *pp2 = pp1+1, *pi1 = spr.vpos + *pp1 - index;
double aux, *pvec = vec - index, *pd2 = res;
double *pd1 = spr.vval + *pp1 - index;
// If the MSR format is used, first the diagonal has to be processed
if (spr.vptr == spr.vpos)
VvecDoubles (1.0, spr.vval, vec, 1.0, res, spr.dim1);
for (i=0; i<spr.dim1; i++) {
// The dot product between the row i and the vector vec is computed
aux = 0.0;
for (j=*pp1; j<*pp2; j++)
aux += *(pd1++) * pvec[*(pi1++)];
// for (j=spr.vptr[i]; j<spr.vptr[i+1]; j++)
// aux += spr.vval[j] * pvec[spr.vpos[j]];
// Accumulate the obtained value on the result
*(pd2++) += aux; pp1 = pp2++;
}
}
// This routine computes the product { res += spr * vec }.
// The parameter index indicates if 0-indexing or 1-indexing is used,
void ProdSparseMatrixVectorByRows (SparseMatrix spr, int index, double *vec, double *res) {
int i, j, dim = spr.dim1;
int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index;
double aux, *pvec = vec + *pp1 - index;
double *pd1 = spr.vval + *pp1 - index;
// Process all the rows of the matrix
for (i=0; i<dim; i++) {
// The dot product between the row i and the vector vec is computed
aux = 0.0;
for (j=pp1[i]; j<pp1[i+1]; j++)
aux = fma(pd1[j], pvec[pi1[j]], aux);
// Accumulate the obtained value on the result
res[i] += aux;
}
}
// This routine computes the product { res += spr * vec }.
// The parameter index indicates if 0-indexing or 1-indexing is used,
void ProdSparseMatrixVectorByRows_OMP (SparseMatrix spr, int index, double *vec, double *res) {
int i, j, dim = spr.dim1;
int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index;
double aux, *pvec = vec + *pp1 - index;
double *pd1 = spr.vval + *pp1 - index;
// Process all the rows of the matrix
#pragma omp parallel for private(j, aux)
for (i=0; i<dim; i++) {
// The dot product between the row i and the vector vec is computed
aux = 0.0;
for (j=pp1[i]; j<pp1[i+1]; j++)
aux += pd1[j] * pvec[pi1[j]];
// Accumulate the obtained value on the result
res[i] += aux;
}
}
/*void ProdSparseMatrixVectorByRows_OMPTasks (SparseMatrix spr, int index, double *vec, double *res, int bm) {
int i, dim = spr.dim1;
// Process all the rows of the matrix
//#pragma omp taskloop grainsize(bm)
for ( i=0; i<dim; i+=bm) {
int cs = dim - i;
int c = cs < bm ? cs : bm;
// for (i=0; i<dim; i++) {
#pragma omp task depend(inout:res[i:i+c-1]) //shared(c)
{
// printf("Task SPMV ---- i: %d, c: %d \n", i, c);
int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index;
double aux, *pvec = vec + *pp1 - index;
double *pd1 = spr.vval + *pp1 - index;
// The dot product between the row i and the vector vec is computed
aux = 0.0;
for(int idx=i; idx < i+c; idx++){
// printf("Task SPMV ---- idx: %d\n", idx);
for (int j=pp1[idx]; j<pp1[idx+1]; j++)
aux += pd1[j] * pvec[pi1[j]];
// Accumulate the obtained value on the result
res[idx] += aux;
}
}
}
}
*/
void ProdSparseMatrixVectorByRows_OMPTasks (SparseMatrix spr, int index, double *vec, double *res, int bm) {
int i, j, idx, dim = spr.dim1;
int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index;
double aux, *pvec = vec + *pp1 - index;
double *pd1 = spr.vval + *pp1 - index;
// Process all the rows of the matrix
#pragma omp taskloop grainsize(bm)
for ( i=0; i<dim; i++ ) {
// The dot product between the row i and the vector vec is computed
aux = 0.0;
for (j=pp1[i]; j<pp1[i+1]; j++)
aux += pd1[j] * pvec[pi1[j]];
// Accumulate the obtained value on the result
res[i] += aux;
}
}
/*********************************************************************************/
// This routine computes the product { res += spr * vec }.
// The parameter index indicates if 0-indexing or 1-indexing is used,
void ProdSparseMatrixVectorByCols (SparseMatrix spr, int index, double *vec, double *res) {
int i, j, dim = spr.dim1;
int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index;
double aux, *pres = res + *pp1 - index;
double *pd1 = spr.vval + *pp1 - index;
// Process all the columns of the matrix
for (i=0; i<dim; i++) {
// The result is scaled by the column i and the scalar vec[i]
aux = vec[i];
for (j=pp1[i]; j<pp1[i+1]; j++)
pres[pi1[j]] += pd1[j] * aux;
}
}
// This routine computes the product { res += spr * vec }.
// The parameter index indicates if 0-indexing or 1-indexing is used,
void ProdSparseMatrixVectorByCols_OMP (SparseMatrix spr, int index, double *vec, double *res) {
int i, j, dim = spr.dim1;
int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index;
double aux, *pres = res + *pp1 - index;
double *pd1 = spr.vval + *pp1 - index;
// Process all the columns of the matrix
#pragma omp parallel for private(j, aux)
for (i=0; i<dim; i++) {
// The result is scaled by the column i and the scalar vec[i]
for (j=pp1[i]; j<pp1[i+1]; j++) {
aux = vec[i] * pd1[j];
#pragma omp atomic
pres[pi1[j]] += aux;
}
}
}
/*********************************************************************************/
void GetDiagonalSparseMatrix2 (SparseMatrix spr, int shft, double *diag, int *posd) {
int i, j, dim = (spr.dim1 < spr.dim2) ? spr.dim1 : spr.dim2;
int *pp1 = NULL, *pp2 = NULL, *pi1 = NULL, *pi2 = posd;
double *pd1 = NULL, *pd2 = diag;
if (spr.vptr == spr.vpos)
CopyDoubles (spr.vval, diag, spr.dim1);
else {
pp1 = spr.vptr; pp2 = pp1+1; j = (*pp2-*pp1);
pi1 = spr.vpos+*pp1; pd1 = spr.vval+*pp1;
for (i=0; i<dim; i++) {
while ((j > 0) && (*pi1 < (i+shft))) {
pi1++; pd1++; j--;
}
*(pd2++) = ((j > 0) && (*pi1 == (i+shft))) ? *pd1: 0.0;
//*(pi2++) = ((j > 0) && (*pi1 == (i+shft))) ? *pp2-j: -1;
pi1 += j; pd1 += j; pp1 = (pp2++); j = (*pp2-*pp1);
}
}
}
/*********************************************************************************/
|
ten_tusscher_2004_epi_S2_15.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S2_15.h"
GET_CELL_MODEL_DATA(init_cell_model_data) {
assert(cell_model);
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
//TODO: this should be called only once for the whole mesh, like in the GPU code
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) {
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.4855897827032,0.00131304048220611,0.777673256476332,0.777530419758781,0.000176915007944578,0.484229873407731,0.00295766051225702,0.999998320538839,1.96031195718503e-08,1.91202485653593e-05,0.999769095072611,1.00710495848039,0.999995509954569,4.49502542744173e-05,0.671374359732192,10.7525810292738,138.733913720923};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) {
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++) {
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = i;
for (int j = 0; j < num_steps; ++j) {
solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu(real dt, real *sv, real stim_current) {
assert(sv);
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) {
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
///#ifdef EPI
real Gks=0.245;
///#endif
///#ifdef ENDO
/// real Gks=0.245;
///#endif
///#ifdef MCELL
/// real Gks=0.062;
///#endif
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
//#ifdef EPI
real Gto=0.294;
//#endif
// #ifdef ENDO
// real Gto=0.073;
//#endif
//#ifdef MCELL
// real Gto=0.294;
///#endif
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={14.7328911543692,0.000268220573270157,0.000159694102989303,4.95038560493972e-05,0.281222894359262,0.155491530964224,0.222154844407151,4.08947089393252,0.0209965622527636,1.02972284723443,1096.92640050885,0.000622419783707689,0.0929425682382634,0.0199277276192553,0.00362501998690467,4.31336229850729e-05};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
///Ileak=0.00008f*(CaSR-Cai);
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
#ifdef EPI
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
#ifdef ENDO
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+28)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.;
#endif
#ifdef MCELL
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10));
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
trsm_x_coo_n_lo_row.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include "alphasparse/opt.h"
#include <memory.h>
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_COO *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_Number diag[m];
memset(diag, '\0', m * 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 = 0; r < A->nnz; r++)
{
if(A->row_indx[r] == A->col_indx[r])
{
diag[A->row_indx[r]] = A->values[r];
}
}
#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 < m; r++)
{
ALPHA_Number temp;
alpha_setzero(temp);
for (ALPHA_INT cr = 0; cr < A->nnz; cr++)
{
int row = A->row_indx[cr];
int col = A->col_indx[cr];
if(row == r && col < r)
alpha_madde(temp, A->values[cr], y[col * ldy + out_y_col]);
}
ALPHA_Number t;
alpha_mul(t, alpha, x[r * ldx + out_y_col]);
alpha_sub(t, t, temp);
alpha_div(y[r * ldy + out_y_col], t, diag[r]);
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
GB_unop__identity_fc64_uint32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_fc64_uint32
// op(A') function: GB_unop_tran__identity_fc64_uint32
// C type: GxB_FC64_t
// A type: uint32_t
// cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
GxB_FC64_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) \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FC64 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_fc64_uint32
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const 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++)
{
uint32_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_fc64_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_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
pubkeylp.h | /**
* @file pubkeylp.h -- Public key type for lattice crypto operations.
* @author TPOC: palisade@njit.edu
*
* @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef LBCRYPTO_CRYPTO_PUBKEYLP_H
#define LBCRYPTO_CRYPTO_PUBKEYLP_H
//Includes Section
#include <vector>
#include "lattice/elemparams.h"
#include "lattice/ilparams.h"
#include "lattice/ildcrtparams.h"
#include "lattice/ilelement.h"
#include "utils/inttypes.h"
#include "math/distrgen.h"
#include "utils/serializablehelper.h"
#include "encoding/encodingparams.h"
/**
* @namespace lbcrypto
* The namespace of lbcrypto
*/
namespace lbcrypto {
//forward declarations, used to resolve circular header dependencies
template<typename Element>
class Ciphertext;
template<typename Element>
class RationalCiphertext;
template<typename Element>
class LPCryptoParameters;
template<typename Element>
class LPCryptoParametersLTV;
template<typename Element>
class LPCryptoParametersBV;
template<typename Element>
class LPCryptoParametersFV;
template<typename Element>
class LPCryptoParametersStehleSteinfeld;
template<typename Element>
class LPCryptoParametersSHIELD;
template<typename Element>
class CryptoObject;
struct EncryptResult {
explicit EncryptResult() : isValid(false), numBytesEncrypted(0) {}
explicit EncryptResult(size_t len) : isValid(true), numBytesEncrypted(len) {}
bool isValid; /**< whether the encryption was successful */
usint numBytesEncrypted; /**< count of the number of plaintext bytes that were encrypted */
};
/**
* @brief Decryption result. This represents whether the decryption of a cipheretext was performed correctly.
*
* This is intended to eventually incorporate information about the amount of padding in a decoded ciphertext,
* to ensure that the correct amount of padding is stripped away.
* It is intended to provided a very simple kind of checksum eventually.
* This notion of a decoding output is inherited from the crypto++ library.
* It is also intended to be used in a recover and restart robust functionality if not all ciphertext is recieved over a lossy channel, so that if all information is eventually recieved, decoding/decryption can be performed eventually.
* This is intended to be returned with the output of a decryption operation.
*/
struct DecryptResult {
/**
* Constructor that initializes all message lengths to 0.
*/
explicit DecryptResult() : isValid(false), messageLength(0) {}
/**
* Constructor that initializes all message lengths.
* @param len the new length.
*/
explicit DecryptResult(size_t len) : isValid(true), messageLength(len) {}
bool isValid; /**< whether the decryption was successful */
usint messageLength; /**< the length of the decrypted plaintext message */
};
/**
* @brief Abstract interface class for LP Keys
*
* @tparam Element a ring element.
*/
template <class Element>
class LPKey : public CryptoObject<Element>, public Serializable {
public:
LPKey(CryptoContext<Element>* cc) : CryptoObject<Element>(cc) {}
LPKey(shared_ptr<CryptoContext<Element>> cc) : CryptoObject<Element>(cc.get()) {}
virtual ~LPKey() {}
};
/**
* @brief Concrete class for LP public keys
* @tparam Element a ring element.
*/
template <typename Element>
class LPPublicKey : public LPKey<Element> {
public:
/**
* Basic constructor for setting crypto params
*
* @param &cryptoParams is the reference to cryptoParams
*/
LPPublicKey(CryptoContext<Element>* cc) : LPKey<Element>(cc) {}
/**
* Copy constructor
*
*@param &rhs LPPublicKey to copy from
*/
explicit LPPublicKey(const LPPublicKey<Element> &rhs) : LPKey<Element>(rhs.GetCryptoContext()) {
m_h = rhs.m_h;
}
/**
* Move constructor
*
*@param &rhs LPPublicKey to move from
*/
explicit LPPublicKey(LPPublicKey<Element> &&rhs) : LPKey<Element>(rhs.GetCryptoContext()) {
m_h = std::move(rhs.m_h);
}
/**
* Assignment Operator.
*
* @param &rhs LPPublicKey to copy from
*/
const LPPublicKey<Element>& operator=(const LPPublicKey<Element> &rhs) {
this->context = rhs.context;
this->m_h = rhs.m_h;
return *this;
}
/**
* Move Assignment Operator.
*
* @param &rhs LPPublicKey to copy from
*/
const LPPublicKey<Element>& operator=(LPPublicKey<Element> &&rhs) {
this->context = rhs.context;
rhs.context = 0;
m_h = std::move(rhs.m_h);
return *this;
}
//@Get Properties
/**
* Gets the computed public key
* @return the public key element.
*/
const std::vector<Element> &GetPublicElements() const {
return this->m_h;
}
//@Set Properties
/**
* Sets the public key vector of Element.
* @param &element is the public key Element vector to be copied.
*/
void SetPublicElements(const std::vector<Element> &element) {
m_h = element;
}
/**
* Sets the public key vector of Element.
* @param &&element is the public key Element vector to be moved.
*/
void SetPublicElements(std::vector<Element> &&element) {
m_h = std::move(element);
}
/**
* Sets the public key Element at index idx.
* @param &element is the public key Element to be copied.
*/
void SetPublicElementAtIndex(usint idx, const Element &element) {
m_h.insert(m_h.begin() + idx, element);
}
/**
* Sets the public key Element at index idx.
* @param &&element is the public key Element to be moved.
*/
void SetPublicElementAtIndex(usint idx, Element &&element) {
m_h.insert(m_h.begin() + idx, std::move(element));
}
/**
* Serialize the object into a Serialized
* @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject());
* @param fileFlag is an object-specific parameter for the serialization
* @return true if successfully serialized
*/
bool Serialize(Serialized *serObj) const;
/**
* Populate the object from the deserialization of the Serialized
* @param &serObj contains the serialized object
* @return true on success
*/
bool Deserialize(const Serialized &serObj);
bool operator==(const LPPublicKey& other) const {
if( *this->GetCryptoParameters() != *other.GetCryptoParameters() )
return false;
if( m_h.size() != other.m_h.size() )
return false;
for( size_t i = 0; i < m_h.size(); i++ )
if( m_h[i] != other.m_h[i] )
return false;
return true;
}
bool operator!=(const LPPublicKey& other) const { return ! (*this == other); }
private:
std::vector<Element> m_h;
};
/**
* @brief Abstract interface for LP evaluation/proxy keys
* @tparam Element a ring element.
*/
template <class Element>
class LPEvalKey : public LPKey<Element> {
public:
/**
* Basic constructor for setting crypto params
*
* @param &cryptoParams is the reference to cryptoParams
*/
LPEvalKey(CryptoContext<Element>* cc) : LPKey<Element>(cc) {}
virtual ~LPEvalKey() {}
/**
* Setter function to store Relinearization Element Vector A.
* Throws exception, to be overridden by derived class.
*
* @param &a is the Element vector to be copied.
*/
virtual void SetAVector(const std::vector<Element> &a) {
throw std::runtime_error("SetAVector copy operation not supported");
}
/**
* Setter function to store Relinearization Element Vector A.
* Throws exception, to be overridden by derived class.
*
* @param &&a is the Element vector to be moved.
*/
virtual void SetAVector(std::vector<Element> &&a) {
throw std::runtime_error("SetAVector move operation not supported");
}
/**
* Getter function to access Relinearization Element Vector A.
* Throws exception, to be overridden by derived class.
*
* @return Element vector A.
*/
virtual const std::vector<Element> &GetAVector() const {
throw std::runtime_error("GetAVector operation not supported");
}
/**
* Setter function to store Relinearization Element Vector B.
* Throws exception, to be overridden by derived class.
*
* @param &b is the Element vector to be copied.
*/
virtual void SetBVector(const std::vector<Element> &b) {
throw std::runtime_error("SetBVector copy operation not supported");
}
/**
* Setter function to store Relinearization Element Vector B.
* Throws exception, to be overridden by derived class.
*
* @param &&b is the Element vector to be moved.
*/
virtual void SetBVector(std::vector<Element> &&b) {
throw std::runtime_error("SetBVector move operation not supported");
}
/**
* Getter function to access Relinearization Element Vector B.
* Throws exception, to be overridden by derived class.
*
* @return Element vector B.
*/
virtual const std::vector<Element> &GetBVector() const {
throw std::runtime_error("GetBVector operation not supported");
}
/**
* Setter function to store key switch Element.
* Throws exception, to be overridden by derived class.
*
* @param &a is the Element to be copied.
*/
virtual void SetA(const Element &a) {
throw std::runtime_error("SetA copy operation not supported");
}
/**
* Setter function to store key switch Element.
* Throws exception, to be overridden by derived class.
*
* @param &&a is the Element to be moved.
*/
virtual void SetA(Element &&a) {
throw std::runtime_error("SetA move operation not supported");
}
/**
* Getter function to access key switch Element.
* Throws exception, to be overridden by derived class.
*
* @return Element.
*/
virtual const Element &GetA() const {
throw std::runtime_error("GetA operation not supported");
}
friend bool operator==(const LPEvalKey& a, const LPEvalKey& b) {
return a.key_compare(b);
}
friend bool operator!=(const LPEvalKey& a, LPEvalKey& b) { return ! (a == b); }
virtual bool key_compare(const LPEvalKey& other) const = 0;
};
/**
* @brief Concrete class for Relinearization keys of RLWE scheme
* @tparam Element a ring element.
*/
template <class Element>
class LPEvalKeyRelin : public LPEvalKey<Element> {
public:
/**
* Basic constructor for setting crypto params
*
* @param &cryptoParams is the reference to cryptoParams
*/
LPEvalKeyRelin(CryptoContext<Element>* cc) : LPEvalKey<Element>(cc) {}
virtual ~LPEvalKeyRelin() {}
/**
* Copy constructor
*
*@param &rhs key to copy from
*/
explicit LPEvalKeyRelin(const LPEvalKeyRelin<Element> &rhs) : LPEvalKey<Element>(rhs.GetCryptoContext()) {
m_rKey = rhs.m_rKey;
}
/**
* Move constructor
*
*@param &rhs key to move from
*/
explicit LPEvalKeyRelin(LPEvalKeyRelin<Element> &&rhs) : LPEvalKey<Element>(rhs.GetCryptoContext()) {
m_rKey = std::move(rhs.m_rKey);
}
/**
* Assignment Operator.
*
* @param &rhs key to copy from
*/
const LPEvalKeyRelin<Element>& operator=(const LPEvalKeyRelin<Element> &rhs) {
this->context = rhs.context;
this->m_rKey = rhs.m_rKey;
return *this;
}
/**
* Move Assignment Operator.
*
* @param &rhs key to move from
*/
const LPEvalKeyRelin<Element>& operator=(LPEvalKeyRelin<Element> &&rhs) {
this->context = rhs.context;
rhs.context = 0;
m_rKey = std::move(rhs.m_rKey);
return *this;
}
/**
* Setter function to store Relinearization Element Vector A.
* Overrides base class implementation.
*
* @param &a is the Element vector to be copied.
*/
virtual void SetAVector(const std::vector<Element> &a) {
m_rKey.insert(m_rKey.begin() + 0, a);
}
/**
* Setter function to store Relinearization Element Vector A.
* Overrides base class implementation.
*
* @param &&a is the Element vector to be moved.
*/
virtual void SetAVector(std::vector<Element> &&a) {
m_rKey.insert(m_rKey.begin() + 0, std::move(a));
}
/**
* Getter function to access Relinearization Element Vector A.
* Overrides base class implementation.
*
* @return Element vector A.
*/
virtual const std::vector<Element> &GetAVector() const {
return m_rKey.at(0);
}
/**
* Setter function to store Relinearization Element Vector B.
* Overrides base class implementation.
*
* @param &b is the Element vector to be copied.
*/
virtual void SetBVector(const std::vector<Element> &b) {
m_rKey.insert(m_rKey.begin() + 1, b);
}
/**
* Setter function to store Relinearization Element Vector B.
* Overrides base class implementation.
*
* @param &&b is the Element vector to be moved.
*/
virtual void SetBVector(std::vector<Element> &&b) {
m_rKey.insert(m_rKey.begin() + 1, std::move(b));
}
/**
* Getter function to access Relinearization Element Vector B.
* Overrides base class implementation.
*
* @return Element vector B.
*/
virtual const std::vector<Element> &GetBVector() const {
return m_rKey.at(1);
}
/**
* Serialize the object into a Serialized
* @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject());
* @return true if successfully serialized
*/
bool Serialize(Serialized *serObj) const;
/**
* SerializeWithoutContext - serializes the object into a Serialized, withut the cryptocontext
* @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject());
* @return true if successfully serialized
*/
bool SerializeWithoutContext(Serialized *serObj) const;
/**
* Deserialize from the serialization
* @param serObj - contains the serialization
* @return true on success
*/
bool Deserialize(const Serialized &serObj);
bool key_compare(const LPEvalKey<Element>& other) const {
const LPEvalKeyRelin<Element> &oth = dynamic_cast<const LPEvalKeyRelin<Element> &>(other);
if( *this->GetCryptoParameters() != *oth.GetCryptoParameters() ) return false;
if( this->m_rKey.size() != oth.m_rKey.size() ) return false;
for( size_t i=0; i<this->m_rKey.size(); i++ ) {
if( this->m_rKey[i].size() != oth.m_rKey[i].size() ) return false;
for( size_t j=0; j<this->m_rKey[i].size(); j++ ) {
if( this->m_rKey[i][j] != oth.m_rKey[i][j] )
return false;
}
}
return true;
}
private:
//private member to store vector of vector of Element.
std::vector< std::vector<Element> > m_rKey;
};
/**
* @brief Evaluation Relinearization keys for NTRU scheme.
* @tparam Element a ring element.
*/
template <class Element>
class LPEvalKeyNTRURelin : public LPEvalKey<Element> {
public:
/**
* Basic constructor for setting crypto params
*
* @param &cryptoParams is the reference to cryptoParams
*/
LPEvalKeyNTRURelin(CryptoContext<Element>* cc) : LPEvalKey<Element>(cc) {}
virtual ~LPEvalKeyNTRURelin() {}
/**
* Copy constructor
*
*@param &rhs key to copy from
*/
explicit LPEvalKeyNTRURelin(const LPEvalKeyNTRURelin<Element> &rhs) : LPEvalKey<Element>(rhs.GetCryptoContext()) {
m_rKey = rhs.m_rKey;
}
/**
* Move constructor
*
*@param &rhs key to move from
*/
explicit LPEvalKeyNTRURelin(LPEvalKeyNTRURelin<Element> &&rhs) : LPEvalKey<Element>(rhs.GetCryptoContext()) {
m_rKey = std::move(rhs.m_rKey);
}
/**
* Assignment Operator.
*
* @param &rhs key to copy from
*/
const LPEvalKeyNTRURelin<Element>& operator=(const LPEvalKeyNTRURelin<Element> &rhs) {
this->context = rhs.context;
this->m_rKey = rhs.m_rKey;
return *this;
}
/**
* Move Assignment Operator.
*
* @param &rhs key to move from
*/
const LPEvalKeyNTRURelin<Element>& operator=(LPEvalKeyNTRURelin<Element> &&rhs) {
this->context = rhs.context;
rhs.context = 0;
m_rKey = std::move(rhs.m_rKey);
return *this;
}
/**
* Setter function to store Relinearization Element Vector A.
* Overrides base class implementation.
*
* @param &a is the Element vector to be copied.
*/
virtual void SetAVector(const std::vector<Element> &a) {
for (usint i = 0; i < a.size(); i++) {
m_rKey.insert(m_rKey.begin() + i, a.at(i));
}
}
/**
* Setter function to store Relinearization Element Vector A.
* Overrides base class implementation.
*
* @param &&a is the Element vector to be moved.
*/
virtual void SetAVector(std::vector<Element> &&a) {
m_rKey = std::move(a);
}
/**
* Getter function to access Relinearization Element Vector A.
* Overrides base class implementation.
*
* @return Element vector A.
*/
virtual const std::vector<Element> &GetAVector() const {
return m_rKey;
}
/**
* Serialize the object into a Serialized
* @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject());
* @return true if successfully serialized
*/
bool Serialize(Serialized *serObj) const;
/**
* SerializeWithoutContext - serializes the object into a Serialized, withut the cryptocontext
* @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject());
* @return true if successfully serialized
*/
bool SerializeWithoutContext(Serialized *serObj) const;
/**
* Deserialize from the serialization
* @param serObj - contains the serialization
* @return true on success
*/
bool Deserialize(const Serialized &serObj);
bool key_compare(const LPEvalKey<Element>& other) const {
const LPEvalKeyNTRURelin<Element> &oth = dynamic_cast<const LPEvalKeyNTRURelin<Element> &>(other);
if( *this->GetCryptoParameters() != *oth.GetCryptoParameters() ) return false;
if( this->m_rKey.size() != oth.m_rKey.size() ) return false;
for( size_t i=0; i<this->m_rKey.size(); i++ ) {
if( this->m_rKey[i] != oth.m_rKey[i] )
return false;
}
return true;
}
private:
//private member to store vector of Element.
std::vector<Element> m_rKey;
};
/**
* @brief Concrete class for facilitating NTRU key switch.
* @tparam Element a ring element.
*/
template <class Element>
class LPEvalKeyNTRU : public LPEvalKey<Element> {
public:
/**
* Basic constructor for setting crypto params
*
* @param &cryptoParams is the reference to cryptoParams
*/
LPEvalKeyNTRU(CryptoContext<Element>* cc) : LPEvalKey<Element>(cc) {}
virtual ~LPEvalKeyNTRU() {}
/**
* Copy constructor
*
*@param &rhs key to copy from
*/
explicit LPEvalKeyNTRU(const LPEvalKeyNTRU<Element> &rhs) : LPEvalKey<Element>(rhs.GetCryptoContext()) {
m_Key = rhs.m_Key;
}
/**
* Move constructor
*
*@param &rhs key to move from
*/
explicit LPEvalKeyNTRU(LPEvalKeyNTRU<Element> &&rhs) : LPEvalKey<Element>(rhs.GetCryptoContext()) {
m_Key = std::move(rhs.m_Key);
}
/**
* Assignment Operator.
*
* @param &rhs key to copy from
*/
const LPEvalKeyNTRU<Element>& operator=(const LPEvalKeyNTRU<Element> &rhs) {
this->context = rhs.context;
this->m_Key = rhs.m_Key;
return *this;
}
/**
* Move Assignment Operator.
*
* @param &rhs key to move from
*/
const LPEvalKeyNTRU<Element>& operator=(LPEvalKeyNTRU<Element> &&rhs) {
this->context = rhs.context;
rhs.context = 0;
m_Key = std::move(rhs.m_Key);
return *this;
}
/**
* Setter function to store NTRU key switch element.
* Function copies the key.
* Overrides the virtual function from base class LPEvalKey.
*
* @param &a is the key switch element to be copied.
*/
virtual void SetA(const Element &a) {
m_Key = a;
}
/**
* Setter function to store NTRU key switch Element.
* Function moves the key.
* Overrides the virtual function from base class LPEvalKey.
*
* @param &&a is the key switch Element to be moved.
*/
virtual void SetA(Element &&a) {
m_Key = std::move(a);
}
/**
* Getter function to access NTRU key switch Element.
* Overrides the virtual function from base class LPEvalKey.
*
* @return NTRU key switch Element.
*/
virtual const Element& GetA() const {
return m_Key;
}
/**
* Serialize the object into a Serialized
* @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject());
* @return true if successfully serialized
*/
bool Serialize(Serialized *serObj) const;
/**
* SerializeWithoutContext - serializes the object into a Serialized, withut the cryptocontext
* @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject());
* @return true if successfully serialized
*/
bool SerializeWithoutContext(Serialized *serObj) const;
/**
* Deserialize from the serialization
* @param serObj - contains the serialization
* @return true on success
*/
bool Deserialize(const Serialized &serObj);
bool key_compare(const LPEvalKey<Element>& other) const {
const LPEvalKeyNTRU<Element> &oth = dynamic_cast<const LPEvalKeyNTRU<Element> &>(other);
if( *this->GetCryptoParameters() != *oth.GetCryptoParameters() ) return false;
if( this->m_Key != oth.m_Key )
return false;
return true;
}
private:
/**
* private member Element to store key.
*/
Element m_Key;
};
/**
* @brief Private key implementation template for Ring-LWE, NTRU-based schemes,
* @tparam Element a ring element.
*/
template <class Element>
class LPPrivateKey : public LPKey<Element> {
public:
/**
* Construct in context
*/
LPPrivateKey(CryptoContext<Element>* cc) : LPKey<Element>(cc) {}
/**
* Construct in context
*/
LPPrivateKey(shared_ptr<CryptoContext<Element>> cc) : LPKey<Element>(cc) {}
/**
* Copy constructor
*@param &rhs the LPPrivateKey to copy from
*/
explicit LPPrivateKey(const LPPrivateKey<Element> &rhs) {
this->context = rhs.context;
this->m_sk = rhs.m_sk;
}
/**
* Move constructor
*@param &rhs the LPPrivateKey to move from
*/
explicit LPPrivateKey(LPPrivateKey<Element> &&rhs) {
this->context = rhs.context;
rhs.context = 0;
this->m_sk = std::move(rhs.m_sk);
}
/**
* Assignment Operator.
*
* @param &rhs LPPrivateKeyto assign from.
* @return the resulting LPPrivateKey
*/
const LPPrivateKey<Element>& operator=(const LPPrivateKey<Element> &rhs) {
this->context = rhs.context;
this->m_sk = rhs.m_sk;
return *this;
}
/**
* Move Assignment Operator.
*
* @param &rhs LPPrivateKey to assign from.
* @return the resulting LPPrivateKey
*/
const LPPrivateKey<Element>& operator=(LPPrivateKey<Element> &&rhs) {
this->context = rhs.context;
rhs.context = 0;
this->m_sk = std::move(rhs.m_sk);
return *this;
}
/**
* Implementation of the Get accessor for private element.
* @return the private element.
*/
const Element & GetPrivateElement() const { return m_sk; }
/**
* Set accessor for private element.
* @private &x private element to set to.
*/
void SetPrivateElement(const Element &x) { m_sk = x; }
/**
* Set accessor for private element.
* @private &x private element to set to.
*/
void SetPrivateElement(Element &&x) { m_sk = std::move(x); }
bool Serialize(Serialized *serObj) const {
serObj->SetObject();
if (!this->context->Serialize(serObj))
return false;
serObj->AddMember("Object", "PrivateKey", serObj->GetAllocator());
return this->GetPrivateElement().Serialize(serObj);
}
/**
* Populate the object from the deserialization of the Setialized
* @param &serObj contains the serialized object
* @return true on success
*/
bool Deserialize(const Serialized &serObj) {
Serialized::ConstMemberIterator mIt = serObj.FindMember("Object");
if( mIt == serObj.MemberEnd() || string(mIt->value.GetString()) != "PrivateKey" )
return false;
Element json_ilElement;
if (json_ilElement.Deserialize(serObj)) {
this->SetPrivateElement(json_ilElement);
return true;
}
return false;
}
bool operator==(const LPPrivateKey& other) const {
if( *this->GetCryptoParameters() != *other.GetCryptoParameters() )
return false;
return m_sk == other.m_sk;
}
bool operator!=(const LPPrivateKey& other) const { return ! (*this == other); }
private:
Element m_sk;
};
template <class Element>
class LPKeyPair {
public:
shared_ptr<LPPublicKey<Element>> publicKey;
shared_ptr<LPPrivateKey<Element>> secretKey;
LPKeyPair(LPPublicKey<Element>* a=0, LPPrivateKey<Element>* b=0) : publicKey(a), secretKey(b) {}
bool good() { return publicKey && secretKey; }
};
/**
* @brief Abstract interface for parameter generation algorithm
* @tparam Element a ring element.
*/
template <class Element>
class LPParameterGenerationAlgorithm {
public:
virtual ~LPParameterGenerationAlgorithm() {}
/**
* Method for computing all derived parameters based on chosen primitive parameters
*
* @param *cryptoParams the crypto parameters object to be populated with parameters.
* @param evalAddCount number of EvalAdds assuming no EvalMult and KeySwitch operations are performed.
* @param evalMultCount number of EvalMults assuming no EvalAdd and KeySwitch operations are performed.
* @param keySwitchCount number of KeySwitch operations assuming no EvalAdd and EvalMult operations are performed.
*/
virtual bool ParamsGen(shared_ptr<LPCryptoParameters<Element>> cryptoParams, int32_t evalAddCount = 0,
int32_t evalMultCount = 0, int32_t keySwitchCount = 0) const = 0;
};
/**
* @brief Abstract interface for encryption algorithm
* @tparam Element a ring element.
*/
template <class Element>
class LPEncryptionAlgorithm {
public:
virtual ~LPEncryptionAlgorithm() {}
/**
* Method for encrypting plaintex using LBC
*
* @param &publicKey public key used for encryption.
* @param &plaintext the plaintext input.
* @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false
* @param *ciphertext ciphertext which results from encryption.
*/
virtual shared_ptr<Ciphertext<Element>> Encrypt(const shared_ptr<LPPublicKey<Element>> publicKey, Poly &plaintext, bool doEncryption = true) const = 0;
/**
* Method for decrypting plaintext using LBC
*
* @param &privateKey private key used for decryption.
* @param &ciphertext ciphertext id decrypted.
* @param *plaintext the plaintext output.
* @return the decoding result.
*/
virtual DecryptResult Decrypt(const shared_ptr<LPPrivateKey<Element>> privateKey,
const shared_ptr<Ciphertext<Element>> ciphertext,
Poly *plaintext) const = 0;
/**
* Function to generate public and private keys
*
* @param &publicKey private key used for decryption.
* @param &privateKey private key used for decryption.
* @return function ran correctly.
*/
virtual LPKeyPair<Element> KeyGen(CryptoContext<Element>* cc, bool makeSparse=false) = 0;
};
/**
* @brief Abstract interface for Leveled SHE operations
* @tparam Element a ring element.
*/
template <class Element>
class LPLeveledSHEAlgorithm {
public:
virtual ~LPLeveledSHEAlgorithm() {}
/**
* Method for Modulus Reduction.
*
* @param &cipherText Ciphertext to perform mod reduce on.
*/
virtual shared_ptr<Ciphertext<Element>> ModReduce(shared_ptr<Ciphertext<Element>> cipherText) const = 0;
/**
* Method for Ring Reduction.
*
* @param &cipherText Ciphertext to perform ring reduce on.
* @param &privateKey Private key used to encrypt the first argument.
*/
virtual shared_ptr<Ciphertext<Element>> RingReduce(shared_ptr<Ciphertext<Element>> cipherText, const shared_ptr<LPEvalKey<Element>> keySwitchHint) const = 0;
/**
* Method for Composed EvalMult
*
* @param &cipherText1 ciphertext1, first input ciphertext to perform multiplication on.
* @param &cipherText2 cipherText2, second input ciphertext to perform multiplication on.
* @param &quadKeySwitchHint is for resultant quadratic secret key after multiplication to the secret key of the particular level.
* @param &cipherTextResult is the resulting ciphertext that can be decrypted with the secret key of the particular level.
*/
virtual shared_ptr<Ciphertext<Element>> ComposedEvalMult(
const shared_ptr<Ciphertext<Element>> cipherText1,
const shared_ptr<Ciphertext<Element>> cipherText2,
const shared_ptr<LPEvalKey<Element>> quadKeySwitchHint) const = 0;
/**
* Method for Level Reduction from sk -> sk1. This method peforms a keyswitch on the ciphertext and then performs a modulus reduction.
*
* @param &cipherText1 is the original ciphertext to be key switched and mod reduced.
* @param &linearKeySwitchHint is the linear key switch hint to perform the key switch operation.
* @param &cipherTextResult is the resulting ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> LevelReduce(const shared_ptr<Ciphertext<Element>> cipherText1,
const shared_ptr<LPEvalKey<Element>> linearKeySwitchHint) const = 0;
/**
* Function that determines if security requirements are met if ring dimension is reduced by half.
*
* @param ringDimension is the original ringDimension
* @param &moduli is the vector of moduli that is used
* @param rootHermiteFactor is the security threshold
*/
virtual bool CanRingReduce(usint ringDimension, const std::vector<BigInteger> &moduli, const double rootHermiteFactor) const = 0;
};
/**
* @brief Abstract interface class for LBC PRE algorithms
* @tparam Element a ring element.
*/
template <class Element>
class LPPREAlgorithm {
public:
virtual ~LPPREAlgorithm() {}
/**
* Virtual function to generate 1..log(q) encryptions for each bit of the original private key.
* Variant that uses the new secret key directly.
*
* @param &newKey new private key for the new ciphertext.
* @param &origPrivateKey original private key used for decryption.
* @param *evalKey the evaluation key.
* @return the re-encryption key.
*/
virtual shared_ptr<LPEvalKey<Element>> ReKeyGen(const shared_ptr<LPPrivateKey<Element>> newKey,
const shared_ptr<LPPrivateKey<Element>> origPrivateKey) const = 0;
/**
* Virtual function to generate 1..log(q) encryptions for each bit of the original private key
* Variant that uses the public key for the new secret key.
*
* @param &newKey public key for the new secret key.
* @param &origPrivateKey original private key used for decryption.
* @param *evalKey the evaluation key.
* @return the re-encryption key.
*/
virtual shared_ptr<LPEvalKey<Element>> ReKeyGen(const shared_ptr<LPPublicKey<Element>> newKey,
const shared_ptr<LPPrivateKey<Element>> origPrivateKey) const = 0;
/**
* Virtual function to define the interface for re-encypting ciphertext using the array generated by ProxyGen
*
* @param &evalKey proxy re-encryption key.
* @param &ciphertext the input ciphertext.
* @param *newCiphertext the new ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> ReEncrypt(const shared_ptr<LPEvalKey<Element>> evalKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const = 0;
};
/**
* @brief Abstract interface class for LBC Multiparty algorithms. A version of this multiparty scheme built on the BGV scheme is seen here:
* - Asharov G., Jain A., López-Alt A., Tromer E., Vaikuntanathan V., Wichs D. (2012) Multiparty Computation with Low Communication, Computation and Interaction via Threshold FHE. In: Pointcheval D., Johansson T. (eds) Advances in Cryptology – EUROCRYPT 2012. EUROCRYPT 2012. Lecture Notes in Computer Science, vol 7237. Springer, Berlin, Heidelberg
*
* During offline key generation, this multiparty scheme relies on the clients coordinating their public key generation. To do this, a single client generates a public-secret key pair.
* This public key is shared with other keys which use an element in the public key to generate their own public keys.
* The clients generate a shared key pair using a scheme-specific approach, then generate re-encryption keys. Re-encryption keys are uploaded to the server.
* Clients encrypt data with their public keys and send the encrypted data server.
* The data is re-encrypted. Computations are then run on the data.
* The result is sent to each of the clients.
* One client runs a "Leader" multiparty decryption operation with its own secret key. All other clients run a regular "Main" multiparty decryption with their own secret key.
* The resulting partially decrypted ciphertext are then fully decrypted with the decryption fusion algorithms.
*
* @tparam Element a ring element.
*/
template <class Element>
class LPMultipartyAlgorithm {
public:
virtual ~LPMultipartyAlgorithm() {}
/**
* Function to generate public and private keys for multiparty homomrophic encryption in coordination with a leading client that generated a first public key.
*
* @param cc cryptocontext for the keys to be generated.
* @param pk1 private key used for decryption to be fused.
* @param makeSparse set to true if ring reduce by a factor of 2 is to be used.
* @return key pair including the private and public key
*/
virtual LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element>* cc,
const shared_ptr<LPPublicKey<Element>> pk1,
bool makeSparse=false) = 0;
/**
* Function to generate public and private keys for multiparty homomrophic encryption server key pair in coordination with secret keys of clients.
*
* @param cc cryptocontext for the keys to be generated.
* @param secretkeys private keys used for decryption to be fused.
* @param makeSparse set to true if ring reduce by a factor of 2 is to be used.
* @return key pair including the private and public key
*/
virtual LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element>* cc,
const vector<shared_ptr<LPPrivateKey<Element>>>& secretKeys,
bool makeSparse=false) = 0;
/**
* Method for main decryption operation run by most decryption clients for multiparty homomorphic encryption
*
* @param privateKey private key used for decryption.
* @param ciphertext ciphertext id decrypted.
*/
virtual shared_ptr<Ciphertext<Element>> MultipartyDecryptMain(const shared_ptr<LPPrivateKey<Element>> privateKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const = 0;
/**
* Method for decryption operation run by the lead decryption client for multiparty homomorphic encryption
*
* @param privateKey private key used for decryption.
* @param ciphertext ciphertext id decrypted.
*/
virtual shared_ptr<Ciphertext<Element>> MultipartyDecryptLead(const shared_ptr<LPPrivateKey<Element>> privateKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const = 0;
/**
* Method for fusing the partially decrypted ciphertext.
*
* @param &ciphertextVec ciphertext id decrypted.
* @param *plaintext the plaintext output.
* @return the decoding result.
*/
virtual DecryptResult MultipartyDecryptFusion(const vector<shared_ptr<Ciphertext<Element>>>& ciphertextVec,
Poly *plaintext) const = 0;
};
/**
* @brief Abstract interface class for LBC SHE algorithms
* @tparam Element a ring element.
*/
template <class Element>
class LPSHEAlgorithm {
public:
virtual ~LPSHEAlgorithm() {}
/**
* Virtual function to define the interface for homomorphic addition of ciphertexts.
*
* @param &ciphertext1 the input ciphertext.
* @param &ciphertext2 the input ciphertext.
* @param *newCiphertext the new ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> EvalAdd(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2) const = 0;
/**
* Virtual function to define the interface for homomorphic subtraction of ciphertexts.
*
* @param &ciphertext1 the input ciphertext.
* @param &ciphertext2 the input ciphertext.
* @param *newCiphertext the new ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> EvalSub(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2) const = 0;
/**
* Virtual function to define the interface for multiplicative homomorphic evaluation of ciphertext.
*
* @param &ciphertext1 the input ciphertext.
* @param &ciphertext2 the input ciphertext.
* @param *newCiphertext the new ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> EvalMult(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2) const = 0;
/**
* Virtual function to define the interface for multiplication of ciphertext by plaintext.
*
* @param &ciphertext the input ciphertext.
* @param &plaintext the input plaintext embedded in the cryptocontext.
* @param *newCiphertext the new ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> EvalMultPlain(const shared_ptr<Ciphertext<Element>> ciphertext,
const shared_ptr<Ciphertext<Element>> plaintext) const = 0;
/**
* Virtual function to define the interface for multiplicative homomorphic evaluation of ciphertext using the evaluation key.
*
* @param &ciphertext1 first input ciphertext.
* @param &ciphertext2 second input ciphertext.
* @param &ek is the evaluation key to make the newCiphertext decryptable by the same secret key as that of ciphertext1 and ciphertext2.
* @param *newCiphertext the new resulting ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> EvalMult(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2, const shared_ptr<LPEvalKey<Element>> ek) const = 0;
/**
* EvalLinRegression - Computes the parameter vector for linear regression using the least squares method
* @param x - matrix of regressors
* @param y - vector of dependent variables
* @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method)
*/
shared_ptr<Matrix<RationalCiphertext<Element>>>
EvalLinRegression(const shared_ptr<Matrix<RationalCiphertext<Element>>> x,
const shared_ptr<Matrix<RationalCiphertext<Element>>> y) const
{
// multiplication is done in reverse order to minimize the number of inner products
Matrix<RationalCiphertext<Element>> xTransposed = x->Transpose();
shared_ptr<Matrix<RationalCiphertext<Element>>> result(new Matrix<RationalCiphertext<Element>>(xTransposed * (*y)));
Matrix<RationalCiphertext<Element>> xCovariance = xTransposed * (*x);
Matrix<RationalCiphertext<Element>> cofactorMatrix = xCovariance.CofactorMatrix();
Matrix<RationalCiphertext<Element>> adjugateMatrix = cofactorMatrix.Transpose();
*result = adjugateMatrix * (*result);
RationalCiphertext<Element> determinant;
xCovariance.Determinant(&determinant);
for (size_t row = 0; row < result->GetRows(); row++)
for (size_t col = 0; col < result->GetCols(); col++)
(*result)(row, col).SetDenominator(*determinant.GetNumerator());
return result;
}
/**
* Virtual function to define the interface for homomorphic negation of ciphertext.
*
* @param &ciphertext the input ciphertext.
* @param *newCiphertext the new ciphertext.
*/
virtual shared_ptr<Ciphertext<Element>> EvalNegate(const shared_ptr<Ciphertext<Element>> ciphertext) const = 0;
/**
* Function to add random noise to all plaintext slots except for the first one; used in EvalInnerProduct
*
* @param &ciphertext the input ciphertext.
* @return modified ciphertext
*/
shared_ptr<Ciphertext<Element>> AddRandomNoise(const shared_ptr<Ciphertext<Element>> ciphertext) const {
const shared_ptr<LPCryptoParameters<Element>> cryptoParams = ciphertext->GetCryptoParameters();
const shared_ptr<EncodingParams> encodingParams = cryptoParams->GetEncodingParams();
const shared_ptr<typename Element::Params> elementParams = cryptoParams->GetElementParams();
usint n = elementParams->GetRingDimension();
auto cc = ciphertext->GetCryptoContext();
DiscreteUniformGenerator dug;
dug.SetModulus(encodingParams->GetPlaintextModulus());
BigVector randomVector = dug.GenerateVector(n - 1);
std::vector<usint> randomIntVector(n);
//first plainext slot does not need to change
randomIntVector[0] = 0;
for (usint i = 0; i < n - 1; i++)
{
randomIntVector[i + 1] = randomVector.GetValAtIndex(i).ConvertToInt();
}
PackedIntPlaintextEncoding plaintext(randomIntVector);
Poly encodedPlaintext(elementParams);
plaintext.Encode(encodingParams->GetPlaintextModulus(), &encodedPlaintext);
shared_ptr<LPPublicKey<Element>> pk(new LPPublicKey<Element>(cc));
shared_ptr<Ciphertext<Element>> embeddedPlaintext = cc->GetEncryptionAlgorithm()->Encrypt(pk, encodedPlaintext, false);
return EvalAdd(ciphertext, embeddedPlaintext);
};
/**
* Method for KeySwitchGen
*
* @param &originalPrivateKey Original private key used for encryption.
* @param &newPrivateKey New private key to generate the keyswitch hint.
* @param *KeySwitchHint is where the resulting keySwitchHint will be placed.
*/
virtual shared_ptr<LPEvalKey<Element>> KeySwitchGen(
const shared_ptr<LPPrivateKey<Element>> originalPrivateKey,
const shared_ptr<LPPrivateKey<Element>> newPrivateKey) const = 0;
/**
* Method for KeySwitch
*
* @param &keySwitchHint Hint required to perform the ciphertext switching.
* @param &cipherText Original ciphertext to perform switching on.
*/
virtual shared_ptr<Ciphertext<Element>> KeySwitch(
const shared_ptr<LPEvalKey<Element>> keySwitchHint,
const shared_ptr<Ciphertext<Element>> cipherText) const = 0;
/**
* Method for KeySwitching based on RLWE relinearization (used only for the LTV scheme).
* Function to generate 1..log(q) encryptions for each bit of the original private key
*
* @param &newPublicKey encryption key for the new ciphertext.
* @param origPrivateKey original private key used for decryption.
*/
virtual shared_ptr<LPEvalKey<Element>> KeySwitchRelinGen(const shared_ptr<LPPublicKey<Element>> newPublicKey,
const shared_ptr<LPPrivateKey<Element>> origPrivateKey) const = 0;
/**
* Method for KeySwitching based on RLWE relinearization (used only for the LTV scheme).
*
* @param evalKey the evaluation key.
* @param ciphertext the input ciphertext.
* @return the resulting Ciphertext
*/
virtual shared_ptr<Ciphertext<Element>> KeySwitchRelin(const shared_ptr<LPEvalKey<Element>> evalKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const = 0;
/**
* Virtual function to define the interface for generating a evaluation key which is used after each multiplication.
*
* @param &ciphertext1 first input ciphertext.
* @param &ciphertext2 second input ciphertext.
* @param &ek is the evaluation key to make the newCiphertext decryptable by the same secret key as that of ciphertext1 and ciphertext2.
* @param *newCiphertext the new resulting ciphertext.
*/
virtual shared_ptr<LPEvalKey<Element>> EvalMultKeyGen(
const shared_ptr<LPPrivateKey<Element>> originalPrivateKey) const = 0;
/**
* Virtual function to generate all isomorphism keys for a given private key
*
* @param publicKey encryption key for the new ciphertext.
* @param origPrivateKey original private key used for decryption.
* @param indexList list of automorphism indices to be computed
* @return returns the evaluation keys
*/
virtual shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> EvalAutomorphismKeyGen(const shared_ptr<LPPublicKey<Element>> publicKey,
const shared_ptr<LPPrivateKey<Element>> origPrivateKey,
const std::vector<usint> &indexList) const = 0;
/**
* Virtual function for evaluating automorphism of ciphertext at index i
*
* @param ciphertext the input ciphertext.
* @param i automorphism index
* @param &evalKeys - reference to the vector of evaluation keys generated by EvalAutomorphismKeyGen.
* @return resulting ciphertext
*/
virtual shared_ptr<Ciphertext<Element>> EvalAutomorphism(const shared_ptr<Ciphertext<Element>> ciphertext, usint i,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalKeys) const = 0;
/**
* Virtual function to generate automophism keys for a given private key; Uses the private key for encryption
*
* @param privateKey private key.
* @param indexList list of automorphism indices to be computed
* @return returns the evaluation keys
*/
virtual shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> EvalAutomorphismKeyGen(const shared_ptr<LPPrivateKey<Element>> privateKey,
const std::vector<usint> &indexList) const = 0;
/**
* Virtual function to generate the automorphism keys for EvalSum; works only for packed encoding
*
* @param privateKey private key.
* @return returns the evaluation keys
*/
shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> EvalSumKeyGen(const shared_ptr<LPPrivateKey<Element>> privateKey,
const shared_ptr<LPPublicKey<Element>> publicKey) const
{
const shared_ptr<LPCryptoParameters<Element>> cryptoParams = privateKey->GetCryptoParameters();
const shared_ptr<EncodingParams> encodingParams = cryptoParams->GetEncodingParams();
const shared_ptr<typename Element::Params> elementParams = cryptoParams->GetElementParams();
usint batchSize = encodingParams->GetBatchSize();
usint g = encodingParams->GetPlaintextGenerator();
usint m = elementParams->GetCyclotomicOrder();
// stores automorphism indices needed for EvalSum
std::vector<usint> indices;
for (int i = 0; i < floor(log2(batchSize)); i++)
{
indices.push_back(g);
g = (g * g) % m;
}
if (publicKey)
// NTRU-based scheme
return EvalAutomorphismKeyGen(publicKey, privateKey, indices);
else
// Regular RLWE scheme
return EvalAutomorphismKeyGen(privateKey, indices);
}
/**
* Sums all elements in log (batch size) time - works only with packed encoding
*
* @param ciphertext the input ciphertext.
* @param batchSize size of the batch to be summed up
* @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen.
* @return resulting ciphertext
*/
shared_ptr<Ciphertext<Element>> EvalSum(const shared_ptr<Ciphertext<Element>> ciphertext, usint batchSize,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalKeys) const {
const shared_ptr<LPCryptoParameters<Element>> cryptoParams = ciphertext->GetCryptoParameters();
shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(*ciphertext));
const shared_ptr<EncodingParams> encodingParams = cryptoParams->GetEncodingParams();
const shared_ptr<typename Element::Params> elementParams = cryptoParams->GetElementParams();
usint g = encodingParams->GetPlaintextGenerator();
usint m = elementParams->GetCyclotomicOrder();
for (int i = 0; i < floor(log2(batchSize)); i++)
{
newCiphertext = EvalAdd(newCiphertext, EvalAutomorphism(newCiphertext, g, evalKeys));
g = (g * g) % m;
}
return newCiphertext;
}
/**
* Evaluates inner product in batched encoding
*
* @param ciphertext1 first vector.
* @param ciphertext2 second vector.
* @param batchSize size of the batch to be summed up
* @param &evalSumKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen.
* @param &evalMultKey - reference to the evaluation key generated by EvalMultKeyGen.
* @return resulting ciphertext
*/
shared_ptr<Ciphertext<Element>> EvalInnerProduct(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2, usint batchSize,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalSumKeys,
const shared_ptr<LPEvalKey<Element>> evalMultKey) const {
shared_ptr<Ciphertext<Element>> result = EvalMult(ciphertext1, ciphertext2, evalMultKey);
result = EvalSum(result, batchSize, evalSumKeys);
// add a random number to all slots except for the first one so that no information is leaked
return AddRandomNoise(result);
}
/**
* EvalLinRegressBatched - Computes the parameter vector for linear regression using the least squares method
* Currently supports only two regressors
* @param x - matrix of regressors
* @param y - vector of dependent variables
* @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method)
*/
shared_ptr<Matrix<RationalCiphertext<Element>>>
EvalLinRegressBatched(const shared_ptr<Matrix<RationalCiphertext<Element>>> x,
const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalSumKeys,
const shared_ptr<LPEvalKey<Element>> evalMultKey) const
{
Matrix<RationalCiphertext<Element>> covarianceMatrix(x->GetAllocator(), 2, 2);
shared_ptr<Ciphertext<Element>> x0 = (*x)(0, 0).GetNumerator();
shared_ptr<Ciphertext<Element>> x1 = (*x)(0, 1).GetNumerator();
shared_ptr<Ciphertext<Element>> y0 = (*y)(0, 0).GetNumerator();
//Compute the covariance matrix for X
covarianceMatrix(0, 0).SetNumerator(*EvalInnerProduct(x0, x0, batchSize, evalSumKeys, evalMultKey));
covarianceMatrix(0, 1).SetNumerator(*EvalInnerProduct(x0, x1, batchSize, evalSumKeys, evalMultKey));
covarianceMatrix(1, 0) = covarianceMatrix(0, 1);
covarianceMatrix(1, 1).SetNumerator(*EvalInnerProduct(x1, x1, batchSize, evalSumKeys, evalMultKey));
Matrix<RationalCiphertext<Element>> cofactorMatrix = covarianceMatrix.CofactorMatrix();
Matrix<RationalCiphertext<Element>> adjugateMatrix = cofactorMatrix.Transpose();
shared_ptr<Matrix<RationalCiphertext<Element>>> result(new Matrix<RationalCiphertext<Element>>(x->GetAllocator(), 2, 1));
(*result)(0, 0).SetNumerator(*EvalInnerProduct(x0, y0, batchSize, evalSumKeys, evalMultKey));
(*result)(1, 0).SetNumerator(*EvalInnerProduct(x1, y0, batchSize, evalSumKeys, evalMultKey));
*result = adjugateMatrix * (*result);
RationalCiphertext<Element> determinant;
covarianceMatrix.Determinant(&determinant);
for (size_t row = 0; row < result->GetRows(); row++)
for (size_t col = 0; col < result->GetCols(); col++)
(*result)(row, col).SetDenominator(*determinant.GetNumerator());
return result;
}
/**
* EvalCrossCorrelation - Computes the sliding sum of inner products (known as
* as cross-correlation, sliding inner product, or sliding dot product in
* image processing
* @param x - first vector of row vectors
* @param y - second vector of row vectors
* @param batchSize - batch size for packed encoding
* @param indexStart - starting index in the vectors of row vectors
* @param length - length of the slice in the vectors of row vectors
* @param evalSumKeys - evaluation keys used for the automorphism operation
* @param evalMultKey - the evaluation key used for multiplication
* @return sum(x_i*y_i), i.e., a sum of inner products
*/
shared_ptr<Ciphertext<Element>>
EvalCrossCorrelation(const shared_ptr<Matrix<RationalCiphertext<Element>>> x,
const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize,
usint indexStart, usint length,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalSumKeys,
const shared_ptr<LPEvalKey<Element>> evalMultKey) const
{
if (length == 0)
length = x->GetRows();
if (length - indexStart > x->GetRows())
throw std::runtime_error("The number of rows exceeds the dimension of the vector");
//additional error checking can be added here
shared_ptr<Ciphertext<Element>> result;
shared_ptr<Ciphertext<Element>> x0 = (*x)(indexStart, 0).GetNumerator();
shared_ptr<Ciphertext<Element>> y0 = (*y)(indexStart, 0).GetNumerator();
result = EvalInnerProduct(x0, y0, batchSize, evalSumKeys, evalMultKey);
#pragma omp parallel for ordered schedule(dynamic)
for (usint i = indexStart + 1; i < indexStart + length; i++)
{
shared_ptr<Ciphertext<Element>> xi = (*x)(i, 0).GetNumerator();
shared_ptr<Ciphertext<Element>> yi = (*y)(i, 0).GetNumerator();
auto product = EvalInnerProduct(xi, yi, batchSize, evalSumKeys, evalMultKey);
#pragma omp ordered
{
result = EvalAdd(result,product);
}
}
return result;
}
};
/**
* @brief Abstract interface class for LBC SHE algorithms
* @tparam Element a ring element.
*/
template <class Element>
class LPFHEAlgorithm {
public:
virtual ~LPFHEAlgorithm() {}
/**
* Virtual function to define the interface for bootstrapping evaluation of ciphertext
*
* @param &ciphertext the input ciphertext.
* @param *newCiphertext the new ciphertext.
*/
virtual void Bootstrap(const Ciphertext<Element> &ciphertext,
Ciphertext<Element> *newCiphertext) const = 0;
};
/**
* @brief main implementation class to capture essential cryptoparameters of any LBC system
* @tparam Element a ring element.
*/
template <typename Element>
class LPCryptoParameters : public Serializable
{
public:
virtual ~LPCryptoParameters() {}
/**
* Returns the value of plaintext modulus p
*
* @return the plaintext modulus.
*/
const typename Element::Integer &GetPlaintextModulus() const { return m_encodingParams->GetPlaintextModulus(); }
/**
* Returns the reference to IL params
*
* @return the ring element parameters.
*/
const shared_ptr<typename Element::Params> GetElementParams() const { return m_params; }
/**
* Returns the reference to encoding params
*
* @return the encoding parameters.
*/
const shared_ptr<EncodingParams> GetEncodingParams() const { return m_encodingParams; }
/**
* Sets the value of plaintext modulus p
*/
void SetPlaintextModulus(const typename Element::Integer &plaintextModulus) {
m_encodingParams->SetPlaintextModulus(plaintextModulus);
}
virtual bool operator==(const LPCryptoParameters<Element>& cmp) const = 0;
bool operator!=(const LPCryptoParameters<Element>& cmp) const { return !(*this == cmp); }
/**
* Sets the reference to element params
*/
void SetElementParams(shared_ptr<typename Element::Params> params) { m_params = params; }
/**
* Sets the reference to element params
*/
void SetEncodingParams(shared_ptr<EncodingParams> encodingParams) {
m_encodingParams = encodingParams;
}
/**
* Overload to allow printing of parameters to an iostream
* NOTE that the implementation relies on calling the virtual PrintParameters method
* @param out - the stream to print to
* @param item - reference to the item to print
* @return the stream
*/
friend std::ostream& operator<<(std::ostream& out, const LPCryptoParameters& item) {
item.PrintParameters(out);
return out;
}
virtual usint GetRelinWindow() const { return 0; }
virtual const typename Element::DggType &GetDiscreteGaussianGenerator() const {
throw std::logic_error("No DGG Available for this parameter set");
}
protected:
LPCryptoParameters() {
m_encodingParams = std::make_shared<EncodingParams>(2);
}
LPCryptoParameters(const typename Element::Integer &plaintextModulus) {
m_encodingParams = std::make_shared<EncodingParams>(plaintextModulus);
}
LPCryptoParameters(shared_ptr<typename Element::Params> params, const BigInteger &plaintextModulus) {
m_params = params;
m_encodingParams = std::make_shared<EncodingParams>(plaintextModulus);
}
LPCryptoParameters(shared_ptr<typename Element::Params> params, shared_ptr<EncodingParams> encodingParams) {
m_params = params;
m_encodingParams = encodingParams;
}
LPCryptoParameters(LPCryptoParameters<Element> *from, shared_ptr<typename Element::Params> newElemParms) {
*this = *from;
m_params = newElemParms;
}
virtual void PrintParameters(std::ostream& out) const {
out << "Element Parameters: " << *m_params << std::endl;
out << "Encoding Parameters: " << *m_encodingParams << std::endl;
}
private:
//element-specific parameters
shared_ptr<typename Element::Params> m_params;
//encoding-specific parameters
shared_ptr<EncodingParams> m_encodingParams;
};
/**
* @brief Abstract interface for public key encryption schemes
* @tparam Element a ring element.
*/
template <class Element>
class LPPublicKeyEncryptionScheme {
public:
LPPublicKeyEncryptionScheme() :
m_algorithmParamsGen(0), m_algorithmEncryption(0), m_algorithmPRE(0), m_algorithmMultiparty(0),
m_algorithmSHE(0), m_algorithmFHE(0), m_algorithmLeveledSHE(0) {}
virtual ~LPPublicKeyEncryptionScheme() {
if (this->m_algorithmParamsGen != NULL)
delete this->m_algorithmParamsGen;
if (this->m_algorithmEncryption != NULL)
delete this->m_algorithmEncryption;
if (this->m_algorithmPRE != NULL)
delete this->m_algorithmPRE;
if (this->m_algorithmMultiparty != NULL)
delete this->m_algorithmMultiparty;
if (this->m_algorithmSHE != NULL)
delete this->m_algorithmSHE;
if (this->m_algorithmFHE != NULL)
delete this->m_algorithmFHE;
if (this->m_algorithmLeveledSHE != NULL)
delete this->m_algorithmLeveledSHE;
}
/**
* Enable features with a bit mast of PKESchemeFeature codes
* @param mask
*/
void Enable(usint mask) {
if (mask&ENCRYPTION) Enable(ENCRYPTION);
if (mask&PRE) Enable(PRE);
if (mask&SHE) Enable(SHE);
if (mask&LEVELEDSHE) Enable(LEVELEDSHE);
if (mask&MULTIPARTY) Enable(MULTIPARTY);
if (mask&FHE) Enable(FHE);
}
usint GetEnabled() const {
usint flag = 0;
if (m_algorithmEncryption != NULL)
flag |= ENCRYPTION;
if (m_algorithmPRE != NULL)
flag |= PRE;
if (m_algorithmSHE != NULL)
flag |= SHE;
if (m_algorithmFHE != NULL)
flag |= FHE;
if (m_algorithmLeveledSHE != NULL)
flag |= LEVELEDSHE;
if (m_algorithmMultiparty != NULL)
flag |= MULTIPARTY;
return flag;
}
//instantiated in the scheme implementation class
virtual void Enable(PKESchemeFeature feature) = 0;
/////////////////////////////////////////
// wrapper for LPParameterSelectionAlgorithm
//
bool ParamsGen(shared_ptr<LPCryptoParameters<Element>> cryptoParams, int32_t evalAddCount = 0,
int32_t evalMultCount = 0, int32_t keySwitchCount = 0) const {
if (this->m_algorithmParamsGen) {
return this->m_algorithmParamsGen->ParamsGen(cryptoParams, evalAddCount, evalMultCount, keySwitchCount);
}
else {
throw std::logic_error("Parameter generation operation has not been implemented");
}
}
/////////////////////////////////////////
// the three functions below are wrappers for things in LPEncryptionAlgorithm (ENCRYPT)
//
shared_ptr<Ciphertext<Element>> Encrypt(const shared_ptr<LPPublicKey<Element>> publicKey,
Poly &plaintext, bool doEncryption = true) const {
if(this->m_algorithmEncryption) {
return this->m_algorithmEncryption->Encrypt(publicKey,plaintext,doEncryption);
}
else {
throw std::logic_error("Encrypt operation has not been enabled");
}
}
DecryptResult Decrypt(const shared_ptr<LPPrivateKey<Element>> privateKey, const shared_ptr<Ciphertext<Element>> ciphertext,
Poly *plaintext) const {
if(this->m_algorithmEncryption)
return this->m_algorithmEncryption->Decrypt(privateKey,ciphertext,plaintext);
else {
throw std::logic_error("Decrypt operation has not been enabled");
}
}
LPKeyPair<Element> KeyGen(CryptoContext<Element>* cc, bool makeSparse) {
if(this->m_algorithmEncryption)
return this->m_algorithmEncryption->KeyGen(cc, makeSparse);
else {
throw std::logic_error("KeyGen operation has not been enabled");
}
}
/////////////////////////////////////////
// the three functions below are wrappers for things in LPPREAlgorithm (PRE)
//
shared_ptr<LPEvalKey<Element>> ReKeyGen(const shared_ptr<LPPublicKey<Element>> newKey, const shared_ptr<LPPrivateKey<Element>> origPrivateKey) const{
if(this->m_algorithmPRE)
return this->m_algorithmPRE->ReKeyGen(newKey,origPrivateKey);
else {
throw std::logic_error("ReKeyGen operation has not been enabled");
}
}
shared_ptr<LPEvalKey<Element>> ReKeyGen(const shared_ptr<LPPrivateKey<Element>> newKey, const shared_ptr<LPPrivateKey<Element>> origPrivateKey) const {
if (this->m_algorithmPRE)
return this->m_algorithmPRE->ReKeyGen(newKey, origPrivateKey);
else {
throw std::logic_error("ReKeyGen operation has not been enabled");
}
}
//wrapper for ReEncrypt method
shared_ptr<Ciphertext<Element>> ReEncrypt(const shared_ptr<LPEvalKey<Element>> evalKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const {
if(this->m_algorithmPRE)
return this->m_algorithmPRE->ReEncrypt(evalKey,ciphertext);
else {
throw std::logic_error("ReEncrypt operation has not been enabled");
}
}
/////////////////////////////////////////
// the three functions below are wrappers for things in LPMultipartyAlgorithm (Multiparty)
//
// Wrapper for Multiparty Key Gen
LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element>* cc,
const shared_ptr<LPPublicKey<Element>> pk1,
bool makeSparse) {
if(this->m_algorithmMultiparty)
return this->m_algorithmMultiparty->MultipartyKeyGen(cc, pk1, makeSparse);
else {
throw std::logic_error("MultipartyKeyGen operation has not been enabled");
}
}
// Wrapper for Multiparty Key Gen
LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element>* cc,
const vector<shared_ptr<LPPrivateKey<Element>>>& secretKeys,
bool makeSparse) {
if(this->m_algorithmMultiparty)
return this->m_algorithmMultiparty->MultipartyKeyGen(cc, secretKeys, makeSparse);
else {
throw std::logic_error("MultipartyKeyGen operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> MultipartyDecryptMain(const shared_ptr<LPPrivateKey<Element>> privateKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const {
if(this->m_algorithmMultiparty)
return this->m_algorithmMultiparty->MultipartyDecryptMain(privateKey,ciphertext);
else {
throw std::logic_error("MultipartyDecryptMain operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> MultipartyDecryptLead(const shared_ptr<LPPrivateKey<Element>> privateKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const {
if(this->m_algorithmMultiparty)
return this->m_algorithmMultiparty->MultipartyDecryptLead(privateKey,ciphertext);
else {
throw std::logic_error("MultipartyDecryptLead operation has not been enabled");
}
}
DecryptResult MultipartyDecryptFusion(const vector<shared_ptr<Ciphertext<Element>>>& ciphertextVec,
Poly *plaintext) const {
if(this->m_algorithmMultiparty)
return this->m_algorithmMultiparty->MultipartyDecryptFusion(ciphertextVec,plaintext);
else {
throw std::logic_error("MultipartyDecrypt operation has not been enabled");
}
}
/////////////////////////////////////////
// the three functions below are wrappers for things in LPSHEAlgorithm (SHE)
//
shared_ptr<Ciphertext<Element>> AddRandomNoise(const shared_ptr<Ciphertext<Element>> ciphertext) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->AddRandomNoise(ciphertext);
else {
throw std::logic_error("EvalAdd operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> EvalAdd(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalAdd(ciphertext1, ciphertext2);
else {
throw std::logic_error("EvalAdd operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> EvalSub(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalSub(ciphertext1, ciphertext2);
else {
throw std::logic_error("EvalSub operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> EvalMult(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalMult(ciphertext1, ciphertext2);
else {
throw std::logic_error("EvalMult operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> EvalMultPlain(const shared_ptr<Ciphertext<Element>> ciphertext,
const shared_ptr<Ciphertext<Element>> plaintext) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalMultPlain(ciphertext, plaintext);
else {
throw std::logic_error("EvalMult operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> EvalMult(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2,
const shared_ptr<LPEvalKey<Element>> evalKey) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalMult(ciphertext1, ciphertext2, evalKey);
else {
throw std::logic_error("EvalMult operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> EvalNegate(const shared_ptr<Ciphertext<Element>> ciphertext) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalNegate(ciphertext);
else {
throw std::logic_error("EvalNegate operation has not been enabled");
}
}
shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> EvalAutomorphismKeyGen(const shared_ptr<LPPublicKey<Element>> publicKey,
const shared_ptr<LPPrivateKey<Element>> origPrivateKey,
const std::vector<usint> &indexList) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalAutomorphismKeyGen(publicKey,origPrivateKey,indexList);
else
throw std::logic_error("EvalAutomorphismKeyGen operation has not been enabled");
}
shared_ptr<Ciphertext<Element>> EvalAutomorphism(const shared_ptr<Ciphertext<Element>> ciphertext, usint i,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalKeys) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalAutomorphism(ciphertext, i, evalKeys);
else
throw std::logic_error("EvalAutomorphism operation has not been enabled");
}
shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> EvalAutomorphismKeyGen(const shared_ptr<LPPrivateKey<Element>> privateKey,
const std::vector<usint> &indexList) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalAutomorphismKeyGen(privateKey, indexList);
else
throw std::logic_error("EvalAutomorphismKeyGen operation has not been enabled");
}
shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> EvalSumKeyGen(
const shared_ptr<LPPrivateKey<Element>> privateKey,
const shared_ptr<LPPublicKey<Element>> publicKey) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalSumKeyGen(privateKey,publicKey);
else
throw std::logic_error("EvalSumKeyGen operation has not been enabled");
}
shared_ptr<Ciphertext<Element>> EvalSum(const shared_ptr<Ciphertext<Element>> ciphertext, usint batchSize,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalKeys) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalSum(ciphertext, batchSize, evalKeys);
else
throw std::logic_error("EvalSum operation has not been enabled");
}
shared_ptr<Ciphertext<Element>> EvalInnerProduct(const shared_ptr<Ciphertext<Element>> ciphertext1,
const shared_ptr<Ciphertext<Element>> ciphertext2, usint batchSize,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalSumKeys,
const shared_ptr<LPEvalKey<Element>> evalMultKey) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalInnerProduct(ciphertext1, ciphertext2, batchSize, evalSumKeys, evalMultKey);
else
throw std::logic_error("EvalInnerProduct operation has not been enabled");
}
shared_ptr<Matrix<RationalCiphertext<Element>>>
EvalLinRegressBatched(const shared_ptr<Matrix<RationalCiphertext<Element>>> x,
const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalSumKeys,
const shared_ptr<LPEvalKey<Element>> evalMultKey) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalLinRegressBatched(x, y, batchSize, evalSumKeys, evalMultKey);
else
throw std::logic_error("EvalLinRegressionBatched operation has not been enabled");
}
shared_ptr<Ciphertext<Element>>
EvalCrossCorrelation(const shared_ptr<Matrix<RationalCiphertext<Element>>> x,
const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize,
usint indexStart, usint length,
const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalSumKeys,
const shared_ptr<LPEvalKey<Element>> evalMultKey) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalCrossCorrelation(x, y, batchSize, indexStart, length, evalSumKeys, evalMultKey);
else
throw std::logic_error("EvalCrossCorrelation operation has not been enabled");
}
/**
* EvalLinRegression - Computes the parameter vector for linear regression using the least squares method
* @param x - matrix of regressors
* @param y - vector of dependent variables
* @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method)
*/
shared_ptr<Matrix<RationalCiphertext<Element>>>
EvalLinRegression(const shared_ptr<Matrix<RationalCiphertext<Element>>> x,
const shared_ptr<Matrix<RationalCiphertext<Element>>> y) const
{
if (this->m_algorithmSHE)
return this->m_algorithmSHE->EvalLinRegression(x, y);
else {
throw std::logic_error("EvalLinRegression operation has not been enabled");
}
}
shared_ptr<LPEvalKey<Element>> KeySwitchGen(
const shared_ptr<LPPrivateKey<Element>> originalPrivateKey,
const shared_ptr<LPPrivateKey<Element>> newPrivateKey) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->KeySwitchGen(originalPrivateKey, newPrivateKey);
else {
throw std::logic_error("KeySwitchGen operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> KeySwitch(
const shared_ptr<LPEvalKey<Element>> keySwitchHint,
const shared_ptr<Ciphertext<Element>> cipherText) const {
if (this->m_algorithmSHE) {
return this->m_algorithmSHE->KeySwitch(keySwitchHint, cipherText);
}
else {
throw std::logic_error("KeySwitch operation has not been enabled");
}
}
shared_ptr<LPEvalKey<Element>> KeySwitchRelinGen(const shared_ptr<LPPublicKey<Element>> newKey, const shared_ptr<LPPrivateKey<Element>> origPrivateKey) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->KeySwitchRelinGen(newKey, origPrivateKey);
else {
throw std::logic_error("KeySwitchRelinGen operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> KeySwitchRelin(const shared_ptr<LPEvalKey<Element>> evalKey,
const shared_ptr<Ciphertext<Element>> ciphertext) const {
if (this->m_algorithmSHE)
return this->m_algorithmSHE->KeySwitchRelin(evalKey, ciphertext);
else {
throw std::logic_error("KeySwitchRelin operation has not been enabled");
}
}
shared_ptr<LPEvalKey<Element>> EvalMultKeyGen(const shared_ptr<LPPrivateKey<Element>> originalPrivateKey) const {
if(this->m_algorithmSHE)
return this->m_algorithmSHE->EvalMultKeyGen(originalPrivateKey);
else {
throw std::logic_error("EvalMultKeyGen operation has not been enabled");
}
}
/////////////////////////////////////////
// the functions below are wrappers for things in LPFHEAlgorithm (FHE)
//
// TODO: Add Functions?
/////////////////////////////////////////
// the functions below are wrappers for things in LPSHEAlgorithm (SHE)
//
shared_ptr<Ciphertext<Element>> ModReduce(shared_ptr<Ciphertext<Element>> cipherText) const {
if(this->m_algorithmLeveledSHE){
return this->m_algorithmLeveledSHE->ModReduce(cipherText);
}
else{
throw std::logic_error("ModReduce operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> RingReduce(shared_ptr<Ciphertext<Element>> cipherText, const shared_ptr<LPEvalKey<Element>> keySwitchHint) const {
if(this->m_algorithmLeveledSHE){
return this->m_algorithmLeveledSHE->RingReduce(cipherText,keySwitchHint);
}
else{
throw std::logic_error("RingReduce operation has not been enabled");
}
}
bool CanRingReduce(usint ringDimension, const std::vector<BigInteger> &moduli, const double rootHermiteFactor) const {
if (this->m_algorithmLeveledSHE) {
return this->m_algorithmLeveledSHE->CanRingReduce(ringDimension, moduli, rootHermiteFactor);
}
else {
throw std::logic_error("CanRingReduce operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> ComposedEvalMult(
const shared_ptr<Ciphertext<Element>> cipherText1,
const shared_ptr<Ciphertext<Element>> cipherText2,
const shared_ptr<LPEvalKey<Element>> quadKeySwitchHint) const {
if(this->m_algorithmLeveledSHE){
return this->m_algorithmLeveledSHE->ComposedEvalMult(cipherText1,cipherText2,quadKeySwitchHint);
}
else{
throw std::logic_error("ComposedEvalMult operation has not been enabled");
}
}
shared_ptr<Ciphertext<Element>> LevelReduce(const shared_ptr<Ciphertext<Element>> cipherText1,
const shared_ptr<LPEvalKeyNTRU<Element>> linearKeySwitchHint) const {
if(this->m_algorithmLeveledSHE){
return this->m_algorithmLeveledSHE->LevelReduce(cipherText1,linearKeySwitchHint);
}
else{
throw std::logic_error("LevelReduce operation has not been enabled");
}
}
const LPEncryptionAlgorithm<Element>& getAlgorithm() const { return *m_algorithmEncryption; }
protected:
LPParameterGenerationAlgorithm<Element> *m_algorithmParamsGen;
LPEncryptionAlgorithm<Element> *m_algorithmEncryption;
LPPREAlgorithm<Element> *m_algorithmPRE;
LPMultipartyAlgorithm<Element> *m_algorithmMultiparty;
LPSHEAlgorithm<Element> *m_algorithmSHE;
LPFHEAlgorithm<Element> *m_algorithmFHE;
LPLeveledSHEAlgorithm<Element> *m_algorithmLeveledSHE;
};
} // namespace lbcrypto ends
#endif
|
loopct_r8.c | /*
* Input: ntabs nchannels padded_size
* Output: ntabs ntimes -nchannels ; ntimes < padded_size
*
* We process a finished tab directly, so no need to build up the full ntabs array
*/
void deinterleave(const char *page, char *transposed, const int ntabs, const int nchannels, const int ntimes, const int padded_size) {
int tab;
for (tab = 0; tab < ntabs; tab++) {
int channel;
#pragma omp parallel for
for (channel = 0; channel < nchannels; channel+=6) {
const char *channelA = &page[(tab*nchannels + channel + 0)*padded_size];
const char *channelB = &page[(tab*nchannels + channel + 1)*padded_size];
const char *channelC = &page[(tab*nchannels + channel + 2)*padded_size];
const char *channelD = &page[(tab*nchannels + channel + 3)*padded_size];
const char *channelE = &page[(tab*nchannels + channel + 4)*padded_size];
const char *channelF = &page[(tab*nchannels + channel + 5)*padded_size];
const char *channelG = &page[(tab*nchannels + channel + 6)*padded_size];
const char *channelH = &page[(tab*nchannels + channel + 7)*padded_size];
int time;
for (time = 0; time < ntimes; time++) {
// reverse freq order to comply with header
transposed[time*nchannels+nchannels-(channel+0)-1] = channelA[time];
transposed[time*nchannels+nchannels-(channel+1)-1] = channelB[time];
transposed[time*nchannels+nchannels-(channel+2)-1] = channelC[time];
transposed[time*nchannels+nchannels-(channel+3)-1] = channelD[time];
transposed[time*nchannels+nchannels-(channel+4)-1] = channelE[time];
transposed[time*nchannels+nchannels-(channel+5)-1] = channelF[time];
transposed[time*nchannels+nchannels-(channel+6)-1] = channelG[time];
transposed[time*nchannels+nchannels-(channel+7)-1] = channelH[time];
}
}
}
}
|
parallel-calculations.c | #include <stdio.h>
#include <omp.h>
int main()
{
int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519};
int largest, largest_factor = 0;
omp_set_num_threads(4);
/* "omp parallel for" turns the for loop multithreaded by making each thread
* iterating only a part of the loop variable, in this case i; variables declared
* as "shared" will be implicitly locked on access
*/
#pragma omp parallel for shared(largest_factor, largest)
for (int i = 0; i < 7; i++) {
int p, n = data[i];
for (p = 3; p * p <= n && n % p; p += 2);
if (p * p > n) p = n;
if (p > largest_factor) {
largest_factor = p;
largest = n;
printf("thread %d: found larger: %d of %d\n",
omp_get_thread_num(), p, n);
} else {
printf("thread %d: not larger: %d of %d\n",
omp_get_thread_num(), p, n);
}
}
printf("Largest factor: %d of %d\n", largest_factor, largest);
return 0;
}
|
ast-dump-openmp-declare-variant-extensions.c | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -verify -ast-dump %s | FileCheck %s
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -verify -ast-dump %s -x c++| FileCheck %s
// expected-no-diagnostics
int picked1(void) { return 0; }
int picked2(void) { return 0; }
int picked3(void);
int picked4(void);
int picked5(void) { return 0; }
int picked6(void) { return 0; }
int picked7(void) { return 0; }
int not_picked1(void) { return 1; }
int not_picked2(void) { return 2; }
int not_picked3(void);
int not_picked4(void);
int not_picked5(void);
int not_picked6(void);
#pragma omp declare variant(picked1) match(implementation={extension(match_any)}, device={kind(cpu, gpu)})
int base1(void) { return 3; }
#pragma omp declare variant(picked2) match(implementation={extension(match_none)}, device={kind(gpu, fpga)})
int base2(void) { return 4; }
#pragma omp declare variant(picked3) match(implementation={vendor(pgi), extension(match_any)}, device={kind(cpu, gpu)})
int base3(void) { return 5; }
#pragma omp declare variant(picked4) match(user={condition(0)}, implementation={extension(match_none)}, device={kind(gpu, fpga)})
int base4(void) { return 6; }
#pragma omp declare variant(picked5) match(user={condition(1)}, implementation={extension(match_all)}, device={kind(cpu)})
int base5(void) { return 7; }
#pragma omp declare variant(not_picked1) match(implementation={extension(match_any)}, device={kind(gpu, fpga)})
int base6(void) { return 0; }
#pragma omp declare variant(not_picked2) match(implementation={extension(match_none)}, device={kind(gpu, cpu)})
int base7(void) { return 0; }
#pragma omp declare variant(not_picked3) match(implementation={vendor(llvm), extension(match_any)}, device={kind(fpga, gpu)})
int base8(void) { return 0; }
#pragma omp declare variant(not_picked4) match(user={condition(1)}, implementation={extension(match_none)}, device={kind(gpu, fpga)})
int base9(void) { return 0; }
#pragma omp declare variant(not_picked5) match(user={condition(1)}, implementation={extension(match_all)}, device={kind(cpu, gpu)})
int base10(void) { return 0; }
#pragma omp declare variant(not_picked6) match(implementation={extension(match_any)})
int base11(void) { return 0; }
#pragma omp declare variant(picked6) match(implementation={extension(match_all)})
int base12(void) { return 8; }
#pragma omp declare variant(picked7) match(implementation={extension(match_none)})
int base13(void) { return 9; }
#pragma omp begin declare variant match(implementation={extension(match_any)}, device={kind(cpu, gpu)})
int overloaded1(void) { return 0; }
#pragma omp end declare variant
int overloaded2(void) { return 1; }
#pragma omp begin declare variant match(implementation={extension(match_none)}, device={kind(fpga, gpu)})
int overloaded2(void) { return 0; }
#pragma omp end declare variant
#pragma omp begin declare variant match(implementation={extension(match_none)}, device={kind(cpu)})
NOT PARSED
#pragma omp end declare variant
int picked3(void) { return 0; }
int picked4(void) { return 0; }
int not_picked3(void) { return 10; }
int not_picked4(void) { return 11; }
int not_picked5(void) { return 12; }
int not_picked6(void) { return 13; }
int test(void) {
// Should return 0.
return base1() + base2() + base3() + base4() + base5() + base6() + base7() +
base8() + base9() + base10() + base11() + base12() + base13() +
overloaded1() + overloaded2();
}
// 1) All "picked" versions are called but none of the "non_picked" ones is.
// 2) The overloaded functions that return 0 are called.
// CHECK: |-FunctionDecl [[ADDR_0:0x[a-z0-9]*]] <{{.*}}, col:31> col:5 referenced picked1 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_1:0x[a-z0-9]*]] <col:19, col:31>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_2:0x[a-z0-9]*]] <col:21, col:28>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_3:0x[a-z0-9]*]] <col:28> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_4:0x[a-z0-9]*]] <line:6:1, col:31> col:5 referenced picked2 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_5:0x[a-z0-9]*]] <col:19, col:31>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_6:0x[a-z0-9]*]] <col:21, col:28>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_7:0x[a-z0-9]*]] <col:28> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_8:0x[a-z0-9]*]] <line:7:1, col:17> col:5 referenced picked3 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_9:0x[a-z0-9]*]] <line:8:1, col:17> col:5 referenced picked4 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_10:0x[a-z0-9]*]] <line:9:1, col:31> col:5 referenced picked5 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_11:0x[a-z0-9]*]] <col:19, col:31>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_12:0x[a-z0-9]*]] <col:21, col:28>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_13:0x[a-z0-9]*]] <col:28> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_14:0x[a-z0-9]*]] <line:10:1, col:31> col:5 referenced picked6 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_15:0x[a-z0-9]*]] <col:19, col:31>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_16:0x[a-z0-9]*]] <col:21, col:28>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_17:0x[a-z0-9]*]] <col:28> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_18:0x[a-z0-9]*]] <line:11:1, col:31> col:5 referenced picked7 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_19:0x[a-z0-9]*]] <col:19, col:31>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_20:0x[a-z0-9]*]] <col:21, col:28>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_21:0x[a-z0-9]*]] <col:28> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_22:0x[a-z0-9]*]] <line:12:1, col:35> col:5 referenced not_picked1 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_23:0x[a-z0-9]*]] <col:23, col:35>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_24:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_25:0x[a-z0-9]*]] <col:32> 'int' 1
// CHECK-NEXT: |-FunctionDecl [[ADDR_26:0x[a-z0-9]*]] <line:13:1, col:35> col:5 referenced not_picked2 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_27:0x[a-z0-9]*]] <col:23, col:35>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_28:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_29:0x[a-z0-9]*]] <col:32> 'int' 2
// CHECK-NEXT: |-FunctionDecl [[ADDR_30:0x[a-z0-9]*]] <line:14:1, col:21> col:5 referenced not_picked3 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_31:0x[a-z0-9]*]] <line:15:1, col:21> col:5 referenced not_picked4 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_32:0x[a-z0-9]*]] <line:16:1, col:21> col:5 referenced not_picked5 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_33:0x[a-z0-9]*]] <line:17:1, col:21> col:5 referenced not_picked6 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_34:0x[a-z0-9]*]] <line:20:1, col:29> col:5 used base1 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_35:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_36:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_37:0x[a-z0-9]*]] <col:26> 'int' 3
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_38:0x[a-z0-9]*]] <line:19:1, col:107> Implicit implementation={extension(match_any)}, device={kind(cpu, gpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_39:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_0]] 'picked1' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_40:0x[a-z0-9]*]] <line:23:1, col:29> col:5 used base2 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_41:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_42:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_43:0x[a-z0-9]*]] <col:26> 'int' 4
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_44:0x[a-z0-9]*]] <line:22:1, col:109> Implicit implementation={extension(match_none)}, device={kind(gpu, fpga)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_45:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_4]] 'picked2' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_46:0x[a-z0-9]*]] <line:26:1, col:29> col:5 used base3 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_47:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_48:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_49:0x[a-z0-9]*]] <col:26> 'int' 5
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_50:0x[a-z0-9]*]] <line:25:1, col:120> Implicit implementation={vendor(pgi), extension(match_any)}, device={kind(cpu, gpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_51:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_8]] 'picked3' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_52:0x[a-z0-9]*]] <line:29:1, col:29> col:5 used base4 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_53:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_54:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_55:0x[a-z0-9]*]] <col:26> 'int' 6
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_56:0x[a-z0-9]*]] <line:28:1, col:130> Implicit user={condition(0)}, implementation={extension(match_none)}, device={kind(gpu, fpga)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_57:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_9]] 'picked4' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_58:0x[a-z0-9]*]] <line:32:1, col:29> col:5 used base5 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_59:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_60:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_61:0x[a-z0-9]*]] <col:26> 'int' 7
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_62:0x[a-z0-9]*]] <line:31:1, col:123> Implicit user={condition(1)}, implementation={extension(match_all)}, device={kind(cpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_63:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_10]] 'picked5' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_64:0x[a-z0-9]*]] <line:35:1, col:29> col:5 used base6 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_65:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_66:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_67:0x[a-z0-9]*]] <col:26> 'int' 0
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_68:0x[a-z0-9]*]] <line:34:1, col:112> Implicit implementation={extension(match_any)}, device={kind(gpu, fpga)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_69:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_22]] 'not_picked1' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_70:0x[a-z0-9]*]] <line:38:1, col:29> col:5 used base7 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_71:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_72:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_73:0x[a-z0-9]*]] <col:26> 'int' 0
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_74:0x[a-z0-9]*]] <line:37:1, col:112> Implicit implementation={extension(match_none)}, device={kind(gpu, cpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_75:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_26]] 'not_picked2' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_76:0x[a-z0-9]*]] <line:41:1, col:29> col:5 used base8 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_77:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_78:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_79:0x[a-z0-9]*]] <col:26> 'int' 0
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_80:0x[a-z0-9]*]] <line:40:1, col:126> Implicit implementation={vendor(llvm), extension(match_any)}, device={kind(fpga, gpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_81:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_30]] 'not_picked3' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_82:0x[a-z0-9]*]] <line:44:1, col:29> col:5 used base9 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_83:0x[a-z0-9]*]] <col:17, col:29>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_84:0x[a-z0-9]*]] <col:19, col:26>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_85:0x[a-z0-9]*]] <col:26> 'int' 0
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_86:0x[a-z0-9]*]] <line:43:1, col:134> Implicit user={condition(1)}, implementation={extension(match_none)}, device={kind(gpu, fpga)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_87:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_31]] 'not_picked4' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_88:0x[a-z0-9]*]] <line:47:1, col:30> col:5 used base10 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_89:0x[a-z0-9]*]] <col:18, col:30>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_90:0x[a-z0-9]*]] <col:20, col:27>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_91:0x[a-z0-9]*]] <col:27> 'int' 0
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_92:0x[a-z0-9]*]] <line:46:1, col:132> Implicit user={condition(1)}, implementation={extension(match_all)}, device={kind(cpu, gpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_93:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_32]] 'not_picked5' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_94:0x[a-z0-9]*]] <line:50:1, col:30> col:5 used base11 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_95:0x[a-z0-9]*]] <col:18, col:30>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_96:0x[a-z0-9]*]] <col:20, col:27>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_97:0x[a-z0-9]*]] <col:27> 'int' 0
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_98:0x[a-z0-9]*]] <line:49:1, col:86> Implicit implementation={extension(match_any)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_99:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_33]] 'not_picked6' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_100:0x[a-z0-9]*]] <line:53:1, col:30> col:5 used base12 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_101:0x[a-z0-9]*]] <col:18, col:30>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_102:0x[a-z0-9]*]] <col:20, col:27>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_103:0x[a-z0-9]*]] <col:27> 'int' 8
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_104:0x[a-z0-9]*]] <line:52:1, col:82> Implicit implementation={extension(match_all)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_105:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_14]] 'picked6' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_106:0x[a-z0-9]*]] <line:56:1, col:30> col:5 used base13 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_107:0x[a-z0-9]*]] <col:18, col:30>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_108:0x[a-z0-9]*]] <col:20, col:27>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_109:0x[a-z0-9]*]] <col:27> 'int' 9
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_110:0x[a-z0-9]*]] <line:55:1, col:83> Implicit implementation={extension(match_none)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_111:0x[a-z0-9]*]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_18]] 'picked7' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: |-FunctionDecl [[ADDR_112:0x[a-z0-9]*]] <line:59:1, col:21> col:5 implicit used overloaded1 'int ({{.*}})'
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_113:0x[a-z0-9]*]] <<invalid sloc>> Implicit implementation={extension(match_any)}, device={kind(cpu, gpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_114:0x[a-z0-9]*]] <col:1> 'int ({{.*}})' {{.*}}Function [[ADDR_115:0x[a-z0-9]*]] 'overloaded1[implementation={extension(match_any)}, device={kind(cpu, gpu)}]' 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_115]] <col:1, col:35> col:1 overloaded1[implementation={extension(match_any)}, device={kind(cpu, gpu)}] 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_116:0x[a-z0-9]*]] <col:23, col:35>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_117:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_118:0x[a-z0-9]*]] <col:32> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_119:0x[a-z0-9]*]] <line:62:1, col:35> col:5 used overloaded2 'int ({{.*}})'
// CHECK-NEXT: | |-CompoundStmt [[ADDR_120:0x[a-z0-9]*]] <col:23, col:35>
// CHECK-NEXT: | | `-ReturnStmt [[ADDR_121:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | | `-IntegerLiteral [[ADDR_122:0x[a-z0-9]*]] <col:32> 'int' 1
// CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_123:0x[a-z0-9]*]] <<invalid sloc>> Implicit implementation={extension(match_none)}, device={kind(fpga, gpu)}
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_124:0x[a-z0-9]*]] <line:64:1> 'int ({{.*}})' {{.*}}Function [[ADDR_125:0x[a-z0-9]*]] 'overloaded2[implementation={extension(match_none)}, device={kind(fpga, gpu)}]' 'int ({{.*}})'
// CHECK-NEXT: |-FunctionDecl [[ADDR_125]] <col:1, col:35> col:1 overloaded2[implementation={extension(match_none)}, device={kind(fpga, gpu)}] 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_126:0x[a-z0-9]*]] <col:23, col:35>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_127:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_128:0x[a-z0-9]*]] <col:32> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_129:0x[a-z0-9]*]] prev [[ADDR_8]] <line:72:1, col:31> col:5 picked3 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_130:0x[a-z0-9]*]] <col:19, col:31>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_131:0x[a-z0-9]*]] <col:21, col:28>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_132:0x[a-z0-9]*]] <col:28> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_133:0x[a-z0-9]*]] prev [[ADDR_9]] <line:73:1, col:31> col:5 picked4 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_134:0x[a-z0-9]*]] <col:19, col:31>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_135:0x[a-z0-9]*]] <col:21, col:28>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_136:0x[a-z0-9]*]] <col:28> 'int' 0
// CHECK-NEXT: |-FunctionDecl [[ADDR_137:0x[a-z0-9]*]] prev [[ADDR_30]] <line:74:1, col:36> col:5 not_picked3 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_138:0x[a-z0-9]*]] <col:23, col:36>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_139:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_140:0x[a-z0-9]*]] <col:32> 'int' 10
// CHECK-NEXT: |-FunctionDecl [[ADDR_141:0x[a-z0-9]*]] prev [[ADDR_31]] <line:75:1, col:36> col:5 not_picked4 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_142:0x[a-z0-9]*]] <col:23, col:36>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_143:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_144:0x[a-z0-9]*]] <col:32> 'int' 11
// CHECK-NEXT: |-FunctionDecl [[ADDR_145:0x[a-z0-9]*]] prev [[ADDR_32]] <line:76:1, col:36> col:5 not_picked5 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_146:0x[a-z0-9]*]] <col:23, col:36>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_147:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_148:0x[a-z0-9]*]] <col:32> 'int' 12
// CHECK-NEXT: |-FunctionDecl [[ADDR_149:0x[a-z0-9]*]] prev [[ADDR_33]] <line:77:1, col:36> col:5 not_picked6 'int ({{.*}})'
// CHECK-NEXT: | `-CompoundStmt [[ADDR_150:0x[a-z0-9]*]] <col:23, col:36>
// CHECK-NEXT: | `-ReturnStmt [[ADDR_151:0x[a-z0-9]*]] <col:25, col:32>
// CHECK-NEXT: | `-IntegerLiteral [[ADDR_152:0x[a-z0-9]*]] <col:32> 'int' 13
// CHECK-NEXT: `-FunctionDecl [[ADDR_153:0x[a-z0-9]*]] <line:79:1, line:84:1> line:79:5 test 'int ({{.*}})'
// CHECK-NEXT: `-CompoundStmt [[ADDR_154:0x[a-z0-9]*]] <col:16, line:84:1>
// CHECK-NEXT: `-ReturnStmt [[ADDR_155:0x[a-z0-9]*]] <line:81:3, line:83:38>
// CHECK-NEXT: `-BinaryOperator [[ADDR_156:0x[a-z0-9]*]] <line:81:10, line:83:38> 'int' '+'
// CHECK-NEXT: |-BinaryOperator [[ADDR_157:0x[a-z0-9]*]] <line:81:10, line:83:22> 'int' '+'
// CHECK-NEXT: | |-BinaryOperator [[ADDR_158:0x[a-z0-9]*]] <line:81:10, line:82:70> 'int' '+'
// CHECK-NEXT: | | |-BinaryOperator [[ADDR_159:0x[a-z0-9]*]] <line:81:10, line:82:59> 'int' '+'
// CHECK-NEXT: | | | |-BinaryOperator [[ADDR_160:0x[a-z0-9]*]] <line:81:10, line:82:48> 'int' '+'
// CHECK-NEXT: | | | | |-BinaryOperator [[ADDR_161:0x[a-z0-9]*]] <line:81:10, line:82:37> 'int' '+'
// CHECK-NEXT: | | | | | |-BinaryOperator [[ADDR_162:0x[a-z0-9]*]] <line:81:10, line:82:26> 'int' '+'
// CHECK-NEXT: | | | | | | |-BinaryOperator [[ADDR_163:0x[a-z0-9]*]] <line:81:10, line:82:16> 'int' '+'
// CHECK-NEXT: | | | | | | | |-BinaryOperator [[ADDR_164:0x[a-z0-9]*]] <line:81:10, col:76> 'int' '+'
// CHECK-NEXT: | | | | | | | | |-BinaryOperator [[ADDR_165:0x[a-z0-9]*]] <col:10, col:66> 'int' '+'
// CHECK-NEXT: | | | | | | | | | |-BinaryOperator [[ADDR_166:0x[a-z0-9]*]] <col:10, col:56> 'int' '+'
// CHECK-NEXT: | | | | | | | | | | |-BinaryOperator [[ADDR_167:0x[a-z0-9]*]] <col:10, col:46> 'int' '+'
// CHECK-NEXT: | | | | | | | | | | | |-BinaryOperator [[ADDR_168:0x[a-z0-9]*]] <col:10, col:36> 'int' '+'
// CHECK-NEXT: | | | | | | | | | | | | |-BinaryOperator [[ADDR_169:0x[a-z0-9]*]] <col:10, col:26> 'int' '+'
// CHECK-NEXT: | | | | | | | | | | | | | |-PseudoObjectExpr [[ADDR_170:0x[a-z0-9]*]] <col:10, col:16> 'int'
// CHECK-NEXT: | | | | | | | | | | | | | | |-CallExpr [[ADDR_171:0x[a-z0-9]*]] <col:10, col:16> 'int'
// CHECK-NEXT: | | | | | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_172:0x[a-z0-9]*]] <col:10> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | | | | | `-DeclRefExpr [[ADDR_173:0x[a-z0-9]*]] <col:10> 'int ({{.*}})' {{.*}}Function [[ADDR_34]] 'base1' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | | | | | | | | `-CallExpr [[ADDR_174:0x[a-z0-9]*]] <line:19:29, line:81:16> 'int'
// CHECK-NEXT: | | | | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_175:0x[a-z0-9]*]] <line:19:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | | | | `-DeclRefExpr [[ADDR_39]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_0]] 'picked1' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | | | | | | | | | | | | | `-PseudoObjectExpr [[ADDR_176:0x[a-z0-9]*]] <line:81:20, col:26> 'int'
// CHECK-NEXT: | | | | | | | | | | | | | |-CallExpr [[ADDR_177:0x[a-z0-9]*]] <col:20, col:26> 'int'
// CHECK-NEXT: | | | | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_178:0x[a-z0-9]*]] <col:20> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | | | | `-DeclRefExpr [[ADDR_179:0x[a-z0-9]*]] <col:20> 'int ({{.*}})' {{.*}}Function [[ADDR_40]] 'base2' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | | | | | | | `-CallExpr [[ADDR_180:0x[a-z0-9]*]] <line:22:29, line:81:26> 'int'
// CHECK-NEXT: | | | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_181:0x[a-z0-9]*]] <line:22:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | | | `-DeclRefExpr [[ADDR_45]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_4]] 'picked2' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | | | | | | | | | | | | `-PseudoObjectExpr [[ADDR_182:0x[a-z0-9]*]] <line:81:30, col:36> 'int'
// CHECK-NEXT: | | | | | | | | | | | | |-CallExpr [[ADDR_183:0x[a-z0-9]*]] <col:30, col:36> 'int'
// CHECK-NEXT: | | | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_184:0x[a-z0-9]*]] <col:30> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | | | `-DeclRefExpr [[ADDR_185:0x[a-z0-9]*]] <col:30> 'int ({{.*}})' {{.*}}Function [[ADDR_46]] 'base3' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | | | | | | `-CallExpr [[ADDR_186:0x[a-z0-9]*]] <line:25:29, line:81:36> 'int'
// CHECK-NEXT: | | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_187:0x[a-z0-9]*]] <line:25:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | | `-DeclRefExpr [[ADDR_51]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_8]] 'picked3' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | | | | | | | | | | | `-PseudoObjectExpr [[ADDR_188:0x[a-z0-9]*]] <line:81:40, col:46> 'int'
// CHECK-NEXT: | | | | | | | | | | | |-CallExpr [[ADDR_189:0x[a-z0-9]*]] <col:40, col:46> 'int'
// CHECK-NEXT: | | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_190:0x[a-z0-9]*]] <col:40> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | | `-DeclRefExpr [[ADDR_191:0x[a-z0-9]*]] <col:40> 'int ({{.*}})' {{.*}}Function [[ADDR_52]] 'base4' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | | | | | `-CallExpr [[ADDR_192:0x[a-z0-9]*]] <line:28:29, line:81:46> 'int'
// CHECK-NEXT: | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_193:0x[a-z0-9]*]] <line:28:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | `-DeclRefExpr [[ADDR_57]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_9]] 'picked4' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | | | | | | | | | | `-PseudoObjectExpr [[ADDR_194:0x[a-z0-9]*]] <line:81:50, col:56> 'int'
// CHECK-NEXT: | | | | | | | | | | |-CallExpr [[ADDR_195:0x[a-z0-9]*]] <col:50, col:56> 'int'
// CHECK-NEXT: | | | | | | | | | | | `-ImplicitCastExpr [[ADDR_196:0x[a-z0-9]*]] <col:50> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | | `-DeclRefExpr [[ADDR_197:0x[a-z0-9]*]] <col:50> 'int ({{.*}})' {{.*}}Function [[ADDR_58]] 'base5' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | | | | `-CallExpr [[ADDR_198:0x[a-z0-9]*]] <line:31:29, line:81:56> 'int'
// CHECK-NEXT: | | | | | | | | | | `-ImplicitCastExpr [[ADDR_199:0x[a-z0-9]*]] <line:31:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | | `-DeclRefExpr [[ADDR_63]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_10]] 'picked5' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | | | | | | | | | `-CallExpr [[ADDR_200:0x[a-z0-9]*]] <line:81:60, col:66> 'int'
// CHECK-NEXT: | | | | | | | | | `-ImplicitCastExpr [[ADDR_201:0x[a-z0-9]*]] <col:60> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr [[ADDR_202:0x[a-z0-9]*]] <col:60> 'int ({{.*}})' {{.*}}Function [[ADDR_64]] 'base6' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | | `-CallExpr [[ADDR_203:0x[a-z0-9]*]] <col:70, col:76> 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr [[ADDR_204:0x[a-z0-9]*]] <col:70> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr [[ADDR_205:0x[a-z0-9]*]] <col:70> 'int ({{.*}})' {{.*}}Function [[ADDR_70]] 'base7' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | `-PseudoObjectExpr [[ADDR_206:0x[a-z0-9]*]] <line:82:10, col:16> 'int'
// CHECK-NEXT: | | | | | | | |-CallExpr [[ADDR_207:0x[a-z0-9]*]] <col:10, col:16> 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr [[ADDR_208:0x[a-z0-9]*]] <col:10> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr [[ADDR_209:0x[a-z0-9]*]] <col:10> 'int ({{.*}})' {{.*}}Function [[ADDR_76]] 'base8' 'int ({{.*}})'
// CHECK-NEXT: | | | | | | | `-CallExpr [[ADDR_210:0x[a-z0-9]*]] <line:40:29, line:82:16> 'int'
// CHECK-NEXT: | | | | | | | `-ImplicitCastExpr [[ADDR_211:0x[a-z0-9]*]] <line:40:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr [[ADDR_81]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_30]] 'not_picked3' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | | | | | | `-CallExpr [[ADDR_212:0x[a-z0-9]*]] <line:82:20, col:26> 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr [[ADDR_213:0x[a-z0-9]*]] <col:20> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | | `-DeclRefExpr [[ADDR_214:0x[a-z0-9]*]] <col:20> 'int ({{.*}})' {{.*}}Function [[ADDR_82]] 'base9' 'int ({{.*}})'
// CHECK-NEXT: | | | | | `-CallExpr [[ADDR_215:0x[a-z0-9]*]] <col:30, col:37> 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr [[ADDR_216:0x[a-z0-9]*]] <col:30> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | | `-DeclRefExpr [[ADDR_217:0x[a-z0-9]*]] <col:30> 'int ({{.*}})' {{.*}}Function [[ADDR_88]] 'base10' 'int ({{.*}})'
// CHECK-NEXT: | | | | `-CallExpr [[ADDR_218:0x[a-z0-9]*]] <col:41, col:48> 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr [[ADDR_219:0x[a-z0-9]*]] <col:41> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | `-DeclRefExpr [[ADDR_220:0x[a-z0-9]*]] <col:41> 'int ({{.*}})' {{.*}}Function [[ADDR_94]] 'base11' 'int ({{.*}})'
// CHECK-NEXT: | | | `-PseudoObjectExpr [[ADDR_221:0x[a-z0-9]*]] <col:52, col:59> 'int'
// CHECK-NEXT: | | | |-CallExpr [[ADDR_222:0x[a-z0-9]*]] <col:52, col:59> 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr [[ADDR_223:0x[a-z0-9]*]] <col:52> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | | `-DeclRefExpr [[ADDR_224:0x[a-z0-9]*]] <col:52> 'int ({{.*}})' {{.*}}Function [[ADDR_100]] 'base12' 'int ({{.*}})'
// CHECK-NEXT: | | | `-CallExpr [[ADDR_225:0x[a-z0-9]*]] <line:52:29, line:82:59> 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr [[ADDR_226:0x[a-z0-9]*]] <line:52:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | `-DeclRefExpr [[ADDR_105]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_14]] 'picked6' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | | `-PseudoObjectExpr [[ADDR_227:0x[a-z0-9]*]] <line:82:63, col:70> 'int'
// CHECK-NEXT: | | |-CallExpr [[ADDR_228:0x[a-z0-9]*]] <col:63, col:70> 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr [[ADDR_229:0x[a-z0-9]*]] <col:63> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | | `-DeclRefExpr [[ADDR_230:0x[a-z0-9]*]] <col:63> 'int ({{.*}})' {{.*}}Function [[ADDR_106]] 'base13' 'int ({{.*}})'
// CHECK-NEXT: | | `-CallExpr [[ADDR_231:0x[a-z0-9]*]] <line:55:29, line:82:70> 'int'
// CHECK-NEXT: | | `-ImplicitCastExpr [[ADDR_232:0x[a-z0-9]*]] <line:55:29> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | `-DeclRefExpr [[ADDR_111]] <col:29> 'int ({{.*}})' {{.*}}Function [[ADDR_18]] 'picked7' 'int ({{.*}})' non_odr_use_unevaluated
// CHECK-NEXT: | `-PseudoObjectExpr [[ADDR_233:0x[a-z0-9]*]] <line:83:10, col:22> 'int'
// CHECK-NEXT: | |-CallExpr [[ADDR_234:0x[a-z0-9]*]] <col:10, col:22> 'int'
// CHECK-NEXT: | | `-ImplicitCastExpr [[ADDR_235:0x[a-z0-9]*]] <col:10> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | | `-DeclRefExpr [[ADDR_236:0x[a-z0-9]*]] <col:10> 'int ({{.*}})' {{.*}}Function [[ADDR_112]] 'overloaded1' 'int ({{.*}})'
// CHECK-NEXT: | `-CallExpr [[ADDR_237:0x[a-z0-9]*]] <line:59:1, line:83:22> 'int'
// CHECK-NEXT: | `-ImplicitCastExpr [[ADDR_238:0x[a-z0-9]*]] <line:59:1> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_114]] <col:1> 'int ({{.*}})' {{.*}}Function [[ADDR_115]] 'overloaded1[implementation={extension(match_any)}, device={kind(cpu, gpu)}]' 'int ({{.*}})'
// CHECK-NEXT: `-PseudoObjectExpr [[ADDR_239:0x[a-z0-9]*]] <line:83:26, col:38> 'int'
// CHECK-NEXT: |-CallExpr [[ADDR_240:0x[a-z0-9]*]] <col:26, col:38> 'int'
// CHECK-NEXT: | `-ImplicitCastExpr [[ADDR_241:0x[a-z0-9]*]] <col:26> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: | `-DeclRefExpr [[ADDR_242:0x[a-z0-9]*]] <col:26> 'int ({{.*}})' {{.*}}Function [[ADDR_119]] 'overloaded2' 'int ({{.*}})'
// CHECK-NEXT: `-CallExpr [[ADDR_243:0x[a-z0-9]*]] <line:64:1, line:83:38> 'int'
// CHECK-NEXT: `-ImplicitCastExpr [[ADDR_244:0x[a-z0-9]*]] <line:64:1> 'int (*)({{.*}})' <FunctionToPointerDecay>
// CHECK-NEXT: `-DeclRefExpr [[ADDR_124]] <col:1> 'int ({{.*}})' {{.*}}Function [[ADDR_125]] 'overloaded2[implementation={extension(match_none)}, device={kind(fpga, gpu)}]' 'int ({{.*}})'
|
transform.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT RRRR AAA N N SSSSS FFFFF OOO RRRR M M %
% T R R A A NN N SS F O O R R MM MM %
% T RRRR AAAAA N N N SSS FFF O O RRRR M M M %
% T R R A A N NN SS F O O R R M M %
% T R R A A N N SSSSS F OOO R R M M %
% %
% %
% MagickCore Image Transform Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/effect.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/memory_.h"
#include "magick/layer.h"
#include "magick/list.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-private.h"
#include "magick/resource_.h"
#include "magick/resize.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/transform.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o O r i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoOrientImage() adjusts an image so that its orientation is suitable for
% viewing (i.e. top-left orientation).
%
% The format of the AutoOrientImage method is:
%
% Image *AutoOrientImage(const Image *image,
% const OrientationType orientation,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o orientation: Current image orientation.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *AutoOrientImage(const Image *image,
const OrientationType orientation,ExceptionInfo *exception)
{
Image
*orient_image;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
orient_image=(Image *) NULL;
switch(orientation)
{
case UndefinedOrientation:
case TopLeftOrientation:
default:
{
orient_image=CloneImage(image,0,0,MagickTrue,exception);
break;
}
case TopRightOrientation:
{
orient_image=FlopImage(image,exception);
break;
}
case BottomRightOrientation:
{
orient_image=RotateImage(image,180.0,exception);
break;
}
case BottomLeftOrientation:
{
orient_image=FlipImage(image,exception);
break;
}
case LeftTopOrientation:
{
orient_image=TransposeImage(image,exception);
break;
}
case RightTopOrientation:
{
orient_image=RotateImage(image,90.0,exception);
break;
}
case RightBottomOrientation:
{
orient_image=TransverseImage(image,exception);
break;
}
case LeftBottomOrientation:
{
orient_image=RotateImage(image,270.0,exception);
break;
}
}
if (orient_image != (Image *) NULL)
orient_image->orientation=TopLeftOrientation;
return(orient_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ChopImage() removes a region of an image and collapses the image to occupy
% the removed portion.
%
% The format of the ChopImage method is:
%
% Image *ChopImage(const Image *image,const RectangleInfo *chop_info)
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o chop_info: Define the region of the image to chop.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info,
ExceptionInfo *exception)
{
#define ChopImageTag "Chop/Image"
CacheView
*chop_view,
*image_view;
Image
*chop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
extent;
ssize_t
y;
/*
Check chop geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
assert(chop_info != (RectangleInfo *) NULL);
if (((chop_info->x+(ssize_t) chop_info->width) < 0) ||
((chop_info->y+(ssize_t) chop_info->height) < 0) ||
(chop_info->x > (ssize_t) image->columns) ||
(chop_info->y > (ssize_t) image->rows))
ThrowImageException(OptionWarning,"GeometryDoesNotContainImage");
extent=(*chop_info);
if ((extent.x+(ssize_t) extent.width) > (ssize_t) image->columns)
extent.width=(size_t) ((ssize_t) image->columns-extent.x);
if ((extent.y+(ssize_t) extent.height) > (ssize_t) image->rows)
extent.height=(size_t) ((ssize_t) image->rows-extent.y);
if (extent.x < 0)
{
extent.width-=(size_t) (-extent.x);
extent.x=0;
}
if (extent.y < 0)
{
extent.height-=(size_t) (-extent.y);
extent.y=0;
}
chop_image=CloneImage(image,image->columns-extent.width,image->rows-
extent.height,MagickTrue,exception);
if (chop_image == (Image *) NULL)
return((Image *) NULL);
/*
Extract chop image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
chop_view=AcquireAuthenticCacheView(chop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,chop_image,extent.y,1)
#endif
for (y=0; y < (ssize_t) extent.y; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict chop_indexes,
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,y,chop_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
chop_indexes=GetCacheViewAuthenticIndexQueue(chop_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
*q=(*p);
if (indexes != (IndexPacket *) NULL)
{
if (chop_indexes != (IndexPacket *) NULL)
*chop_indexes++=GetPixelIndex(indexes+x);
}
q++;
}
p++;
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ChopImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
/*
Extract chop image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) (image->rows-(extent.y+extent.height)); y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict chop_indexes,
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,extent.y+extent.height+y,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,extent.y+y,chop_image->columns,
1,exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
chop_indexes=GetCacheViewAuthenticIndexQueue(chop_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
*q=(*p);
if (indexes != (IndexPacket *) NULL)
{
if (chop_indexes != (IndexPacket *) NULL)
*chop_indexes++=GetPixelIndex(indexes+x);
}
q++;
}
p++;
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ChopImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
chop_view=DestroyCacheView(chop_view);
image_view=DestroyCacheView(image_view);
chop_image->type=image->type;
if (status == MagickFalse)
chop_image=DestroyImage(chop_image);
return(chop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n s o l i d a t e C M Y K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConsolidateCMYKImage() consolidates separate C, M, Y, and K planes into a
% single image.
%
% The format of the ConsolidateCMYKImage method is:
%
% Image *ConsolidateCMYKImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image sequence.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ConsolidateCMYKImages(const Image *images,
ExceptionInfo *exception)
{
CacheView
*cmyk_view,
*image_view;
Image
*cmyk_image,
*cmyk_images;
register ssize_t
i;
ssize_t
y;
/*
Consolidate separate C, M, Y, and K planes into a single image.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
cmyk_images=NewImageList();
for (i=0; i < (ssize_t) GetImageListLength(images); i+=4)
{
cmyk_image=CloneImage(images,0,0,MagickTrue,exception);
if (cmyk_image == (Image *) NULL)
break;
if (SetImageStorageClass(cmyk_image,DirectClass) == MagickFalse)
break;
(void) SetImageColorspace(cmyk_image,CMYKColorspace);
image_view=AcquireVirtualCacheView(images,exception);
cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception);
for (y=0; y < (ssize_t) images->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception);
q=QueueCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) images->columns; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumRange-GetPixelIntensity(images,p)));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse)
break;
}
cmyk_view=DestroyCacheView(cmyk_view);
image_view=DestroyCacheView(image_view);
images=GetNextImageInList(images);
if (images == (Image *) NULL)
break;
image_view=AcquireVirtualCacheView(images,exception);
cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception);
for (y=0; y < (ssize_t) images->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception);
q=GetCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) images->columns; x++)
{
q->green=ClampToQuantum(QuantumRange-GetPixelIntensity(images,p));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse)
break;
}
cmyk_view=DestroyCacheView(cmyk_view);
image_view=DestroyCacheView(image_view);
images=GetNextImageInList(images);
if (images == (Image *) NULL)
break;
image_view=AcquireVirtualCacheView(images,exception);
cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception);
for (y=0; y < (ssize_t) images->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception);
q=GetCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) images->columns; x++)
{
q->blue=ClampToQuantum(QuantumRange-GetPixelIntensity(images,p));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse)
break;
}
cmyk_view=DestroyCacheView(cmyk_view);
image_view=DestroyCacheView(image_view);
images=GetNextImageInList(images);
if (images == (Image *) NULL)
break;
image_view=AcquireVirtualCacheView(images,exception);
cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception);
for (y=0; y < (ssize_t) images->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception);
q=GetCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
break;
indexes=GetCacheViewAuthenticIndexQueue(cmyk_view);
for (x=0; x < (ssize_t) images->columns; x++)
{
SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange-
GetPixelIntensity(images,p)));
p++;
}
if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse)
break;
}
cmyk_view=DestroyCacheView(cmyk_view);
image_view=DestroyCacheView(image_view);
AppendImageToList(&cmyk_images,cmyk_image);
images=GetNextImageInList(images);
if (images == (Image *) NULL)
break;
}
return(cmyk_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C r o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropImage() extracts a region of the image starting at the offset defined
% by geometry. Region must be fully defined, and no special handling of
% geometry flags is performed.
%
% The format of the CropImage method is:
%
% Image *CropImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to crop with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CropImage(const Image *image,const RectangleInfo *geometry,
ExceptionInfo *exception)
{
#define CropImageTag "Crop/Image"
CacheView
*crop_view,
*image_view;
Image
*crop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
bounding_box,
page;
ssize_t
y;
/*
Check crop geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
bounding_box=image->page;
if ((bounding_box.width == 0) || (bounding_box.height == 0))
{
bounding_box.width=image->columns;
bounding_box.height=image->rows;
}
page=(*geometry);
if (page.width == 0)
page.width=bounding_box.width;
if (page.height == 0)
page.height=bounding_box.height;
if (((bounding_box.x-page.x) >= (ssize_t) page.width) ||
((bounding_box.y-page.y) >= (ssize_t) page.height) ||
((page.x-bounding_box.x) > (ssize_t) image->columns) ||
((page.y-bounding_box.y) > (ssize_t) image->rows))
{
/*
Crop is not within virtual canvas, return 1 pixel transparent image.
*/
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
crop_image=CloneImage(image,1,1,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->background_color.opacity=(Quantum) TransparentOpacity;
(void) SetImageBackgroundColor(crop_image);
crop_image->page=bounding_box;
crop_image->page.x=(-1);
crop_image->page.y=(-1);
if (crop_image->dispose == BackgroundDispose)
crop_image->dispose=NoneDispose;
return(crop_image);
}
if ((page.x < 0) && (bounding_box.x >= 0))
{
page.width+=page.x-bounding_box.x;
page.x=0;
}
else
{
page.width-=bounding_box.x-page.x;
page.x-=bounding_box.x;
if (page.x < 0)
page.x=0;
}
if ((page.y < 0) && (bounding_box.y >= 0))
{
page.height+=page.y-bounding_box.y;
page.y=0;
}
else
{
page.height-=bounding_box.y-page.y;
page.y-=bounding_box.y;
if (page.y < 0)
page.y=0;
}
if ((page.x+(ssize_t) page.width) > (ssize_t) image->columns)
page.width=image->columns-page.x;
if ((geometry->width != 0) && (page.width > geometry->width))
page.width=geometry->width;
if ((page.y+(ssize_t) page.height) > (ssize_t) image->rows)
page.height=image->rows-page.y;
if ((geometry->height != 0) && (page.height > geometry->height))
page.height=geometry->height;
bounding_box.x+=page.x;
bounding_box.y+=page.y;
if ((page.width == 0) || (page.height == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
return((Image *) NULL);
}
/*
Initialize crop image attributes.
*/
crop_image=CloneImage(image,page.width,page.height,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->page.width=image->page.width;
crop_image->page.height=image->page.height;
if (((ssize_t) (bounding_box.x+bounding_box.width) > (ssize_t) image->page.width) ||
((ssize_t) (bounding_box.y+bounding_box.height) > (ssize_t) image->page.height))
{
crop_image->page.width=bounding_box.width;
crop_image->page.height=bounding_box.height;
}
crop_image->page.x=bounding_box.x;
crop_image->page.y=bounding_box.y;
/*
Crop image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
crop_view=AcquireAuthenticCacheView(crop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,crop_image,crop_image->rows,1)
#endif
for (y=0; y < (ssize_t) crop_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict crop_indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,page.x,page.y+y,crop_image->columns,
1,exception);
q=QueueCacheViewAuthenticPixels(crop_view,0,y,crop_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
crop_indexes=GetCacheViewAuthenticIndexQueue(crop_view);
(void) memcpy(q,p,(size_t) crop_image->columns*sizeof(*p));
if ((indexes != (IndexPacket *) NULL) &&
(crop_indexes != (IndexPacket *) NULL))
(void) memcpy(crop_indexes,indexes,(size_t) crop_image->columns*
sizeof(*crop_indexes));
if (SyncCacheViewAuthenticPixels(crop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,CropImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
crop_view=DestroyCacheView(crop_view);
image_view=DestroyCacheView(image_view);
crop_image->type=image->type;
if (status == MagickFalse)
crop_image=DestroyImage(crop_image);
return(crop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C r o p I m a g e T o T i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropImageToTiles() crops a single image, into a possible list of tiles.
% This may include a single sub-region of the image. This basically applies
% all the normal geometry flags for Crop.
%
% Image *CropImageToTiles(const Image *image,
% const RectangleInfo *crop_geometry, ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double ConstrainPixelOffset(double x)
{
if (x < (double) -(SSIZE_MAX-512))
return((double) -(SSIZE_MAX-512));
if (x > (double) (SSIZE_MAX-512))
return((double) (SSIZE_MAX-512));
return(x);
}
static inline ssize_t PixelRoundOffset(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return((ssize_t) floor(ConstrainPixelOffset(x)));
return((ssize_t) ceil(ConstrainPixelOffset(x)));
}
MagickExport Image *CropImageToTiles(const Image *image,
const char *crop_geometry,ExceptionInfo *exception)
{
Image
*next,
*crop_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
crop_image=NewImageList();
next=NewImageList();
flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception);
if ((flags & AreaValue) != 0)
{
PointInfo
delta,
offset;
RectangleInfo
crop;
size_t
height,
width;
/*
Crop into NxM tiles (@ flag).
*/
width=image->columns;
height=image->rows;
if (geometry.width == 0)
geometry.width=1;
if (geometry.height == 0)
geometry.height=1;
if ((flags & AspectValue) == 0)
{
width-=(geometry.x < 0 ? -1 : 1)*geometry.x;
height-=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
else
{
width+=(geometry.x < 0 ? -1 : 1)*geometry.x;
height+=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
delta.x=(double) width/geometry.width;
delta.y=(double) height/geometry.height;
if (delta.x < 1.0)
delta.x=1.0;
if (delta.y < 1.0)
delta.y=1.0;
for (offset.y=0; offset.y < (double) height; )
{
if ((flags & AspectValue) == 0)
{
crop.y=PixelRoundOffset((MagickRealType) (offset.y-
(geometry.y > 0 ? 0 : geometry.y)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) PixelRoundOffset((MagickRealType) (offset.y+
(geometry.y < 0 ? 0 : geometry.y)));
}
else
{
crop.y=PixelRoundOffset((MagickRealType) (offset.y-
(geometry.y > 0 ? geometry.y : 0)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) PixelRoundOffset((MagickRealType) (offset.y+
(geometry.y < 0 ? geometry.y : 0)));
}
crop.height-=crop.y;
crop.y+=image->page.y;
for (offset.x=0; offset.x < (double) width; )
{
if ((flags & AspectValue) == 0)
{
crop.x=PixelRoundOffset((MagickRealType) (offset.x-
(geometry.x > 0 ? 0 : geometry.x)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) PixelRoundOffset((MagickRealType) (offset.x+
(geometry.x < 0 ? 0 : geometry.x)));
}
else
{
crop.x=PixelRoundOffset((MagickRealType) (offset.x-
(geometry.x > 0 ? geometry.x : 0)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) PixelRoundOffset((MagickRealType) (offset.x+
(geometry.x < 0 ? geometry.x : 0)));
}
crop.width-=crop.x;
crop.x+=image->page.x;
next=CropImage(image,&crop,exception);
if (next != (Image *) NULL)
AppendImageToList(&crop_image,next);
}
}
ClearMagickException(exception);
return(crop_image);
}
if (((geometry.width == 0) && (geometry.height == 0)) ||
((flags & XValue) != 0) || ((flags & YValue) != 0))
{
/*
Crop a single region at +X+Y.
*/
crop_image=CropImage(image,&geometry,exception);
if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0))
{
crop_image->page.width=geometry.width;
crop_image->page.height=geometry.height;
crop_image->page.x-=geometry.x;
crop_image->page.y-=geometry.y;
}
return(crop_image);
}
if ((image->columns > geometry.width) || (image->rows > geometry.height))
{
RectangleInfo
page;
size_t
height,
width;
ssize_t
x,
y;
/*
Crop into tiles of fixed size WxH.
*/
page=image->page;
if (page.width == 0)
page.width=image->columns;
if (page.height == 0)
page.height=image->rows;
width=geometry.width;
if (width == 0)
width=page.width;
height=geometry.height;
if (height == 0)
height=page.height;
next=NewImageList();
for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height)
{
for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width)
{
geometry.width=width;
geometry.height=height;
geometry.x=x;
geometry.y=y;
next=CropImage(image,&geometry,exception);
if (next == (Image *) NULL)
break;
AppendImageToList(&crop_image,next);
}
if (next == (Image *) NULL)
break;
}
return(crop_image);
}
return(CloneImage(image,0,0,MagickTrue,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x c e r p t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExcerptImage() returns a excerpt of the image as defined by the geometry.
%
% The format of the ExcerptImage method is:
%
% Image *ExcerptImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExcerptImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define ExcerptImageTag "Excerpt/Image"
CacheView
*excerpt_view,
*image_view;
Image
*excerpt_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate excerpt image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
excerpt_image=CloneImage(image,geometry->width,geometry->height,MagickTrue,
exception);
if (excerpt_image == (Image *) NULL)
return((Image *) NULL);
/*
Excerpt each row.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
excerpt_view=AcquireAuthenticCacheView(excerpt_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,excerpt_image,excerpt_image->rows,1)
#endif
for (y=0; y < (ssize_t) excerpt_image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict excerpt_indexes,
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,geometry->x,geometry->y+y,
geometry->width,1,exception);
q=GetCacheViewAuthenticPixels(excerpt_view,0,y,excerpt_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
(void) memcpy(q,p,(size_t) excerpt_image->columns*sizeof(*q));
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if (indexes != (IndexPacket *) NULL)
{
excerpt_indexes=GetCacheViewAuthenticIndexQueue(excerpt_view);
if (excerpt_indexes != (IndexPacket *) NULL)
(void) memcpy(excerpt_indexes,indexes,(size_t)
excerpt_image->columns*sizeof(*excerpt_indexes));
}
if (SyncCacheViewAuthenticPixels(excerpt_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ExcerptImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
excerpt_view=DestroyCacheView(excerpt_view);
image_view=DestroyCacheView(image_view);
excerpt_image->type=image->type;
if (status == MagickFalse)
excerpt_image=DestroyImage(excerpt_image);
return(excerpt_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x t e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExtentImage() extends the image as defined by the geometry, gravity, and
% image background color. Set the (x,y) offset of the geometry to move the
% original image relative to the extended image.
%
% The format of the ExtentImage method is:
%
% Image *ExtentImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExtentImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
Image
*extent_image;
MagickBooleanType
status;
/*
Allocate extent image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
extent_image=CloneImage(image,geometry->width,geometry->height,MagickTrue,
exception);
if (extent_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageBackgroundColor(extent_image);
if (status == MagickFalse)
{
InheritException(exception,&extent_image->exception);
extent_image=DestroyImage(extent_image);
return((Image *) NULL);
}
status=CompositeImage(extent_image,image->compose,image,-geometry->x,
-geometry->y);
if (status == MagickFalse)
{
InheritException(exception,&extent_image->exception);
extent_image=DestroyImage(extent_image);
return((Image *) NULL);
}
return(extent_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l i p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FlipImage() creates a vertical mirror image by reflecting the pixels
% around the central x-axis.
%
% The format of the FlipImage method is:
%
% Image *FlipImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FlipImage(const Image *image,ExceptionInfo *exception)
{
#define FlipImageTag "Flip/Image"
CacheView
*flip_view,
*image_view;
Image
*flip_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
flip_image=CloneImage(image,0,0,MagickTrue,exception);
if (flip_image == (Image *) NULL)
return((Image *) NULL);
/*
Flip image.
*/
status=MagickTrue;
progress=0;
page=image->page;
image_view=AcquireVirtualCacheView(image,exception);
flip_view=AcquireAuthenticCacheView(flip_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,flip_image,flip_image->rows,1)
#endif
for (y=0; y < (ssize_t) flip_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict flip_indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(flip_view,0,(ssize_t) (flip_image->rows-y-
1),flip_image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
(void) memcpy(q,p,(size_t) image->columns*sizeof(*q));
indexes=GetCacheViewVirtualIndexQueue(image_view);
if (indexes != (const IndexPacket *) NULL)
{
flip_indexes=GetCacheViewAuthenticIndexQueue(flip_view);
if (flip_indexes != (IndexPacket *) NULL)
(void) memcpy(flip_indexes,indexes,(size_t) image->columns*
sizeof(*flip_indexes));
}
if (SyncCacheViewAuthenticPixels(flip_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,FlipImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flip_view=DestroyCacheView(flip_view);
image_view=DestroyCacheView(image_view);
flip_image->type=image->type;
if (page.height != 0)
page.y=(ssize_t) (page.height-flip_image->rows-page.y);
flip_image->page=page;
if (status == MagickFalse)
flip_image=DestroyImage(flip_image);
return(flip_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FlopImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis.
%
% The format of the FlopImage method is:
%
% Image *FlopImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FlopImage(const Image *image,ExceptionInfo *exception)
{
#define FlopImageTag "Flop/Image"
CacheView
*flop_view,
*image_view;
Image
*flop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
flop_image=CloneImage(image,0,0,MagickTrue,exception);
if (flop_image == (Image *) NULL)
return((Image *) NULL);
/*
Flop each row.
*/
status=MagickTrue;
progress=0;
page=image->page;
image_view=AcquireVirtualCacheView(image,exception);
flop_view=AcquireAuthenticCacheView(flop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,flop_image,flop_image->rows,1)
#endif
for (y=0; y < (ssize_t) flop_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict flop_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(flop_view,0,y,flop_image->columns,1,
exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
q+=flop_image->columns;
indexes=GetCacheViewVirtualIndexQueue(image_view);
flop_indexes=GetCacheViewAuthenticIndexQueue(flop_view);
for (x=0; x < (ssize_t) flop_image->columns; x++)
{
(*--q)=(*p++);
if ((indexes != (const IndexPacket *) NULL) &&
(flop_indexes != (IndexPacket *) NULL))
SetPixelIndex(flop_indexes+flop_image->columns-x-1,
GetPixelIndex(indexes+x));
}
if (SyncCacheViewAuthenticPixels(flop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,FlopImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flop_view=DestroyCacheView(flop_view);
image_view=DestroyCacheView(image_view);
flop_image->type=image->type;
if (page.width != 0)
page.x=(ssize_t) (page.width-flop_image->columns-page.x);
flop_image->page=page;
if (status == MagickFalse)
flop_image=DestroyImage(flop_image);
return(flop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R o l l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RollImage() offsets an image as defined by x_offset and y_offset.
%
% The format of the RollImage method is:
%
% Image *RollImage(const Image *image,const ssize_t x_offset,
% const ssize_t y_offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x_offset: the number of columns to roll in the horizontal direction.
%
% o y_offset: the number of rows to roll in the vertical direction.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType CopyImageRegion(Image *destination,const Image *source, const size_t columns,const size_t rows,const ssize_t sx,const ssize_t sy,
const ssize_t dx,const ssize_t dy,ExceptionInfo *exception)
{
CacheView
*source_view,
*destination_view;
MagickBooleanType
status;
ssize_t
y;
if (columns == 0)
return(MagickTrue);
status=MagickTrue;
source_view=AcquireVirtualCacheView(source,exception);
destination_view=AcquireAuthenticCacheView(destination,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(source,destination,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict destination_indexes;
register PixelPacket
*magick_restrict q;
/*
Transfer scanline.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,sx,sy+y,columns,1,exception);
q=GetCacheViewAuthenticPixels(destination_view,dx,dy+y,columns,1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(source_view);
(void) memcpy(q,p,(size_t) columns*sizeof(*p));
if (indexes != (IndexPacket *) NULL)
{
destination_indexes=GetCacheViewAuthenticIndexQueue(destination_view);
if (destination_indexes != (IndexPacket *) NULL)
(void) memcpy(destination_indexes,indexes,(size_t)
columns*sizeof(*indexes));
}
sync=SyncCacheViewAuthenticPixels(destination_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
destination_view=DestroyCacheView(destination_view);
source_view=DestroyCacheView(source_view);
return(status);
}
MagickExport Image *RollImage(const Image *image,const ssize_t x_offset,
const ssize_t y_offset,ExceptionInfo *exception)
{
#define RollImageTag "Roll/Image"
Image
*roll_image;
MagickStatusType
status;
RectangleInfo
offset;
/*
Initialize roll image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
roll_image=CloneImage(image,0,0,MagickTrue,exception);
if (roll_image == (Image *) NULL)
return((Image *) NULL);
offset.x=x_offset;
offset.y=y_offset;
while (offset.x < 0)
offset.x+=(ssize_t) image->columns;
while (offset.x >= (ssize_t) image->columns)
offset.x-=(ssize_t) image->columns;
while (offset.y < 0)
offset.y+=(ssize_t) image->rows;
while (offset.y >= (ssize_t) image->rows)
offset.y-=(ssize_t) image->rows;
/*
Roll image.
*/
status=CopyImageRegion(roll_image,image,(size_t) offset.x,
(size_t) offset.y,(ssize_t) image->columns-offset.x,(ssize_t) image->rows-
offset.y,0,0,exception);
(void) SetImageProgress(image,RollImageTag,0,3);
status&=CopyImageRegion(roll_image,image,image->columns-offset.x,
(size_t) offset.y,0,(ssize_t) image->rows-offset.y,offset.x,0,
exception);
(void) SetImageProgress(image,RollImageTag,1,3);
status&=CopyImageRegion(roll_image,image,(size_t) offset.x,image->rows-
offset.y,(ssize_t) image->columns-offset.x,0,0,offset.y,exception);
(void) SetImageProgress(image,RollImageTag,2,3);
status&=CopyImageRegion(roll_image,image,image->columns-offset.x,image->rows-
offset.y,0,0,offset.x,offset.y,exception);
(void) SetImageProgress(image,RollImageTag,3,3);
roll_image->type=image->type;
if (status == MagickFalse)
roll_image=DestroyImage(roll_image);
return(roll_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShaveImage() shaves pixels from the image edges. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the ShaveImage method is:
%
% Image *ShaveImage(const Image *image,const RectangleInfo *shave_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o shave_image: Method ShaveImage returns a pointer to the shaved
% image. A null image is returned if there is a memory shortage or
% if the image width or height is zero.
%
% o image: the image.
%
% o shave_info: Specifies a pointer to a RectangleInfo which defines the
% region of the image to crop.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShaveImage(const Image *image,
const RectangleInfo *shave_info,ExceptionInfo *exception)
{
Image
*shave_image;
RectangleInfo
geometry;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (((2*shave_info->width) >= image->columns) ||
((2*shave_info->height) >= image->rows))
ThrowImageException(OptionWarning,"GeometryDoesNotContainImage");
SetGeometry(image,&geometry);
geometry.width-=2*shave_info->width;
geometry.height-=2*shave_info->height;
geometry.x=(ssize_t) shave_info->width+image->page.x;
geometry.y=(ssize_t) shave_info->height+image->page.y;
shave_image=CropImage(image,&geometry,exception);
if (shave_image == (Image *) NULL)
return((Image *) NULL);
shave_image->page.width-=2*shave_info->width;
shave_image->page.height-=2*shave_info->height;
shave_image->page.x-=(ssize_t) shave_info->width;
shave_image->page.y-=(ssize_t) shave_info->height;
return(shave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S p l i c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SpliceImage() splices a solid color into the image as defined by the
% geometry.
%
% The format of the SpliceImage method is:
%
% Image *SpliceImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to splice with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SpliceImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define SpliceImageTag "Splice/Image"
CacheView
*image_view,
*splice_view;
Image
*splice_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
splice_geometry;
ssize_t
columns,
y;
/*
Allocate splice image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
splice_geometry=(*geometry);
splice_image=CloneImage(image,image->columns+splice_geometry.width,
image->rows+splice_geometry.height,MagickTrue,exception);
if (splice_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(splice_image,DirectClass) == MagickFalse)
{
InheritException(exception,&splice_image->exception);
splice_image=DestroyImage(splice_image);
return((Image *) NULL);
}
(void) SetImageBackgroundColor(splice_image);
/*
Respect image geometry.
*/
switch (image->gravity)
{
default:
case UndefinedGravity:
case NorthWestGravity:
break;
case NorthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
break;
}
case NorthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
break;
}
case WestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.width/2;
break;
}
case StaticGravity:
case CenterGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case EastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case SouthWestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
}
/*
Splice image.
*/
status=MagickTrue;
progress=0;
columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
splice_view=AcquireAuthenticCacheView(splice_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,splice_image,splice_geometry.y,1)
#endif
for (y=0; y < (ssize_t) splice_geometry.y; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict indexes,
*magick_restrict splice_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
splice_indexes=GetCacheViewAuthenticIndexQueue(splice_view);
for (x=0; x < columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes));
indexes++;
p++;
q++;
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q++;
for ( ; x < (ssize_t) splice_image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes));
indexes++;
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SpliceImageTag,progress,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,splice_image,splice_image->rows,1)
#endif
for (y=(ssize_t) (splice_geometry.y+splice_geometry.height);
y < (ssize_t) splice_image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict indexes,
*magick_restrict splice_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
if ((y < 0) || (y >= (ssize_t)splice_image->rows))
continue;
p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,
splice_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
splice_indexes=GetCacheViewAuthenticIndexQueue(splice_view);
for (x=0; x < columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes));
indexes++;
p++;
q++;
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q++;
for ( ; x < (ssize_t) splice_image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes));
indexes++;
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SpliceImageTag,progress,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
splice_view=DestroyCacheView(splice_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
splice_image=DestroyImage(splice_image);
return(splice_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImage() is a convenience method that behaves like ResizeImage() or
% CropImage() but accepts scaling and/or cropping information as a region
% geometry specification. If the operation fails, the original image handle
% is left as is.
%
% This should only be used for single images.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImage(Image **image,const char *crop_geometry,
% const char *image_geometry)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
*/
/*
DANGER: This function destroys what it assumes to be a single image list.
If the input image is part of a larger list, all other images in that list
will be simply 'lost', not destroyed.
Also if the crop generates a list of images only the first image is resized.
And finally if the crop succeeds and the resize failed, you will get a
cropped image, as well as a 'false' or 'failed' report.
This function and should probably be deprecated in favor of direct calls
to CropImageToTiles() or ResizeImage(), as appropriate.
*/
MagickExport MagickBooleanType TransformImage(Image **image,
const char *crop_geometry,const char *image_geometry)
{
Image
*resize_image,
*transform_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image **) NULL);
assert((*image)->signature == MagickCoreSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
transform_image=(*image);
if (crop_geometry != (const char *) NULL)
{
Image
*crop_image;
/*
Crop image to a user specified size.
*/
crop_image=CropImageToTiles(*image,crop_geometry,&(*image)->exception);
if (crop_image == (Image *) NULL)
transform_image=CloneImage(*image,0,0,MagickTrue,&(*image)->exception);
else
{
transform_image=DestroyImage(transform_image);
transform_image=GetFirstImageInList(crop_image);
}
*image=transform_image;
}
if (image_geometry == (const char *) NULL)
return(MagickTrue);
/*
Scale image to a user specified size.
*/
flags=ParseRegionGeometry(transform_image,image_geometry,&geometry,
&(*image)->exception);
(void) flags;
if ((transform_image->columns == geometry.width) &&
(transform_image->rows == geometry.height))
return(MagickTrue);
resize_image=ResizeImage(transform_image,geometry.width,geometry.height,
transform_image->filter,transform_image->blur,&(*image)->exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
transform_image=DestroyImage(transform_image);
transform_image=resize_image;
*image=transform_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImages() calls TransformImage() on each image of a sequence.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImages(Image **image,
% const char *crop_geometry,const char *image_geometry)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
*/
MagickExport MagickBooleanType TransformImages(Image **images,
const char *crop_geometry,const char *image_geometry)
{
Image
*image,
**image_list,
*transform_images;
MagickStatusType
status;
register ssize_t
i;
assert(images != (Image **) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
image_list=ImageListToArray(*images,&(*images)->exception);
if (image_list == (Image **) NULL)
return(MagickFalse);
status=MagickTrue;
transform_images=NewImageList();
for (i=0; image_list[i] != (Image *) NULL; i++)
{
image=image_list[i];
status&=TransformImage(&image,crop_geometry,image_geometry);
AppendImageToList(&transform_images,image);
}
*images=transform_images;
image_list=(Image **) RelinquishMagickMemory(image_list);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p o s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransposeImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis while rotating them by 90 degrees.
%
% The format of the TransposeImage method is:
%
% Image *TransposeImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TransposeImage(const Image *image,ExceptionInfo *exception)
{
#define TransposeImageTag "Transpose/Image"
CacheView
*image_view,
*transpose_view;
Image
*transpose_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
transpose_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transpose_image == (Image *) NULL)
return((Image *) NULL);
/*
Transpose image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transpose_view=AcquireAuthenticCacheView(transpose_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,transpose_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict transpose_indexes,
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-y-1,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transpose_view,(ssize_t) (image->rows-y-1),
0,1,transpose_image->rows,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
(void) memcpy(q,p,(size_t) image->columns*sizeof(*q));
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if (indexes != (IndexPacket *) NULL)
{
transpose_indexes=GetCacheViewAuthenticIndexQueue(transpose_view);
if (transpose_indexes != (IndexPacket *) NULL)
(void) memcpy(transpose_indexes,indexes,(size_t)
image->columns*sizeof(*transpose_indexes));
}
if (SyncCacheViewAuthenticPixels(transpose_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TransposeImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transpose_view=DestroyCacheView(transpose_view);
image_view=DestroyCacheView(image_view);
transpose_image->type=image->type;
page=transpose_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
transpose_image->page=page;
if (status == MagickFalse)
transpose_image=DestroyImage(transpose_image);
return(transpose_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s v e r s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransverseImage() creates a vertical mirror image by reflecting the pixels
% around the central x-axis while rotating them by 270 degrees.
%
% The format of the TransverseImage method is:
%
% Image *TransverseImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TransverseImage(const Image *image,ExceptionInfo *exception)
{
#define TransverseImageTag "Transverse/Image"
CacheView
*image_view,
*transverse_view;
Image
*transverse_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
transverse_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transverse_image == (Image *) NULL)
return((Image *) NULL);
/*
Transverse image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transverse_view=AcquireAuthenticCacheView(transverse_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,transverse_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict transverse_indexes,
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transverse_view,(ssize_t) (image->rows-y-
1),0,1,transverse_image->rows,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
q+=image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
*--q=(*p++);
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if (indexes != (IndexPacket *) NULL)
{
transverse_indexes=GetCacheViewAuthenticIndexQueue(transverse_view);
if (transverse_indexes != (IndexPacket *) NULL)
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(transverse_indexes+image->columns-x-1,
GetPixelIndex(indexes+x));
}
sync=SyncCacheViewAuthenticPixels(transverse_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TransverseImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transverse_view=DestroyCacheView(transverse_view);
image_view=DestroyCacheView(image_view);
transverse_image->type=image->type;
page=transverse_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
if (page.width != 0)
page.x=(ssize_t) (page.width-transverse_image->columns-page.x);
if (page.height != 0)
page.y=(ssize_t) (page.height-transverse_image->rows-page.y);
transverse_image->page=page;
if (status == MagickFalse)
transverse_image=DestroyImage(transverse_image);
return(transverse_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r i m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TrimImage() trims pixels from the image edges. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the TrimImage method is:
%
% Image *TrimImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TrimImage(const Image *image,ExceptionInfo *exception)
{
RectangleInfo
geometry;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
geometry=GetImageBoundingBox(image,exception);
if ((geometry.width == 0) || (geometry.height == 0))
{
Image
*crop_image;
crop_image=CloneImage(image,1,1,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->background_color.opacity=(Quantum) TransparentOpacity;
(void) SetImageBackgroundColor(crop_image);
crop_image->page=image->page;
crop_image->page.x=(-1);
crop_image->page.y=(-1);
return(crop_image);
}
geometry.x+=image->page.x;
geometry.y+=image->page.y;
return(CropImage(image,&geometry,exception));
}
|
GB_unaryop__lnot_uint64_fp32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_uint64_fp32
// op(A') function: GB_tran__lnot_uint64_fp32
// C type: uint64_t
// A type: float
// cast: uint64_t cij ; GB_CAST_UNSIGNED(cij,aij,64)
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
float
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
uint64_t z ; GB_CAST_UNSIGNED(z,x,64) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_UINT64 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_uint64_fp32
(
uint64_t *restrict Cx,
const float *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_uint64_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
pmv-OpenMP-a_atcgrid.c | #include <stdlib.h> // biblioteca con funciones atoi(), malloc() y free()
#include <stdio.h> // biblioteca donde se encuentra la función printf()
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_set_dynamic(0);
#define omp_set_num_threads(12);
#endif
int main(int argc, char ** argv){
int **M;
int *v1, *v2;
int i, k, N;
double cgt1, cgt2, ncgt; //para tiempo de ejecución
time_t t;
// Semilla de rand()
srand((unsigned) time(&t));
// Obtenemos el numero de filas x columnas de la matriz cuadrada
if(argc < 2){
fprintf(stderr,"Falta iteraciones\n");
exit(-1);
}
N = atoi(argv[1]);
// == Reserva de Memoria
// ====================================================>
v1 = (int *) malloc(N*sizeof(int));
v2 = (int *) malloc(N*sizeof(int));
if ( v1 == NULL || v2 == NULL ){
printf("Error en la reserva de espacio para los vectores\n");
exit(-2);
}
M = (int**) malloc (N*sizeof(int*));
// i como private en un for establece que cada hebra tendra una copia de i, pero en parallel for tendra cada una i como sigue
// i = 0, i = 3, i = 6 para un bucle de N = 9
#pragma omp parallel for shared(M,N) private(i) default(none)
for(i = 0; i<N; i++){
M[i] = (int*) malloc (N*sizeof(int));
if( M[i] == NULL ){
printf("Error en la reserva de espacio para los vectores\n");
exit(-2);
}
}
// == Inicializacion
// ====================================================>
// M, v1, v2, N, i compartidas
// Cada hebra se encargará de una parte del bucle usando i
// k es privada
// Para que cada hebra que este calculando la parte iesima del bucle y tenga una copia de k = 0 propia, parte k es secuencial
#pragma omp parallel for shared(N,M) private(i,k) default(none)
for(i = 0; i<N; i++){
for(k = 0; k<N; k++)
M[i][k] = rand() % 8;
}
#pragma omp parallel for shared(v1,v2,N) private(i) default(none)
for(i = 0; i<N; i++){
v1[i] = rand() % 6;
v2[i] = 0;
}
// == Calculo
// ====================================================>
cgt1 = omp_get_wtime();
#pragma omp parallel for shared(v1,v2,M,N) private(i,k) default(none)
for(i = 0; i<N; i++){
for(k = 0; k<N; k++)
v2[i] += M[i][k] * v1[k];
}
cgt2 = omp_get_wtime();
ncgt = (double)(cgt2 - cgt1);
// == Imprimir Mensajes
// ====================================================>
printf("Tiempo(seg.):%11.9f\n", ncgt);
printf("Tamaño de los vectores: %u\n", N);
printf("\tv1 = %uElem -> %lu bytes\n\tv2 = %uElem -> %lu bytes\n", N, N*sizeof(int), N, N*sizeof(int));
printf("Tamaño de la matriz: %ux%u -> %lu bytes\n", N, N, N*N*sizeof(int));
// Imprimir el primer y último componente del resultado evita que las optimizaciones del compilador
// eliminen el código de la suma.
printf("v2[0] = %u ... v2[N-1] = %u \n", v2[0], v2[N-1]);
// Para tamaños pequeños de N < 15 mostrar los valores calculados
if(N < 15){
printf("\n----------- Matriz M ----------- \n");
for(i = 0; i<N; i++){
for(k = 0; k<N; k++)
printf("%u\t", M[i][k]);
printf("\n");
}
printf("\n----------- Vector V1 ----------- \n");
for(i = 0; i<N; i++)
printf("%u\t", v1[i]);
printf("\n");
printf("\n----------- Vector V2----------- \n");
for(i = 0; i<N; i++)
printf("%u\t", v2[i]);
printf("\n");
}
// == Liberar Memoria
// ====================================================>
free(v1);
free(v2);
#pragma omp parallel for shared(M,N) private(i) default(none)
for(i = 0; i<N; i++)
free(M[i]);
free(M);
} |
sink-2.c | /* { dg-do compile } */
void bar (int *);
void
foo ()
{
int i,j;
#pragma omp parallel for ordered(1)
for (i=0; i < 100; ++i)
{
#pragma omp ordered depend(sink:i-1)
bar(&i);
#pragma omp ordered depend(source)
}
}
|
GB_binop__lor_uint8.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__lor_uint8
// A.*B function (eWiseMult): GB_AemultB__lor_uint8
// A*D function (colscale): GB_AxD__lor_uint8
// D*A function (rowscale): GB_DxB__lor_uint8
// C+=B function (dense accum): GB_Cdense_accumB__lor_uint8
// C+=b function (dense accum): GB_Cdense_accumb__lor_uint8
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lor_uint8
// C=scalar+B GB_bind1st__lor_uint8
// C=scalar+B' GB_bind1st_tran__lor_uint8
// C=A+scalar GB_bind2nd__lor_uint8
// C=A'+scalar GB_bind2nd_tran__lor_uint8
// C type: uint8_t
// A type: uint8_t
// B,b type: uint8_t
// BinaryOp: cij = ((aij != 0) || (bij != 0))
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_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) \
uint8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint8_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint8_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 != 0) || (y != 0)) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LOR || GxB_NO_UINT8 || GxB_NO_LOR_UINT8)
//------------------------------------------------------------------------------
// 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__lor_uint8
(
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__lor_uint8
(
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__lor_uint8
(
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 uint8_t
uint8_t bwork = (*((uint8_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__lor_uint8
(
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
uint8_t *GB_RESTRICT Cx = (uint8_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__lor_uint8
(
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
uint8_t *GB_RESTRICT Cx = (uint8_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__lor_uint8
(
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__lor_uint8
(
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__lor_uint8
(
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
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_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 ;
uint8_t bij = Bx [p] ;
Cx [p] = ((x != 0) || (bij != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__lor_uint8
(
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 ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = Ax [p] ;
Cx [p] = ((aij != 0) || (y != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = ((x != 0) || (aij != 0)) ; \
}
GrB_Info GB_bind1st_tran__lor_uint8
(
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 \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_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) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = ((aij != 0) || (y != 0)) ; \
}
GrB_Info GB_bind2nd_tran__lor_uint8
(
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
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#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/Attr.h"
#include "clang/AST/Availability.h"
#include "clang/AST/ComparisonCategories.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/LocInfoType.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/TypeLoc.h"
#include "clang/APINotes/APINotesManager.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/PragmaKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/CleanupInfo.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
struct InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class ParsedAttr;
class BindingDecl;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class CoroutineBodyStmt;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPRequiresDecl;
class OMPDeclareReductionDecl;
class OMPDeclareSimdDecl;
class OMPClause;
struct OMPVarListLocTy;
struct OverloadCandidate;
enum class OverloadCandidateParamOrder : char;
enum OverloadCandidateRewriteKind : unsigned;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateInstantiationCallback;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class Capture;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class SemaPPCallbacks;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// The end location for the first pointer declarator in the file. Used for
/// placing fix-its.
SourceLocation PointerEndLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
/// Keeps track of expected type during expression parsing. The type is tied to
/// a particular token, all functions that update or consume the type take a
/// start location of the token they are looking at as a parameter. This allows
/// to avoid updating the type on hot paths in the parser.
class PreferredTypeBuilder {
public:
PreferredTypeBuilder() = default;
explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
void enterCondition(Sema &S, SourceLocation Tok);
void enterReturn(Sema &S, SourceLocation Tok);
void enterVariableInit(SourceLocation Tok, Decl *D);
/// Computing a type for the function argument may require running
/// overloading, so we postpone its computation until it is actually needed.
///
/// Clients should be very careful when using this funciton, as it stores a
/// function_ref, clients should make sure all calls to get() with the same
/// location happen while function_ref is alive.
void enterFunctionArgument(SourceLocation Tok,
llvm::function_ref<QualType()> ComputeType);
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
SourceLocation OpLoc);
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
/// Handles all type casts, including C-style cast, C++ casts, etc.
void enterTypeCast(SourceLocation Tok, QualType CastType);
QualType get(SourceLocation Tok) const {
if (Tok != ExpectedLoc)
return QualType();
if (!Type.isNull())
return Type;
if (ComputeType)
return ComputeType();
return QualType();
}
private:
/// Start position of a token for which we store expected type.
SourceLocation ExpectedLoc;
/// Expected type for a token starting at ExpectedLoc.
QualType Type;
/// A function to compute expected type at ExpectedLoc. It is only considered
/// if Type is null.
llvm::function_ref<QualType()> ComputeType;
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema {
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:
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions FPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
api_notes::APINotesManager APINotes;
/// Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
/// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
/// `TransformTypos` in order to keep track of any TypoExprs that are created
/// recursively during typo correction and wipe them away if the correction
/// fails.
llvm::SmallVector<TypoExpr *, 2> TypoExprs;
/// pragma clang section kind
enum PragmaClangSectionKind {
PCSK_Invalid = 0,
PCSK_BSS = 1,
PCSK_Data = 2,
PCSK_Rodata = 3,
PCSK_Text = 4,
PCSK_Relro = 5
};
enum PragmaClangSectionAction {
PCSA_Set = 0,
PCSA_Clear = 1
};
struct PragmaClangSection {
std::string SectionName;
bool Valid = false;
SourceLocation PragmaLocation;
void Act(SourceLocation PragmaLocation,
PragmaClangSectionAction Action,
StringLiteral* Name);
};
PragmaClangSection PragmaClangBSSSection;
PragmaClangSection PragmaClangDataSection;
PragmaClangSection PragmaClangRodataSection;
PragmaClangSection PragmaClangRelroSection;
PragmaClangSection PragmaClangTextSection;
enum PragmaMsStackAction {
PSK_Reset = 0x0, // #pragma ()
PSK_Set = 0x1, // #pragma (value)
PSK_Push = 0x2, // #pragma (push[, id])
PSK_Pop = 0x4, // #pragma (pop[, id])
PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
};
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
SourceLocation PragmaPushLocation;
Slot(llvm::StringRef StackSlotLabel, ValueType Value,
SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation),
PragmaPushLocation(PragmaPushLocation) {}
};
void Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
ValueType Value);
// MSVC seems to add artificial slots to #pragma stacks on entering a C++
// method body to restore the stacks on exit, so it works like this:
//
// struct S {
// #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
// void Method {}
// #pragma <name>(pop, InternalPragmaSlot)
// };
//
// It works even with #pragma vtordisp, although MSVC doesn't support
// #pragma vtordisp(push [, id], n)
// syntax.
//
// Push / pop a named sentinel slot.
void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
assert((Action == PSK_Push || Action == PSK_Pop) &&
"Can only push / pop #pragma stack sentinels!");
Act(CurrentPragmaLocation, Action, Label, CurrentValue);
}
// Constructors.
explicit PragmaStack(const ValueType &Default)
: DefaultValue(Default), CurrentValue(Default) {}
bool hasValue() const { return CurrentValue != DefaultValue; }
SmallVector<Slot, 2> Stack;
ValueType DefaultValue; // Value used for PSK_Reset action.
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
/// Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
// #pragma pack.
// Sentinel to represent when the stack is set to mac68k alignment.
static const unsigned kMac68kAlignmentSentinel = ~0U;
PragmaStack<unsigned> PackStack;
// The current #pragma pack values and locations at each #include.
struct PackIncludeState {
unsigned CurrentValue;
SourceLocation CurrentPragmaLocation;
bool HasNonDefaultValue, ShouldWarnOnInclude;
};
SmallVector<PackIncludeState, 8> PackIncludeStack;
// Segment #pragmas.
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
// RAII object to push / pop sentinel slots for all MS #pragma stacks.
// Actions should be performed only if we enter / exit a C++ method body.
class PragmaStackSentinelRAII {
public:
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
~PragmaStackSentinelRAII();
private:
Sema &S;
StringRef SlotLabel;
bool ShouldAct;
};
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// This an attribute introduced by \#pragma clang attribute.
struct PragmaAttributeEntry {
SourceLocation Loc;
ParsedAttr *Attribute;
SmallVector<attr::SubjectMatchRule, 4> MatchRules;
bool IsUsed;
};
/// A push'd group of PragmaAttributeEntries.
struct PragmaAttributeGroup {
/// The location of the push attribute.
SourceLocation Loc;
/// The namespace of this push group.
const IdentifierInfo *Namespace;
SmallVector<PragmaAttributeEntry, 2> Entries;
};
SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
/// The declaration that is currently receiving an attribute from the
/// #pragma attribute stack.
const Decl *PragmaAttributeCurrentTargetDecl;
/// This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// Used to control the generation of ExprWithCleanups.
CleanupInfo Cleanup;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression. The
/// element type here is ExprWithCleanups::Object.
SmallVector<BlockDecl*, 8> ExprCleanupObjects;
/// Store a set of either DeclRefExprs or MemberExprs that contain a reference
/// to a variable (constant) that may or may not be odr-used in this Expr, and
/// we won't know until all lvalue-to-rvalue and discarded value conversions
/// have been applied to all subexpressions of the enclosing full expression.
/// This is cleared at the end of each full expression.
using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
MaybeODRUseExprSet MaybeODRUseExprs;
std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
/// Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
/// Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedOverridingExceptionSpecChecks;
/// All the function redeclarations seen during a class definition that had
/// their exception spec checks delayed, plus the prior declaration they
/// should be checked against. Except during error recovery, the new decl
/// should always be a friend declaration, as that's the only valid way to
/// redeclare a special member before its class is complete.
SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
DelayedEquivalentExceptionSpecChecks;
typedef llvm::MapVector<const FunctionDecl *,
std::unique_ptr<LateParsedTemplate>>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
/// \brief Callback to the parser to parse a type expressed as a string.
std::function<TypeResult(StringRef, StringRef, SourceLocation)>
ParseTypeFromStringCallback;
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// Used to change context to isConstantEvaluated without pushing a heavy
/// ExpressionEvaluationContextRecord object.
bool isConstantEvaluatedOverride;
bool isConstantEvaluated() {
return ExprEvalContexts.back().isConstantEvaluated() ||
isConstantEvaluatedOverride;
}
/// RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
bool PushedCodeSynthesisContext = false;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC) {
S.PushFunctionScope();
S.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
if (auto *FD = dyn_cast<FunctionDecl>(DC))
FD->setWillHaveBody(true);
else
assert(isa<ObjCMethodDecl>(DC));
}
void addContextNote(SourceLocation UseLoc) {
assert(!PushedCodeSynthesisContext);
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
Ctx.PointOfInstantiation = UseLoc;
Ctx.Entity = cast<Decl>(S.CurContext);
S.pushCodeSynthesisContext(Ctx);
PushedCodeSynthesisContext = true;
}
~SynthesizedFunctionScope() {
if (PushedCodeSynthesisContext)
S.popCodeSynthesisContext();
if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
FD->setWillHaveBody(false);
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// The C++ "std::align_val_t" enum class, which is defined by the C++
/// standard library.
LazyDeclPtr StdAlignValT;
/// The C++ "std::experimental" namespace, where the experimental parts
/// of the standard library resides.
NamespaceDecl *StdExperimentalNamespaceCache;
/// The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// The C++ "std::coroutine_traits" template, which is defined in
/// \<coroutine_traits>
ClassTemplateDecl *StdCoroutineTraitsCache;
/// The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// Caches identifiers/selectors for NSFoundation APIs.
std::unique_ptr<NSAPI> NSAPIObj;
/// The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// id<NSCopying> type.
QualType QIDNSCopying;
/// will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum class ExpressionEvaluationContext {
/// The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// The current expression occurs within a braced-init-list within
/// an unevaluated operand. This is mostly like a regular unevaluated
/// context, except that we still instantiate constexpr functions that are
/// referenced here so that we can perform narrowing checks correctly.
UnevaluatedList,
/// The current expression occurs within a discarded statement.
/// This behaves largely similarly to an unevaluated operand in preventing
/// definitions from being required, but not in other ways.
DiscardedStatement,
/// The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
/// Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// The expression evaluation context.
ExpressionEvaluationContext Context;
/// Whether the enclosing context needed a cleanup.
CleanupInfo ParentCleanup;
/// Whether we are in a decltype expression.
bool IsDecltype;
/// The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
MaybeODRUseExprSet SavedMaybeODRUseExprs;
/// The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
/// Expressions appearing as the LHS of a volatile assignment in this
/// context. We produce a warning for these when popping the context if
/// they are not discarded-value expressions nor unevaluated operands.
SmallVector<Expr*, 2> VolatileAssignmentLHSs;
/// \brief Describes whether we are in an expression constext which we have
/// to handle differently.
enum ExpressionKind {
EK_Decltype, EK_TemplateArgument, EK_Other
} ExprContext;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
CleanupInfo ParentCleanup,
Decl *ManglingContextDecl,
ExpressionKind ExprContext)
: Context(Context), ParentCleanup(ParentCleanup),
NumCleanupObjects(NumCleanupObjects), NumTypos(0),
ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
bool isUnevaluated() const {
return Context == ExpressionEvaluationContext::Unevaluated ||
Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
Context == ExpressionEvaluationContext::UnevaluatedList;
}
bool isConstantEvaluated() const {
return Context == ExpressionEvaluationContext::ConstantEvaluated;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// Emit a warning for all pending noderef expressions that we recorded.
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
/// Compute the mangling number context for a lambda expression or
/// block literal. Also return the extra mangling decl if any.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
std::tuple<MangleNumberingContext *, Decl *>
getCurrentMangleNumberContext(const DeclContext *DC);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl *MD)
: Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
class SpecialMemberOverloadResultEntry
: public llvm::FastFoldingSetNode,
public SpecialMemberOverloadResult {
public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
};
/// A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
/// A cache of the flags available in enumerations with the flag_bits
/// attribute.
mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
/// The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
TranslationUnitKind TUKind;
llvm::BumpPtrAllocator BumpAlloc;
/// The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Determine if VD, which must be a variable or function, is an external
/// symbol that nonetheless can't be referenced from outside this translation
/// unit because its type has no linkage and it's not extern "C".
bool isExternalWithNoLinkageType(ValueDecl *VD);
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// List of SourceLocations where 'self' is implicitly retained inside a
/// block.
llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
ImplicitlyRetainedSelfLocs;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
/// Kinds of defaulted comparison operator functions.
enum class DefaultedComparisonKind : unsigned char {
/// This is not a defaultable comparison operator.
None,
/// This is an operator== that should be implemented as a series of
/// subobject comparisons.
Equal,
/// This is an operator<=> that should be implemented as a series of
/// subobject comparisons.
ThreeWay,
/// This is an operator!= that should be implemented as a rewrite in terms
/// of a == comparison.
NotEqual,
/// This is an <, <=, >, or >= that should be implemented as a rewrite in
/// terms of a <=> comparison.
Relational,
};
/// The function definitions which were renamed as part of typo-correction
/// to match their respective declarations. We want to keep track of them
/// to ensure that we don't emit a "redefinition" error if we encounter a
/// correctly named definition after the renamed definition.
llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
/// Stack of types that correspond to the parameter entities that are
/// currently being copy-initialized. Can be empty.
llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
void ReadMethodPool(Selector Sel);
void updateOutOfDateSelector(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the FP_CONTRACT state on entry/exit of compound
/// statements.
class FPContractStateRAII {
public:
FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
private:
Sema& S;
FPOptions OldFPFeaturesState;
};
void addImplicitTypedef(StringRef Name, QualType T);
bool WarnedStackExhausted = false;
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getFPOptions() { return FPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
///Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// Warn that the stack is nearly exhausted.
void warnStackExhausted(SourceLocation Loc);
/// Run some code with "sufficient" stack space. (Currently, at least 256K is
/// guaranteed). Produces a warning if we're low on stack space and allocates
/// more in that case. Use this in code that may recurse deeply (for example,
/// in template instantiation) to avoid stack overflow.
void runWithSufficientStackSpace(SourceLocation Loc,
llvm::function_ref<void()> Fn);
/// Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. SemaDiagnosticBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
// This is a cunning lie. DiagnosticBuilder actually performs move
// construction in its copy constructor (but due to varied uses, it's not
// possible to conveniently express this as actual move construction). So
// the default copy ctor here is fine, because the base class disables the
// source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
// in that case anwyay.
SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and clear the diagnostic builder itself so it
// won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template<typename T>
friend const SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
enum TUFragmentKind {
/// The global module fragment, between 'module;' and a module-declaration.
Global,
/// A normal translation unit fragment. For a non-module unit, this is the
/// entire translation unit. Otherwise, it runs from the module-declaration
/// to the private-module-fragment (if any) or the end of the TU (if not).
Normal,
/// The private module fragment, between 'module :private;' and the end of
/// the translation unit.
Private
};
void ActOnStartOfTranslationUnit();
void ActOnEndOfTranslationUnit();
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD, CapturedRegionKind K,
unsigned OpenMPCaptureLevel = 0);
/// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
/// time after they've been popped.
class PoppedFunctionScopeDeleter {
Sema *Self;
public:
explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
void operator()(sema::FunctionScopeInfo *Scope) const;
};
using PoppedFunctionScopePtr =
std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
PoppedFunctionScopePtr
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
QualType BlockType = QualType());
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const;
void setFunctionHasBranchIntoScope();
void setFunctionHasBranchProtectedScope();
void setFunctionHasIndirectGoto();
void PushCompoundScope(bool IsStmtExpr);
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// Get the innermost lambda enclosing the current location, if any. This
/// looks through intervening non-lambda scopes such as local functions and
/// blocks.
sema::LambdaScopeInfo *getEnclosingLambda() const;
/// Retrieve the current lambda scope info, if any.
/// \param IgnoreNonLambdaCapturingScope true if should find the top-most
/// lambda scope info ignoring all inner capturing scopes that are not
/// lambda scopes.
sema::LambdaScopeInfo *
getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
/// Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
SourceLocation AttrLoc);
/// Same as above, but constructs the AddressSpace index if not provided.
QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
SourceLocation AttrLoc);
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
/// Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
QualType BuildFunctionType(QualType T,
MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI);
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
QualType BuildReadPipeType(QualType T,
SourceLocation Loc);
QualType BuildWritePipeType(QualType T,
SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
/// Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Expr *E);
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const PartialDiagnostic &NoThrowDiagID,
const FunctionProtoType *Superset,
SourceLocation SuperLoc,
const FunctionProtoType *Subset,
SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const FunctionProtoType *Target,
SourceLocation TargetLoc,
const FunctionProtoType *Source,
SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
TypeDiagnoser() {}
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
std::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
assert(DiagID != 0 && "no diagnostic for type diagnoser");
}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, std::index_sequence_for<Ts...>());
DB << T;
}
};
/// Do a check to make sure \p Name looks like a legal swift_name
/// attribute for the decl \p D. Raise a diagnostic if the name is invalid
/// for the given declaration.
///
/// For a function, this will validate a compound Swift name,
/// e.g. <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>,
/// and the function will output the number of parameter names, and whether
/// this is a single-arg initializer.
///
/// For a type, enum constant, property, or variable declaration, this will
/// validate either a simple identifier, or a qualified
/// <code>context.identifier</code> name.
///
/// \returns true if the name is a valid swift name for \p D, false otherwise.
bool DiagnoseSwiftName(Decl *D, StringRef Name,
SourceLocation ArgLoc,
const IdentifierInfo *AttrName);
private:
/// Methods for marking which expressions involve dereferencing a pointer
/// marked with the 'noderef' attribute. Expressions are checked bottom up as
/// they are parsed, meaning that a noderef pointer may not be accessed. For
/// example, in `&*p` where `p` is a noderef pointer, we will first parse the
/// `*p`, but need to check that `address of` is called on it. This requires
/// keeping a container of all pending expressions and checking if the address
/// of them are eventually taken.
void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
void CheckAddressOfNoDeref(const Expr *E);
void CheckMemberAccessOfNoDeref(const MemberExpr *E);
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser *Diagnoser);
struct ModuleScope {
SourceLocation BeginLoc;
clang::Module *Module = nullptr;
bool ModuleInterface = false;
bool ImplicitGlobalModuleFragment = false;
VisibleModuleSet OuterVisibleModules;
};
/// The modules we're currently parsing.
llvm::SmallVector<ModuleScope, 16> ModuleScopes;
/// Namespace definitions that we will export when they finish.
llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
/// Get the module whose scope we are currently within.
Module *getCurrentModule() const {
return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
}
VisibleModuleSet VisibleModules;
public:
/// Get the module owning an entity.
Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
/// Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND);
bool isModuleVisible(const Module *M, bool ModulePrivate = false);
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return !D->isHidden() || isVisibleSlow(D);
}
/// Determine whether any declaration of an entity is visible.
bool
hasVisibleDeclaration(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
}
bool hasVisibleDeclarationSlow(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules);
bool hasVisibleMergedDefinition(NamedDecl *Def);
bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
/// Determine if \p D and \p Suggested have a structurally compatible
/// layout as described in C11 6.2.7/1.
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is an explicit
/// specialization declaration for a specialization of a template. (For a
/// member specialization, use hasVisibleMemberSpecialization.)
bool hasVisibleExplicitSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is a member
/// specialization declaration (as opposed to an instantiated declaration).
bool hasVisibleMemberSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if \p A and \p B are equivalent internal linkage declarations
/// from different modules, and thus an ambiguity error can be downgraded to
/// an extension warning.
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
const NamedDecl *B);
void diagnoseEquivalentInternalLinkageDeclarations(
SourceLocation Loc, const NamedDecl *D,
ArrayRef<const NamedDecl *> Equiv);
bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
bool isCompleteType(SourceLocation Loc, QualType T) {
return !RequireCompleteTypeImpl(Loc, T, nullptr);
}
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
unsigned DiagID);
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
void completeExprArrayBound(Expr *E);
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T,
TagDecl *OwnedTagDecl = nullptr);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
struct SkipBodyInfo {
SkipBodyInfo()
: ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
New(nullptr) {}
bool ShouldSkip;
bool CheckSameAsPrevious;
NamedDecl *Previous;
NamedDecl *New;
};
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false, bool HasTrailingDot = false,
ParsedType ObjectType = nullptr,
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
bool IsClassTemplateDeductionContext = true,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool IsTemplateName = false);
/// Attempt to behave like MSVC in situations where lookup of an unqualified
/// type name has failed in a dependent context. In these situations, we
/// automatically form a DependentTypeName that will retry lookup in a related
/// scope during instantiation.
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
SourceLocation NameLoc,
bool IsTemplateTypeArg);
/// Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
/// This name is not a type or template in this context, but might be
/// something else.
NC_Unknown,
/// Classification failed; an error has been produced.
NC_Error,
/// The name has been typo-corrected to a keyword.
NC_Keyword,
/// The name was classified as a type.
NC_Type,
/// The name was classified as a specific non-type, non-template
/// declaration. ActOnNameClassifiedAsNonType should be called to
/// convert the declaration to an expression.
NC_NonType,
/// The name was classified as an ADL-only function name.
/// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
/// result to an expression.
NC_UndeclaredNonType,
/// The name denotes a member of a dependent type that could not be
/// resolved. ActOnNameClassifiedAsDependentNonType should be called to
/// convert the result to an expression.
NC_DependentNonType,
/// The name was classified as a non-type, and an expression representing
/// that name has been formed.
NC_ContextIndependentExpr,
/// The name was classified as a template whose specializations are types.
NC_TypeTemplate,
/// The name was classified as a variable template name.
NC_VarTemplate,
/// The name was classified as a function template name.
NC_FunctionTemplate,
/// The name was classified as an ADL-only function template name.
NC_UndeclaredTemplate,
};
class NameClassification {
NameClassificationKind Kind;
union {
ExprResult Expr;
NamedDecl *NonTypeDecl;
TemplateName Template;
ParsedType Type;
};
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification ContextIndependentExpr(ExprResult E) {
NameClassification Result(NC_ContextIndependentExpr);
Result.Expr = E;
return Result;
}
static NameClassification NonType(NamedDecl *D) {
NameClassification Result(NC_NonType);
Result.NonTypeDecl = D;
return Result;
}
static NameClassification UndeclaredNonType() {
return NameClassification(NC_UndeclaredNonType);
}
static NameClassification DependentNonType() {
return NameClassification(NC_DependentNonType);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
static NameClassification UndeclaredTemplate(TemplateName Name) {
NameClassification Result(NC_UndeclaredTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ExprResult getExpression() const {
assert(Kind == NC_ContextIndependentExpr);
return Expr;
}
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
NamedDecl *getNonTypeDecl() const {
assert(Kind == NC_NonType);
return NonTypeDecl;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
case NC_UndeclaredTemplate:
return TNK_Undeclared_template;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name, SourceLocation NameLoc,
const Token &NextToken,
CorrectionCandidateCallback *CCC = nullptr);
/// Act on the result of classifying a name as an undeclared (ADL-only)
/// non-type declaration.
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
SourceLocation NameLoc);
/// Act on the result of classifying a name as an undeclared member of a
/// dependent base class.
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsAddressOfOperand);
/// Act on the result of classifying a name as a specific non-type
/// declaration.
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
NamedDecl *Found,
SourceLocation NameLoc,
const Token &NextToken);
/// Describes the detailed kind of a template name. Used in diagnostics.
enum class TemplateNameKindForDiagnostics {
ClassTemplate,
FunctionTemplate,
VarTemplate,
AliasTemplate,
TemplateTemplateParam,
Concept,
DependentTemplate
};
TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name);
/// Determine whether it's plausible that E was intended to be a
/// template-name.
bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
if (!getLangOpts().CPlusPlus || E.isInvalid())
return false;
Dependent = false;
if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
return !DRE->hasExplicitTemplateArgs();
if (auto *ME = dyn_cast<MemberExpr>(E.get()))
return !ME->hasExplicitTemplateArgs();
Dependent = true;
if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
return !DSDRE->hasExplicitTemplateArgs();
if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
return !DSME->hasExplicitTemplateArgs();
// Any additional cases recognized here should also be handled by
// diagnoseExprIntendedAsTemplateName.
return false;
}
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
SourceLocation Less,
SourceLocation Greater);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name, SourceLocation Loc,
bool IsTemplateId);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation(),
SourceLocation UnalignedQualLoc = SourceLocation());
void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range);
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
const LookupResult &R);
NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
const LookupResult &R);
void CheckShadow(Scope *S, VarDecl *D);
/// Warn if 'E', which is an expression that is about to be modified, refers
/// to a shadowing declaration.
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
private:
/// Map of current shadowing declarations to shadowed declarations. Warn if
/// it looks like the user is trying to modify the shadowing declaration.
llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
public:
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope,
ArrayRef<BindingDecl *> Bindings = None);
NamedDecl *
ActOnDecompositionDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists);
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
void CheckVariableDeclarationType(VarDecl *NewVD);
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
Expr *Init);
void CheckCompleteVariableDeclaration(VarDecl *VD);
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
enum class CheckConstexprKind {
/// Diagnose issues that are non-constant or that are extensions.
Diagnose,
/// Identify whether this function satisfies the formal rules for constexpr
/// functions in the current lanugage mode (with no extensions).
CheckValid
};
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
CheckConstexprKind Kind);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsMemberSpecialization);
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
QualType NewT, QualType OldT);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
bool IsDefinition);
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
QualType adjustParameterTypeForObjCAutoRefCount(QualType T,
SourceLocation NameLoc,
TypeSourceInfo *TSInfo);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC);
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
// Contexts where using non-trivial C union types can be disallowed. This is
// passed to err_non_trivial_c_union_in_invalid_context.
enum NonTrivialCUnionContext {
// Function parameter.
NTCUC_FunctionParam,
// Function return.
NTCUC_FunctionReturn,
// Default-initialized object.
NTCUC_DefaultInitializedObject,
// Variable with automatic storage duration.
NTCUC_AutoVar,
// Initializer expression that might copy from another object.
NTCUC_CopyInit,
// Assignment.
NTCUC_Assignment,
// Compound literal.
NTCUC_CompoundLiteral,
// Block capture.
NTCUC_BlockCapture,
// lvalue-to-rvalue conversion of volatile type.
NTCUC_LValueToRValueVolatile,
};
/// Emit diagnostics if the initializer or any of its explicit or
/// implicitly-generated subexpressions require copying or
/// default-initializing a type that is or contains a C union type that is
/// non-trivial to copy or default-initialize.
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
// These flags are passed to checkNonTrivialCUnion.
enum NonTrivialCUnionKind {
NTCUK_Init = 0x1,
NTCUK_Destruct = 0x2,
NTCUK_Copy = 0x4,
};
/// Emit diagnostics if a non-trivial C union type or a struct that contains
/// a non-trivial C union is used in an invalid context.
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
NonTrivialCUnionContext UseContext,
unsigned NonTrivialKind);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
void ActOnUninitializedDecl(Decl *dcl);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void CheckStaticLocalForDllExport(VarDecl *VD);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(
FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
SkipBodyInfo *SkipBody = nullptr);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineFunctionDef(FunctionDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
/// Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
QualType ReturnTy, NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
SourceLocation SemiLoc);
enum class ModuleDeclKind {
Interface, ///< 'export module X;'
Implementation, ///< 'module X;'
};
/// The parser has processed a module-declaration that begins the definition
/// of a module interface or implementation.
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
SourceLocation ModuleLoc, ModuleDeclKind MDK,
ModuleIdPath Path, bool IsFirstDecl);
/// The parser has processed a global-module-fragment declaration that begins
/// the definition of the global module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
/// The parser has processed a private-module-fragment declaration that begins
/// the definition of the private module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
/// \param PrivateLoc The location of the 'private' keyword.
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
SourceLocation PrivateLoc);
/// The parser has processed a module import declaration.
///
/// \param StartLoc The location of the first token in the declaration. This
/// could be the location of an '@', 'export', or 'import'.
/// \param ExportLoc The location of the 'export' keyword, if any.
/// \param ImportLoc The location of the 'import' keyword.
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path);
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, Module *M,
ModuleIdPath Path = {});
/// The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument,
ExplicitSpecialization,
PartialSpecialization
};
/// Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
MissingImportKind MIK, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
SourceLocation LBraceLoc);
Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
SourceLocation RBraceLoc);
/// We've found a use of a templated declaration that would trigger an
/// implicit instantiation. Check that any relevant explicit specializations
/// and partial specializations are visible, and diagnose if not.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
/// We've found a use of a template specialization that would select a
/// partial specialization. Check that the partial specialization is visible,
/// and diagnose if not.
void checkPartialSpecializationVisibility(SourceLocation Loc,
NamedDecl *Spec);
/// Retrieve a suitable printing policy for diagnostics.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// Retrieve a suitable printing policy for diagnostics.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
RecordDecl *&AnonRecord);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation,
RecordDecl *&AnonRecord);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
/// Common ways to introduce type names without a tag for use in diagnostics.
/// Keep in sync with err_tag_reference_non_tag.
enum NonTagKind {
NTK_NonStruct,
NTK_NonClass,
NTK_NonUnion,
NTK_NonEnum,
NTK_Typedef,
NTK_TypeAlias,
NTK_Template,
NTK_TypeAliasTemplate,
NTK_TemplateTemplateArgument,
};
/// Given a non-tag type declaration, returns an enum useful for indicating
/// what kind of non-tag type this is.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc, const ParsedAttributesView &Attr,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
bool &IsDependent, SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, bool IsTemplateParamOrArg,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart, Declarator &D,
Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
const ParsedAttr &MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
enum TrivialABIHandling {
/// The triviality of a method unaffected by "trivial_abi".
TAH_IgnoreTrivialABI,
/// The triviality of a method affected by "trivial_abi".
TAH_ConsiderTrivialABI
};
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
bool Diagnose = false);
/// For a defaulted function, the kind of defaulted function that it is.
class DefaultedFunctionKind {
CXXSpecialMember SpecialMember : 8;
DefaultedComparisonKind Comparison : 8;
public:
DefaultedFunctionKind()
: SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
}
DefaultedFunctionKind(CXXSpecialMember CSM)
: SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)
: SpecialMember(CXXInvalid), Comparison(Comp) {}
bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
bool isComparison() const {
return Comparison != DefaultedComparisonKind::None;
}
explicit operator bool() const {
return isSpecialMember() || isComparison();
}
CXXSpecialMember asSpecialMember() const { return SpecialMember; }
DefaultedComparisonKind asComparison() const { return Comparison; }
/// Get the index of this function kind for use in diagnostics.
unsigned getDiagnosticIndex() const {
static_assert(CXXInvalid > CXXDestructor,
"invalid should have highest index");
static_assert((unsigned)DefaultedComparisonKind::None == 0,
"none should be equal to zero");
return SpecialMember + (unsigned)Comparison;
}
};
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
return getDefaultedFunctionKind(MD).asSpecialMember();
}
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
return getDefaultedFunctionKind(FD).asComparison();
}
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac, const ParsedAttributesView &AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
/// Perform ODR-like check for C/ObjC when merging tag types from modules.
/// Differently from C++, actually parse the body and reject / error out
/// in case of a structural mismatch.
bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
SkipBodyInfo &SkipBody);
typedef void *SkippedDefinitionContext;
/// Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceRange BraceRange);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, bool IsFixed,
const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
const ParsedAttributesView &Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
const ParsedAttributesView &Attr);
DeclContext *getContainingDC(DeclContext *DC);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// Don't merge availability attributes at all.
AMK_None,
/// Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override,
/// Merge availability attributes for an implementation of
/// a protocol requirement.
AMK_ProtocolImplementation,
};
/// Describes the kind of priority given to an availability attribute.
///
/// The sum of priorities deteremines the final priority of the attribute.
/// The final priority determines how the attribute will be merged.
/// An attribute with a lower priority will always remove higher priority
/// attributes for the specified platform when it is being applied. An
/// attribute with a higher priority will not be applied if the declaration
/// already has an availability attribute with a lower priority for the
/// specified platform. The final prirority values are not expected to match
/// the values in this enumeration, but instead should be treated as a plain
/// integer value. This enumeration just names the priority weights that are
/// used to calculate that final vaue.
enum AvailabilityPriority : int {
/// The availability attribute was specified explicitly next to the
/// declaration.
AP_Explicit = 0,
/// The availability attribute was applied using '#pragma clang attribute'.
AP_PragmaClangAttribute = 1,
/// The availability attribute for a specific platform was inferred from
/// an availability attribute for another platform.
AP_InferredFromOtherPlatform = 2
};
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *
mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Platform, bool Implicit,
VersionTuple Introduced, VersionTuple Deprecated,
VersionTuple Obsoleted, bool IsUnavailable,
StringRef Message, bool IsStrict, StringRef Replacement,
AvailabilityMergeKind AMK, int Priority);
TypeVisibilityAttr *
mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
TypeVisibilityAttr::VisibilityType Vis);
VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
VisibilityAttr::VisibilityType Vis);
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Uuid);
DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
MSInheritanceAttr *
mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase,
MSInheritanceAttr::Spelling SemanticSpelling);
FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Format, int FormatIdx,
int FirstArg);
SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
const AttributeCommonInfo &CI,
const IdentifierInfo *Ident);
MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
NoSpeculativeLoadHardeningAttr *
mergeNoSpeculativeLoadHardeningAttr(Decl *D,
const NoSpeculativeLoadHardeningAttr &AL);
SpeculativeLoadHardeningAttr *
mergeSpeculativeLoadHardeningAttr(Decl *D,
const SpeculativeLoadHardeningAttr &AL);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
const AttributeCommonInfo &CI);
SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name, bool Override);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
const InternalLinkageAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous);
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
bool ConsiderCudaAttrs = true);
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess,
bool Diagnose = true);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsFunctionConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformAggregateInitializationForOverloadResolution(
const InitializedEntity &Entity, InitListExpr *From);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
/// Check that the lifetime of the initializer (and its subobjects) is
/// sufficient for initializing the entity, and perform lifetime extension
/// (when permitted) if not.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
using ADLCallKind = CallExpr::ADLCallKind;
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = true,
bool AllowExplicitConversion = false,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool FirstArgumentIsBase = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false,
OverloadCandidateParamOrder PO = {});
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
OverloadCandidateParamOrder PO = {});
void AddTemplateOverloadCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
bool PartialOverloading = false, bool AllowExplicit = true,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
OverloadCandidateParamOrder PO = {});
bool CheckNonDependentConversions(
FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
ConversionSequenceList &Conversions, bool SuppressUserConversions,
CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
Expr::Classification ObjectClassification = {},
OverloadCandidateParamOrder PO = {});
void AddConversionCandidate(
CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddTemplateConversionCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddNonMemberOperatorCandidates(
const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
OverloadCandidateParamOrder PO = {});
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(
NamedDecl *Found, FunctionDecl *Fn,
OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
QualType DestType = QualType(), bool TakingAddress = false);
// Emit as a series of 'note's all template and non-templates identified by
// the expression Expr
void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
bool TakingAddress = false);
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
/// Find the failed Boolean condition within a given Boolean
/// constant expression, and describe it with a string.
std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// non-ArgDependent DiagnoseIfAttrs.
///
/// Argument-dependent diagnose_if attributes should be checked each time a
/// function is used as a direct callee of a function call.
///
/// Returns true if any errors were emitted.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
const Expr *ThisArg,
ArrayRef<const Expr *> Args,
SourceLocation Loc);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// ArgDependent DiagnoseIfAttrs.
///
/// Argument-independent diagnose_if attributes should be checked on every use
/// of a function.
///
/// Returns true if any errors were emitted.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
SourceLocation Loc);
/// Returns whether the given function's address can be taken or not,
/// optionally emitting a diagnostic if the address can't be taken.
///
/// Returns false if taking the address of the function is illegal.
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
bool Complain = false,
SourceLocation Loc = SourceLocation());
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
DeclAccessPair &FoundResult);
bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
SourceRange OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
SourceLocation RangeLoc,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true,
bool CalleesAddressIsTaken=false);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
UnaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *input, bool RequiresADL = true);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
BinaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
bool RequiresADL = true,
bool AllowRewrittenCandidates = true);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult
BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// Look up the name of an OpenMP user-defined reduction operation.
LookupOMPReductionName,
/// Look up the name of an OpenMP user-defined mapper.
LookupOMPMapperName,
/// Look up any declaration with any name.
LookupAnyName
};
/// Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists and is visible.
ForVisibleRedeclaration,
/// The lookup results will be used for redeclaration of a name
/// with external linkage; non-visible lookup results with external linkage
/// may also be found.
ForExternalRedeclaration
};
RedeclarationKind forRedeclarationInCurContext() {
// A declaration with an owning module for linkage can never link against
// anything that is not visible. We don't need to check linkage here; if
// the context has internal linkage, redeclaration lookup won't find things
// from other TUs, and we can't safely compute linkage yet in general.
if (cast<Decl>(CurContext)
->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
return ForVisibleRedeclaration;
return ForExternalRedeclaration;
}
/// The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// The lookup resulted in an error.
LOLR_Error,
/// The lookup found no match but no diagnostic was issued.
LOLR_ErrorNoDiagnostic,
/// The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplate
};
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState &&other) noexcept;
TypoExprState &operator=(TypoExprState &&other) noexcept;
};
/// The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupBuiltin(LookupResult &R);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate,
bool DiagnoseMissing);
bool isKnownName(StringRef name);
/// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
enum class FunctionEmissionStatus {
Emitted,
CUDADiscarded, // Discarded due to CUDA/HIP hostness
OMPDiscarded, // Discarded due to OpenMP hostness
TemplateDiscarded, // Discarded due to uninstantiated templates
Unknown,
};
FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
// Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool LoadExternal = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool IncludeDependentBases = false,
bool LoadExternal = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult
CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult
CorrectDelayedTyposInExpr(Expr *E,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(E, nullptr, Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
// Helper for delayed processing of attributes.
void ProcessDeclAttributeDelayed(Decl *D,
const ParsedAttributesView &AttrList);
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const ParsedAttributesView &AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Map any API notes provided for this declaration to attributes on the
/// declaration.
///
/// Triggered by declaration-attribute processing.
void ProcessAPINotes(Decl *D);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckAttrTarget(const ParsedAttr &CurrAttr);
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceAttr::Spelling SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
SourceLocation Loc);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Check whether a nullability type specifier can be added to the given
/// type through some means not written in source (e.g. API notes).
///
/// \param type The type to which the nullability specifier will be
/// added. On success, this type will be updated appropriately.
///
/// \param nullability The nullability specifier to add.
///
/// \param diagLoc The location to use for diagnostics.
///
/// \param allowArrayTypes Whether to accept nullability specifiers on an
/// array type (e.g., because it will decay to a pointer).
///
/// \param overrideExisting Whether to override an existing, locally-specified
/// nullability specifier rather than complaining about the conflict.
///
/// \returns true if nullability cannot be applied, false otherwise.
bool checkImplicitNullabilityTypeSpecifier(QualType &type,
NullabilityKind nullability,
SourceLocation diagLoc,
bool allowArrayTypes,
bool overrideExisting);
/// Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt,
const ParsedAttributesView &Attrs,
SourceRange Range);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
ObjCInterfaceDecl *IDecl,
SourceLocation AtEnd);
void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
unsigned &Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// - Returns instance or factory methods in global method pool for
/// given selector. It checks the desired kind first, if none is found, and
/// parameter checkTheOther is set, it then checks the other kind. If no such
/// method or only one method is found, function returns false; otherwise, it
/// returns true.
bool
CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool InstanceFirst, bool CheckTheOther,
const ObjCObjectType *TypeBound = nullptr);
bool
AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R, bool receiverIdOrClass,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
void
DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
/// Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg() : E(nullptr) { }
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(
ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
StmtResult ActOnExprStmtError();
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt(bool IsStmtExpr);
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
S.ActOnStartOfCompoundStmt(IsStmtExpr);
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
SourceLocation DotDotDotLoc, ExprResult RHS,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
class ConditionResult;
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Stmt *InitStmt,
ConditionResult Cond);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc, SourceLocation CondLParen,
Expr *Cond, SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First,
ConditionResult Second,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *Begin, Stmt *End,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params,
unsigned OpenMPCaptureLevel = 0);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
enum CopyElisionSemanticsKind {
CES_Strict = 0,
CES_AllowParameters = 1,
CES_AllowDifferentTypes = 2,
CES_AllowExceptionVariables = 4,
CES_FormerDefault = (CES_AllowParameters),
CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
CES_AllowExceptionVariables),
};
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
CopyElisionSemanticsKind CESK);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
CopyElisionSemanticsKind CESK);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
unsigned NumLabels,
SourceLocation RParenLoc);
void FillInlineAsmIdentifierInfo(Expr *Res,
llvm::InlineAsmIdentifierInfo &Info);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
/// Warn if we're implicitly casting from a _Nullable pointer type to a
/// _Nonnull one.
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
SourceLocation Loc);
/// Warn when implicitly casting 0 to nullptr.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass,
bool ObjCPropertyAccess,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReceiver = nullptr);
bool makeUnavailableInSystemHeader(SourceLocation loc,
UnavailableAttr::ImplicitReason reason);
/// Issue any -Wunguarded-availability warnings in \c FD
void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
bool ObjCPropertyAccess = false,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReciever = nullptr);
void NoteDeletedFunction(FunctionDecl *FD);
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult CheckUnevaluatedOperand(Expr *E);
void CheckUnusedVolatileAssignment(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
//
// MightBeOdrUse indicates whether the use could possibly be an odr-use, and
// should usually be true. This only needs to be set to false if the lack of
// odr-use cannot be determined from the current context (for instance,
// because the name denotes a virtual function and was written without an
// explicit nested-name-specifier).
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool MightBeOdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
void MarkMemberReferenced(MemberExpr *E);
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
unsigned CapturingScopeIndex);
ExprResult CheckLValueToRValueConversionOperand(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
/// Mark all of the declarations referenced within a particular AST node as
/// referenced. Used when template instantiation instantiates a non-dependent
/// type -- entities referenced by the type are now referenced.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
/// Similar, but diagnostic is only produced if all the specified statements
/// are reachable.
bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
CorrectionCandidateCallback *CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
CorrectionCandidateCallback &CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
IdentifierInfo *II);
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
/// If \p D cannot be odr-used in the current expression evaluation context,
/// return a reason explaining why. Otherwise, return NOUR_None.
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
NestedNameSpecifierLoc NNS,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance,
const Scope *S);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult
BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, const Scope *S,
TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentKind IK);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
bool isQualifiedMemberAccess(Expr *E);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
SourceRange ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
Expr *LowerBound, SourceLocation ColonLoc,
Expr *Length, SourceLocation RBLoc);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
SourceLocation OpLoc,
const CXXScopeSpec &SS, FieldDecl *Field,
DeclAccessPair FoundDecl,
const DeclarationNameInfo &MemberNameInfo);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr);
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false);
enum class AtomicArgumentOrder { API, AST };
ExprResult
BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
SourceLocation RParenLoc, MultiExprArg Args,
AtomicExpr::AtomicOp Op,
AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
ExprResult
BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
Expr *Config = nullptr, bool IsExecConfig = false,
ADLCallKind UsesADL = ADLCallKind::NotADL);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult BuildInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation EqualOrColonLoc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc); // "({..})"
// Handle the final expression in a statement expression.
ExprResult ActOnStmtExprResult(ExprResult E);
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
// __builtin_COLUMN()
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc,
SourceLocation RPLoc);
// Build a potentially resolved SourceLocExpr.
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc, SourceLocation RPLoc,
DeclContext *ParentContext);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// The symbol exists.
IER_Exists,
/// The symbol does not exist.
IER_DoesNotExist,
/// The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc, IdentifierInfo *Ident,
SourceLocation LBrace,
const ParsedAttributesView &AttrList,
UsingDirectiveDecl *&UsingDecl);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
NamespaceDecl *lookupStdExperimentalNamespace();
CXXRecordDecl *getStdBadAlloc() const;
EnumDecl *getStdAlignValT() const;
private:
// A cache representing if we've fully checked the various comparison category
// types stored in ASTContext. The bit-index corresponds to the integer value
// of a ComparisonCategoryType enumerator.
llvm::SmallBitVector FullyCheckedComparisonCategories;
ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
CXXScopeSpec &SS,
ParsedType TemplateTypeTy,
IdentifierInfo *MemberOrBase);
public:
/// 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);
/// Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const FunctionDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
SourceLocation NamespcLoc, CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
const ParsedAttributesView &AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
bool HasTypename,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc);
NamedDecl *BuildUsingDeclaration(
Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList, bool IsInstantiation);
NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
ArrayRef<NamedDecl *> Expansions);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
/// Given a derived-class using shadow declaration for a constructor and the
/// correspnding base class constructor, find or create the implicit
/// synthesized derived class constructor to use for this initialization.
CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
ConstructorUsingShadowDecl *DerivedShadow);
Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation TypenameLoc, CXXScopeSpec &SS,
UnqualifiedId &Name, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc, UnqualifiedId &Name,
const ParsedAttributesView &AttrList,
TypeResult Type, Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
/// Build a CXXConstructExpr whose constructor has already been resolved if
/// it denotes an inherited constructor.
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// Instantiate or parse a C++ default argument expression as necessary.
/// Return true on error.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
ParmVarDecl *Param);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E);
/// Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_NoexceptFalse;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
CXXConstructorDecl *CD);
/// Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
/// 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);
/// Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
/// Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// Check a completed declaration of an implicit special member.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
/// Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr*> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
ExprResult Operand,
SourceLocation RParenLoc);
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
Expr *Operand, SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc,
Optional<unsigned> NumExpansions);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// Build a CXXThisExpr and mark it referenced in the current context.
Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
void MarkThisReferenced(CXXThisExpr *This);
/// Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr,
bool ByCopy = false);
/// Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
ExprResult
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
SourceLocation AtLoc, SourceLocation RParen);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenOrBraceLoc,
MultiExprArg Exprs,
SourceLocation RParenOrBraceLoc,
bool ListInitialization);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc,
bool ListInitialization);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Optional<Expr *> ArraySize,
SourceRange DirectInitRange,
Expr *Initializer);
/// Determine whether \p FD is an aligned allocation or deallocation
/// function that is unavailable.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
/// Produce diagnostics if \p FD is an aligned allocation or deallocation
/// function that is unavailable.
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
SourceLocation Loc);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
/// The scope in which to find allocation functions.
enum AllocationFunctionScope {
/// Only look for allocation functions in the global scope.
AFS_Global,
/// Only look for allocation functions in the scope of the
/// allocated class.
AFS_Class,
/// Look for allocation functions in both the global scope
/// and in the scope of the allocated class.
AFS_Both
};
/// Finds the overloads of operator new and delete that are appropriate
/// for the allocation.
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
AllocationFunctionScope NewScope,
AllocationFunctionScope DeleteScope,
QualType AllocType, bool IsArray,
bool &PassAlignment, MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
ArrayRef<QualType> Params);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
bool Overaligned,
DeclarationName Name);
FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
CXXRecordDecl *RD);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
bool IsDelete, bool CallCanBeVirtual,
bool WarnOnNonAbstractTypes,
SourceLocation DtorLoc);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the binary type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
MaterializeTemporaryExpr *
CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
bool BoundToLvalueReference);
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
return ActOnFinishFullExpr(
Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue, bool IsConstexpr = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
/// Keeps information about an identifier in a nested-name-spec.
///
struct NestedNameSpecInfo {
/// The type of the object, if we're parsing nested-name-specifier in
/// a member access expression.
ParsedType ObjectType;
/// The identifier preceding the '::'.
IdentifierInfo *Identifier;
/// The location of the identifier.
SourceLocation IdentifierLoc;
/// The location of the '::'.
SourceLocation CCLoc;
/// Creates info object for the most typical case.
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
: ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
CCLoc(ColonColonLoc) {
}
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, QualType ObjectType)
: ObjectType(ParsedType::make(ObjectType)), Identifier(II),
IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
}
};
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo);
bool BuildCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
/// The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param IdInfo Parser information about an identifier in the
/// nested-name-spec.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \param OnlyNamespace If true, only considers namespaces in lookup.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo,
bool EnteringContext);
/// The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params,
ConstexprSpecKind ConstexprKind);
/// Number lambda for linkage purposes if necessary.
void handleLambdaNumbering(
CXXRecordDecl *Class, CXXMethodDecl *Method,
Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
/// Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
ParsedType actOnLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
return ParsedType::make(buildLambdaInitCaptureInitialization(
Loc, ByRef, EllipsisLoc, None, Id,
InitKind != LambdaCaptureInitKind::CopyInit, Init));
}
QualType buildLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
Expr *&Init);
/// Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType,
SourceLocation EllipsisLoc,
IdentifierInfo *Id,
unsigned InitStyle, Expr *Init);
/// Add an init-capture to a lambda scope.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief This is called after parsing the explicit template parameter list
/// on a lambda (if it exists) in C++2a.
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> TParams,
SourceLocation RAngleLoc);
/// Introduce the lambda parameters into scope.
void addLambdaParameters(
ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
CXXMethodDecl *CallOperator, Scope *CurScope);
/// Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// Does copying/destroying the captured variable have side effects?
bool CaptureHasSideEffects(const sema::Capture &From);
/// Diagnose if an explicit lambda capture is unused. Returns true if a
/// diagnostic is emitted.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
const sema::Capture &From);
/// Build a FieldDecl suitable to hold the given capture.
FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
/// Initialize the given capture with a suitable expression.
ExprResult BuildCaptureInit(const sema::Capture &Capture,
SourceLocation ImplicitCaptureLoc,
bool IsOpenMPMapping = false);
/// Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// Get the return type to use for a lambda's conversion function(s) to
/// function pointer type, given the type of the call operator.
QualType
getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
/// Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
/// Check whether the given expression is a valid constraint expression.
/// A diagnostic is emitted if it is not, and false is returned.
bool CheckConstraintExpression(Expr *CE);
bool CalculateConstraintSatisfaction(ConceptDecl *NamedConcept,
MultiLevelTemplateArgumentList &MLTAL,
Expr *ConstraintExpr,
bool &IsSatisfied);
/// Check that the associated constraints of a template declaration match the
/// associated constraints of an older declaration of which it is a
/// redeclaration.
bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old,
TemplateParameterList *New);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
MutableArrayRef<ObjCDictionaryElement> Elements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
SourceLocation ColonLoc,
const ParsedAttributesView &Attrs);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
bool ConstexprOnly = false);
/// Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
/// Check class-level dllimport/dllexport attribute. The caller must
/// ensure that referenceDLLExportedClassMethods is called some point later
/// when all outer classes of Class are complete.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
void referenceDLLExportedClassMethods();
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
/// Add gsl::Pointer attribute to std::container::iterator
/// \param ND The declaration that introduces the name
/// std::container::iterator. \param UnderlyingRecord The record named by ND.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
/// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
/// Add [[gsl::Pointer]] attributes for std:: types.
void inferGslPointerAttribute(TypedefNameDecl *TD);
void CheckCompletedCXXClass(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(Decl *D);
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
StorageClass &SC);
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
void CheckExplicitlyDefaultedFunction(FunctionDecl *MD);
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
CXXSpecialMember CSM);
void CheckDelayedMemberExceptionSpecs();
bool CheckExplicitlyDefaultedComparison(FunctionDecl *MD,
DefaultedComparisonKind DCK);
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class,
MutableArrayRef<CXXBaseSpecifier *> Bases);
void ActOnBaseSpecifiers(Decl *ClassDecl,
MutableArrayRef<CXXBaseSpecifier *> Bases);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbigiousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath,
bool IgnoreAccess = false);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult
CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *DecomposedClass,
DeclAccessPair Field);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
QualType BaseType);
bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
AccessSpecifier access,
QualType objectType);
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool isAbstractType(SourceLocation Loc, QualType T);
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true,
bool AllowNonTemplateFunctions = false);
/// Try to interpret the lookup result D as a template-name.
///
/// \param D A declaration found by name lookup.
/// \param AllowFunctionTemplates Whether function templates should be
/// considered valid results.
/// \param AllowDependent Whether unresolved using declarations (that might
/// name templates) should be considered valid results.
NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
enum class AssumedTemplateKind {
/// This is not assumed to be a template name.
None,
/// This is assumed to be a template name because lookup found nothing.
FoundNothing,
/// This is assumed to be a template name because lookup found one or more
/// functions (but no function templates).
FoundFunctions,
};
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization,
SourceLocation TemplateKWLoc = SourceLocation(),
AssumedTemplateKind *ATK = nullptr);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
const UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
/// Try to resolve an undeclared template name as a type template.
///
/// Sets II to the identifier corresponding to the template name, and updates
/// Name to a corresponding (typo-corrected) type template name and TNK to
/// the corresponding kind, if possible.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
TemplateNameKind &TNK,
SourceLocation NameLoc,
IdentifierInfo *&II);
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
SourceLocation NameLoc,
bool Diagnose = true);
/// Determine whether a particular identifier might be the name in a C++1z
/// deduction-guide declaration.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
SourceLocation NameLoc,
ParsedTemplateTy *Template = nullptr);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
NamedDecl *Instantiation,
bool InstantiatedFromMember,
const NamedDecl *Pattern,
const NamedDecl *PatternDef,
TemplateSpecializationKind TSK,
bool Complain = true);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg);
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
SourceLocation Loc);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> Params,
SourceLocation RAngleLoc,
Expr *RequiresClause);
/// The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC,
SkipBodyInfo *SkipBody = nullptr);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
QualType NTTPType,
SourceLocation Loc);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false, bool IsClassName = false);
/// Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult
CheckConceptTemplateId(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
SourceLocation ConceptNameLoc, NamedDecl *FoundDecl,
ConceptDecl *NamedConcept,
const TemplateArgumentListInfo *TemplateArgs);
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnDependentTemplateName(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
TemplateTy &Template, bool AllowInjectedClassName = false);
DeclResult ActOnClassTemplateSpecialization(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
TemplateDecl *PrimaryTemplate,
unsigned NumExplicitArgs,
ArrayRef<TemplateArgument> Args);
void CheckTemplatePartialSpecialization(
ClassTemplatePartialSpecializationDecl *Partial);
void CheckTemplatePartialSpecialization(
VarTemplatePartialSpecializationDecl *Partial);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(
FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous, bool QualifiedFriend = false);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult ActOnExplicitInstantiation(
Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
TemplateTy Template, SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
/// contain the converted forms of the template arguments as written.
/// Otherwise, \p TemplateArgs will not be modified.
///
/// \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 CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
TemplateArgumentLoc &Arg);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateII The identifier used to name the template.
/// \param TemplateIILoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
// Concepts
Decl *ActOnConceptDefinition(
Scope *S, MultiTemplateParamsArg TemplateParameterLists,
IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// An arbitrary expression.
UPPC_Expression = 0,
/// The base type of a class type.
UPPC_BaseType,
/// The type of an arbitrary declaration.
UPPC_DeclarationType,
/// The type of a data member.
UPPC_DataMemberType,
/// The size of a bit-field.
UPPC_BitFieldWidth,
/// The expression in a static assertion.
UPPC_StaticAssertExpression,
/// The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// The enumerator value.
UPPC_EnumeratorValue,
/// A using declaration.
UPPC_UsingDeclaration,
/// A friend declaration.
UPPC_FriendDeclaration,
/// A declaration qualifier.
UPPC_DeclarationQualifier,
/// An initializer.
UPPC_Initializer,
/// A default argument.
UPPC_DefaultArgument,
/// The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// The type of an exception.
UPPC_ExceptionType,
/// Partial specialization.
UPPC_PartialSpecialization,
/// Microsoft __if_exists.
UPPC_IfExists,
/// Microsoft __if_not_exists.
UPPC_IfNotExists,
/// Lambda expression.
UPPC_Lambda,
/// Block expression,
UPPC_Block
};
/// Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param NNS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
/// Given a template argument that contains an unexpanded parameter pack, but
/// which has already been substituted, attempt to determine the number of
/// elements that will be produced once this argument is fully-expanded.
///
/// This is intended for use when transforming 'sizeof...(Arg)' in order to
/// avoid actually expanding the pack where possible.
Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
/// Adjust the type \p ArgFunctionType to match the calling convention,
/// noreturn, and optionally the exception specification of \p FunctionType.
/// Deduction often wants to ignore these properties when matching function
/// types.
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
bool AdjustExceptionSpec = false);
/// Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// Template argument deduction was successful.
TDK_Success = 0,
/// The declaration was invalid; do nothing.
TDK_Invalid,
/// Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// Template argument deduction did not deduce a value for every
/// expansion of an expanded template parameter pack.
TDK_IncompletePack,
/// Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// After substituting deduced template arguments, a dependent
/// parameter type did not match the corresponding argument.
TDK_DeducedMismatch,
/// After substituting deduced template arguments, an element of
/// a dependent parameter type did not match the corresponding element
/// of the corresponding argument (when deducing from an initializer list).
TDK_DeducedMismatchNested,
/// A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// Checking non-dependent argument conversions failed.
TDK_NonDependentConversionFailure,
/// Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure,
/// CUDA Target attributes do not match.
TDK_CUDATargetMismatch
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
unsigned ArgIdx, QualType OriginalArgType)
: OriginalParamType(OriginalParamType),
DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) {}
QualType OriginalParamType;
bool DecomposedParam;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult FinishTemplateArgumentDeduction(
FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false,
llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
TemplateDeductionResult DeduceTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
bool PartialOverloading,
llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
/// Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// Completely replace the \c auto in \p TypeWithAuto by
/// \p Replacement. This does not retain any \c auto type sugar.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
/// Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult
DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
DeduceAutoResult
DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
/// Declare implicit deduction guides for a class template if we've
/// not already done so.
void DeclareImplicitDeductionGuides(TemplateDecl *Template,
SourceLocation Loc);
QualType DeduceTemplateSpecializationFromInitializer(
TypeSourceInfo *TInfo, const InitializedEntity &Entity,
const InitializationKind &Kind, MultiExprArg Init);
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
QualType Type, TypeSourceInfo *TSI,
SourceRange Range, bool DirectInit,
Expr *Init);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
FunctionTemplateDecl *FT2,
SourceLocation Loc,
TemplatePartialOrderingContext TPOC,
unsigned NumCallArguments1,
unsigned NumCallArguments2);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
struct CodeSynthesisContext {
/// The kind of template instantiation we are performing
enum SynthesisKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template parameter whose argument is
/// being instantiated, the Template is the template, and the
/// TemplateArgs/NumTemplateArguments provide the template arguments as
/// specified.
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
/// a TemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are computing the exception specification for a defaulted special
/// member function.
ExceptionSpecEvaluation,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation,
/// We are declaring an implicit special member function.
DeclaringSpecialMember,
/// We are 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 rewriting a comparison operator in terms of an operator<=>.
RewritingOperatorAsSpaceship,
/// Added for Template instantiation observation.
/// Memoization means we are _not_ instantiating a template because
/// it is already instantiated (but we entered a context where we
/// would have had to if it was not already instantiated).
Memoization
} Kind;
/// Was the enclosing context a non-instantiation SFINAE context?
bool SavedInNonInstantiationSFINAEContext;
/// The point of instantiation or synthesis within the source code.
SourceLocation PointOfInstantiation;
/// The entity that is being synthesized.
Decl *Entity;
/// The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
// FIXME: Wrap this union around more members, or perhaps store the
// kind-specific members in the RAII object owning the context.
union {
/// The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// The special member being declared or defined.
CXXSpecialMember SpecialMember;
};
ArrayRef<TemplateArgument> template_arguments() const {
assert(Kind != DeclaringSpecialMember);
return {TemplateArgs, NumTemplateArgs};
}
/// The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
CodeSynthesisContext()
: Kind(TemplateInstantiation),
SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
DeductionInfo(nullptr) {}
/// Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
};
/// List of active code synthesis contexts.
///
/// This vector is treated as a stack. As synthesis of one entity requires
/// synthesis of another, additional contexts are pushed onto the stack.
SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
/// Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
/// Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm::DenseSet<Module*> LookupModulesCache;
/// Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm::DenseSet<Module*> &getLookupModules();
/// Map from the most recent declaration of a namespace to the most
/// recent visible declaration of that namespace.
llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
/// Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// The number of \p CodeSynthesisContexts that are not template
/// instantiations and, therefore, should not be counted as part of the
/// instantiation depth.
///
/// When the instantiation depth reaches the user-configurable limit
/// \p LangOptions::InstantiationDepth we will abort instantiation.
// FIXME: Should we have a similar limit for other forms of synthesis?
unsigned NonInstantiationEntries;
/// The depth of the context stack at the point when the most recent
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant context stacks
/// when there are multiple errors or warnings in the same instantiation.
// FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
unsigned LastEmittedCodeSynthesisContextDepth = 0;
/// The template instantiation callbacks to trace or track
/// instantiations (objects can be chained).
///
/// This callbacks is used to print, trace or track template
/// instantiations as they are being constructed.
std::vector<std::unique_ptr<TemplateInstantiationCallback>>
TemplateInstCallbacks;
/// The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// Note that we are instantiating a class template,
/// function template, variable template, alias template,
/// or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateParameter Param, TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting either explicitly-specified or
/// deduced template arguments during function template argument deduction.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
CodeSynthesisContext::SynthesisKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template declaration.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument for a function
/// parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
struct ConstraintsCheck {};
/// \brief Note that we are checking the constraints associated with some
/// constrained entity (a concept declaration or a template with associated
/// constraints).
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintsCheck, TemplateDecl *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, TemplateDecl *Template,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange);
/// Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
/// Determine whether we are already instantiating this
/// specialization in some surrounding active instantiation.
bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
private:
Sema &SemaRef;
bool Invalid;
bool AlreadyInstantiating;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = None,
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
void popCodeSynthesisContext();
/// Determine whether we are currently performing template instantiation.
bool inTemplateInstantiation() const {
return CodeSynthesisContexts.size() > NonInstantiationEntries;
}
void PrintContextStack() {
if (!CodeSynthesisContexts.empty() &&
CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
PrintInstantiationStack();
LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
}
if (PragmaAttributeCurrentTargetDecl)
PrintPragmaAttributeInstantiationPoint();
}
void PrintInstantiationStack();
void PrintPragmaAttributeInstantiationPoint();
/// Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
bool PrevLastDiagnosticIgnored;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
PrevLastDiagnosticIgnored(
SemaRef.getDiagnostics().isLastDiagnosticIgnored())
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
SemaRef.getDiagnostics().setLastDiagnosticIgnored(
PrevLastDiagnosticIgnored);
}
/// Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
/// Queue of implicit template instantiations that cannot be performed
/// eagerly.
SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
class GlobalEagerInstantiationScope {
public:
GlobalEagerInstantiationScope(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
void perform() {
if (Enabled) {
S.DefineUsedVTables();
S.PerformPendingInstantiations();
}
}
~GlobalEagerInstantiationScope() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class LocalEagerInstantiationScope {
public:
LocalEagerInstantiationScope(Sema &S) : S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
~LocalEagerInstantiationScope() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
/// A helper class for building up ExtParameterInfos.
class ExtParameterInfoBuilder {
SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
bool HasInteresting = false;
public:
/// Set the ExtParameterInfo for the parameter at the given index,
///
void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
assert(Infos.size() <= index);
Infos.resize(index);
Infos.push_back(info);
if (!HasInteresting)
HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
}
/// Return a pointer (suitable for setting in an ExtProtoInfo) to the
/// ExtParameterInfo array we've built up.
const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams) {
if (!HasInteresting) return nullptr;
Infos.resize(numParams);
return Infos.data();
}
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity,
bool AllowDeducedTST = false);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
Qualifiers ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
bool SubstExceptionSpec(SourceLocation Loc,
FunctionProtoType::ExceptionSpecInfo &ESI,
SmallVectorImpl<QualType> &ExceptionStorage,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams,
ExtParameterInfoBuilder &ParamInfos);
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateParameterList *
SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
void
InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
bool usesPartialOrExplicitSpecialization(
SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
const TemplateArgumentList *Args,
SourceLocation Loc);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation, void *InsertPos,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false,
VarTemplateSpecializationDecl *PrevVTSD = nullptr);
VarDecl *getVarTemplateSpecialization(
VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool FindingInstantiatedContext = false);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(
Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName, SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
SmallVectorImpl<SourceLocation> &ProtocolLocs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryInterface(
SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc,
const ParsedAttributesView &AttrList);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
ArrayRef<IdentifierLocPair> IdentList,
const ParsedAttributesView &attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
ArrayRef<IdentifierLocPair> ProtocolId,
SmallVectorImpl<Decl *> &Protocols);
void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
SourceLocation ProtocolLoc,
IdentifierInfo *TypeArgId,
SourceLocation TypeArgLoc,
bool SelectProtocolFirst = false);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C type parameter type.
QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
void ProcessPropertyDecl(ObjCPropertyDecl *property);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc,
ObjCPropertyQueryKind QueryKind);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
ParsedAttributesView ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
unsigned CNumArgs, // c-style args
const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// The message is sent to 'super'.
ObjCSuperMessage,
/// The message is an instance message.
ObjCInstanceMessage,
/// The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs, bool Diagnose = true);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr, bool Diagnose = true);
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
bool Diagnose = true);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
/// Check whether the declared result type of the given Objective-C
/// method declaration is compatible with the method's class.
ResultTypeCompatibilityKind
checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method,
const ObjCInterfaceDecl *CurrentClass);
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaClangSection - Called on well formed \#pragma clang section
void ActOnPragmaClangSection(SourceLocation PragmaLoc,
PragmaClangSectionAction Action,
PragmaClangSectionKind SecKind, StringRef SecName);
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
StringRef SlotLabel, Expr *Alignment);
enum class PragmaPackDiagnoseKind {
NonDefaultStateAtInclude,
ChangedStateAtExit
};
void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
SourceLocation IncludeLoc);
void DiagnoseUnterminatedPragmaPack();
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
SourceLocation PragmaLoc,
MSVtorDispAttr::Mode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName,
int SectionFlags,
DeclaratorDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName);
/// Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// Called on #pragma clang __debug dump II
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
StringRef Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT and
/// \#pragma clang fp contract
void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
/// ActOnPragmaFenvAccess - Called on well formed
/// \#pragma STDC FENV_ACCESS
void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
SourceLocation PragmaLoc,
attr::ParsedSubjectMatchRuleSet Rules);
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Called on well-formed '\#pragma clang attribute pop'.
void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Adds the attributes that have been specified using the
/// '\#pragma clang attribute push' directives to the given declaration.
void AddPragmaAttributes(Scope *S, Decl *D);
void DiagnoseUnterminatedPragmaAttribute();
/// Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
bool IsPackExpansion);
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
Expr *OE);
/// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
/// declaration.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *ParamExpr);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *MaxThreads, Expr *MinBlocks);
/// AddModeAttr - Adds a mode attribute to a particular declaration.
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
bool InInstantiation = false);
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
ParameterABI ABI);
enum class RetainOwnershipKind {NS, CF, OS};
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
RetainOwnershipKind K, bool IsTemplateInstantiation);
/// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
/// attribute to a particular declaration.
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
/// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
/// particular declaration.
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
//===--------------------------------------------------------------------===//
// C++ Coroutines TS
//
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
StringRef Keyword);
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
UnresolvedLookupExpr* Lookup);
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
bool buildCoroutineParameterMoves(SourceLocation Loc);
VarDecl *buildCoroutinePromise(SourceLocation Loc);
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
SourceLocation FuncLoc);
//===--------------------------------------------------------------------===//
// OpenCL extensions.
//
private:
std::string CurrOpenCLExtension;
/// Extensions required by an OpenCL type.
llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
/// Extensions required by an OpenCL declaration.
llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
public:
llvm::StringRef getCurrentOpenCLExtension() const {
return CurrOpenCLExtension;
}
/// Check if a function declaration \p FD associates with any
/// extensions present in OpenCLDeclExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
/// Check if a function type \p FT associates with any
/// extensions present in OpenCLTypeExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
/// Find an extension in an appropriate extension map and return its name
template<typename T, typename MapT>
std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
void setCurrentOpenCLExtension(llvm::StringRef Ext) {
CurrOpenCLExtension = Ext;
}
/// Set OpenCL extensions for a type which can only be used when these
/// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
/// Set OpenCL extensions for a declaration which can only be
/// used when these OpenCL extensions are enabled. If \p Exts is empty, do
/// nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
/// Set current OpenCL extensions for a type which can only be used
/// when these OpenCL extensions are enabled. If current OpenCL extension is
/// empty, do nothing.
void setCurrentOpenCLExtensionForType(QualType T);
/// Set current OpenCL extensions for a declaration which
/// can only be used when these OpenCL extensions are enabled. If current
/// OpenCL extension is empty, do nothing.
void setCurrentOpenCLExtensionForDecl(Decl *FD);
bool isOpenCLDisabledDecl(Decl *FD);
/// Check if type \p T corresponding to declaration specifier \p DS
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
/// Check if declaration \p D used by expression \p E
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
//===--------------------------------------------------------------------===//
// OpenMP directives and clauses.
//
private:
void *VarDataSharingAttributesStack;
/// Number of nested '#pragma omp declare target' directives.
unsigned DeclareTargetNestingLevel = 0;
/// Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult
VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
bool StrictlyPositive = true);
/// Returns OpenMP nesting level for current directive.
unsigned getOpenMPNestingLevel() const;
/// Adjusts the function scopes index for the target-based regions.
void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
unsigned Level) const;
/// Returns the number of scopes associated with the construct on the given
/// OpenMP level.
int getNumberOfConstructScopes(unsigned Level) const;
/// Push new OpenMP function region for non-capturing function.
void pushOpenMPFunctionRegion();
/// Pop OpenMP function region for non-capturing function.
void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
/// Check whether we're allowed to call Callee from the current function.
void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
bool CheckForDelayedContext = true);
/// Check whether we're allowed to call Callee from the current function.
void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
bool CheckCaller = true);
/// Check if the expression is allowed to be used in expressions for the
/// OpenMP devices.
void checkOpenMPDeviceExpr(const Expr *E);
/// Finishes analysis of the deferred functions calls that may be declared as
/// host/nohost during device/host compilation.
void finalizeOpenMPDelayedAnalysis();
/// Checks if a type or a declaration is disabled due to the owning extension
/// being disabled, and emits diagnostic messages if it is disabled.
/// \param D type or declaration to be checked.
/// \param DiagLoc source location for the diagnostic message.
/// \param DiagInfo information to be emitted for the diagnostic message.
/// \param SrcRange source range of the declaration.
/// \param Map maps type or declaration to the extensions.
/// \param Selector selects diagnostic message: 0 for type and 1 for
/// declaration.
/// \return true if the type or declaration is disabled.
template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
MapT &Map, unsigned Selector = 0,
SourceRange SrcRange = SourceRange());
/// Marks all the functions that might be required for the currently active
/// OpenMP context.
void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
FunctionDecl *Func,
bool MightBeOdrUse);
public:
/// Struct to store the context selectors info for declare variant directive.
struct OpenMPDeclareVariantCtsSelectorData {
OMPDeclareVariantAttr::CtxSelectorSetType CtxSet =
OMPDeclareVariantAttr::CtxSetUnknown;
OMPDeclareVariantAttr::CtxSelectorType Ctx =
OMPDeclareVariantAttr::CtxUnknown;
MutableArrayRef<StringRef> ImplVendors;
ExprResult CtxScore;
explicit OpenMPDeclareVariantCtsSelectorData() = default;
explicit OpenMPDeclareVariantCtsSelectorData(
OMPDeclareVariantAttr::CtxSelectorSetType CtxSet,
OMPDeclareVariantAttr::CtxSelectorType Ctx,
MutableArrayRef<StringRef> ImplVendors, ExprResult CtxScore)
: CtxSet(CtxSet), Ctx(Ctx), ImplVendors(ImplVendors),
CtxScore(CtxScore) {}
};
/// Checks if the variant/multiversion functions are compatible.
bool areMultiversionVariantFunctionsCompatible(
const FunctionDecl *OldFD, const FunctionDecl *NewFD,
const PartialDiagnostic &NoProtoDiagID,
const PartialDiagnosticAt &NoteCausedDiagIDAt,
const PartialDiagnosticAt &NoSupportDiagIDAt,
const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
bool ConstexprSupported, bool CLinkageMayDiffer);
/// Function tries to capture lambda's captured variables in the OpenMP region
/// before the original lambda is captured.
void tryCaptureOpenMPLambdas(ValueDecl *V);
/// Return true if the provided declaration \a VD should be captured by
/// reference.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
/// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
unsigned OpenMPCaptureLevel) const;
/// Check if the specified variable is used in one of the private
/// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
/// constructs.
VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
unsigned StopAt = 0);
ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
ExprObjectKind OK, SourceLocation Loc);
/// If the current region is a loop-based region, mark the start of the loop
/// construct.
void startOpenMPLoop();
/// If the current region is a range loop-based region, mark the start of the
/// loop construct.
void startOpenMPCXXRangeFor();
/// Check if the specified variable is used in 'private' clause.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
/// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
/// for \p FD based on DSA for the provided corresponding captured declaration
/// \p D.
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
/// Check if the specified variable is captured by 'target' directive.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// End analysis of clauses.
void EndOpenMPClause();
/// Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
OpenMPDirectiveKind Kind);
/// Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Called on well-formed '#pragma omp allocate'.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
ArrayRef<Expr *> VarList,
ArrayRef<OMPClause *> Clauses,
DeclContext *Owner = nullptr);
/// Called on well-formed '#pragma omp requires'.
DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
ArrayRef<OMPClause *> ClauseList);
/// Check restrictions on Requires directive
OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
ArrayRef<OMPClause *> Clauses);
/// Check if the specified type is allowed to be used in 'omp declare
/// reduction' construct.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name,
ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
/// Initialize declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
/// Initialize declare reduction construct initializer.
/// \return omp_priv variable.
VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
VarDecl *OmpPrivParm);
/// Called at the end of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
/// Check variable declaration in 'omp declare mapper' construct.
TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
/// Check if the specified type is allowed to be used in 'omp declare
/// mapper' construct.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare mapper'.
OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
Decl *PrevDeclInScope = nullptr);
/// Build the mapper variable of '#pragma omp declare mapper'.
void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
Scope *S, QualType MapperType,
SourceLocation StartLoc,
DeclarationName VN);
/// Called at the end of '#pragma omp declare mapper'.
DeclGroupPtrTy
ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
ArrayRef<OMPClause *> ClauseList);
/// Called on the start of target region i.e. '#pragma omp declare target'.
bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
/// Called at the end of target region i.e. '#pragme omp end declare target'.
void ActOnFinishOpenMPDeclareTargetDirective();
/// Searches for the provided declaration name for OpenMP declare target
/// directive.
NamedDecl *
lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
NamedDeclSetType &SameDirectiveDecls);
/// Called on correct id-expression from the '#pragma omp declare target'.
void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
OMPDeclareTargetDeclAttr::MapTypeTy MT,
OMPDeclareTargetDeclAttr::DevTypeTy DT);
/// Check declaration inside target region.
void
checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
SourceLocation IdLoc = SourceLocation());
/// Return true inside OpenMP declare target region.
bool isInOpenMPDeclareTargetContext() const {
return DeclareTargetNestingLevel > 0;
}
/// Return true inside OpenMP target region.
bool isInOpenMPTargetExecutionDirective() const;
/// Return the number of captured regions created for an OpenMP directive.
static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
/// Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
using VarsWithInheritedDSAType =
llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
/// Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target data' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target enter data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target exit data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target parallel' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp taskloop' after parsing of the
/// associated statement.
StmtResult
ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target update'.
StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp distribute parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target simd' after parsing of
/// the associated statement.
StmtResult
ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target teams distribute' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for
/// simd' after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Checks correctness of linear modifiers.
bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
SourceLocation LinLoc);
/// Checks that the specified declaration matches requirements for the linear
/// decls.
bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
OpenMPLinearClauseKind LinKind, QualType Type);
/// Called on well-formed '\#pragma omp declare simd' after parsing of
/// the associated method/function.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
/// Checks '\#pragma omp declare variant' variant function and original
/// functions after parsing of the associated method/function.
/// \param DG Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \returns None, if the function/variant function are not compatible with
/// the pragma, pair of original function/variant ref expression otherwise.
Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
/// Called on well-formed '\#pragma omp declare variant' after parsing of
/// the associated method/function.
/// \param FD Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \param Data Set of context-specific data for the specified context
/// selector.
void ActOnOpenMPDeclareVariantDirective(
FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
const Sema::OpenMPDeclareVariantCtsSelectorData &Data);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'allocator' clause.
OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation NameModifierLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simdlen' clause.
OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'ordered' clause.
OMPClause *
ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
SourceLocation LParenLoc = SourceLocation(),
Expr *NumForLoops = nullptr);
/// Called on well-formed 'grainsize' clause.
OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_tasks' clause.
OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'hint' clause.
OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(
OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
SourceLocation StartLoc, SourceLocation LParenLoc,
ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
SourceLocation EndLoc);
/// Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(
OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'threads' clause.
OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simd' clause.
OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nogroup' clause.
OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reverse_offload' clause.
OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dynamic_allocators' clause.
OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'atomic_default_mem_order' clause.
OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
CXXScopeSpec &ReductionOrMapperIdScopeSpec,
DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
OpenMPLinearClauseKind LinKind,
ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
bool IsMapTypeImplicit, SourceLocation DepLinMapLoc);
/// 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,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reduction' clause.
OMPClause *ActOnOpenMPReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'task_reduction' clause.
OMPClause *ActOnOpenMPTaskReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'in_reduction' clause.
OMPClause *ActOnOpenMPInReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'linear' clause.
OMPClause *
ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
SourceLocation ColonLoc, SourceLocation EndLoc);
/// Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'device' clause.
OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'map' clause.
OMPClause *
ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc,
CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
SourceLocation MapLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'num_teams' clause.
OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'thread_limit' clause.
OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'priority' clause.
OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dist_schedule' clause.
OMPClause *ActOnOpenMPDistScheduleClause(
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
SourceLocation CommaLoc, SourceLocation EndLoc);
/// Called on well-formed 'defaultmap' clause.
OMPClause *ActOnOpenMPDefaultmapClause(
OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
SourceLocation KindLoc, SourceLocation EndLoc);
/// Called on well-formed 'to' clause.
OMPClause *
ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'from' clause.
OMPClause *ActOnOpenMPFromClause(
ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'use_device_ptr' clause.
OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'is_device_ptr' clause.
OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// The kind of conversion being performed.
enum CheckedConversionKind {
/// An implicit conversion.
CCK_ImplicitConversion,
/// A C-style cast.
CCK_CStyleCast,
/// A functional-style cast.
CCK_FunctionalCast,
/// A cast other than a C-style cast.
CCK_OtherCast,
/// A conversion for an operand of a builtin overloaded operator.
CCK_ForBuiltinOverloadedOp
};
static bool isCast(CheckedConversionKind CCK) {
return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
CCK == CCK_OtherCast;
}
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_RValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
bool Diagnose = true);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This is DefaultFunctionArrayLvalueConversion,
// except that it assumes the operand isn't of function or array
// type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
/// If \p E is a prvalue denoting an unmaterialized temporary, materialize
/// it as an xvalue. In C++98, the result will still be a prvalue, because
/// we don't have xvalues there.
ExprResult TemporaryMaterializationConversion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
// 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,
bool IsCompAssign = false);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatiblePointerSign - The assignment is between two pointers types
/// which point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
/// changes address spaces in nested pointer types which is not allowed.
/// For instance, converting __private int ** to __generic int ** is
/// illegal even though __private could be converted to __generic.
IncompatibleNestedPointerAddressSpaceMismatch,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and optionally prepare for a conversion of
/// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
/// is true.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind,
bool ConvertRHS = true);
/// Check assignment constraints for an assignment of RHS to LHSType.
///
/// \param LHSType The destination type for the assignment.
/// \param RHS The source expression for the assignment.
/// \param Diagnose If \c true, diagnostics may be produced when checking
/// for assignability. If a diagnostic is produced, \p RHS will be
/// set to ExprError(). Note that this function may still return
/// without producing a diagnostic, even for an invalid assignment.
/// \param DiagnoseCFAudited If \c true, the target is a function parameter
/// in an audited Core Foundation API and does not need to be checked
/// for ARC retain issues.
/// \param ConvertRHS If \c true, \p RHS will be updated to model the
/// conversions necessary to perform the assignment. If \c false,
/// \p Diagnose must also be \c false.
AssignConvertType CheckSingleAssignmentConstraints(
QualType LHSType, ExprResult &RHS, bool Diagnose = true,
bool DiagnoseCFAudited = false, bool ConvertRHS = true);
// If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
ExprResult PerformQualificationConversion(
Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
CheckedConversionKind CCK = CCK_ImplicitConversion);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, bool IsCompAssign = false);
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool ConvertArgs = true);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool ConvertArgs = true) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite =
FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool, bool AllowBoolConversion);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible - The two types are reference-compatible.
Ref_Compatible
};
ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
bool &DerivedToBase, bool &ObjCConversion,
bool &ObjCLifetimeConversion,
bool &FunctionConversion);
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);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
/// Prepare `SplattedExpr` for a vector splat operation, adding
/// implicit casts if necessary.
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
/// Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds for ARC and Weak.
ARCConversionResult CheckObjCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool Diagnose = true,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage, SourceLocation lbrac,
SourceLocation rbrac, SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage);
/// If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
class ConditionResult {
Decl *ConditionVar;
FullExprArg Condition;
bool Invalid;
bool HasKnownValue;
bool KnownValue;
friend class Sema;
ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
bool IsConstexpr)
: ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
HasKnownValue(IsConstexpr && Condition.get() &&
!Condition.get()->isValueDependent()),
KnownValue(HasKnownValue &&
!!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
explicit ConditionResult(bool Invalid)
: ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
HasKnownValue(false), KnownValue(false) {}
public:
ConditionResult() : ConditionResult(false) {}
bool isInvalid() const { return Invalid; }
std::pair<VarDecl *, Expr *> get() const {
return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
Condition.get());
}
llvm::Optional<bool> getKnownValue() const {
if (!HasKnownValue)
return None;
return KnownValue;
}
};
static ConditionResult ConditionError() { return ConditionResult(true); }
enum class ConditionKind {
Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
Switch ///< An integral condition for a 'switch' statement.
};
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr, ConditionKind CK);
ConditionResult ActOnConditionVariable(Decl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
bool IsConstexpr = false);
/// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
/// found in an explicit(bool) specifier.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
/// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
/// Returns true if the explicit specifier is now resolved.
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr);
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
private:
unsigned ForceCUDAHostDeviceDepth = 0;
public:
/// Increments our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. So long as this count is greater
/// than zero, all functions encountered will be __host__ __device__.
void PushForceCUDAHostDevice();
/// Decrements our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. Returns false if the count is 0
/// before incrementing, so you can emit an error.
bool PopForceCUDAHostDevice();
/// Diagnostics that are emitted only if we discover that the given function
/// must be codegen'ed. Because handling these correctly adds overhead to
/// compilation, this is currently only enabled for CUDA compilations.
llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
std::vector<PartialDiagnosticAt>>
DeviceDeferredDiags;
/// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
/// key in a hashtable, both the FD and location are hashed.
struct FunctionDeclAndLoc {
CanonicalDeclPtr<FunctionDecl> FD;
SourceLocation Loc;
};
/// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
/// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
/// same deferred diag twice.
llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
/// An inverse call graph, mapping known-emitted functions to one of their
/// known-emitted callers (plus the location of the call).
///
/// Functions that we can tell a priori must be emitted aren't added to this
/// map.
llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
/* Caller = */ FunctionDeclAndLoc>
DeviceKnownEmittedFns;
/// A partial call graph maintained during CUDA/OpenMP device code compilation
/// to support deferred diagnostics.
///
/// Functions are only added here if, at the time they're considered, they are
/// not known-emitted. As soon as we discover that a function is
/// known-emitted, we remove it and everything it transitively calls from this
/// set and add those functions to DeviceKnownEmittedFns.
llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
/* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
SourceLocation>>
DeviceCallGraph;
/// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
/// deferred.
///
/// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
/// which are not allowed to appear inside __device__ functions and are
/// allowed to appear in __host__ __device__ functions only if the host+device
/// function is never codegen'ed.
///
/// To handle this, we use the notion of "deferred diagnostics", where we
/// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
///
/// This class lets you emit either a regular diagnostic, a deferred
/// diagnostic, or no diagnostic at all, according to an argument you pass to
/// its constructor, thus simplifying the process of creating these "maybe
/// deferred" diagnostics.
class DeviceDiagBuilder {
public:
enum Kind {
/// Emit no diagnostics.
K_Nop,
/// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
K_Immediate,
/// Emit the diagnostic immediately, and, if it's a warning or error, also
/// emit a call stack showing how this function can be reached by an a
/// priori known-emitted function.
K_ImmediateWithCallStack,
/// Create a deferred diagnostic, which is emitted only if the function
/// it's attached to is codegen'ed. Also emit a call stack as with
/// K_ImmediateWithCallStack.
K_Deferred
};
DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
FunctionDecl *Fn, Sema &S);
DeviceDiagBuilder(DeviceDiagBuilder &&D);
DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
~DeviceDiagBuilder();
/// Convertible to bool: True if we immediately emitted an error, false if
/// we didn't emit an error or we created a deferred error.
///
/// Example usage:
///
/// if (DeviceDiagBuilder(...) << foo << bar)
/// return ExprError();
///
/// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
/// want to use these instead of creating a DeviceDiagBuilder yourself.
operator bool() const { return ImmediateDiag.hasValue(); }
template <typename T>
friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
const T &Value) {
if (Diag.ImmediateDiag.hasValue())
*Diag.ImmediateDiag << Value;
else if (Diag.PartialDiagId.hasValue())
Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
<< Value;
return Diag;
}
private:
Sema &S;
SourceLocation Loc;
unsigned DiagID;
FunctionDecl *Fn;
bool ShowCallStack;
// Invariant: At most one of these Optionals has a value.
// FIXME: Switch these to a Variant once that exists.
llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
llvm::Optional<unsigned> PartialDiagId;
};
/// Indicate that this function (and thus everything it transtively calls)
/// will be codegen'ed, and emit any deferred diagnostics on this function and
/// its (transitive) callees.
void markKnownEmitted(
Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
SourceLocation OrigLoc,
const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as device code".
///
/// - If CurContext is a __host__ function, does not emit any diagnostics.
/// - If CurContext is a __device__ or __global__ function, emits the
/// diagnostics immediately.
/// - If CurContext is a __host__ __device__ function and we are compiling for
/// the device, creates a diagnostic which is emitted if and when we realize
/// that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in CUDA device code.
/// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the device, emits the diagnostics immediately.
/// - If CurContext is a non-`declare target` function and we are compiling
/// for the device, creates a diagnostic which is emitted if and when we
/// realize that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current
/// context is "used as host code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the host, emits the diagnostics immediately.
/// - If CurContext is a non-host function, just ignore it.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
/// Determines whether the given function is a CUDA device/host/kernel/etc.
/// function.
///
/// Use this rather than examining the function's attributes yourself -- you
/// will get it wrong. Returns CFT_Host if D is null.
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
bool IgnoreImplicitHDAttr = false);
CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
/// Gets the CUDA target for the current context.
CUDAFunctionTarget CurrentCUDATarget() {
return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
}
// CUDA function call preference. Must be ordered numerically from
// worst to best.
enum CUDAFunctionPreference {
CFP_Never, // Invalid caller/callee combination.
CFP_WrongSide, // Calls from host-device to host or device
// function that do not match current compilation
// mode.
CFP_HostDevice, // Any calls to host/device functions.
CFP_SameSide, // Calls from host-device to host or device
// function matching current compilation mode.
CFP_Native, // host-to-host or device-to-device calls.
};
/// Identifies relative preference of a given Caller/Callee
/// combination, based on their host/device attributes.
/// \param Caller function which needs address of \p Callee.
/// nullptr in case of global context.
/// \param Callee target function
///
/// \returns preference value for particular Caller/Callee combination.
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
const FunctionDecl *Callee);
/// Determines whether Caller may invoke Callee, based on their CUDA
/// host/device attributes. Returns false if the call is not allowed.
///
/// Note: Will return true for CFP_WrongSide calls. These may appear in
/// semantically correct CUDA programs, but only if they're never codegen'ed.
bool IsAllowedCUDACall(const FunctionDecl *Caller,
const FunctionDecl *Callee) {
return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
}
/// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
/// depending on FD and the current compilation settings.
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
const LookupResult &Previous);
public:
/// Check whether we're allowed to call Callee from the current context.
///
/// - If the call is never allowed in a semantically-correct program
/// (CFP_Never), emits an error and returns false.
///
/// - If the call is allowed in semantically-correct programs, but only if
/// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
/// be emitted if and when the caller is codegen'ed, and returns true.
///
/// Will only create deferred diagnostics for a given SourceLocation once,
/// so you can safely call this multiple times without generating duplicate
/// deferred errors.
///
/// - Otherwise, returns true without emitting any diagnostics.
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
/// Set __device__ or __host__ __device__ attributes on the given lambda
/// operator() method.
///
/// CUDA lambdas declared inside __device__ or __global__ functions inherit
/// the __device__ attribute. Similarly, lambdas inside __host__ __device__
/// functions become __host__ __device__ themselves.
void CUDASetLambdaAttrs(CXXMethodDecl *Method);
/// Finds a function in \p Matches with highest calling priority
/// from \p Caller context and erases all functions with lower
/// calling priority.
void EraseUnwantedCUDAMatches(
const FunctionDecl *Caller,
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \return true if \p CD can be considered empty according to CUDA
/// (E.2.3.1 in CUDA 7.5 Programming guide).
bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
// \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
// case of error emits appropriate diagnostic and invalidates \p Var.
//
// \details CUDA allows only empty constructors as initializers for global
// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
// __shared__ variables whether they are local or not (they all are implicitly
// static in CUDA). One exception is that CUDA allows constant initializers
// for __constant__ and __device__ variables.
void checkAllowedCUDAInitializer(VarDecl *VD);
/// Check whether NewFD is a valid overload for CUDA. Emits
/// diagnostics and invalidates NewFD if not.
void checkCUDATargetOverload(FunctionDecl *NewFD,
const LookupResult &Previous);
/// Copies target attributes from the template TD to the function FD.
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
/// Returns the name of the launch configuration function. This is the name
/// of the function that will be called to configure kernel call, with the
/// parameters specified via <<<>>>.
std::string getCudaConfigureFuncName() const;
/// \name Code completion
//@{
/// Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// Code completion occurs within a class, struct, or union.
PCC_Class,
/// Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// Code completion occurs following one or more template
/// headers.
PCC_Template,
/// Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// Code completion occurs within an expression.
PCC_Expression,
/// Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// Code completion occurs where only a type is permitted.
PCC_Type,
/// Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteExpression(Scope *S, QualType PreferredType,
bool IsParenthesized = false);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement,
QualType PreferredType);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
QualType PreferredType);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
const VirtSpecifiers *VS = nullptr);
void CodeCompleteBracketDeclarator(Scope *S);
void CodeCompleteCase(Scope *S);
/// Reports signatures for a call to CodeCompleteConsumer and returns the
/// preferred type for the current argument. Returned type can be null.
QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
SourceLocation Loc,
ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
CXXScopeSpec SS,
ParsedType TemplateTypeTy,
ArrayRef<Expr *> ArgExprs,
IdentifierInfo *II,
SourceLocation OpenParLoc);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
bool IsUsingDeclaration, QualType BaseType,
QualType PreferredType);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(
ArrayRef<IdentifierLocPair> Protocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
SourceLocation ClassNameLoc,
bool IsBaseExprStatement);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
void CodeCompleteNaturalLanguage();
void CodeCompleteAvailabilityPlatformName();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
const Expr *ThisArg, ArrayRef<const Expr *> Args,
bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckOSLogFormatStringArg(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
bool SemaBuiltinVSX(CallExpr *TheCall);
bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
bool IsDelete);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
int High, bool RangeIsError = true);
bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
unsigned Multiple);
bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_OSLog,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
bool FormatStringHasSArg(const StringLiteral *FExpr);
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl);
void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
public:
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
private:
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// Check if there is a field shadowing.
void CheckShadowInheritedFields(const SourceLocation &Loc,
DeclarationName FieldName,
const CXXRecordDecl *RD,
bool DeclIsField = true);
/// Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const ArrayRef<const Expr *> ExprArgs,
SourceLocation CallSiteLoc);
/// Check if we are taking the address of a packed field
/// as this may be a problem if the pointer value is dereferenced.
void CheckAddressOfPackedMember(Expr *rhs);
/// The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
/// The handler for the FileChanged preprocessor events.
///
/// Used for diagnostics that implement custom semantic analysis for #include
/// directives, like -Wpragma-pack.
sema::SemaPPCallbacks *SemaPPCallbackHandler;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
bool isCFError(RecordDecl *D);
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
// Emitting members of dllexported classes is delayed until the class
// (including field initializers) is fully parsed.
SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
private:
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");
assert(S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes");
swapSavedState();
}
private:
Sema &S;
decltype(DelayedOverridingExceptionSpecChecks)
SavedOverridingExceptionSpecChecks;
decltype(DelayedEquivalentExceptionSpecChecks)
SavedEquivalentExceptionSpecChecks;
decltype(DelayedDllExportClasses) SavedDllExportClasses;
void swapSavedState() {
SavedOverridingExceptionSpecChecks.swap(
S.DelayedOverridingExceptionSpecChecks);
SavedEquivalentExceptionSpecChecks.swap(
S.DelayedEquivalentExceptionSpecChecks);
SavedDllExportClasses.swap(S.DelayedDllExportClasses);
}
};
/// Helper class that collects misaligned member designations and
/// their location info for delayed diagnostics.
struct MisalignedMember {
Expr *E;
RecordDecl *RD;
ValueDecl *MD;
CharUnits Alignment;
MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment)
: E(E), RD(RD), MD(MD), Alignment(Alignment) {}
explicit MisalignedMember(Expr *E)
: MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
bool operator==(const MisalignedMember &m) { return this->E == m.E; }
};
/// Small set of gathered accesses to potentially misaligned members
/// due to the packed attribute.
SmallVector<MisalignedMember, 4> MisalignedMembers;
/// Adds an expression to the set of gathered misaligned members.
void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment);
public:
/// Diagnoses the current set of gathered accesses. This typically
/// happens at full expression level. The set is cleared after emitting the
/// diagnostics.
void DiagnoseMisalignedMembers();
/// This function checks if the expression is in the sef of potentially
/// misaligned members and it is converted to some pointer type T with lower
/// or equal alignment requirements. If so it removes it. This is used when
/// we do not want to diagnose such misaligned access (e.g. in conversions to
/// void*).
void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
/// This function calls Action when it determines that E designates a
/// misaligned member due to the packed attribute. This is used to emit
/// local diagnostics like in reference binding.
void RefersToMemberWithReducedAlignment(
Expr *E,
llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
Action);
/// Describes the reason a calling convention specification was ignored, used
/// for diagnostics.
enum class CallingConventionIgnoredReason {
ForThisTarget = 0,
VariadicFunction,
ConstructorDestructor,
BuiltinFunction
};
};
/// RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
bool Entered = true;
public:
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other,
bool ShouldEnter = true)
: Actions(Actions), Entered(ShouldEnter) {
if (Entered)
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
ExprContext);
}
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(
NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
}
enum InitListTag { InitList };
EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
bool ShouldEnter = true)
: Actions(Actions), Entered(false) {
// In C++11 onwards, narrowing checks are performed on the contents of
// braced-init-lists, even when they occur within unevaluated operands.
// Therefore we still need to instantiate constexpr functions used in such
// a context.
if (ShouldEnter && Actions.isUnevaluatedContext() &&
Actions.getLangOpts().CPlusPlus11) {
Actions.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::UnevaluatedList);
Entered = true;
}
}
~EnterExpressionEvaluationContext() {
if (Entered)
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// The template function declaration to be late parsed.
Decl *D;
};
} // end namespace clang
namespace llvm {
// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
// SourceLocation.
template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
static FunctionDeclAndLoc getEmptyKey() {
return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
}
static FunctionDeclAndLoc getTombstoneKey() {
return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
}
static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
FDL.Loc.getRawEncoding());
}
static bool isEqual(const FunctionDeclAndLoc &LHS,
const FunctionDeclAndLoc &RHS) {
return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
}
};
} // namespace llvm
#endif
|
pcptdesdecryptcbccaomp.c | /*******************************************************************************
* Copyright 2002-2018 Intel Corporation
* All Rights Reserved.
*
* If this software was obtained under the Intel Simplified Software License,
* the following terms apply:
*
* The source code, information and material ("Material") contained herein is
* owned by Intel Corporation or its suppliers or licensors, and title to such
* Material remains with Intel Corporation or its suppliers or licensors. The
* Material contains proprietary information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright laws and treaty
* provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed or disclosed
* in any way without Intel's prior express written permission. No license under
* any patent, copyright or other intellectual property rights in the Material
* is granted to or conferred upon you, either expressly, by implication,
* inducement, estoppel or otherwise. Any license under such intellectual
* property rights must be express and approved by Intel in writing.
*
* Unless otherwise agreed by Intel in writing, you may not remove or alter this
* notice or any other notice embedded in Materials by Intel or Intel's
* suppliers or licensors in any way.
*
*
* If this software was obtained under the Apache License, Version 2.0 (the
* "License"), the following terms apply:
*
* 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.
*******************************************************************************/
/*
// Name:
// ippsTDESDecryptCBC
//
// Purpose:
// Cryptography Primitives.
// Decrypt a byte data stream according to TDES.
//
//
*/
#include "owndefs.h"
#if defined ( _OPENMP )
#include "owncp.h"
#include "pcpdes.h"
#include "pcptool.h"
#include "omp.h"
/*F*
// Name:
// ippsTDESDecryptCBC
//
// Purpose:
// Decrypt byte data stream according to DES in EBC mode using OpenMP API.
//
// Returns:
// ippStsNoErr No errors, it's OK
// ippStsNullPtrErr ( pCtx1 == NULL ) || ( pCtx2 == NULL ) ||
// ( pCtx3 == NULL ) || ( pSrc == NULL ) ||
// ( pDst == NULL ) || ( pIV == NULL )
// ippStsLengthErr srcLen < 1
// ippStsContextMatchErr ( pCtx1->idCtx != idCtxDES ) ||
// ( pCtx2->idCtx != idCtxDES ) ||
// ( pCtx3->idCtx != idCtxDES )
// ippStsUnderRunErr ( srcLen % 8 ) != 0
//
// Parameters:
// pSrc Pointer to the input ciphertext data stream.
// pDst Pointer to the resulting plaintext data stream.
// srcLen Ciphertext data stream length in bytes.
// pCtx DES context.
// pIV Pointers to the IppsDESSpec contexts.
// padding Padding scheme indicator.
//
// Notes:
//
*F*/
static
void TDES_CBC_processing(const Ipp8u* pIV,
const Ipp8u* pSrc, Ipp8u* pDst, int nBlocks,
const RoundKeyDES* pRKey[3])
{
/* copy IV */
Ipp64u iv;
CopyBlock8(pIV, &iv);
/*
// decrypt block-by-block aligned streams
*/
if( !(IPP_UINT_PTR(pSrc) & 0x7) && !(IPP_UINT_PTR(pDst) & 0x7) && pSrc!=pDst) {
DecryptCBC_TDES((const Ipp64u*)pSrc, (Ipp64u*)pDst, nBlocks, pRKey, iv, DESspbox);
}
/*
// decrypt block-by-block misaligned streams
*/
else {
Ipp64u tmpInp;
Ipp64u tmpOut;
while(nBlocks) {
CopyBlock8(pSrc, &tmpInp);
tmpOut = Cipher_DES(tmpInp, pRKey[0], DESspbox);
tmpOut = Cipher_DES(tmpOut, pRKey[1], DESspbox);
tmpOut = iv ^ Cipher_DES(tmpOut, pRKey[2], DESspbox);
CopyBlock8(&tmpOut, pDst);
iv = tmpInp;
pSrc += MBS_DES;
pDst += MBS_DES;
nBlocks--;
}
}
}
IPPFUN( IppStatus, ippsTDESDecryptCBC,(const Ipp8u* pSrc, Ipp8u* pDst, int srcLen,
const IppsDESSpec* pCtx1,
const IppsDESSpec* pCtx2,
const IppsDESSpec* pCtx3,
const Ipp8u* pIV,
IppsPadding padding))
{
/* test the pointers */
IPP_BAD_PTR3_RET(pCtx1, pCtx2, pCtx3);
IPP_BAD_PTR3_RET(pSrc, pIV, pDst);
/* align the context */
pCtx1 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx1, DES_ALIGNMENT));
pCtx2 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx2, DES_ALIGNMENT));
pCtx3 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx3, DES_ALIGNMENT));
/* test the context */
IPP_BADARG_RET(!DES_ID_TEST(pCtx1), ippStsContextMatchErr);
IPP_BADARG_RET(!DES_ID_TEST(pCtx2), ippStsContextMatchErr);
IPP_BADARG_RET(!DES_ID_TEST(pCtx3), ippStsContextMatchErr);
/* test the data stream length */
IPP_BADARG_RET((srcLen<1), ippStsLengthErr);
/* Test data stream integrity. */
IPP_BADARG_RET((srcLen&(MBS_DES-1)), ippStsUnderRunErr);
UNREFERENCED_PARAMETER(padding);
{
int nBlocks = srcLen / MBS_DES;
int nThreads = IPP_MIN(IPPCP_GET_NUM_THREADS(), IPP_MAX(nBlocks/TDES_MIN_BLK_PER_THREAD, 1));
const RoundKeyDES* pRKey[3];
pRKey[0] = DES_DKEYS(pCtx3);
pRKey[1] = DES_EKEYS(pCtx2);
pRKey[2] = DES_DKEYS(pCtx1);
if(1==nThreads)
TDES_CBC_processing(pIV, pSrc, pDst, nBlocks, pRKey);
else {
int blksThreadReg;
int blksThreadTail;
Ipp8u locIV[MBS_DES*DEFAULT_CPU_NUM];
#if defined(__INTEL_COMPILER)
Ipp8u* pLocIV = nThreads>DEFAULT_CPU_NUM? kmp_malloc(nThreads*MBS_DES) : locIV;
#else
Ipp8u* pLocIV = nThreads>DEFAULT_CPU_NUM ? malloc(nThreads*MBS_DES) : locIV;
#endif
if(pLocIV) {
#pragma omp parallel IPPCP_OMP_LIMIT_MAX_NUM_THREADS(nThreads)
{
#pragma omp master
{
int nt;
nThreads = omp_get_num_threads();
blksThreadReg = nBlocks / nThreads;
blksThreadTail = blksThreadReg + nBlocks % nThreads;
CopyBlock8(pIV, pLocIV+0);
for(nt=1; nt<nThreads; nt++)
CopyBlock8(pSrc+nt*blksThreadReg*MBS_DES-MBS_DES, pLocIV+nt*MBS_DES);
}
#pragma omp barrier
{
int id = omp_get_thread_num();
Ipp8u* pThreadIV = (Ipp8u*)pLocIV +id*MBS_DES;
Ipp8u* pThreadSrc = (Ipp8u*)pSrc + id*blksThreadReg*MBS_DES;
Ipp8u* pThreadDst = (Ipp8u*)pDst + id*blksThreadReg*MBS_DES;
int blkThread = (id==(nThreads-1))? blksThreadTail : blksThreadReg;
TDES_CBC_processing(pThreadIV, pThreadSrc, pThreadDst, blkThread, pRKey);
}
}
if (pLocIV != locIV)
#if defined(__INTEL_COMPILER)
kmp_free(pLocIV);
#else
free(pLocIV);
#endif
}
else
return ippStsMemAllocErr;
}
return ippStsNoErr;
}
}
#endif
|
convolution_winograd_transform_fp16s.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv3x3s1_winograd63_transform_output_fp16sa_neon(const Mat& top_blob_tm, Mat& top_blob, const Mat& bias, const Option& opt)
{
const int outw = top_blob.w;
const int outh = top_blob.h;
const int outch = top_blob.c;
const int w_tiles = outw / 6;
const int h_tiles = outh / 6;
const int tiles = w_tiles * h_tiles;
const __fp16* biasptr = bias;
// 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)
#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.channel(p);
const __fp16 bias0 = biasptr ? biasptr[p] : 0.f;
__fp16 tmp[6][8];
// tile
for (int i = 0; i < h_tiles; i++)
{
for (int j = 0; j < w_tiles; j++)
{
const __fp16* output0_tm_0 = (const __fp16*)out0_tm + (i * w_tiles + j) * 1;
const __fp16* output0_tm_1 = output0_tm_0 + tiles * 1;
const __fp16* output0_tm_2 = output0_tm_0 + tiles * 2;
const __fp16* output0_tm_3 = output0_tm_0 + tiles * 3;
const __fp16* output0_tm_4 = output0_tm_0 + tiles * 4;
const __fp16* output0_tm_5 = output0_tm_0 + tiles * 5;
const __fp16* output0_tm_6 = output0_tm_0 + tiles * 6;
const __fp16* output0_tm_7 = output0_tm_0 + tiles * 7;
// TODO neon optimize
for (int m = 0; m < 8; m++)
{
__fp16 tmp024a = output0_tm_1[0] + output0_tm_2[0];
__fp16 tmp135a = output0_tm_1[0] - output0_tm_2[0];
__fp16 tmp024b = output0_tm_3[0] + output0_tm_4[0];
__fp16 tmp135b = output0_tm_3[0] - output0_tm_4[0];
__fp16 tmp024c = output0_tm_5[0] + output0_tm_6[0];
__fp16 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 += tiles * 8;
output0_tm_1 += tiles * 8;
output0_tm_2 += tiles * 8;
output0_tm_3 += tiles * 8;
output0_tm_4 += tiles * 8;
output0_tm_5 += tiles * 8;
output0_tm_6 += tiles * 8;
output0_tm_7 += tiles * 8;
}
__fp16* output0 = out0.row<__fp16>(i * 6) + j * 6;
for (int m = 0; m < 6; m++)
{
const __fp16* tmp0 = tmp[m];
__fp16 tmp024a = tmp0[1] + tmp0[2];
__fp16 tmp135a = tmp0[1] - tmp0[2];
__fp16 tmp024b = tmp0[3] + tmp0[4];
__fp16 tmp135b = tmp0[3] - tmp0[4];
__fp16 tmp024c = tmp0[5] + tmp0[6];
__fp16 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;
}
}
}
}
}
|
no_omp_cpu.c | /*
* Copyright (c) 2015 - 2021, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <assert.h>
void no_omp_cpu(int num_cpu, cpu_set_t *no_omp)
{
int cpu_index, i;
for (i = 0; i < num_cpu; ++i) {
CPU_SET(i, no_omp);
}
#pragma omp parallel default(shared)
{
#pragma omp critical
{
cpu_index = sched_getcpu();
assert(cpu_index < num_cpu);
CPU_CLR(cpu_index, no_omp);
} /* end pragma omp critical */
} /* end pragam omp parallel */
}
int main(int argc, char **argv)
{
int i, num_cpu = sysconf(_SC_NPROCESSORS_ONLN);
cpu_set_t *no_omp = CPU_ALLOC(num_cpu);
no_omp_cpu(num_cpu, no_omp);
printf("Free cpu list: ");
for (i = 0; i < num_cpu; ++i) {
if (CPU_ISSET(i, no_omp)) {
printf("%i ", i);
}
}
printf("\n\n");
CPU_FREE(no_omp);
return 0;
}
|
triplet.c | /* Copyright (C) 2015 Atsushi Togo */
/* All rights reserved. */
/* These codes were originally parts of spglib, but only develped */
/* and used for phono3py. Therefore these were moved from spglib to */
/* phono3py. 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 <stddef.h>
#include <mathfunc.h>
#include <triplet_h/triplet.h>
#include <triplet_h/triplet_iw.h>
#include <triplet_h/triplet_kpoint.h>
static size_t get_triplets_reciprocal_mesh_at_q(size_t *map_triplets,
size_t *map_q,
int (*grid_address)[3],
const int grid_point,
const int mesh[3],
const int is_time_reversal,
const int num_rot,
TPLCONST int (*rotations)[3][3],
const int swappable);
size_t tpl_get_BZ_triplets_at_q(size_t (*triplets)[3],
const size_t grid_point,
TPLCONST int (*bz_grid_address)[3],
const size_t *bz_map,
const size_t *map_triplets,
const size_t num_map_triplets,
const int mesh[3])
{
return tpk_get_BZ_triplets_at_q(triplets,
grid_point,
bz_grid_address,
bz_map,
map_triplets,
num_map_triplets,
mesh);
}
size_t tpl_get_triplets_reciprocal_mesh_at_q(size_t *map_triplets,
size_t *map_q,
int (*grid_address)[3],
const size_t grid_point,
const int mesh[3],
const int is_time_reversal,
const int num_rot,
TPLCONST int (*rotations)[3][3],
const int swappable)
{
return get_triplets_reciprocal_mesh_at_q(map_triplets,
map_q,
grid_address,
grid_point,
mesh,
is_time_reversal,
num_rot,
rotations,
swappable);
}
void tpl_get_integration_weight(double *iw,
char *iw_zero,
const double *frequency_points,
const size_t num_band0,
TPLCONST int relative_grid_address[24][4][3],
const int mesh[3],
TPLCONST size_t (*triplets)[3],
const size_t num_triplets,
TPLCONST int (*bz_grid_address)[3],
const size_t *bz_map,
const double *frequencies,
const size_t num_band,
const size_t num_iw,
const int openmp_per_triplets,
const int openmp_per_bands)
{
size_t i, num_band_prod;
int tp_relative_grid_address[2][24][4][3];
tpl_set_relative_grid_address(tp_relative_grid_address,
relative_grid_address);
num_band_prod = num_band0 * num_band * num_band;
#pragma omp parallel for if (openmp_per_triplets)
for (i = 0; i < num_triplets; i++) {
tpi_get_integration_weight(iw + i * num_band_prod,
iw_zero + i * num_band_prod,
frequency_points,
num_band0,
tp_relative_grid_address,
mesh,
triplets[i],
num_triplets,
bz_grid_address,
bz_map,
frequencies,
num_band,
num_iw,
openmp_per_bands);
}
}
void tpl_get_integration_weight_with_sigma(double *iw,
char *iw_zero,
const double sigma,
const double sigma_cutoff,
const double *frequency_points,
const size_t num_band0,
TPLCONST size_t (*triplets)[3],
const size_t num_triplets,
const double *frequencies,
const size_t num_band,
const size_t num_iw)
{
size_t i, num_band_prod, const_adrs_shift;
double cutoff;
cutoff = sigma * sigma_cutoff;
num_band_prod = num_band0 * num_band * num_band;
const_adrs_shift = num_triplets * num_band0 * num_band * num_band;
#pragma omp parallel for
for (i = 0; i < num_triplets; i++) {
tpi_get_integration_weight_with_sigma(
iw + i * num_band_prod,
iw_zero + i * num_band_prod,
sigma,
cutoff,
frequency_points,
num_band0,
triplets[i],
const_adrs_shift,
frequencies,
num_band,
num_iw,
0);
}
}
int tpl_is_N(const size_t triplet[3], const int *grid_address)
{
int i, j, sum_q, is_N;
is_N = 1;
for (i = 0; i < 3; i++) {
sum_q = 0;
for (j = 0; j < 3; j++) { /* 1st, 2nd, 3rd triplet */
sum_q += grid_address[triplet[j] * 3 + i];
}
if (sum_q) {
is_N = 0;
break;
}
}
return is_N;
}
void tpl_set_relative_grid_address(
int tp_relative_grid_address[2][24][4][3],
TPLCONST int relative_grid_address[24][4][3])
{
int i, j, k, l, sign;
for (i = 0; i < 2; i++) {
sign = 1 - i * 2;
for (j = 0; j < 24; j++) {
for (k = 0; k < 4; k++) {
for (l = 0; l < 3; l++) {
tp_relative_grid_address[i][j][k][l] =
relative_grid_address[j][k][l] * sign;
}
}
}
}
}
static size_t get_triplets_reciprocal_mesh_at_q(size_t *map_triplets,
size_t *map_q,
int (*grid_address)[3],
const int grid_point,
const int mesh[3],
const int is_time_reversal,
const int num_rot,
TPLCONST int (*rotations)[3][3],
const int swappable)
{
MatINT *rot_real;
int i;
size_t num_ir;
rot_real = mat_alloc_MatINT(num_rot);
for (i = 0; i < num_rot; i++) {
mat_copy_matrix_i3(rot_real->mat[i], rotations[i]);
}
num_ir = tpk_get_ir_triplets_at_q(map_triplets,
map_q,
grid_address,
grid_point,
mesh,
is_time_reversal,
rot_real,
swappable);
mat_free_MatINT(rot_real);
return num_ir;
}
|
pomelo_fmt_plug.c | /*
* POMELO cracker patch for JtR. Hacked together during the Hash Runner 2015
* contest by Dhiru Kholia.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_pomelo;
#elif FMT_REGISTERS_H
john_register_one(&fmt_pomelo);
#else
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "arch.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 512 // XXX
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "pomelo"
#define FORMAT_NAME ""
#define FORMAT_TAG "$pomelo$"
#define TAG_LENGTH sizeof(FORMAT_TAG) - 1
#if __SSE2__
#define ALGORITHM_NAME "POMELO 128/128 SSE2 1x"
#elif !defined(USE_GCC_ASM_IA32) && defined(USE_GCC_ASM_X64)
#define ALGORITHM_NAME "POMELO 64/64"
#else
#define ALGORITHM_NAME "POMELO 32/" ARCH_BITS_STR
#endif
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 125
#define CIPHERTEXT_LENGTH 64
#define BINARY_SIZE 32
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN sizeof(ARCH_WORD_32)
#define SALT_ALIGN sizeof(int)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static struct fmt_tests pomelo_tests[] = {
{"$pomelo$2$3$hash runner 2015$8333ad83e46e425872c5545741d6da105cd31ad58926e437d32247e59b26703e", "HashRunner2014"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)];
static struct custom_salt {
unsigned char salt[64];
unsigned int saltlen;
unsigned int t_cost;
unsigned int m_cost;
} *cur_salt;
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
int omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
if (!saved_key) {
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 int valid(char *ciphertext, struct fmt_main *self)
{
char *p = ciphertext;
char Buf[256];
if (strncmp(p, FORMAT_TAG, TAG_LENGTH))
return 0;
p += TAG_LENGTH;
strnzcpy(Buf, p, sizeof(Buf));
p = strtokm(Buf, "$");
if (!p || !isdec(p))
return 0;
p = strtokm(NULL, "$");
if (!p || !isdec(p))
return 0;
p = strtokm(NULL, "$");
if (!p || strlen(p) >= sizeof(cur_salt->salt))
return 0;
p = strtokm(NULL, "$");
if (!p || strlen(p) != CIPHERTEXT_LENGTH)
return 0;
while(*p)
if(atoi16l[ARCH_INDEX(*p++)]==0x7f)
return 0;
return 1;
}
static void *get_salt(char *ciphertext)
{
static struct custom_salt cs;
char *p, *q;
memset(&cs, 0, sizeof(cs));
p = ciphertext + TAG_LENGTH;
cs.t_cost = atoi(p);
p = strchr(p, '$') + 1;
cs.m_cost = atoi(p);
p = strchr(p, '$') + 1;
q = strchr(p, '$');
cs.saltlen = q - p;
strncpy((char*)cs.salt, p, cs.saltlen);
return (void *)&cs;
}
static void *get_binary(char *ciphertext)
{
static unsigned char *out;
int i;
char *p = strrchr(ciphertext, '$') + 1;
if (!out) out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD);
memset(out, 0, BINARY_SIZE);
for (i = 0; i < BINARY_SIZE; i++) {
out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
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 void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
}
int PHS_pomelo(void *out, size_t outlen, const void *in, size_t inlen, const void *salt, size_t saltlen, unsigned int t_cost, unsigned int m_cost);
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
PHS_pomelo((unsigned char *)crypt_out[index], 32, saved_key[index], strlen(saved_key[index]), cur_salt->salt, cur_salt->saltlen, cur_salt->t_cost, cur_salt->m_cost);
}
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], ARCH_SIZE))
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 pomelo_set_key(char *key, int index)
{
int saved_len = strlen(key);
if (saved_len > PLAINTEXT_LENGTH)
saved_len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_len);
saved_key[index][saved_len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_pomelo = {
{
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,
{ NULL },
pomelo_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
set_salt,
pomelo_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 */
|
omp3-3.c | #include<stdio.h>
#ifndef N
#define N 5000
#endif
#define M 1000000000
int a[N][N], b[N][N];
int main() {
int i, j, sum;
#pragma omp parallel sections
{
#pragma omp section
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
a[i][j] = i + j;
}
#pragma omp section
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
b[i][j] = i - j;
}
}
sum = 0;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++) {
sum += a[i][j];
sum %= M;
}
printf("%d\n", sum);
sum = 0;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++) {
sum += b[i][j];
sum %= M;
}
printf("%d\n", sum);
return 0;
}
|
SplitStencil_opt1.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "malloc2D.h"
#include "timer.h"
void SplitStencil(double **a, int imax, int jmax);
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
int main(int argc, char *argv[])
{
#pragma omp parallel
if (omp_get_thread_num() == 0)
printf("Running with %d thread(s)\n",omp_get_num_threads());
struct timespec tstart_init, tstart_flush, tstart_stencil, tstart_total;
double init_time, flush_time, stencil_time, total_time;
int imax=2002, jmax = 2002;
char string[60];
double** a = malloc2D(jmax, imax);
int *flush = (int *)malloc(jmax*imax*sizeof(int)*4);
cpu_timer_start(&tstart_total);
#pragma omp parallel
{
int thread_id = omp_get_thread_num();
int nthreads = omp_get_num_threads();
int jltb = 1 + (jmax-2) * ( thread_id ) / nthreads;
int jutb = 1 + (jmax-2) * ( thread_id + 1 ) / nthreads;
int ifltb = (jmax*imax*4) * ( thread_id ) / nthreads;
int ifutb = (jmax*imax*4) * ( thread_id + 1 ) / nthreads;
int jltb0 = jltb;
if (thread_id == 0) jltb0--;
int jutb0 = jutb;
if (thread_id == nthreads-1) jutb0++;
int kmin = MAX(jmax/2-5,jltb);
int kmax = MIN(jmax/2+5,jutb);
if (thread_id == 0) cpu_timer_start(&tstart_init);
for (int j = jltb0; j < jutb0; j++){
for (int i = 0; i < imax; i++){
a[j][i] = 5.0;
}
}
for (int j = kmin; j < kmax; j++){
for (int i = imax/2 - 5; i < imax/2 -1; i++){
a[j][i] = 400.0;
}
}
#pragma omp barrier
if (thread_id == 0) init_time += cpu_timer_stop(tstart_init);
for (int iter = 0; iter < 10000; iter++){
if (thread_id == 0) cpu_timer_start(&tstart_flush);
for (int l = ifltb; l < ifutb; l++){
flush[l] = 1.0;
}
if (thread_id == 0){
flush_time += cpu_timer_stop(tstart_flush);
sprintf(string,"flush %d\n",flush[5]);
cpu_timer_start(&tstart_stencil);
}
SplitStencil(a, imax, jmax);
if (thread_id == 0){
stencil_time += cpu_timer_stop(tstart_stencil);
sprintf(string,"a %lf\n",a[5][5]);
if (iter%1000 == 0) printf("Iter %d\n",iter);
}
}
} // end omp parallel
total_time += cpu_timer_stop(tstart_total);
printf("Timing is init %f flush %f stencil %f total %f\n",
init_time,flush_time,stencil_time,total_time);
free(a);
free(flush);
}
void SplitStencil(double **a, int imax, int jmax)
{
int thread_id = omp_get_thread_num();
int nthreads = omp_get_num_threads();
int jltb = 1 + (jmax-2) * ( thread_id ) / nthreads;
int jutb = 1 + (jmax-2) * ( thread_id + 1 ) / nthreads;
int jfltb = jltb;
int jfutb = jutb;
if (thread_id == 0) jfltb--;
double** xface = (double **)malloc2D(jutb-jltb, imax-1);
static double** yface;
if (thread_id == 0) yface = (double **)malloc2D(jmax+2, imax);
#pragma omp barrier
for (int j = jltb; j < jutb; j++){
for (int i = 0; i < imax-1; i++){
xface[j-jltb][i] = (a[j][i+1]+a[j][i])/2.0;
}
}
for (int j = jfltb; j < jfutb; j++){
for (int i = 1; i < imax-1; i++){
yface[j][i] = (a[j+1][i]+a[j][i])/2.0;
}
}
#pragma omp barrier
for (int j = jltb; j < jutb; j++){
for (int i = 1; i < imax-1; i++){
a[j][i] = (a[j][i]+xface[j-jltb][i]+xface[j-jltb][i-1]+
yface[j][i]+yface[j-1][i])/5.0;
}
}
free(xface);
#pragma omp barrier
if (thread_id == 0) free(yface);
}
|
convolution_sgemm_pack8to1_int8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void im2col_sgemm_pack8to1_int8_neon(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt)
{
// Mat bottom_im2col(size, maxk, inch, 8u, 8, 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;
// permute
Mat tmp;
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
if (size >= 16)
tmp.create(16 * maxk, inch, size / 16 + (size % 16) / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 8u, 8, opt.workspace_allocator);
#else // __ARM_FEATURE_DOTPROD
if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 8u, 8, opt.workspace_allocator);
#endif // __ARM_FEATURE_DOTPROD
#else // __aarch64__
if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 8u, 8, opt.workspace_allocator);
#endif // __aarch64__
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
int nn_size = size >> 4;
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 * 16;
signed char* tmpptr = tmp.channel(i / 16);
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
// split pack8to1 to pack4
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld2 {v0.4s, v1.4s}, [%0], #32 \n"
"ld2 {v2.4s, v3.4s}, [%0], #32 \n"
"ld2 {v4.4s, v5.4s}, [%0], #32 \n"
"ld2 {v6.4s, v7.4s}, [%0] \n"
"sub %0, %0, #96 \n"
"st1 {v0.16b}, [%1], #16 \n"
"st1 {v2.16b}, [%1], #16 \n"
"st1 {v4.16b}, [%1], #16 \n"
"st1 {v6.16b}, [%1], #16 \n"
"st1 {v1.16b}, [%1], #16 \n"
"st1 {v3.16b}, [%1], #16 \n"
"st1 {v5.16b}, [%1], #16 \n"
"st1 {v7.16b}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7");
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 4;
nn_size = (size - remain_size_start) >> 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8);
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld2 {v0.4s, v1.4s}, [%0], #32 \n"
"ld2 {v2.4s, v3.4s}, [%0] \n"
"sub %0, %0, #32 \n"
"st1 {v0.16b}, [%1], #16 \n"
"st1 {v2.16b}, [%1], #16 \n"
"st1 {v1.16b}, [%1], #16 \n"
"st1 {v3.16b}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3");
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#else // __ARM_FEATURE_DOTPROD
int remain_size_start = 0;
int nn_size = (size - remain_size_start) >> 2;
#endif // __ARM_FEATURE_DOTPROD
#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 __ARM_FEATURE_DOTPROD
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4);
#else
signed char* tmpptr = tmp.channel(i / 4);
#endif
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
#if __ARM_FEATURE_DOTPROD
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld2 {v0.4s, v1.4s}, [%0] \n"
"st1 {v0.4s, v1.4s}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#else
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.16b, v1.16b}, [%0] \n"
"st1 {v0.16b, v1.16b}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#endif // __ARM_FEATURE_DOTPROD
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 2;
nn_size = (size - remain_size_start) >> 1;
#else
int remain_size_start = 0;
int nn_size = (size - remain_size_start) >> 1;
#endif
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 2;
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2);
#else
signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
#endif
#else
signed char* tmpptr = tmp.channel(i / 2);
#endif
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld2 {v0.2s, v1.2s}, [%0] \n"
"st1 {v0.2s, v1.2s}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#else
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.16b}, [%0] \n"
"st1 {v0.16b}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
#endif // __ARM_FEATURE_DOTPROD
#else
asm volatile(
"pld [%0, #128] \n"
"vld1.s8 {d0-d1}, [%0 :64] \n"
"vst1.s8 {d0-d1}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0");
#endif
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
#else
signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
#endif
#else
signed char* tmpptr = tmp.channel(i / 2 + i % 2);
#endif
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #64] \n"
"ld1 {v0.8b}, [%0] \n"
"st1 {v0.8b}, [%1], #8 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
#else
asm volatile(
"pld [%0, #64] \n"
"vld1.s8 {d0}, [%0 :64] \n"
"vst1.s8 {d0}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "d0");
#endif
img0 += size * 8;
}
}
}
}
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 4;
int* outptr0 = top_blob.channel(p);
int* outptr1 = top_blob.channel(p + 1);
int* outptr2 = top_blob.channel(p + 2);
int* outptr3 = top_blob.channel(p + 3);
int i = 0;
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
for (; i + 15 < size; i += 16)
{
const signed char* tmpptr = tmp.channel(i / 16);
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v24.16b}, [%6], #16 \n" // _w0123_l
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"ld1 {v16.16b}, [%5], #16 \n" // _val0123_l
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"eor v4.16b, v4.16b, v4.16b \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"
"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"
"0: \n"
"ld1 {v17.16b}, [%5], #16 \n" // _val4567_l
"sdot v0.4s, v24.16b, v16.4b[0] \n"
"sdot v1.4s, v24.16b, v16.4b[1] \n"
"sdot v2.4s, v24.16b, v16.4b[2] \n"
"sdot v3.4s, v24.16b, v16.4b[3] \n"
"ld1 {v18.16b}, [%5], #16 \n" // _val891011_l
"sdot v4.4s, v24.16b, v17.4b[0] \n"
"sdot v5.4s, v24.16b, v17.4b[1] \n"
"sdot v6.4s, v24.16b, v17.4b[2] \n"
"sdot v7.4s, v24.16b, v17.4b[3] \n"
"ld1 {v19.16b}, [%5], #16 \n" // _val12131415_l
"sdot v8.4s, v24.16b, v18.4b[0] \n"
"sdot v9.4s, v24.16b, v18.4b[1] \n"
"ld1 {v25.16b}, [%6], #16 \n" // _w0123_h
"sdot v10.4s, v24.16b, v18.4b[2] \n"
"sdot v11.4s, v24.16b, v18.4b[3] \n"
"ld1 {v20.16b}, [%5], #16 \n" // _val0123_h
"sdot v12.4s, v24.16b, v19.4b[0] \n"
"sdot v13.4s, v24.16b, v19.4b[1] \n"
"sdot v14.4s, v24.16b, v19.4b[2] \n"
"sdot v15.4s, v24.16b, v19.4b[3] \n"
"ld1 {v21.16b}, [%5], #16 \n" // _val4567_h
"sdot v0.4s, v25.16b, v20.4b[0] \n"
"sdot v1.4s, v25.16b, v20.4b[1] \n"
"sdot v2.4s, v25.16b, v20.4b[2] \n"
"sdot v3.4s, v25.16b, v20.4b[3] \n"
"ld1 {v22.16b}, [%5], #16 \n" // _val891011_h
"sdot v4.4s, v25.16b, v21.4b[0] \n"
"sdot v5.4s, v25.16b, v21.4b[1] \n"
"sdot v6.4s, v25.16b, v21.4b[2] \n"
"sdot v7.4s, v25.16b, v21.4b[3] \n"
"ld1 {v23.16b}, [%5], #16 \n" // _val12131415_h
"sdot v8.4s, v25.16b, v22.4b[0] \n"
"sdot v9.4s, v25.16b, v22.4b[1] \n"
"ld1 {v24.16b}, [%6], #16 \n" // _w0123_l
"sdot v10.4s, v25.16b, v22.4b[2] \n"
"sdot v11.4s, v25.16b, v22.4b[3] \n"
"ld1 {v16.16b}, [%5], #16 \n" // _val0123_l
"sdot v12.4s, v25.16b, v23.4b[0] \n"
"sdot v13.4s, v25.16b, v23.4b[1] \n"
"subs %w4, %w4, #1 \n"
"sdot v14.4s, v25.16b, v23.4b[2] \n"
"sdot v15.4s, v25.16b, v23.4b[3] \n"
"bne 0b \n"
"sub %5, %5, #16 \n"
"sub %6, %6, #16 \n"
// transpose 4x16
"trn1 v16.4s, v0.4s, v1.4s \n"
"trn2 v17.4s, v0.4s, v1.4s \n"
"trn1 v18.4s, v2.4s, v3.4s \n"
"trn2 v19.4s, v2.4s, v3.4s \n"
"trn1 v20.4s, v4.4s, v5.4s \n"
"trn2 v21.4s, v4.4s, v5.4s \n"
"trn1 v22.4s, v6.4s, v7.4s \n"
"trn2 v23.4s, v6.4s, v7.4s \n"
"trn1 v24.4s, v8.4s, v9.4s \n"
"trn2 v25.4s, v8.4s, v9.4s \n"
"trn1 v26.4s, v10.4s, v11.4s \n"
"trn2 v27.4s, v10.4s, v11.4s \n"
"trn1 v28.4s, v12.4s, v13.4s \n"
"trn2 v29.4s, v12.4s, v13.4s \n"
"trn1 v30.4s, v14.4s, v15.4s \n"
"trn2 v31.4s, v14.4s, v15.4s \n"
"trn1 v0.2d, v16.2d, v18.2d \n"
"trn2 v8.2d, v16.2d, v18.2d \n"
"trn1 v4.2d, v17.2d, v19.2d \n"
"trn2 v12.2d, v17.2d, v19.2d \n"
"trn1 v1.2d, v20.2d, v22.2d \n"
"trn2 v9.2d, v20.2d, v22.2d \n"
"trn1 v5.2d, v21.2d, v23.2d \n"
"trn2 v13.2d, v21.2d, v23.2d \n"
"trn1 v2.2d, v24.2d, v26.2d \n"
"trn2 v10.2d, v24.2d, v26.2d \n"
"trn1 v6.2d, v25.2d, v27.2d \n"
"trn2 v14.2d, v25.2d, v27.2d \n"
"trn1 v3.2d, v28.2d, v30.2d \n"
"trn2 v11.2d, v28.2d, v30.2d \n"
"trn1 v7.2d, v29.2d, v31.2d \n"
"trn2 v15.2d, v29.2d, v31.2d \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"st1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%2], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%3], #64 \n"
: "=r"(outptr0),
"=r"(outptr1),
"=r"(outptr2),
"=r"(outptr3),
"=r"(nn),
"=r"(tmpptr),
"=r"(kptr0)
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(nn),
"5"(tmpptr),
"6"(kptr0)
: "memory", "x4", "x5", "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)
{
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8);
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int32x4_t _sum4 = vdupq_n_s32(0);
int32x4_t _sum5 = vdupq_n_s32(0);
int32x4_t _sum6 = vdupq_n_s32(0);
int32x4_t _sum7 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val4567_l = vld1q_s8(tmpptr + 16);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_l, _val0123_l, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_l, _val0123_l, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_l, _val0123_l, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_l, _val0123_l, 3);
_sum4 = vdotq_laneq_s32(_sum4, _w0123_l, _val4567_l, 0);
_sum5 = vdotq_laneq_s32(_sum5, _w0123_l, _val4567_l, 1);
_sum6 = vdotq_laneq_s32(_sum6, _w0123_l, _val4567_l, 2);
_sum7 = vdotq_laneq_s32(_sum7, _w0123_l, _val4567_l, 3);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 32);
int8x16_t _val4567_h = vld1q_s8(tmpptr + 48);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_h, _val0123_h, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_h, _val0123_h, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_h, _val0123_h, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_h, _val0123_h, 3);
_sum4 = vdotq_laneq_s32(_sum4, _w0123_h, _val4567_h, 0);
_sum5 = vdotq_laneq_s32(_sum5, _w0123_h, _val4567_h, 1);
_sum6 = vdotq_laneq_s32(_sum6, _w0123_h, _val4567_h, 2);
_sum7 = vdotq_laneq_s32(_sum7, _w0123_h, _val4567_h, 3);
tmpptr += 64;
kptr0 += 32;
}
// transpose 4x8
int32x4x2_t _s01 = vtrnq_s32(_sum0, _sum1);
int32x4x2_t _s23 = vtrnq_s32(_sum2, _sum3);
int32x4x2_t _s45 = vtrnq_s32(_sum4, _sum5);
int32x4x2_t _s67 = vtrnq_s32(_sum6, _sum7);
_sum0 = vcombine_s32(vget_low_s32(_s01.val[0]), vget_low_s32(_s23.val[0]));
_sum1 = vcombine_s32(vget_low_s32(_s01.val[1]), vget_low_s32(_s23.val[1]));
_sum2 = vcombine_s32(vget_high_s32(_s01.val[0]), vget_high_s32(_s23.val[0]));
_sum3 = vcombine_s32(vget_high_s32(_s01.val[1]), vget_high_s32(_s23.val[1]));
_sum4 = vcombine_s32(vget_low_s32(_s45.val[0]), vget_low_s32(_s67.val[0]));
_sum5 = vcombine_s32(vget_low_s32(_s45.val[1]), vget_low_s32(_s67.val[1]));
_sum6 = vcombine_s32(vget_high_s32(_s45.val[0]), vget_high_s32(_s67.val[0]));
_sum7 = vcombine_s32(vget_high_s32(_s45.val[1]), vget_high_s32(_s67.val[1]));
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr1, _sum1);
vst1q_s32(outptr2, _sum2);
vst1q_s32(outptr3, _sum3);
vst1q_s32(outptr0 + 4, _sum4);
vst1q_s32(outptr1 + 4, _sum5);
vst1q_s32(outptr2 + 4, _sum6);
vst1q_s32(outptr3 + 4, _sum7);
outptr0 += 8;
outptr1 += 8;
outptr2 += 8;
outptr3 += 8;
}
#endif
for (; i + 3 < size; i += 4)
{
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4);
#else
const signed char* tmpptr = tmp.channel(i / 4);
#endif
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_l, _val0123_l, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_l, _val0123_l, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_l, _val0123_l, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_l, _val0123_l, 3);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 16);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_h, _val0123_h, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_h, _val0123_h, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_h, _val0123_h, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_h, _val0123_h, 3);
tmpptr += 32;
kptr0 += 32;
}
// transpose 4x4
int32x4x2_t _s01 = vtrnq_s32(_sum0, _sum1);
int32x4x2_t _s23 = vtrnq_s32(_sum2, _sum3);
_sum0 = vcombine_s32(vget_low_s32(_s01.val[0]), vget_low_s32(_s23.val[0]));
_sum1 = vcombine_s32(vget_low_s32(_s01.val[1]), vget_low_s32(_s23.val[1]));
_sum2 = vcombine_s32(vget_high_s32(_s01.val[0]), vget_high_s32(_s23.val[0]));
_sum3 = vcombine_s32(vget_high_s32(_s01.val[1]), vget_high_s32(_s23.val[1]));
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr1, _sum1);
vst1q_s32(outptr2, _sum2);
vst1q_s32(outptr3, _sum3);
outptr0 += 4;
outptr1 += 4;
outptr2 += 4;
outptr3 += 4;
#else // __ARM_FEATURE_DOTPROD
asm volatile(
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"eor v4.16b, v4.16b, v4.16b \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"
"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"
"prfm pldl1keep, [%5, #128] \n"
"prfm pldl1keep, [%6, #256] \n"
"lsr w4, %w4, #1 \n" // w4 = nn >> 1
"cmp w4, #0 \n"
"beq 1f \n"
"prfm pldl1keep, [%6, #512] \n"
"add x5, %5, #16 \n"
"prfm pldl1keep, [x5, #128] \n"
"ld1 {v16.16b}, [%5] \n" // val L H
"ld1 {v20.16b, v21.16b, v22.16b, v23.16b}, [%6], #64 \n"
"add %5, %5, #32 \n"
"ext v17.16b, v16.16b, v16.16b, #8 \n" // val H L
"ld1 {v18.16b}, [%5] \n"
"add %5, %5, #32 \n"
"0: \n"
"smull v24.8h, v16.8b, v20.8b \n"
"prfm pldl1keep, [%6, #256] \n"
"smull2 v25.8h, v17.16b, v20.16b \n"
"prfm pldl1keep, [%6, #512] \n"
"smull v26.8h, v16.8b, v21.8b \n"
"subs w4, w4, #1 \n"
"smull2 v27.8h, v17.16b, v21.16b \n"
"ext v19.16b, v18.16b, v18.16b, #8 \n" // val H L
"smlal v24.8h, v18.8b, v22.8b \n"
"smlal2 v25.8h, v19.16b, v22.16b \n"
"smlal v26.8h, v18.8b, v23.8b \n"
"smlal2 v27.8h, v19.16b, v23.16b \n"
"smull2 v29.8h, v16.16b, v20.16b \n"
"sadalp v0.4s, v24.8h \n"
"smull v28.8h, v17.8b, v20.8b \n"
"sadalp v1.4s, v25.8h \n"
"smull2 v31.8h, v16.16b, v21.16b \n"
"ld1 {v16.16b}, [x5] \n" // val L H
"smull v30.8h, v17.8b, v21.8b \n"
"add x5, x5, #32 \n"
"smlal2 v29.8h, v18.16b, v22.16b \n"
"sadalp v2.4s, v26.8h \n"
"smlal v28.8h, v19.8b, v22.8b \n"
"sadalp v3.4s, v27.8h \n"
"smlal2 v31.8h, v18.16b, v23.16b \n"
"ld1 {v18.16b}, [x5] \n"
"smlal v30.8h, v19.8b, v23.8b \n"
"ext v17.16b, v16.16b, v16.16b, #8 \n" // val H L
"smull v24.8h, v16.8b, v20.8b \n"
"add x5, x5, #32 \n"
"smull2 v25.8h, v17.16b, v20.16b \n"
"prfm pldl1keep, [x5, #128] \n"
"smull v26.8h, v16.8b, v21.8b \n"
"prfm pldl1keep, [x5, #384] \n"
"smull2 v27.8h, v17.16b, v21.16b \n"
"ext v19.16b, v18.16b, v18.16b, #8 \n" // val H L
"smlal v24.8h, v18.8b, v22.8b \n"
"sadalp v5.4s, v29.8h \n"
"smlal2 v25.8h, v19.16b, v22.16b \n"
"sadalp v4.4s, v28.8h \n"
"smlal v26.8h, v18.8b, v23.8b \n"
"sadalp v7.4s, v31.8h \n"
"smlal2 v27.8h, v19.16b, v23.16b \n"
"sadalp v6.4s, v30.8h \n"
"smull2 v29.8h, v16.16b, v20.16b \n"
"sadalp v8.4s, v24.8h \n"
"smull v28.8h, v17.8b, v20.8b \n"
"sadalp v9.4s, v25.8h \n"
"smull2 v31.8h, v16.16b, v21.16b \n"
"ld1 {v16.16b}, [%5] \n" // val L H
"smull v30.8h, v17.8b, v21.8b \n"
"add %5, %5, #32 \n"
"smlal2 v29.8h, v18.16b, v22.16b \n"
"sadalp v10.4s, v26.8h \n"
"smlal v28.8h, v19.8b, v22.8b \n"
"sadalp v11.4s, v27.8h \n"
"smlal2 v31.8h, v18.16b, v23.16b \n"
"ld1 {v18.16b}, [%5] \n"
"smlal v30.8h, v19.8b, v23.8b \n"
"add %5, %5, #32 \n"
"ld1 {v20.16b, v21.16b, v22.16b, v23.16b}, [%6], #64 \n"
"sadalp v13.4s, v29.8h \n"
"prfm pldl1keep, [%5, #128] \n"
"sadalp v12.4s, v28.8h \n"
"prfm pldl1keep, [%5, #384] \n"
"sadalp v15.4s, v31.8h \n"
"ext v17.16b, v16.16b, v16.16b, #8 \n" // val H L
"sadalp v14.4s, v30.8h \n"
"bne 0b \n"
"sub %5, %5, #64 \n"
"sub %6, %6, #64 \n"
"1: \n"
"and w4, %w4, #1 \n" // w4 = remain = nn & 1
"cmp w4, #0 \n" // w4 > 0
"beq 2f \n"
"ld1 {v16.8b, v17.8b}, [%5], #16 \n"
"ld1 {v20.8b, v21.8b, v22.8b, v23.8b}, [%6], #32 \n"
"smull v24.8h, v16.8b, v20.8b \n"
"smull v25.8h, v16.8b, v21.8b \n"
"smull v26.8h, v16.8b, v22.8b \n"
"ld1 {v18.8b, v19.8b}, [%5], #16 \n"
"smull v27.8h, v16.8b, v23.8b \n"
"sadalp v0.4s, v24.8h \n"
"smull v28.8h, v17.8b, v20.8b \n"
"sadalp v1.4s, v25.8h \n"
"smull v29.8h, v17.8b, v21.8b \n"
"sadalp v2.4s, v26.8h \n"
"smull v30.8h, v17.8b, v22.8b \n"
"sadalp v3.4s, v27.8h \n"
"smull v31.8h, v17.8b, v23.8b \n"
"sadalp v4.4s, v28.8h \n"
"smull v24.8h, v18.8b, v20.8b \n"
"sadalp v5.4s, v29.8h \n"
"smull v25.8h, v18.8b, v21.8b \n"
"sadalp v6.4s, v30.8h \n"
"smull v26.8h, v18.8b, v22.8b \n"
"sadalp v7.4s, v31.8h \n"
"smull v27.8h, v18.8b, v23.8b \n"
"sadalp v8.4s, v24.8h \n"
"smull v28.8h, v19.8b, v20.8b \n"
"sadalp v9.4s, v25.8h \n"
"smull v29.8h, v19.8b, v21.8b \n"
"sadalp v10.4s, v26.8h \n"
"smull v30.8h, v19.8b, v22.8b \n"
"sadalp v11.4s, v27.8h \n"
"smull v31.8h, v19.8b, v23.8b \n"
"sadalp v12.4s, v28.8h \n"
"sadalp v13.4s, v29.8h \n"
"sadalp v14.4s, v30.8h \n"
"sadalp v15.4s, v31.8h \n"
"2: \n"
"addp v0.4s, v0.4s, v4.4s \n"
"addp v1.4s, v1.4s, v5.4s \n"
"addp v2.4s, v2.4s, v6.4s \n"
"addp v3.4s, v3.4s, v7.4s \n"
"addp v8.4s, v8.4s, v12.4s \n"
"addp v9.4s, v9.4s, v13.4s \n"
"addp v10.4s, v10.4s, v14.4s \n"
"addp v11.4s, v11.4s, v15.4s \n"
"addp v0.4s, v0.4s, v8.4s \n"
"addp v1.4s, v1.4s, v9.4s \n"
"addp v2.4s, v2.4s, v10.4s \n"
"addp v3.4s, v3.4s, v11.4s \n"
"st1 {v0.4s}, [%0], #16 \n"
"st1 {v1.4s}, [%1], #16 \n"
"st1 {v2.4s}, [%2], #16 \n"
"st1 {v3.4s}, [%3], #16 \n"
: "=r"(outptr0),
"=r"(outptr1),
"=r"(outptr2),
"=r"(outptr3),
"=r"(nn),
"=r"(tmpptr),
"=r"(kptr0)
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(nn),
"5"(tmpptr),
"6"(kptr0)
: "memory", "x4", "x5", "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");
#endif // __ARM_FEATURE_DOTPROD
}
#endif // __aarch64__
for (; i + 1 < size; i += 2)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
#endif
#else
const signed char* tmpptr = tmp.channel(i / 2);
#endif
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x16_t _val01_l_h = vld1q_s8(tmpptr);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_l, _val01_l_h, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_l, _val01_l_h, 1);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_h, _val01_l_h, 2);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_h, _val01_l_h, 3);
tmpptr += 16;
kptr0 += 32;
}
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
vst1q_lane_s32(outptr0 + 1, _sum1, 0);
vst1q_lane_s32(outptr1 + 1, _sum1, 1);
vst1q_lane_s32(outptr2 + 1, _sum1, 2);
vst1q_lane_s32(outptr3 + 1, _sum1, 3);
outptr0 += 2;
outptr1 += 2;
outptr2 += 2;
outptr3 += 2;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum00 = vdupq_n_s32(0);
int32x4_t _sum01 = vdupq_n_s32(0);
int32x4_t _sum02 = vdupq_n_s32(0);
int32x4_t _sum03 = vdupq_n_s32(0);
int32x4_t _sum10 = vdupq_n_s32(0);
int32x4_t _sum11 = vdupq_n_s32(0);
int32x4_t _sum12 = vdupq_n_s32(0);
int32x4_t _sum13 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv00 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w01));
int16x8_t _wv01 = vmull_s8(vget_low_s8(_val0), vget_high_s8(_w01));
int16x8_t _wv02 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w23));
int16x8_t _wv03 = vmull_s8(vget_low_s8(_val0), vget_high_s8(_w23));
int16x8_t _wv10 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w01));
int16x8_t _wv11 = vmull_s8(vget_high_s8(_val0), vget_high_s8(_w01));
int16x8_t _wv12 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w23));
int16x8_t _wv13 = vmull_s8(vget_high_s8(_val0), vget_high_s8(_w23));
int8x16_t _w45 = vld1q_s8(kptr0 + 32);
int8x16_t _w67 = vld1q_s8(kptr0 + 48);
_wv00 = vmlal_s8(_wv00, vget_low_s8(_val1), vget_low_s8(_w45));
_wv01 = vmlal_s8(_wv01, vget_low_s8(_val1), vget_high_s8(_w45));
_wv02 = vmlal_s8(_wv02, vget_low_s8(_val1), vget_low_s8(_w67));
_wv03 = vmlal_s8(_wv03, vget_low_s8(_val1), vget_high_s8(_w67));
_wv10 = vmlal_s8(_wv10, vget_high_s8(_val1), vget_low_s8(_w45));
_wv11 = vmlal_s8(_wv11, vget_high_s8(_val1), vget_high_s8(_w45));
_wv12 = vmlal_s8(_wv12, vget_high_s8(_val1), vget_low_s8(_w67));
_wv13 = vmlal_s8(_wv13, vget_high_s8(_val1), vget_high_s8(_w67));
_sum00 = vpadalq_s16(_sum00, _wv00);
_sum01 = vpadalq_s16(_sum01, _wv01);
_sum02 = vpadalq_s16(_sum02, _wv02);
_sum03 = vpadalq_s16(_sum03, _wv03);
_sum10 = vpadalq_s16(_sum10, _wv10);
_sum11 = vpadalq_s16(_sum11, _wv11);
_sum12 = vpadalq_s16(_sum12, _wv12);
_sum13 = vpadalq_s16(_sum13, _wv13);
tmpptr += 32;
kptr0 += 64;
}
for (; j < nn; j++)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv00 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w01));
int16x8_t _wv01 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w01));
int16x8_t _wv02 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w23));
int16x8_t _wv03 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w23));
int16x8_t _wv10 = vmull_s8(vget_high_s8(_val), vget_low_s8(_w01));
int16x8_t _wv11 = vmull_s8(vget_high_s8(_val), vget_high_s8(_w01));
int16x8_t _wv12 = vmull_s8(vget_high_s8(_val), vget_low_s8(_w23));
int16x8_t _wv13 = vmull_s8(vget_high_s8(_val), vget_high_s8(_w23));
_sum00 = vpadalq_s16(_sum00, _wv00);
_sum01 = vpadalq_s16(_sum01, _wv01);
_sum02 = vpadalq_s16(_sum02, _wv02);
_sum03 = vpadalq_s16(_sum03, _wv03);
_sum10 = vpadalq_s16(_sum10, _wv10);
_sum11 = vpadalq_s16(_sum11, _wv11);
_sum12 = vpadalq_s16(_sum12, _wv12);
_sum13 = vpadalq_s16(_sum13, _wv13);
tmpptr += 16;
kptr0 += 32;
}
int32x4_t _s001 = vpaddq_s32(_sum00, _sum01);
int32x4_t _s023 = vpaddq_s32(_sum02, _sum03);
int32x4_t _s101 = vpaddq_s32(_sum10, _sum11);
int32x4_t _s123 = vpaddq_s32(_sum12, _sum13);
int32x4_t _sum0 = vpaddq_s32(_s001, _s023);
int32x4_t _sum1 = vpaddq_s32(_s101, _s123);
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
vst1q_lane_s32(outptr0 + 1, _sum1, 0);
vst1q_lane_s32(outptr1 + 1, _sum1, 1);
vst1q_lane_s32(outptr2 + 1, _sum1, 2);
vst1q_lane_s32(outptr3 + 1, _sum1, 3);
outptr0 += 2;
outptr1 += 2;
outptr2 += 2;
outptr3 += 2;
#endif // __ARM_FEATURE_DOTPROD
#else // __aarch64__
asm volatile(
"veor q0, q0 \n"
"veor q1, q1 \n"
"veor q2, q2 \n"
"veor q3, q3 \n"
"veor q4, q4 \n"
"veor q5, q5 \n"
"veor q6, q6 \n"
"veor q7, q7 \n"
"pld [%5, #256] \n"
"lsr r4, %4, #1 \n" // r4 = nn = size >> 1
"cmp r4, #0 \n"
"beq 1f \n"
"add r5, %6, #16 \n"
"pld [%6, #128] \n"
"mov r6, #32 \n"
"pld [%6, #384] \n"
"vld1.s8 {d20-d21}, [%6 :128], r6 \n" // _w01
"vld1.s8 {d16-d19}, [%5 :128]! \n" // _val0 _val1
"vld1.s8 {d22-d23}, [%6 :128], r6 \n" // _w45
"0: \n"
"vmull.s8 q12, d16, d20 \n"
"pld [%5, #256] \n"
"vmull.s8 q13, d16, d21 \n"
"pld [%6, #384] \n"
"vmull.s8 q14, d17, d20 \n"
"vmull.s8 q15, d17, d21 \n"
"vld1.s8 {d20-d21}, [r5 :128], r6 \n" // _w23
"vmlal.s8 q12, d18, d22 \n"
"vmlal.s8 q13, d18, d23 \n"
"subs r4, r4, #1 \n"
"vmlal.s8 q14, d19, d22 \n"
"vmlal.s8 q15, d19, d23 \n"
"vld1.s8 {d22-d23}, [r5 :128], r6 \n" // _w67
"vpadal.s16 q0, q12 \n"
"vmull.s8 q12, d16, d20 \n"
"vpadal.s16 q1, q13 \n"
"vmull.s8 q13, d16, d21 \n"
"vpadal.s16 q4, q14 \n"
"vmull.s8 q14, d17, d20 \n"
"vpadal.s16 q5, q15 \n"
"vmull.s8 q15, d17, d21 \n"
"vld1.s8 {d16-d17}, [%5 :128]! \n" // _val0
"vmlal.s8 q12, d18, d22 \n"
"vld1.s8 {d20-d21}, [%6 :128], r6 \n" // _w01
"vmlal.s8 q13, d18, d23 \n"
"pld [r5, #128] \n"
"vmlal.s8 q14, d19, d22 \n"
"pld [r5, #384] \n"
"vmlal.s8 q15, d19, d23 \n"
"vld1.s8 {d18-d19}, [%5 :128]! \n" // _val1
"vpadal.s16 q2, q12 \n"
"vld1.s8 {d22-d23}, [%6 :128], r6 \n" // _w45
"vpadal.s16 q3, q13 \n"
"pld [%5, #128] \n"
"vpadal.s16 q6, q14 \n"
"pld [%6, #128] \n"
"vpadal.s16 q7, q15 \n"
"bne 0b \n"
"sub %5, %5, #32 \n"
"sub %6, %6, #64 \n"
"1: \n"
"and r4, %4, #1 \n" // r4 = remain = size & 1
"cmp r4, #0 \n" // r4 > 0
"beq 2f \n"
"vld1.s8 {d16-d17}, [%5 :128]! \n" // _val
"vld1.s8 {d20-d21}, [%6 :128]! \n" // _w01
"vmull.s8 q12, d16, d20 \n"
"vld1.s8 {d22-d23}, [%6 :128]! \n" // _w23
"vmull.s8 q13, d16, d21 \n"
"vmull.s8 q14, d17, d20 \n"
"vmull.s8 q15, d17, d21 \n"
"vpadal.s16 q0, q12 \n"
"vmull.s8 q12, d16, d22 \n"
"vpadal.s16 q1, q13 \n"
"vmull.s8 q13, d16, d23 \n"
"vpadal.s16 q4, q14 \n"
"vmull.s8 q14, d17, d22 \n"
"vpadal.s16 q5, q15 \n"
"vmull.s8 q15, d17, d23 \n"
"vpadal.s16 q2, q12 \n"
"vpadal.s16 q3, q13 \n"
"vpadal.s16 q6, q14 \n"
"vpadal.s16 q7, q15 \n"
"2: \n"
"vpadd.s32 d16, d0, d1 \n"
"vpadd.s32 d17, d2, d3 \n"
"vpadd.s32 d18, d4, d5 \n"
"vpadd.s32 d19, d6, d7 \n"
"vpadd.s32 d20, d8, d9 \n"
"vpadd.s32 d21, d10, d11 \n"
"vpadd.s32 d22, d12, d13 \n"
"vpadd.s32 d23, d14, d15 \n"
"vpadd.s32 d0, d16, d17 \n"
"vpadd.s32 d1, d18, d19 \n"
"vpadd.s32 d2, d20, d21 \n"
"vpadd.s32 d3, d22, d23 \n"
"vst1.s32 {d0[0]}, [%0]! \n"
"vst1.s32 {d0[1]}, [%1]! \n"
"vst1.s32 {d1[0]}, [%2]! \n"
"vst1.s32 {d1[1]}, [%3]! \n"
"vst1.s32 {d2[0]}, [%0]! \n"
"vst1.s32 {d2[1]}, [%1]! \n"
"vst1.s32 {d3[0]}, [%2]! \n"
"vst1.s32 {d3[1]}, [%3]! \n"
: "=r"(outptr0),
"=r"(outptr1),
"=r"(outptr2),
"=r"(outptr3),
"=r"(nn),
"=r"(tmpptr),
"=r"(kptr0)
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(nn),
"5"(tmpptr),
"6"(kptr0)
: "memory", "r4", "r5", "r6", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
}
for (; i < size; i++)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
#endif
#else
const signed char* tmpptr = tmp.channel(i / 2 + i % 2);
#endif
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x8_t _val0_l_h = vld1_s8(tmpptr);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _w0123_l, _val0_l_h, 0);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_lane_s32(_sum0, _w0123_h, _val0_l_h, 1);
tmpptr += 8;
kptr0 += 32;
}
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
outptr0 += 1;
outptr1 += 1;
outptr2 += 1;
outptr3 += 1;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv0 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w01));
int16x8_t _wv1 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w01));
int16x8_t _wv2 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w23));
int16x8_t _wv3 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w23));
int8x16_t _w45 = vld1q_s8(kptr0 + 32);
int8x16_t _w67 = vld1q_s8(kptr0 + 48);
_wv0 = vmlal_s8(_wv0, vget_high_s8(_val), vget_low_s8(_w45));
_wv1 = vmlal_s8(_wv1, vget_high_s8(_val), vget_high_s8(_w45));
_wv2 = vmlal_s8(_wv2, vget_high_s8(_val), vget_low_s8(_w67));
_wv3 = vmlal_s8(_wv3, vget_high_s8(_val), vget_high_s8(_w67));
_sum0 = vpadalq_s16(_sum0, _wv0);
_sum1 = vpadalq_s16(_sum1, _wv1);
_sum2 = vpadalq_s16(_sum2, _wv2);
_sum3 = vpadalq_s16(_sum3, _wv3);
tmpptr += 16;
kptr0 += 64;
}
for (; j < nn; j++)
{
int8x8_t _val = vld1_s8(tmpptr);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv0 = vmull_s8(_val, vget_low_s8(_w01));
int16x8_t _wv1 = vmull_s8(_val, vget_high_s8(_w01));
int16x8_t _wv2 = vmull_s8(_val, vget_low_s8(_w23));
int16x8_t _wv3 = vmull_s8(_val, vget_high_s8(_w23));
_sum0 = vpadalq_s16(_sum0, _wv0);
_sum1 = vpadalq_s16(_sum1, _wv1);
_sum2 = vpadalq_s16(_sum2, _wv2);
_sum3 = vpadalq_s16(_sum3, _wv3);
tmpptr += 8;
kptr0 += 32;
}
#if __aarch64__
int32x4_t _s01 = vpaddq_s32(_sum0, _sum1);
int32x4_t _s23 = vpaddq_s32(_sum2, _sum3);
_sum0 = vpaddq_s32(_s01, _s23);
#else
int32x2_t _s01_low = vpadd_s32(vget_low_s32(_sum0), vget_high_s32(_sum0));
int32x2_t _s01_high = vpadd_s32(vget_low_s32(_sum1), vget_high_s32(_sum1));
int32x2_t _s23_low = vpadd_s32(vget_low_s32(_sum2), vget_high_s32(_sum2));
int32x2_t _s23_high = vpadd_s32(vget_low_s32(_sum3), vget_high_s32(_sum3));
_sum0 = vcombine_s32(vpadd_s32(_s01_low, _s01_high), vpadd_s32(_s23_low, _s23_high));
#endif
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
outptr0 += 1;
outptr1 += 1;
outptr2 += 1;
outptr3 += 1;
#endif // __ARM_FEATURE_DOTPROD
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
int* outptr0 = top_blob.channel(p);
int i = 0;
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
for (; i + 15 < size; i += 16)
{
const signed char* tmpptr = tmp.channel(i / 16);
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val4567_l = vld1q_s8(tmpptr + 16);
int8x16_t _val89ab_l = vld1q_s8(tmpptr + 32);
int8x16_t _valcdef_l = vld1q_s8(tmpptr + 48);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 64);
int8x16_t _val4567_h = vld1q_s8(tmpptr + 80);
int8x16_t _val89ab_h = vld1q_s8(tmpptr + 96);
int8x16_t _valcdef_h = vld1q_s8(tmpptr + 112);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_l, _w_lh, 0);
_sum1 = vdotq_lane_s32(_sum1, _val4567_l, _w_lh, 0);
_sum2 = vdotq_lane_s32(_sum2, _val89ab_l, _w_lh, 0);
_sum3 = vdotq_lane_s32(_sum3, _valcdef_l, _w_lh, 0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_h, _w_lh, 1);
_sum1 = vdotq_lane_s32(_sum1, _val4567_h, _w_lh, 1);
_sum2 = vdotq_lane_s32(_sum2, _val89ab_h, _w_lh, 1);
_sum3 = vdotq_lane_s32(_sum3, _valcdef_h, _w_lh, 1);
tmpptr += 128;
kptr0 += 8;
}
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr0 + 4, _sum1);
vst1q_s32(outptr0 + 8, _sum2);
vst1q_s32(outptr0 + 12, _sum3);
outptr0 += 16;
}
for (; i + 7 < size; i += 8)
{
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8);
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val4567_l = vld1q_s8(tmpptr + 16);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 32);
int8x16_t _val4567_h = vld1q_s8(tmpptr + 48);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_l, _w_lh, 0);
_sum1 = vdotq_lane_s32(_sum1, _val4567_l, _w_lh, 0);
_sum2 = vdotq_lane_s32(_sum2, _val0123_h, _w_lh, 1);
_sum3 = vdotq_lane_s32(_sum3, _val4567_h, _w_lh, 1);
tmpptr += 64;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum2);
_sum1 = vaddq_s32(_sum1, _sum3);
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr0 + 4, _sum1);
outptr0 += 8;
}
#endif // __ARM_FEATURE_DOTPROD
for (; i + 3 < size; i += 4)
{
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4);
#else
const signed char* tmpptr = tmp.channel(i / 4);
#endif
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 16);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_l, _w_lh, 0);
_sum1 = vdotq_lane_s32(_sum1, _val0123_h, _w_lh, 1);
tmpptr += 32;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum1);
vst1q_s32(outptr0, _sum0);
outptr0 += 4;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int32x4_t _sum4 = vdupq_n_s32(0);
int32x4_t _sum5 = vdupq_n_s32(0);
int32x4_t _sum6 = vdupq_n_s32(0);
int32x4_t _sum7 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x16_t _val2 = vld1q_s8(tmpptr + 32);
int8x16_t _val3 = vld1q_s8(tmpptr + 48);
int8x16_t _w = vld1q_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w));
int16x8_t _s1 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w));
int16x8_t _s2 = vmull_s8(vget_low_s8(_val1), vget_low_s8(_w));
int16x8_t _s3 = vmull_s8(vget_high_s8(_val1), vget_low_s8(_w));
_s0 = vmlal_s8(_s0, vget_low_s8(_val2), vget_high_s8(_w));
_s1 = vmlal_s8(_s1, vget_high_s8(_val2), vget_high_s8(_w));
_s2 = vmlal_s8(_s2, vget_low_s8(_val3), vget_high_s8(_w));
_s3 = vmlal_s8(_s3, vget_high_s8(_val3), vget_high_s8(_w));
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
_sum4 = vaddw_s16(_sum4, vget_low_s16(_s2));
_sum5 = vaddw_s16(_sum5, vget_high_s16(_s2));
_sum6 = vaddw_s16(_sum6, vget_low_s16(_s3));
_sum7 = vaddw_s16(_sum7, vget_high_s16(_s3));
tmpptr += 64;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x8_t _w = vld1_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val0), _w);
int16x8_t _s1 = vmull_s8(vget_high_s8(_val0), _w);
int16x8_t _s2 = vmull_s8(vget_low_s8(_val1), _w);
int16x8_t _s3 = vmull_s8(vget_high_s8(_val1), _w);
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
_sum4 = vaddw_s16(_sum4, vget_low_s16(_s2));
_sum5 = vaddw_s16(_sum5, vget_high_s16(_s2));
_sum6 = vaddw_s16(_sum6, vget_low_s16(_s3));
_sum7 = vaddw_s16(_sum7, vget_high_s16(_s3));
tmpptr += 32;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum1);
_sum2 = vaddq_s32(_sum2, _sum3);
_sum4 = vaddq_s32(_sum4, _sum5);
_sum6 = vaddq_s32(_sum6, _sum7);
int32x2_t _s0 = vadd_s32(vget_low_s32(_sum0), vget_high_s32(_sum0));
int32x2_t _s2 = vadd_s32(vget_low_s32(_sum2), vget_high_s32(_sum2));
int32x2_t _s4 = vadd_s32(vget_low_s32(_sum4), vget_high_s32(_sum4));
int32x2_t _s6 = vadd_s32(vget_low_s32(_sum6), vget_high_s32(_sum6));
int32x2_t _ss0 = vpadd_s32(_s0, _s2);
int32x2_t _ss1 = vpadd_s32(_s4, _s6);
int32x4_t _ss = vcombine_s32(_ss0, _ss1);
vst1q_s32(outptr0, _ss);
outptr0 += 4;
#endif // __ARM_FEATURE_DOTPROD
}
#endif // __aarch64__
for (; i + 1 < size; i += 2)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
#endif
#else
const signed char* tmpptr = tmp.channel(i / 2);
#endif
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
#if __ARM_FEATURE_DOTPROD
int32x2_t _sum0 = vdup_n_s32(0);
int32x2_t _sum1 = vdup_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val01_lh = vld1q_s8(tmpptr);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdot_lane_s32(_sum0, vget_low_s8(_val01_lh), _w_lh, 0);
_sum1 = vdot_lane_s32(_sum1, vget_high_s8(_val01_lh), _w_lh, 1);
tmpptr += 16;
kptr0 += 8;
}
int32x2_t _sum = vadd_s32(_sum0, _sum1);
vst1_s32(outptr0, _sum);
outptr0 += 2;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x16_t _w = vld1q_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w));
int16x8_t _s1 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w));
_s0 = vmlal_s8(_s0, vget_low_s8(_val1), vget_high_s8(_w));
_s1 = vmlal_s8(_s1, vget_high_s8(_val1), vget_high_s8(_w));
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
tmpptr += 32;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x8_t _w = vld1_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val), _w);
int16x8_t _s1 = vmull_s8(vget_high_s8(_val), _w);
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
tmpptr += 16;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum1);
_sum2 = vaddq_s32(_sum2, _sum3);
int32x2_t _s0 = vadd_s32(vget_low_s32(_sum0), vget_high_s32(_sum0));
int32x2_t _s2 = vadd_s32(vget_low_s32(_sum2), vget_high_s32(_sum2));
int32x2_t _ss = vpadd_s32(_s0, _s2);
vst1_s32(outptr0, _ss);
outptr0 += 2;
#endif // __ARM_FEATURE_DOTPROD
}
for (; i < size; i++)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
#endif
#else
const signed char* tmpptr = tmp.channel(i / 2 + i % 2);
#endif
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x2_t _sum1 = vdup_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w = vld1q_s8(kptr0);
_sum0 = vdotq_s32(_sum0, _val, _w);
tmpptr += 16;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x8_t _val = vld1_s8(tmpptr);
int8x8_t _w = vld1_s8(kptr0);
_sum1 = vdot_s32(_sum1, _val, _w);
tmpptr += 8;
kptr0 += 8;
}
int sum = vaddvq_s32(_sum0) + vaddv_s32(_sum1);
outptr0[0] = sum;
outptr0 += 1;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w = vld1q_s8(kptr0);
int16x8_t _s8 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w));
_s8 = vmlal_s8(_s8, vget_high_s8(_val), vget_high_s8(_w));
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s8));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s8));
tmpptr += 16;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x8_t _val = vld1_s8(tmpptr);
int8x8_t _w = vld1_s8(kptr0);
int16x8_t _s8 = vmull_s8(_val, _w);
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s8));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s8));
tmpptr += 8;
kptr0 += 8;
}
int32x4_t _sum = vaddq_s32(_sum0, _sum1);
#if __aarch64__
int sum = vaddvq_s32(_sum); // dot
#else
int32x2_t _ss = vadd_s32(vget_low_s32(_sum), vget_high_s32(_sum));
_ss = vpadd_s32(_ss, _ss);
int sum = vget_lane_s32(_ss, 0);
#endif
outptr0[0] = sum;
outptr0 += 1;
#endif // __ARM_FEATURE_DOTPROD
}
}
}
static void convolution_im2col_sgemm_transform_kernel_pack8to1_int8_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 = 8a-4b-maxk-inch/8a-outch/4b
// dst = 4a-4b-2-maxk-inch/8a-outch/4b (arm82)
Mat kernel = _kernel.reshape(maxk, inch, outch);
if (outch >= 4)
kernel_tm.create(32 * maxk, inch / 8, outch / 4 + outch % 4, 1u);
else
kernel_tm.create(8 * maxk, inch / 8, outch, 1u);
int q = 0;
for (; q + 3 < outch; q += 4)
{
signed char* g00 = kernel_tm.channel(q / 4);
for (int p = 0; p + 7 < inch; p += 8)
{
for (int k = 0; k < maxk; k++)
{
#if __ARM_FEATURE_DOTPROD
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j);
g00[0] = k00[k];
g00++;
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 4; j < 8; j++)
{
const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j);
g00[0] = k00[k];
g00++;
}
}
#else
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 8; j++)
{
const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j);
g00[0] = k00[k];
g00++;
}
}
#endif
}
}
}
// TODO unroll 2
for (; q < outch; q++)
{
signed char* g00 = kernel_tm.channel(q / 4 + q % 4);
for (int p = 0; p + 7 < inch; p += 8)
{
for (int k = 0; k < maxk; k++)
{
for (int j = 0; j < 8; j++)
{
const signed char* k00 = kernel.channel(q).row<const signed char>(p + j);
g00[0] = k00[k];
g00++;
}
}
}
}
}
static void convolution_im2col_sgemm_pack8to1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, 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, 8, opt.workspace_allocator);
{
const int gap = (w * stride_h - outw * stride_w) * 8;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
signed char* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const signed char* sptr = img.row<const signed char>(dilation_h * u) + dilation_w * v * 8;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
int8x8_t _val0 = vld1_s8(sptr);
int8x8_t _val1 = vld1_s8(sptr + stride_w * 8);
int8x8_t _val2 = vld1_s8(sptr + stride_w * 16);
int8x8_t _val3 = vld1_s8(sptr + stride_w * 24);
vst1_s8(ptr, _val0);
vst1_s8(ptr + 8, _val1);
vst1_s8(ptr + 16, _val2);
vst1_s8(ptr + 24, _val3);
sptr += stride_w * 32;
ptr += 32;
}
for (; j + 1 < outw; j += 2)
{
int8x8_t _val0 = vld1_s8(sptr);
int8x8_t _val1 = vld1_s8(sptr + stride_w * 8);
vst1_s8(ptr, _val0);
vst1_s8(ptr + 8, _val1);
sptr += stride_w * 16;
ptr += 16;
}
for (; j < outw; j++)
{
int8x8_t _val = vld1_s8(sptr);
vst1_s8(ptr, _val);
sptr += stride_w * 8;
ptr += 8;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_pack8to1_int8_neon(bottom_im2col, top_blob, kernel, opt);
}
|
GB_binop__lor_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 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__lor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__lor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__lor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__lor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lor_fp64)
// A*D function (colscale): GB (_AxD__lor_fp64)
// D*A function (rowscale): GB (_DxB__lor_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__lor_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__lor_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lor_fp64)
// C=scalar+B GB (_bind1st__lor_fp64)
// C=scalar+B' GB (_bind1st_tran__lor_fp64)
// C=A+scalar GB (_bind2nd__lor_fp64)
// C=A'+scalar GB (_bind2nd_tran__lor_fp64)
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = ((aij != 0) || (bij != 0))
#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,A_iso) \
double aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
double bij = GBX (Bx, pB, B_iso)
// 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,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 != 0) || (y != 0)) ;
// 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_LOR || GxB_NO_FP64 || GxB_NO_LOR_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
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__lor_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__lor_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
{
#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__lor_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__lor_fp64)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) 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__lor_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 *restrict Cx = (double *) 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__lor_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 *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__lor_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__lor_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__lor_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__lor_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__lor_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
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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
double bij = GBX (Bx, p, false) ;
Cx [p] = ((x != 0) || (bij != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__lor_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 ;
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 = GBX (Ax, p, false) ;
Cx [p] = ((aij != 0) || (y != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no 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 != 0) || (aij != 0)) ; \
}
GrB_Info GB (_bind1st_tran__lor_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 != 0) || (y != 0)) ; \
}
GrB_Info GB (_bind2nd_tran__lor_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
|
unionreduce.h | /******************************************************************************
* ** Copyright (c) 2016, Intel Corporation **
* ** 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 copyright holder 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.
* * ******************************************************************************/
/* Michael Anderson (Intel Corp.)
* * ******************************************************************************/
#ifndef SRC_SINGLENODE_UNIONREDUCE_H_
#define SRC_SINGLENODE_UNIONREDUCE_H_
#include <algorithm>
template <typename Ta, typename Tb, typename Tc>
void union_dense(Ta* v1, int * bv1, int nnz, int num_ints, Tb * v2, int * bv2, Tc * v3, int * bv3,
void (*op_fp)(const Ta&, const Tb&, Tc*, void*), void* vsp)
{
#pragma omp parallel for
for (int ii = 0; ii < nnz; ii++) {
bool set1 = get_bitvector(ii, bv1);
bool set2 = get_bitvector(ii, bv2);
if(set1 && !set2)
{
v3[ii] = v1[ii];
}
else if(!set1 && set2)
{
v3[ii] = v2[ii];
}
else if(set1 && set2)
{
op_fp(v1[ii], v2[ii], &(v3[ii]), vsp);
}
}
#pragma omp parallel for
for(int i = 0 ; i < num_ints ; i++)
{
bv3[i] = bv1[i] | bv2[i];
}
}
template <typename Ta, typename Tb>
void union_compressed(Ta* v1, int* indices, int nnz, int capacity, int num_ints, Tb * v2, int * bv2,
void (*op_fp)(const Ta&, const Tb&, Tb*, void*), void* vsp)
{
//int * indices = reinterpret_cast<int*>(v1 + nnz);
int npartitions = omp_get_max_threads() * 16;
#pragma omp parallel for
for(int p = 0 ; p < npartitions ; p++)
{
int nz_per = (nnz + npartitions - 1) / npartitions;
int start_nnz = p * nz_per;
int end_nnz = (p+1) * nz_per;
if(end_nnz > nnz) end_nnz = nnz;
// Adjust
if(start_nnz > 0)
{
while((start_nnz < nnz) && (indices[start_nnz]/32 == indices[start_nnz-1]/32)) start_nnz++;
}
while((end_nnz < nnz) && (indices[end_nnz]/32 == indices[end_nnz-1]/32)) end_nnz++;
for(int i = start_nnz ; i < end_nnz ; i++)
{
int idx = indices[i];
if(get_bitvector(idx, bv2))
{
//Tb tmp = v2[idx];
//op_fp(v1[i], tmp, &(v2[idx]), vsp);
//op_fp(v1[i], v2[idx], &(v2[idx]), vsp);
op_fp(v2[idx], v1[i], &(v2[idx]), vsp);
}
else
{
set_bitvector(idx, bv2);
v2[idx] = v1[i];
}
}
}
}
#endif // SRC_SINGLENODE_UNIONREDUCE_H_
|
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] = 24;
tile_size[1] = 24;
tile_size[2] = 16;
tile_size[3] = 1024;
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;
}
|
visual-effects.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF X X %
% F X X %
% FFF X %
% F X X %
% F X X %
% %
% %
% MagickCore Image Special Effects Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% %
% Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/decorate.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/transform.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
#include "MagickCore/visual-effects.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d d N o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AddNoiseImage() adds random noise to the image.
%
% The format of the AddNoiseImage method is:
%
% Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
% const double attenuate,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o noise_type: The type of noise: Uniform, Gaussian, Multiplicative,
% Impulse, Laplacian, or Poisson.
%
% o attenuate: attenuate the random distribution.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
const double attenuate,ExceptionInfo *exception)
{
#define AddNoiseImageTag "AddNoise/Image"
CacheView
*image_view,
*noise_view;
Image
*noise_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Initialize noise image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateAddNoiseImage(image,noise_type,attenuate,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
/*
Add noise in each row.
*/
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireVirtualCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,noise_image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait noise_traits=GetPixelChannelTraits(noise_image,channel);
if ((traits == UndefinedPixelTrait) ||
(noise_traits == UndefinedPixelTrait))
continue;
if ((noise_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(noise_image,channel,p[i],q);
continue;
}
SetPixelChannel(noise_image,channel,ClampToQuantum(
GenerateDifferentialNoise(random_info[id],p[i],noise_type,attenuate)),
q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(noise_image);
}
sync=SyncCacheViewAuthenticPixels(noise_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,AddNoiseImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l u e S h i f t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlueShiftImage() mutes the colors of the image to simulate a scene at
% nighttime in the moonlight.
%
% The format of the BlueShiftImage method is:
%
% Image *BlueShiftImage(const Image *image,const double factor,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o factor: the shift factor.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BlueShiftImage(const Image *image,const double factor,
ExceptionInfo *exception)
{
#define BlueShiftImageTag "BlueShift/Image"
CacheView
*image_view,
*shift_view;
Image
*shift_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate blue shift image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
shift_image=CloneImage(image,0,0,MagickTrue,exception);
if (shift_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(shift_image,DirectClass,exception) == MagickFalse)
{
shift_image=DestroyImage(shift_image);
return((Image *) NULL);
}
/*
Blue-shift DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
shift_view=AcquireAuthenticCacheView(shift_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,shift_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
Quantum
quantum;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=GetPixelRed(image,p);
if (GetPixelGreen(image,p) < quantum)
quantum=GetPixelGreen(image,p);
if (GetPixelBlue(image,p) < quantum)
quantum=GetPixelBlue(image,p);
pixel.red=0.5*(GetPixelRed(image,p)+factor*quantum);
pixel.green=0.5*(GetPixelGreen(image,p)+factor*quantum);
pixel.blue=0.5*(GetPixelBlue(image,p)+factor*quantum);
quantum=GetPixelRed(image,p);
if (GetPixelGreen(image,p) > quantum)
quantum=GetPixelGreen(image,p);
if (GetPixelBlue(image,p) > quantum)
quantum=GetPixelBlue(image,p);
pixel.red=0.5*(pixel.red+factor*quantum);
pixel.green=0.5*(pixel.green+factor*quantum);
pixel.blue=0.5*(pixel.blue+factor*quantum);
SetPixelRed(shift_image,ClampToQuantum(pixel.red),q);
SetPixelGreen(shift_image,ClampToQuantum(pixel.green),q);
SetPixelBlue(shift_image,ClampToQuantum(pixel.blue),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(shift_image);
}
sync=SyncCacheViewAuthenticPixels(shift_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,BlueShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
shift_view=DestroyCacheView(shift_view);
if (status == MagickFalse)
shift_image=DestroyImage(shift_image);
return(shift_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h a r c o a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CharcoalImage() creates a new image that is a copy of an existing one with
% the edge highlighted. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the CharcoalImage method is:
%
% Image *CharcoalImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CharcoalImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*charcoal_image,
*edge_image;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
edge_image=EdgeImage(image,radius,exception);
if (edge_image == (Image *) NULL)
return((Image *) NULL);
charcoal_image=(Image *) NULL;
status=ClampImage(edge_image,exception);
if (status != MagickFalse)
charcoal_image=BlurImage(edge_image,radius,sigma,exception);
edge_image=DestroyImage(edge_image);
if (charcoal_image == (Image *) NULL)
return((Image *) NULL);
status=NormalizeImage(charcoal_image,exception);
if (status != MagickFalse)
status=NegateImage(charcoal_image,MagickFalse,exception);
if (status != MagickFalse)
status=GrayscaleImage(charcoal_image,image->intensity,exception);
if (status == MagickFalse)
charcoal_image=DestroyImage(charcoal_image);
return(charcoal_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorizeImage() blends the fill color with each pixel in the image.
% A percentage blend is specified with opacity. Control the application
% of different color components by specifying a different percentage for
% each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue).
%
% The format of the ColorizeImage method is:
%
% Image *ColorizeImage(const Image *image,const char *blend,
% const PixelInfo *colorize,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o blend: A character string indicating the level of blending as a
% percentage.
%
% o colorize: A color value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ColorizeImage(const Image *image,const char *blend,
const PixelInfo *colorize,ExceptionInfo *exception)
{
#define ColorizeImageTag "Colorize/Image"
#define Colorize(pixel,blend_percentage,colorize) \
(((pixel)*(100.0-(blend_percentage))+(colorize)*(blend_percentage))/100.0)
CacheView
*image_view;
GeometryInfo
geometry_info;
Image
*colorize_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickStatusType
flags;
PixelInfo
blend_percentage;
ssize_t
y;
/*
Allocate colorized image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
colorize_image=CloneImage(image,0,0,MagickTrue,exception);
if (colorize_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(colorize_image,DirectClass,exception) == MagickFalse)
{
colorize_image=DestroyImage(colorize_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(colorize_image->colorspace) != MagickFalse) ||
(IsPixelInfoGray(colorize) != MagickFalse))
(void) SetImageColorspace(colorize_image,sRGBColorspace,exception);
if ((colorize_image->alpha_trait == UndefinedPixelTrait) &&
(colorize->alpha_trait != UndefinedPixelTrait))
(void) SetImageAlpha(colorize_image,OpaqueAlpha,exception);
if (blend == (const char *) NULL)
return(colorize_image);
GetPixelInfo(colorize_image,&blend_percentage);
flags=ParseGeometry(blend,&geometry_info);
blend_percentage.red=geometry_info.rho;
blend_percentage.green=geometry_info.rho;
blend_percentage.blue=geometry_info.rho;
blend_percentage.black=geometry_info.rho;
blend_percentage.alpha=(MagickRealType) TransparentAlpha;
if ((flags & SigmaValue) != 0)
blend_percentage.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
blend_percentage.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
blend_percentage.alpha=geometry_info.psi;
if (blend_percentage.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
blend_percentage.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
blend_percentage.alpha=geometry_info.chi;
}
/*
Colorize DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(colorize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(colorize_image,colorize_image,colorize_image->rows,1)
#endif
for (y=0; y < (ssize_t) colorize_image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,colorize_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) colorize_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(colorize_image); i++)
{
PixelTrait traits = GetPixelChannelTraits(colorize_image,
(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
if ((traits & CopyPixelTrait) != 0)
continue;
SetPixelChannel(colorize_image,(PixelChannel) i,ClampToQuantum(
Colorize(q[i],GetPixelInfoChannel(&blend_percentage,(PixelChannel) i),
GetPixelInfoChannel(colorize,(PixelChannel) i))),q);
}
q+=GetPixelChannels(colorize_image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorizeImageTag,progress,
colorize_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
colorize_image=DestroyImage(colorize_image);
return(colorize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r M a t r i x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorMatrixImage() applies color transformation to an image. This method
% permits saturation changes, hue rotation, luminance to alpha, and various
% other effects. Although variable-sized transformation matrices can be used,
% typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA
% (or RGBA with offsets). The matrix is similar to those used by Adobe Flash
% except offsets are in column 6 rather than 5 (in support of CMYKA images)
% and offsets are normalized (divide Flash offset by 255).
%
% The format of the ColorMatrixImage method is:
%
% Image *ColorMatrixImage(const Image *image,
% const KernelInfo *color_matrix,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_matrix: the color matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
/* FUTURE: modify to make use of a MagickMatrix Mutliply function
That should be provided in "matrix.c"
(ASIDE: actually distorts should do this too but currently doesn't)
*/
MagickExport Image *ColorMatrixImage(const Image *image,
const KernelInfo *color_matrix,ExceptionInfo *exception)
{
#define ColorMatrixImageTag "ColorMatrix/Image"
CacheView
*color_view,
*image_view;
double
ColorMatrix[6][6] =
{
{ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }
};
Image
*color_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
u,
v,
y;
/*
Map given color_matrix, into a 6x6 matrix RGBKA and a constant
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
i=0;
for (v=0; v < (ssize_t) color_matrix->height; v++)
for (u=0; u < (ssize_t) color_matrix->width; u++)
{
if ((v < 6) && (u < 6))
ColorMatrix[v][u]=color_matrix->values[i];
i++;
}
/*
Initialize color image.
*/
color_image=CloneImage(image,0,0,MagickTrue,exception);
if (color_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(color_image,DirectClass,exception) == MagickFalse)
{
color_image=DestroyImage(color_image);
return((Image *) NULL);
}
if (image->debug != MagickFalse)
{
char
format[MagickPathExtent],
*message;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" ColorMatrix image with color matrix:");
message=AcquireString("");
for (v=0; v < 6; v++)
{
*message='\0';
(void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v);
(void) ConcatenateString(&message,format);
for (u=0; u < 6; u++)
{
(void) FormatLocaleString(format,MagickPathExtent,"%+f ",
ColorMatrix[v][u]);
(void) ConcatenateString(&message,format);
}
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message);
}
message=DestroyString(message);
}
/*
Apply the ColorMatrix to image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
color_view=AcquireAuthenticCacheView(color_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,color_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
v;
size_t
height;
GetPixelInfoPixel(image,p,&pixel);
height=color_matrix->height > 6 ? 6UL : color_matrix->height;
for (v=0; v < (ssize_t) height; v++)
{
double
sum;
sum=ColorMatrix[v][0]*GetPixelRed(image,p)+ColorMatrix[v][1]*
GetPixelGreen(image,p)+ColorMatrix[v][2]*GetPixelBlue(image,p);
if (image->colorspace == CMYKColorspace)
sum+=ColorMatrix[v][3]*GetPixelBlack(image,p);
if (image->alpha_trait != UndefinedPixelTrait)
sum+=ColorMatrix[v][4]*GetPixelAlpha(image,p);
sum+=QuantumRange*ColorMatrix[v][5];
switch (v)
{
case 0: pixel.red=sum; break;
case 1: pixel.green=sum; break;
case 2: pixel.blue=sum; break;
case 3: pixel.black=sum; break;
case 4: pixel.alpha=sum; break;
default: break;
}
}
SetPixelViaPixelInfo(color_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(color_image);
}
if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ColorMatrixImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
color_view=DestroyCacheView(color_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
color_image=DestroyImage(color_image);
return(color_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I m p l o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ImplodeImage() creates a new image that is a copy of an existing
% one with the image pixels "implode" by the specified percentage. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ImplodeImage method is:
%
% Image *ImplodeImage(const Image *image,const double amount,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o implode_image: Method ImplodeImage returns a pointer to the image
% after it is implode. A null image is returned if there is a memory
% shortage.
%
% o image: the image.
%
% o amount: Define the extent of the implosion.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ImplodeImage(const Image *image,const double amount,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define ImplodeImageTag "Implode/Image"
CacheView
*canvas_view,
*implode_view,
*interpolate_view;
double
radius;
Image
*canvas_image,
*implode_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize implode image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&
(canvas_image->background_color.alpha != OpaqueAlpha))
(void) SetImageAlphaChannel(canvas_image,OpaqueAlphaChannel,exception);
implode_image=CloneImage(canvas_image,0,0,MagickTrue,exception);
if (implode_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
if (SetImageStorageClass(implode_image,DirectClass,exception) == MagickFalse)
{
canvas_image=DestroyImage(canvas_image);
implode_image=DestroyImage(implode_image);
return((Image *) NULL);
}
/*
Compute scaling factor.
*/
scale.x=1.0;
scale.y=1.0;
center.x=0.5*canvas_image->columns;
center.y=0.5*canvas_image->rows;
radius=center.x;
if (canvas_image->columns > canvas_image->rows)
scale.y=(double) canvas_image->columns/(double) canvas_image->rows;
else
if (canvas_image->columns < canvas_image->rows)
{
scale.x=(double) canvas_image->rows/(double) canvas_image->columns;
radius=center.y;
}
/*
Implode image.
*/
status=MagickTrue;
progress=0;
canvas_view=AcquireVirtualCacheView(canvas_image,exception);
interpolate_view=AcquireVirtualCacheView(canvas_image,exception);
implode_view=AcquireAuthenticCacheView(implode_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(canvas_image,implode_image,canvas_image->rows,1)
#endif
for (y=0; y < (ssize_t) canvas_image->rows; y++)
{
double
distance;
PointInfo
delta;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
delta.y=scale.y*(double) (y-center.y);
for (x=0; x < (ssize_t) canvas_image->columns; x++)
{
register ssize_t
i;
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance >= (radius*radius))
for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(canvas_image,i);
PixelTrait traits = GetPixelChannelTraits(canvas_image,channel);
PixelTrait implode_traits = GetPixelChannelTraits(implode_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(implode_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(implode_image,channel,p[i],q);
}
else
{
double
factor;
/*
Implode the pixel.
*/
factor=1.0;
if (distance > 0.0)
factor=pow(sin(MagickPI*sqrt((double) distance)/radius/2),-amount);
status=InterpolatePixelChannels(canvas_image,interpolate_view,
implode_image,method,(double) (factor*delta.x/scale.x+center.x),
(double) (factor*delta.y/scale.y+center.y),q,exception);
if (status == MagickFalse)
break;
}
p+=GetPixelChannels(canvas_image);
q+=GetPixelChannels(implode_image);
}
if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse)
status=MagickFalse;
if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(canvas_image,ImplodeImageTag,progress,
canvas_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
implode_view=DestroyCacheView(implode_view);
interpolate_view=DestroyCacheView(interpolate_view);
canvas_view=DestroyCacheView(canvas_view);
canvas_image=DestroyImage(canvas_image);
if (status == MagickFalse)
implode_image=DestroyImage(implode_image);
return(implode_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o r p h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The MorphImages() method requires a minimum of two images. The first
% image is transformed into the second by a number of intervening images
% as specified by frames.
%
% The format of the MorphImage method is:
%
% Image *MorphImages(const Image *image,const size_t number_frames,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o number_frames: Define the number of in-between image to generate.
% The more in-between frames, the smoother the morph.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MorphImages(const Image *image,const size_t number_frames,
ExceptionInfo *exception)
{
#define MorphImageTag "Morph/Image"
double
alpha,
beta;
Image
*morph_image,
*morph_images;
MagickBooleanType
status;
MagickOffsetType
scene;
register const Image
*next;
register ssize_t
n;
ssize_t
y;
/*
Clone first frame in sequence.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
morph_images=CloneImage(image,0,0,MagickTrue,exception);
if (morph_images == (Image *) NULL)
return((Image *) NULL);
if (GetNextImageInList(image) == (Image *) NULL)
{
/*
Morph single image.
*/
for (n=1; n < (ssize_t) number_frames; n++)
{
morph_image=CloneImage(image,0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) n,
number_frames);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(GetFirstImageInList(morph_images));
}
/*
Morph image sequence.
*/
status=MagickTrue;
scene=0;
next=image;
for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next))
{
for (n=0; n < (ssize_t) number_frames; n++)
{
CacheView
*image_view,
*morph_view;
beta=(double) (n+1.0)/(double) (number_frames+1.0);
alpha=1.0-beta;
morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta*
GetNextImageInList(next)->columns+0.5),(size_t) (alpha*next->rows+beta*
GetNextImageInList(next)->rows+0.5),next->filter,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
status=SetImageStorageClass(morph_image,DirectClass,exception);
if (status == MagickFalse)
{
morph_image=DestroyImage(morph_image);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns,
morph_images->rows,GetNextImageInList(next)->filter,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
image_view=AcquireVirtualCacheView(morph_image,exception);
morph_view=AcquireAuthenticCacheView(morph_images,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(morph_image,morph_image,morph_image->rows,1)
#endif
for (y=0; y < (ssize_t) morph_images->rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) morph_images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(morph_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(morph_image,i);
PixelTrait traits = GetPixelChannelTraits(morph_image,channel);
PixelTrait morph_traits=GetPixelChannelTraits(morph_images,channel);
if ((traits == UndefinedPixelTrait) ||
(morph_traits == UndefinedPixelTrait))
continue;
if ((morph_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(morph_image,channel,p[i],q);
continue;
}
SetPixelChannel(morph_image,channel,ClampToQuantum(alpha*
GetPixelChannel(morph_images,channel,q)+beta*p[i]),q);
}
p+=GetPixelChannels(morph_image);
q+=GetPixelChannels(morph_images);
}
sync=SyncCacheViewAuthenticPixels(morph_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
morph_view=DestroyCacheView(morph_view);
image_view=DestroyCacheView(image_view);
morph_image=DestroyImage(morph_image);
}
if (n < (ssize_t) number_frames)
break;
/*
Clone last frame in sequence.
*/
morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,scene,
GetImageListLength(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
scene++;
}
if (GetNextImageInList(next) != (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
return(GetFirstImageInList(morph_images));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P l a s m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PlasmaImage() initializes an image with plasma fractal values. The image
% must be initialized with a base color and the random number generator
% seeded before this method is called.
%
% The format of the PlasmaImage method is:
%
% MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment,
% size_t attenuate,size_t depth,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o segment: Define the region to apply plasma fractals values.
%
% o attenuate: Define the plasma attenuation factor.
%
% o depth: Limit the plasma recursion depth.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PlasmaPixel(RandomInfo *magick_restrict random_info,
const double pixel,const double noise)
{
MagickRealType
plasma;
plasma=pixel+noise*GetPseudoRandomValue(random_info)-noise/2.0;
return(ClampToQuantum(plasma));
}
static MagickBooleanType PlasmaImageProxy(Image *image,CacheView *image_view,
CacheView *u_view,CacheView *v_view,RandomInfo *magick_restrict random_info,
const SegmentInfo *magick_restrict segment,size_t attenuate,size_t depth,
ExceptionInfo *exception)
{
double
plasma;
MagickStatusType
status;
register const Quantum
*magick_restrict u,
*magick_restrict v;
register Quantum
*magick_restrict q;
register ssize_t
i;
ssize_t
x,
x_mid,
y,
y_mid;
if ((fabs(segment->x2-segment->x1) < MagickEpsilon) &&
(fabs(segment->y2-segment->y1) < MagickEpsilon))
return(MagickTrue);
if (depth != 0)
{
SegmentInfo
local_info;
/*
Divide the area into quadrants and recurse.
*/
depth--;
attenuate++;
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
local_info=(*segment);
local_info.x2=(double) x_mid;
local_info.y2=(double) y_mid;
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.y1=(double) y_mid;
local_info.x2=(double) x_mid;
status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y2=(double) y_mid;
status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y1=(double) y_mid;
status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth,exception);
return(status == 0 ? MagickFalse : MagickTrue);
}
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
if ((fabs(segment->x1-x_mid) < MagickEpsilon) &&
(fabs(segment->x2-x_mid) < MagickEpsilon) &&
(fabs(segment->y1-y_mid) < MagickEpsilon) &&
(fabs(segment->y2-y_mid) < MagickEpsilon))
return(MagickFalse);
/*
Average pixels and apply plasma.
*/
status=MagickTrue;
plasma=(double) QuantumRange/(2.0*attenuate);
if ((fabs(segment->x1-x_mid) >= MagickEpsilon) ||
(fabs(segment->x2-x_mid) >= MagickEpsilon))
{
/*
Left pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),1,1,
exception);
v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),1,1,
exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma);
}
status=SyncCacheViewAuthenticPixels(image_view,exception);
if (fabs(segment->x1-segment->x2) >= MagickEpsilon)
{
/*
Right pixel.
*/
x=(ssize_t) ceil(segment->x2-0.5);
u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickFalse);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma);
}
status=SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->y1-y_mid) >= MagickEpsilon) ||
(fabs(segment->y2-y_mid) >= MagickEpsilon))
{
if ((fabs(segment->x1-x_mid) >= MagickEpsilon) ||
(fabs(segment->y2-y_mid) >= MagickEpsilon))
{
/*
Bottom pixel.
*/
y=(ssize_t) ceil(segment->y2-0.5);
u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y,
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y,
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma);
}
status=SyncCacheViewAuthenticPixels(image_view,exception);
}
if (fabs(segment->y1-segment->y2) >= MagickEpsilon)
{
/*
Top pixel.
*/
y=(ssize_t) ceil(segment->y1-0.5);
u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y,
1,1,exception);
v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y,
1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma);
}
status=SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->x1-segment->x2) >= MagickEpsilon) ||
(fabs(segment->y1-segment->y2) >= MagickEpsilon))
{
/*
Middle pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
y=(ssize_t) ceil(segment->y1-0.5);
u=GetCacheViewVirtualPixels(u_view,x,y,1,1,exception);
x=(ssize_t) ceil(segment->x2-0.5);
y=(ssize_t) ceil(segment->y2-0.5);
v=GetCacheViewVirtualPixels(v_view,x,y,1,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception);
if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) ||
(q == (Quantum *) NULL))
return(MagickTrue);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma);
}
status=SyncCacheViewAuthenticPixels(image_view,exception);
}
if ((fabs(segment->x2-segment->x1) < 3.0) &&
(fabs(segment->y2-segment->y1) < 3.0))
return(status == 0 ? MagickFalse : MagickTrue);
return(MagickFalse);
}
MagickExport MagickBooleanType PlasmaImage(Image *image,
const SegmentInfo *segment,size_t attenuate,size_t depth,
ExceptionInfo *exception)
{
CacheView
*image_view,
*u_view,
*v_view;
MagickBooleanType
status;
RandomInfo
*random_info;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
image_view=AcquireAuthenticCacheView(image,exception);
u_view=AcquireVirtualCacheView(image,exception);
v_view=AcquireVirtualCacheView(image,exception);
random_info=AcquireRandomInfo();
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment,
attenuate,depth,exception);
random_info=DestroyRandomInfo(random_info);
v_view=DestroyCacheView(v_view);
u_view=DestroyCacheView(u_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l a r o i d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolaroidImage() simulates a Polaroid picture.
%
% The format of the PolaroidImage method is:
%
% Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
% const char *caption,const double angle,
% const PixelInterpolateMethod method,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o caption: the Polaroid caption.
%
% o angle: Apply the effect along this angle.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
const char *caption,const double angle,const PixelInterpolateMethod method,
ExceptionInfo *exception)
{
Image
*bend_image,
*caption_image,
*flop_image,
*picture_image,
*polaroid_image,
*rotate_image,
*trim_image;
size_t
height;
ssize_t
quantum;
/*
Simulate a Polaroid picture.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double)
image->rows)/25.0,10.0);
height=image->rows+2*quantum;
caption_image=(Image *) NULL;
if (caption != (const char *) NULL)
{
char
*text;
/*
Generate caption image.
*/
caption_image=CloneImage(image,image->columns,1,MagickTrue,exception);
if (caption_image == (Image *) NULL)
return((Image *) NULL);
text=InterpretImageProperties((ImageInfo *) NULL,(Image *) image,caption,
exception);
if (text != (char *) NULL)
{
char
geometry[MagickPathExtent];
DrawInfo
*annotate_info;
MagickBooleanType
status;
ssize_t
count;
TypeMetric
metrics;
annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info);
(void) CloneString(&annotate_info->text,text);
count=FormatMagickCaption(caption_image,annotate_info,MagickTrue,
&metrics,&text,exception);
status=SetImageExtent(caption_image,image->columns,(size_t)
((count+1)*(metrics.ascent-metrics.descent)+0.5),exception);
if (status == MagickFalse)
caption_image=DestroyImage(caption_image);
else
{
caption_image->background_color=image->border_color;
(void) SetImageBackgroundColor(caption_image,exception);
(void) CloneString(&annotate_info->text,text);
(void) FormatLocaleString(geometry,MagickPathExtent,"+0+%.20g",
metrics.ascent);
if (annotate_info->gravity == UndefinedGravity)
(void) CloneString(&annotate_info->geometry,AcquireString(
geometry));
(void) AnnotateImage(caption_image,annotate_info,exception);
height+=caption_image->rows;
}
annotate_info=DestroyDrawInfo(annotate_info);
text=DestroyString(text);
}
}
picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue,
exception);
if (picture_image == (Image *) NULL)
{
if (caption_image != (Image *) NULL)
caption_image=DestroyImage(caption_image);
return((Image *) NULL);
}
picture_image->background_color=image->border_color;
(void) SetImageBackgroundColor(picture_image,exception);
(void) CompositeImage(picture_image,image,OverCompositeOp,MagickTrue,quantum,
quantum,exception);
if (caption_image != (Image *) NULL)
{
(void) CompositeImage(picture_image,caption_image,OverCompositeOp,
MagickTrue,quantum,(ssize_t) (image->rows+3*quantum/2),exception);
caption_image=DestroyImage(caption_image);
}
(void) QueryColorCompliance("none",AllCompliance,
&picture_image->background_color,exception);
(void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel,exception);
rotate_image=RotateImage(picture_image,90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0*
picture_image->columns,method,exception);
picture_image=DestroyImage(picture_image);
if (bend_image == (Image *) NULL)
return((Image *) NULL);
picture_image=bend_image;
rotate_image=RotateImage(picture_image,-90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
picture_image->background_color=image->background_color;
polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3,
exception);
if (polaroid_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
flop_image=FlopImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (flop_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
polaroid_image=flop_image;
(void) CompositeImage(polaroid_image,picture_image,OverCompositeOp,
MagickTrue,(ssize_t) (-0.01*picture_image->columns/2.0),0L,exception);
picture_image=DestroyImage(picture_image);
(void) QueryColorCompliance("none",AllCompliance,
&polaroid_image->background_color,exception);
rotate_image=RotateImage(polaroid_image,angle,exception);
polaroid_image=DestroyImage(polaroid_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=rotate_image;
trim_image=TrimImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (trim_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=trim_image;
return(polaroid_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p i a T o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickSepiaToneImage() applies a special effect to the image, similar to the
% effect achieved in a photo darkroom by sepia toning. Threshold ranges from
% 0 to QuantumRange and is a measure of the extent of the sepia toning. A
% threshold of 80% is a good starting point for a reasonable tone.
%
% The format of the SepiaToneImage method is:
%
% Image *SepiaToneImage(const Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: the tone threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SepiaToneImage(const Image *image,const double threshold,
ExceptionInfo *exception)
{
#define SepiaToneImageTag "SepiaTone/Image"
CacheView
*image_view,
*sepia_view;
Image
*sepia_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize sepia-toned image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
sepia_image=CloneImage(image,0,0,MagickTrue,exception);
if (sepia_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse)
{
sepia_image=DestroyImage(sepia_image);
return((Image *) NULL);
}
/*
Tone each row of the image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
sepia_view=AcquireAuthenticCacheView(sepia_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,sepia_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
intensity,
tone;
intensity=GetPixelIntensity(image,p);
tone=intensity > threshold ? (double) QuantumRange : intensity+
(double) QuantumRange-threshold;
SetPixelRed(sepia_image,ClampToQuantum(tone),q);
tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange :
intensity+(double) QuantumRange-7.0*threshold/6.0;
SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0;
SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
tone=threshold/7.0;
if ((double) GetPixelGreen(image,q) < tone)
SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
if ((double) GetPixelBlue(image,q) < tone)
SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(sepia_image);
}
if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SepiaToneImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
sepia_view=DestroyCacheView(sepia_view);
image_view=DestroyCacheView(image_view);
(void) NormalizeImage(sepia_image,exception);
(void) ContrastImage(sepia_image,MagickTrue,exception);
if (status == MagickFalse)
sepia_image=DestroyImage(sepia_image);
return(sepia_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a d o w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShadowImage() simulates a shadow from the specified image and returns it.
%
% The format of the ShadowImage method is:
%
% Image *ShadowImage(const Image *image,const double alpha,
% const double sigma,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o alpha: percentage transparency.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x_offset: the shadow x-offset.
%
% o y_offset: the shadow y-offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShadowImage(const Image *image,const double alpha,
const double sigma,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define ShadowImageTag "Shadow/Image"
CacheView
*image_view;
ChannelType
channel_mask;
Image
*border_image,
*clone_image,
*shadow_image;
MagickBooleanType
status;
PixelInfo
background_color;
RectangleInfo
border_info;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(clone_image,sRGBColorspace,exception);
(void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod,
exception);
border_info.width=(size_t) floor(2.0*sigma+0.5);
border_info.height=(size_t) floor(2.0*sigma+0.5);
border_info.x=0;
border_info.y=0;
(void) QueryColorCompliance("none",AllCompliance,&clone_image->border_color,
exception);
clone_image->alpha_trait=BlendPixelTrait;
border_image=BorderImage(clone_image,&border_info,OverCompositeOp,exception);
clone_image=DestroyImage(clone_image);
if (border_image == (Image *) NULL)
return((Image *) NULL);
if (border_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel,exception);
/*
Shadow image.
*/
status=MagickTrue;
background_color=border_image->background_color;
background_color.alpha_trait=BlendPixelTrait;
image_view=AcquireAuthenticCacheView(border_image,exception);
for (y=0; y < (ssize_t) border_image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) border_image->columns; x++)
{
if (border_image->alpha_trait != UndefinedPixelTrait)
background_color.alpha=GetPixelAlpha(border_image,q)*alpha/100.0;
SetPixelViaPixelInfo(border_image,&background_color,q);
q+=GetPixelChannels(border_image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
border_image=DestroyImage(border_image);
return((Image *) NULL);
}
channel_mask=SetImageChannelMask(border_image,AlphaChannel);
shadow_image=BlurImage(border_image,0.0,sigma,exception);
border_image=DestroyImage(border_image);
if (shadow_image == (Image *) NULL)
return((Image *) NULL);
(void) SetPixelChannelMask(shadow_image,channel_mask);
if (shadow_image->page.width == 0)
shadow_image->page.width=shadow_image->columns;
if (shadow_image->page.height == 0)
shadow_image->page.height=shadow_image->rows;
shadow_image->page.width+=x_offset-(ssize_t) border_info.width;
shadow_image->page.height+=y_offset-(ssize_t) border_info.height;
shadow_image->page.x+=x_offset-(ssize_t) border_info.width;
shadow_image->page.y+=y_offset-(ssize_t) border_info.height;
return(shadow_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S k e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SketchImage() simulates a pencil sketch. We convolve the image with a
% Gaussian operator of the given radius and standard deviation (sigma). For
% reasonable results, radius should be larger than sigma. Use a radius of 0
% and SketchImage() selects a suitable radius for you. Angle gives the angle
% of the sketch.
%
% The format of the SketchImage method is:
%
% Image *SketchImage(const Image *image,const double radius,
% const double sigma,const double angle,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the Gaussian, in pixels, not counting the
% center pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o angle: apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SketchImage(const Image *image,const double radius,
const double sigma,const double angle,ExceptionInfo *exception)
{
CacheView
*random_view;
Image
*blend_image,
*blur_image,
*dodge_image,
*random_image,
*sketch_image;
MagickBooleanType
status;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Sketch image.
*/
random_image=CloneImage(image,image->columns << 1,image->rows << 1,
MagickTrue,exception);
if (random_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
random_info=AcquireRandomInfoThreadSet();
random_view=AcquireAuthenticCacheView(random_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) random_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) random_image->columns; x++)
{
double
value;
register ssize_t
i;
value=GetPseudoRandomValue(random_info[id]);
for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=ClampToQuantum(QuantumRange*value);
}
q+=GetPixelChannels(random_image);
}
if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse)
status=MagickFalse;
}
random_view=DestroyCacheView(random_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
{
random_image=DestroyImage(random_image);
return(random_image);
}
blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception);
random_image=DestroyImage(random_image);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
dodge_image=EdgeImage(blur_image,radius,exception);
blur_image=DestroyImage(blur_image);
if (dodge_image == (Image *) NULL)
return((Image *) NULL);
status=ClampImage(dodge_image,exception);
if (status != MagickFalse)
status=NormalizeImage(dodge_image,exception);
if (status != MagickFalse)
status=NegateImage(dodge_image,MagickFalse,exception);
if (status != MagickFalse)
status=TransformImage(&dodge_image,(char *) NULL,"50%",exception);
sketch_image=CloneImage(image,0,0,MagickTrue,exception);
if (sketch_image == (Image *) NULL)
{
dodge_image=DestroyImage(dodge_image);
return((Image *) NULL);
}
(void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp,
MagickTrue,0,0,exception);
dodge_image=DestroyImage(dodge_image);
blend_image=CloneImage(image,0,0,MagickTrue,exception);
if (blend_image == (Image *) NULL)
{
sketch_image=DestroyImage(sketch_image);
return((Image *) NULL);
}
if (blend_image->alpha_trait != BlendPixelTrait)
(void) SetImageAlpha(blend_image,TransparentAlpha,exception);
(void) SetImageArtifact(blend_image,"compose:args","20x80");
(void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue,
0,0,exception);
blend_image=DestroyImage(blend_image);
return(sketch_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S o l a r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SolarizeImage() applies a special effect to the image, similar to the effect
% achieved in a photo darkroom by selectively exposing areas of photo
% sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a
% measure of the extent of the solarization.
%
% The format of the SolarizeImage method is:
%
% MagickBooleanType SolarizeImage(Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: Define the extent of the solarization.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SolarizeImage(Image *image,
const double threshold,ExceptionInfo *exception)
{
#define SolarizeImageTag "Solarize/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
/*
Solarize colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((double) image->colormap[i].red > threshold)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((double) image->colormap[i].green > threshold)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((double) image->colormap[i].blue > threshold)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
return(SyncImage(image,exception));
}
/*
Solarize image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
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;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if ((double) q[i] > threshold)
q[i]=QuantumRange-q[i];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e g a n o I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SteganoImage() hides a digital watermark within the image. Recover
% the hidden watermark later to prove that the authenticity of an image.
% Offset defines the start position within the image to hide the watermark.
%
% The format of the SteganoImage method is:
%
% Image *SteganoImage(const Image *image,Image *watermark,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o watermark: the watermark image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SteganoImage(const Image *image,const Image *watermark,
ExceptionInfo *exception)
{
#define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0)
#define SetBit(alpha,i,set) (Quantum) ((set) != 0 ? (size_t) (alpha) \
| (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i)))
#define SteganoImageTag "Stegano/Image"
CacheView
*stegano_view,
*watermark_view;
Image
*stegano_image;
int
c;
MagickBooleanType
status;
PixelInfo
pixel;
register Quantum
*q;
register ssize_t
x;
size_t
depth,
one;
ssize_t
i,
j,
k,
y;
/*
Initialize steganographic image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(watermark != (const Image *) NULL);
assert(watermark->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1UL;
stegano_image=CloneImage(image,0,0,MagickTrue,exception);
if (stegano_image == (Image *) NULL)
return((Image *) NULL);
stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH;
if (SetImageStorageClass(stegano_image,DirectClass,exception) == MagickFalse)
{
stegano_image=DestroyImage(stegano_image);
return((Image *) NULL);
}
/*
Hide watermark in low-order bits of image.
*/
c=0;
i=0;
j=0;
depth=stegano_image->depth;
k=stegano_image->offset;
status=MagickTrue;
watermark_view=AcquireVirtualCacheView(watermark,exception);
stegano_view=AcquireAuthenticCacheView(stegano_image,exception);
for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--)
{
for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++)
{
for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++)
{
ssize_t
offset;
(void) GetOneCacheViewVirtualPixelInfo(watermark_view,x,y,&pixel,
exception);
offset=k/(ssize_t) stegano_image->columns;
if (offset >= (ssize_t) stegano_image->rows)
break;
q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t)
stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1,
exception);
if (q == (Quantum *) NULL)
break;
switch (c)
{
case 0:
{
SetPixelRed(stegano_image,SetBit(GetPixelRed(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
case 1:
{
SetPixelGreen(stegano_image,SetBit(GetPixelGreen(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
case 2:
{
SetPixelBlue(stegano_image,SetBit(GetPixelBlue(stegano_image,q),j,
GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q);
break;
}
}
if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse)
break;
c++;
if (c == 3)
c=0;
k++;
if (k == (ssize_t) (stegano_image->columns*stegano_image->columns))
k=0;
if (k == stegano_image->offset)
j++;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType)
(depth-i),depth);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
stegano_view=DestroyCacheView(stegano_view);
watermark_view=DestroyCacheView(watermark_view);
if (status == MagickFalse)
stegano_image=DestroyImage(stegano_image);
return(stegano_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e r e o A n a g l y p h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StereoAnaglyphImage() combines two images and produces a single image that
% is the composite of a left and right image of a stereo pair. Special
% red-green stereo glasses are required to view this effect.
%
% The format of the StereoAnaglyphImage method is:
%
% Image *StereoImage(const Image *left_image,const Image *right_image,
% ExceptionInfo *exception)
% Image *StereoAnaglyphImage(const Image *left_image,
% const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o left_image: the left image.
%
% o right_image: the right image.
%
% o exception: return any errors or warnings in this structure.
%
% o x_offset: amount, in pixels, by which the left image is offset to the
% right of the right image.
%
% o y_offset: amount, in pixels, by which the left image is offset to the
% bottom of the right image.
%
%
*/
MagickExport Image *StereoImage(const Image *left_image,
const Image *right_image,ExceptionInfo *exception)
{
return(StereoAnaglyphImage(left_image,right_image,0,0,exception));
}
MagickExport Image *StereoAnaglyphImage(const Image *left_image,
const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define StereoImageTag "Stereo/Image"
const Image
*image;
Image
*stereo_image;
MagickBooleanType
status;
ssize_t
y;
assert(left_image != (const Image *) NULL);
assert(left_image->signature == MagickCoreSignature);
if (left_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
left_image->filename);
assert(right_image != (const Image *) NULL);
assert(right_image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=left_image;
if ((left_image->columns != right_image->columns) ||
(left_image->rows != right_image->rows))
ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer");
/*
Initialize stereo image attributes.
*/
stereo_image=CloneImage(left_image,left_image->columns,left_image->rows,
MagickTrue,exception);
if (stereo_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stereo_image,DirectClass,exception) == MagickFalse)
{
stereo_image=DestroyImage(stereo_image);
return((Image *) NULL);
}
(void) SetImageColorspace(stereo_image,sRGBColorspace,exception);
/*
Copy left image to red channel and right image to blue channel.
*/
status=MagickTrue;
for (y=0; y < (ssize_t) stereo_image->rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
register Quantum
*magick_restrict r;
p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1,
exception);
q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception);
r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL) ||
(r == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) stereo_image->columns; x++)
{
SetPixelRed(stereo_image,GetPixelRed(left_image,p),r);
SetPixelGreen(stereo_image,GetPixelGreen(right_image,q),r);
SetPixelBlue(stereo_image,GetPixelBlue(right_image,q),r);
if ((GetPixelAlphaTraits(stereo_image) & CopyPixelTrait) != 0)
SetPixelAlpha(stereo_image,(GetPixelAlpha(left_image,p)+
GetPixelAlpha(right_image,q))/2,r);
p+=GetPixelChannels(left_image);
q+=GetPixelChannels(right_image);
r+=GetPixelChannels(stereo_image);
}
if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse)
break;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y,
stereo_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
if (status == MagickFalse)
stereo_image=DestroyImage(stereo_image);
return(stereo_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S w i r l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SwirlImage() swirls the pixels about the center of the image, where
% degrees indicates the sweep of the arc through which each pixel is moved.
% You get a more dramatic effect as the degrees move from 1 to 360.
%
% The format of the SwirlImage method is:
%
% Image *SwirlImage(const Image *image,double degrees,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o degrees: Define the tightness of the swirling effect.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SwirlImage(const Image *image,double degrees,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define SwirlImageTag "Swirl/Image"
CacheView
*canvas_view,
*interpolate_view,
*swirl_view;
double
radius;
Image
*canvas_image,
*swirl_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize swirl image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
swirl_image=CloneImage(canvas_image,0,0,MagickTrue,exception);
if (swirl_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
if (SetImageStorageClass(swirl_image,DirectClass,exception) == MagickFalse)
{
canvas_image=DestroyImage(canvas_image);
swirl_image=DestroyImage(swirl_image);
return((Image *) NULL);
}
if (swirl_image->background_color.alpha_trait != UndefinedPixelTrait)
(void) SetImageAlphaChannel(swirl_image,OnAlphaChannel,exception);
/*
Compute scaling factor.
*/
center.x=(double) canvas_image->columns/2.0;
center.y=(double) canvas_image->rows/2.0;
radius=MagickMax(center.x,center.y);
scale.x=1.0;
scale.y=1.0;
if (canvas_image->columns > canvas_image->rows)
scale.y=(double) canvas_image->columns/(double) canvas_image->rows;
else
if (canvas_image->columns < canvas_image->rows)
scale.x=(double) canvas_image->rows/(double) canvas_image->columns;
degrees=(double) DegreesToRadians(degrees);
/*
Swirl image.
*/
status=MagickTrue;
progress=0;
canvas_view=AcquireVirtualCacheView(canvas_image,exception);
interpolate_view=AcquireVirtualCacheView(image,exception);
swirl_view=AcquireAuthenticCacheView(swirl_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(canvas_image,swirl_image,canvas_image->rows,1)
#endif
for (y=0; y < (ssize_t) canvas_image->rows; y++)
{
double
distance;
PointInfo
delta;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
delta.y=scale.y*(double) (y-center.y);
for (x=0; x < (ssize_t) canvas_image->columns; x++)
{
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance >= (radius*radius))
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(canvas_image,i);
PixelTrait traits = GetPixelChannelTraits(canvas_image,channel);
PixelTrait swirl_traits = GetPixelChannelTraits(swirl_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(swirl_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(swirl_image,channel,p[i],q);
}
}
else
{
double
cosine,
factor,
sine;
/*
Swirl the pixel.
*/
factor=1.0-sqrt((double) distance)/radius;
sine=sin((double) (degrees*factor*factor));
cosine=cos((double) (degrees*factor*factor));
status=InterpolatePixelChannels(canvas_image,interpolate_view,
swirl_image,method,((cosine*delta.x-sine*delta.y)/scale.x+center.x),
(double) ((sine*delta.x+cosine*delta.y)/scale.y+center.y),q,
exception);
if (status == MagickFalse)
break;
}
p+=GetPixelChannels(canvas_image);
q+=GetPixelChannels(swirl_image);
}
if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse)
status=MagickFalse;
if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(canvas_image,SwirlImageTag,progress,
canvas_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
swirl_view=DestroyCacheView(swirl_view);
interpolate_view=DestroyCacheView(interpolate_view);
canvas_view=DestroyCacheView(canvas_view);
canvas_image=DestroyImage(canvas_image);
if (status == MagickFalse)
swirl_image=DestroyImage(swirl_image);
return(swirl_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TintImage() applies a color vector to each pixel in the image. The length
% of the vector is 0 for black and white and at its maximum for the midtones.
% The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5))))
%
% The format of the TintImage method is:
%
% Image *TintImage(const Image *image,const char *blend,
% const PixelInfo *tint,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o blend: A color value used for tinting.
%
% o tint: A color value used for tinting.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TintImage(const Image *image,const char *blend,
const PixelInfo *tint,ExceptionInfo *exception)
{
#define TintImageTag "Tint/Image"
CacheView
*image_view,
*tint_view;
double
intensity;
GeometryInfo
geometry_info;
Image
*tint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
color_vector;
MagickStatusType
flags;
ssize_t
y;
/*
Allocate tint image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
tint_image=CloneImage(image,0,0,MagickTrue,exception);
if (tint_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(tint_image,DirectClass,exception) == MagickFalse)
{
tint_image=DestroyImage(tint_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsPixelInfoGray(tint) == MagickFalse))
(void) SetImageColorspace(tint_image,sRGBColorspace,exception);
if (blend == (const char *) NULL)
return(tint_image);
/*
Determine RGB values of the color.
*/
GetPixelInfo(image,&color_vector);
flags=ParseGeometry(blend,&geometry_info);
color_vector.red=geometry_info.rho;
color_vector.green=geometry_info.rho;
color_vector.blue=geometry_info.rho;
color_vector.alpha=(MagickRealType) OpaqueAlpha;
if ((flags & SigmaValue) != 0)
color_vector.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
color_vector.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
color_vector.alpha=geometry_info.psi;
if (image->colorspace == CMYKColorspace)
{
color_vector.black=geometry_info.rho;
if ((flags & PsiValue) != 0)
color_vector.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
color_vector.alpha=geometry_info.chi;
}
intensity=(double) GetPixelInfoIntensity((const Image *) NULL,tint);
color_vector.red=(double) (color_vector.red*tint->red/100.0-intensity);
color_vector.green=(double) (color_vector.green*tint->green/100.0-intensity);
color_vector.blue=(double) (color_vector.blue*tint->blue/100.0-intensity);
color_vector.black=(double) (color_vector.black*tint->black/100.0-intensity);
color_vector.alpha=(double) (color_vector.alpha*tint->alpha/100.0-intensity);
/*
Tint image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
tint_view=AcquireAuthenticCacheView(tint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,tint_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
PixelInfo
pixel;
double
weight;
GetPixelInfo(image,&pixel);
weight=QuantumScale*GetPixelRed(image,p)-0.5;
pixel.red=(MagickRealType) GetPixelRed(image,p)+color_vector.red*
(1.0-(4.0*(weight*weight)));
weight=QuantumScale*GetPixelGreen(image,p)-0.5;
pixel.green=(MagickRealType) GetPixelGreen(image,p)+color_vector.green*
(1.0-(4.0*(weight*weight)));
weight=QuantumScale*GetPixelBlue(image,p)-0.5;
pixel.blue=(MagickRealType) GetPixelBlue(image,p)+color_vector.blue*
(1.0-(4.0*(weight*weight)));
weight=QuantumScale*GetPixelBlack(image,p)-0.5;
pixel.black=(MagickRealType) GetPixelBlack(image,p)+color_vector.black*
(1.0-(4.0*(weight*weight)));
pixel.alpha=(MagickRealType) GetPixelAlpha(image,p);
SetPixelViaPixelInfo(tint_image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(tint_image);
}
if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TintImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
tint_view=DestroyCacheView(tint_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
tint_image=DestroyImage(tint_image);
return(tint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% V i g n e t t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% VignetteImage() softens the edges of the image in vignette style.
%
% The format of the VignetteImage method is:
%
% Image *VignetteImage(const Image *image,const double radius,
% const double sigma,const ssize_t x,const ssize_t y,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x, y: Define the x and y ellipse offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *VignetteImage(const Image *image,const double radius,
const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception)
{
char
ellipse[MagickPathExtent];
DrawInfo
*draw_info;
Image
*canvas,
*blur_image,
*oval_image,
*vignette_image;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas=CloneImage(image,0,0,MagickTrue,exception);
if (canvas == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(canvas,DirectClass,exception) == MagickFalse)
{
canvas=DestroyImage(canvas);
return((Image *) NULL);
}
canvas->alpha_trait=BlendPixelTrait;
oval_image=CloneImage(canvas,canvas->columns,canvas->rows,MagickTrue,
exception);
if (oval_image == (Image *) NULL)
{
canvas=DestroyImage(canvas);
return((Image *) NULL);
}
(void) QueryColorCompliance("#000000",AllCompliance,
&oval_image->background_color,exception);
(void) SetImageBackgroundColor(oval_image,exception);
draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL);
(void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->stroke,
exception);
(void) FormatLocaleString(ellipse,MagickPathExtent,"ellipse %g,%g,%g,%g,"
"0.0,360.0",image->columns/2.0,image->rows/2.0,image->columns/2.0-x,
image->rows/2.0-y);
draw_info->primitive=AcquireString(ellipse);
(void) DrawImage(oval_image,draw_info,exception);
draw_info=DestroyDrawInfo(draw_info);
blur_image=BlurImage(oval_image,radius,sigma,exception);
oval_image=DestroyImage(oval_image);
if (blur_image == (Image *) NULL)
{
canvas=DestroyImage(canvas);
return((Image *) NULL);
}
blur_image->alpha_trait=UndefinedPixelTrait;
(void) CompositeImage(canvas,blur_image,IntensityCompositeOp,MagickTrue,
0,0,exception);
blur_image=DestroyImage(blur_image);
vignette_image=MergeImageLayers(canvas,FlattenLayer,exception);
canvas=DestroyImage(canvas);
if (vignette_image != (Image *) NULL)
(void) TransformImageColorspace(vignette_image,image->colorspace,exception);
return(vignette_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveImage() creates a "ripple" effect in the image by shifting the pixels
% vertically along a sine wave whose amplitude and wavelength is specified
% by the given parameters.
%
% The format of the WaveImage method is:
%
% Image *WaveImage(const Image *image,const double amplitude,
% const double wave_length,const PixelInterpolateMethod method,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o amplitude, wave_length: Define the amplitude and wave length of the
% sine wave.
%
% o interpolate: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *WaveImage(const Image *image,const double amplitude,
const double wave_length,const PixelInterpolateMethod method,
ExceptionInfo *exception)
{
#define WaveImageTag "Wave/Image"
CacheView
*canvas_image_view,
*wave_view;
float
*sine_map;
Image
*canvas_image,
*wave_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Initialize wave image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&
(canvas_image->background_color.alpha != OpaqueAlpha))
(void) SetImageAlpha(canvas_image,OpaqueAlpha,exception);
wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t)
(canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception);
if (wave_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)
{
canvas_image=DestroyImage(canvas_image);
wave_image=DestroyImage(wave_image);
return((Image *) NULL);
}
/*
Allocate sine map.
*/
sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,
sizeof(*sine_map));
if (sine_map == (float *) NULL)
{
canvas_image=DestroyImage(canvas_image);
wave_image=DestroyImage(wave_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) wave_image->columns; i++)
sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)
((2.0*MagickPI*i)/wave_length));
/*
Wave image.
*/
status=MagickTrue;
progress=0;
canvas_image_view=AcquireVirtualCacheView(canvas_image,exception);
wave_view=AcquireAuthenticCacheView(wave_image,exception);
(void) SetCacheViewVirtualPixelMethod(canvas_image_view,
BackgroundVirtualPixelMethod);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(canvas_image,wave_image,wave_image->rows,1)
#endif
for (y=0; y < (ssize_t) wave_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1,
exception);
q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) wave_image->columns; x++)
{
status=InterpolatePixelChannels(canvas_image,canvas_image_view,
wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception);
if (status == MagickFalse)
break;
p+=GetPixelChannels(canvas_image);
q+=GetPixelChannels(wave_image);
}
if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(canvas_image,WaveImageTag,progress,
canvas_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
wave_view=DestroyCacheView(wave_view);
canvas_image_view=DestroyCacheView(canvas_image_view);
canvas_image=DestroyImage(canvas_image);
sine_map=(float *) RelinquishMagickMemory(sine_map);
if (status == MagickFalse)
wave_image=DestroyImage(wave_image);
return(wave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e l e t D e n o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveletDenoiseImage() removes noise from the image using a wavelet
% transform. The wavelet transform is a fast hierarchical scheme for
% processing an image using a set of consecutive lowpass and high_pass filters,
% followed by a decimation. This results in a decomposition into different
% scales which can be regarded as different “frequency bands”, determined by
% the mother wavelet. Adapted from dcraw.c by David Coffin.
%
% The format of the WaveletDenoiseImage method is:
%
% Image *WaveletDenoiseImage(const Image *image,const double threshold,
% const double softness,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: set the threshold for smoothing.
%
% o softness: attenuate the smoothing threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void HatTransform(const float *magick_restrict pixels,
const size_t stride,const size_t extent,const size_t scale,float *kernel)
{
const float
*magick_restrict p,
*magick_restrict q,
*magick_restrict r;
register ssize_t
i;
p=pixels;
q=pixels+scale*stride;
r=pixels+scale*stride;
for (i=0; i < (ssize_t) scale; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q-=stride;
r+=stride;
}
for ( ; i < (ssize_t) (extent-scale); i++)
{
kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride));
p+=stride;
}
q=p-scale*stride;
r=pixels+stride*(extent-2);
for ( ; i < (ssize_t) extent; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q+=stride;
r-=stride;
}
}
MagickExport Image *WaveletDenoiseImage(const Image *image,
const double threshold,const double softness,ExceptionInfo *exception)
{
CacheView
*image_view,
*noise_view;
float
*kernel,
*pixels;
Image
*noise_image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixels_info;
ssize_t
channel;
static const float
noise_levels[] = { 0.8002f, 0.2735f, 0.1202f, 0.0585f, 0.0291f, 0.0152f,
0.0080f, 0.0044f };
/*
Initialize noise image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
if (AcquireMagickResource(WidthResource,4*image->columns) == MagickFalse)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
pixels_info=AcquireVirtualMemory(3*image->columns,image->rows*
sizeof(*pixels));
kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1,
GetOpenMPMaximumThreads()*sizeof(*kernel));
if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL))
{
if (kernel != (float *) NULL)
kernel=(float *) RelinquishMagickMemory(kernel);
if (pixels_info != (MemoryInfo *) NULL)
pixels_info=RelinquishVirtualMemory(pixels_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(float *) GetVirtualMemoryBlob(pixels_info);
status=MagickTrue;
number_pixels=(MagickSizeType) image->columns*image->rows;
image_view=AcquireAuthenticCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
for (channel=0; channel < (ssize_t) GetPixelChannels(image); channel++)
{
register ssize_t
i;
size_t
high_pass,
low_pass;
ssize_t
level,
y;
PixelChannel
pixel_channel;
PixelTrait
traits;
if (status == MagickFalse)
continue;
traits=GetPixelChannelTraits(image,(PixelChannel) channel);
if (traits == UndefinedPixelTrait)
continue;
pixel_channel=GetPixelChannelChannel(image,channel);
if ((pixel_channel != RedPixelChannel) &&
(pixel_channel != GreenPixelChannel) &&
(pixel_channel != BluePixelChannel))
continue;
/*
Copy channel from image to wavelet pixel array.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
ssize_t
x;
p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixels[i++]=(float) p[channel];
p+=GetPixelChannels(image);
}
}
/*
Low pass filter outputs are called approximation kernel & high pass
filters are referred to as detail kernel. The detail kernel
have high values in the noisy parts of the signal.
*/
high_pass=0;
for (level=0; level < 5; level++)
{
double
magnitude;
ssize_t
x,
y;
low_pass=(size_t) (number_pixels*((level & 0x01)+1));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=kernel+id*image->columns;
q=pixels+y*image->columns;
HatTransform(q+high_pass,1,image->columns,(size_t) (1UL << level),p);
q+=low_pass;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(*p++);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->columns,1)
#endif
for (x=0; x < (ssize_t) image->columns; x++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
y;
p=kernel+id*image->rows;
q=pixels+x+low_pass;
HatTransform(q,image->columns,image->rows,(size_t) (1UL << level),p);
for (y=0; y < (ssize_t) image->rows; y++)
{
*q=(*p++);
q+=image->columns;
}
}
/*
To threshold, each coefficient is compared to a threshold value and
attenuated / shrunk by some factor.
*/
magnitude=threshold*noise_levels[level];
for (i=0; i < (ssize_t) number_pixels; ++i)
{
pixels[high_pass+i]-=pixels[low_pass+i];
if (pixels[high_pass+i] < -magnitude)
pixels[high_pass+i]+=magnitude-softness*magnitude;
else
if (pixels[high_pass+i] > magnitude)
pixels[high_pass+i]-=magnitude-softness*magnitude;
else
pixels[high_pass+i]*=softness;
if (high_pass != 0)
pixels[i]+=pixels[high_pass+i];
}
high_pass=low_pass;
}
/*
Reconstruct image from the thresholded wavelet kernel.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
offset;
q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
break;
}
offset=GetPixelChannelOffset(noise_image,pixel_channel);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
pixel;
pixel=(MagickRealType) pixels[i]+pixels[low_pass+i];
q[offset]=ClampToQuantum(pixel);
i++;
q+=GetPixelChannels(noise_image);
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType)
channel,GetPixelChannels(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
kernel=(float *) RelinquishMagickMemory(kernel);
pixels_info=RelinquishVirtualMemory(pixels_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
|
texture.c | /*
* Texture Manager
*/
#include "zgl.h"
static GLTexture* find_texture(GLint h) {
GLTexture* t;
GLContext* c = gl_get_context();
t = c->shared_state.texture_hash_table[h & TEXTURE_HASH_TABLE_MASK];
while (t != NULL) {
if (t->handle == h)
return t;
t = t->next;
}
return NULL;
}
GLboolean glAreTexturesResident(GLsizei n, const GLuint* textures, GLboolean* residences) {
#define RETVAL GL_FALSE
GLboolean retval = GL_TRUE;
GLint i;
#include "error_check_no_context.h"
for (i = 0; i < n; i++)
if (find_texture(textures[i])) {
residences[i] = GL_TRUE;
} else {
residences[i] = GL_FALSE;
retval = GL_FALSE;
}
return retval;
}
GLboolean glIsTexture(GLuint texture) {
GLContext* c = gl_get_context();
#define RETVAL GL_FALSE
#include "error_check.h"
if (find_texture(texture))
return GL_TRUE;
return GL_FALSE;
}
void* glGetTexturePixmap(GLint text, GLint level, GLint* xsize, GLint* ysize) {
GLTexture* tex;
GLContext* c = gl_get_context();
#if TGL_FEATURE_ERROR_CHECK == 1
if (!(text >= 0 && level < MAX_TEXTURE_LEVELS))
#define ERROR_FLAG GL_INVALID_ENUM
#define RETVAL NULL
#include "error_check.h"
#else
/*assert(text >= 0 && level < MAX_TEXTURE_LEVELS);*/
#endif
tex = find_texture(text);
if (!tex)
#if TGL_FEATURE_ERROR_CHECK == 1
#define ERROR_FLAG GL_INVALID_ENUM
#define RETVAL NULL
#include "error_check.h"
#else
return NULL;
#endif
*xsize = tex->images[level].xsize;
*ysize = tex->images[level].ysize;
return tex->images[level].pixmap;
}
static void free_texture(GLContext* c, GLint h) {
GLTexture *t, **ht;
t = find_texture(h);
if (t->prev == NULL) {
ht = &c->shared_state.texture_hash_table[t->handle & TEXTURE_HASH_TABLE_MASK];
*ht = t->next;
} else {
t->prev->next = t->next;
}
if (t->next != NULL)
t->next->prev = t->prev;
gl_free(t);
}
GLTexture* alloc_texture(GLint h) {
GLContext* c = gl_get_context();
GLTexture *t, **ht;
#define RETVAL NULL
#include "error_check.h"
t = gl_zalloc(sizeof(GLTexture));
if (!t)
#if TGL_FEATURE_ERROR_CHECK == 1
#define ERROR_FLAG GL_OUT_OF_MEMORY
#define RETVAL NULL
#include "error_check.h"
#else
gl_fatal_error("GL_OUT_OF_MEMORY");
#endif
ht = &c->shared_state.texture_hash_table[h & TEXTURE_HASH_TABLE_MASK];
t->next = *ht;
t->prev = NULL;
if (t->next != NULL)
t->next->prev = t;
*ht = t;
t->handle = h;
return t;
}
void glInitTextures() {
/* textures */
GLContext* c = gl_get_context();
c->texture_2d_enabled = 0;
c->current_texture = find_texture(0);
}
void glGenTextures(GLint n, GLuint* textures) {
GLContext* c = gl_get_context();
GLint max, i;
GLTexture* t;
#include "error_check.h"
max = 0;
for (i = 0; i < TEXTURE_HASH_TABLE_SIZE; i++) {
t = c->shared_state.texture_hash_table[i];
while (t != NULL) {
if (t->handle > max)
max = t->handle;
t = t->next;
}
}
for (i = 0; i < n; i++) {
textures[i] = max + i + 1; /* MARK: How texture handles are created.*/
}
}
void glDeleteTextures(GLint n, const GLuint* textures) {
GLint i;
GLTexture* t;
GLContext* c = gl_get_context();
#include "error_check.h"
for (i = 0; i < n; i++) {
t = find_texture(textures[i]);
if (t != NULL && t != 0) {
if (t == c->current_texture) {
glBindTexture(GL_TEXTURE_2D, 0);
#include "error_check.h"
}
free_texture(c, textures[i]);
}
}
}
void glopBindTexture(GLParam* p) {
GLint target = p[1].i;
GLint texture = p[2].i;
GLTexture* t;
GLContext* c = gl_get_context();
#if TGL_FEATURE_ERROR_CHECK == 1
if (!(target == GL_TEXTURE_2D && target > 0))
#define ERROR_FLAG GL_INVALID_ENUM
#include "error_check.h"
#else
#endif
t = find_texture(texture);
if (t == NULL) {
t = alloc_texture(texture);
#include "error_check.h"
}
if (t == NULL) {
#if TGL_FEATURE_ERROR_CHECK == 1
#define ERROR_FLAG GL_OUT_OF_MEMORY
#include "error_check.h"
#else
gl_fatal_error("GL_OUT_OF_MEMORY");
#endif
}
c->current_texture = t;
}
void glCopyTexImage2D(GLenum target,
GLint level,
GLenum internalformat,
GLint x,
GLint y,
GLsizei width,
GLsizei height, GLint border) {
GLParam p[9];
#include "error_check_no_context.h"
p[0].op = OP_CopyTexImage2D;
p[1].i = target;
p[2].i = level;
p[3].i = internalformat;
p[4].i = x;
p[5].i = y;
p[6].i = width;
p[7].i = height;
p[8].i = border;
gl_add_op(p);
}
void glopCopyTexImage2D(GLParam* p) {
GLImage* im;
PIXEL* data;
GLint i, j;
GLint target = p[1].i;
GLint level = p[2].i;
GLint x = p[4].i;
GLint y = p[5].i;
GLsizei w = p[6].i;
GLsizei h = p[7].i;
GLint border = p[8].i;
GLContext* c = gl_get_context();
y -= h;
if (c->readbuffer != GL_FRONT || c->current_texture == NULL || target != GL_TEXTURE_2D || border != 0 ||
w != TGL_FEATURE_TEXTURE_DIM || /*TODO Implement image interp*/
h != TGL_FEATURE_TEXTURE_DIM) {
#if TGL_FEATURE_ERROR_CHECK == 1
#define ERROR_FLAG GL_INVALID_OPERATION
#include "error_check.h"
#else
return;
#endif
}
im = &c->current_texture->images[level];
data = c->current_texture->images[level].pixmap;
im->xsize = TGL_FEATURE_TEXTURE_DIM;
im->ysize = TGL_FEATURE_TEXTURE_DIM;
/* TODO implement the scaling and stuff that the GL spec says it should have.*/
#if TGL_FEATURE_MULTITHREADED_COPY_TEXIMAGE_2D == 1
#pragma omp parallel for
for (j = 0; j < h; j++)
for (i = 0; i < w; i++) {
data[i + j * w] = c->zb->pbuf[((i + x) % (c->zb->xsize)) + ((j + y) % (c->zb->ysize)) * (c->zb->xsize)];
}
#else
for (j = 0; j < h; j++)
for (i = 0; i < w; i++) {
data[i + j * w] = c->zb->pbuf[((i + x) % (c->zb->xsize)) + ((j + y) % (c->zb->ysize)) * (c->zb->xsize)];
}
#endif
}
void glopTexImage1D(GLParam* p) {
GLint target = p[1].i;
GLint level = p[2].i;
GLint components = p[3].i;
GLint width = p[4].i;
/* GLint height = p[5].i;*/
GLint height = 1;
GLint border = p[5].i;
GLint format = p[6].i;
GLint type = p[7].i;
void* pixels = p[8].p;
GLImage* im;
GLubyte* pixels1;
GLint do_free=0;
GLContext* c = gl_get_context();
{
#if TGL_FEATURE_ERROR_CHECK == 1
if (!(c->current_texture != NULL && target == GL_TEXTURE_1D && level == 0 && components == 3 && border == 0 && format == GL_RGB &&
type == GL_UNSIGNED_BYTE))
#define ERROR_FLAG GL_INVALID_ENUM
#include "error_check.h"
#else
if (!(c->current_texture != NULL && target == GL_TEXTURE_1D && level == 0 && components == 3 && border == 0 && format == GL_RGB &&
type == GL_UNSIGNED_BYTE))
gl_fatal_error("glTexImage2D: combination of parameters not handled!!");
#endif
}
if (width != TGL_FEATURE_TEXTURE_DIM || height != TGL_FEATURE_TEXTURE_DIM) {
pixels1 = gl_malloc(TGL_FEATURE_TEXTURE_DIM * TGL_FEATURE_TEXTURE_DIM * 3); /* GUARDED*/
if (pixels1 == NULL) {
#if TGL_FEATURE_ERROR_CHECK == 1
#define ERROR_FLAG GL_OUT_OF_MEMORY
#include "error_check.h"
#else
gl_fatal_error("GL_OUT_OF_MEMORY");
#endif
}
/* no GLinterpolation is done here to respect the original image aliasing ! */
gl_resizeImageNoInterpolate(pixels1, TGL_FEATURE_TEXTURE_DIM, TGL_FEATURE_TEXTURE_DIM, pixels, width, height);
do_free = 1;
width = TGL_FEATURE_TEXTURE_DIM;
height = TGL_FEATURE_TEXTURE_DIM;
} else {
pixels1 = pixels;
}
im = &c->current_texture->images[level];
im->xsize = width;
im->ysize = height;
#if TGL_FEATURE_RENDER_BITS == 32
gl_convertRGB_to_8A8R8G8B(im->pixmap, pixels1, width, height);
#elif TGL_FEATURE_RENDER_BITS == 16
gl_convertRGB_to_5R6G5B(im->pixmap, pixels1, width, height);
#else
#error bad TGL_FEATURE_RENDER_BITS
#endif
if (do_free)
gl_free(pixels1);
}
void glopTexImage2D(GLParam* p) {
GLint target = p[1].i;
GLint level = p[2].i;
GLint components = p[3].i;
GLint width = p[4].i;
GLint height = p[5].i;
GLint border = p[6].i;
GLint format = p[7].i;
GLint type = p[8].i;
void* pixels = p[9].p;
GLImage* im;
GLubyte* pixels1;
GLint do_free=0;
GLContext* c = gl_get_context();
{
#if TGL_FEATURE_ERROR_CHECK == 1
if (!(c->current_texture != NULL && target == GL_TEXTURE_2D && level == 0 && components == 3 && border == 0 && format == GL_RGB &&
type == GL_UNSIGNED_BYTE))
#define ERROR_FLAG GL_INVALID_ENUM
#include "error_check.h"
#else
if (!(c->current_texture != NULL && target == GL_TEXTURE_2D && level == 0 && components == 3 && border == 0 && format == GL_RGB &&
type == GL_UNSIGNED_BYTE))
gl_fatal_error("glTexImage2D: combination of parameters not handled!!");
#endif
}
if (width != TGL_FEATURE_TEXTURE_DIM || height != TGL_FEATURE_TEXTURE_DIM) {
pixels1 = gl_malloc(TGL_FEATURE_TEXTURE_DIM * TGL_FEATURE_TEXTURE_DIM * 3); /* GUARDED*/
if (pixels1 == NULL) {
#if TGL_FEATURE_ERROR_CHECK == 1
#define ERROR_FLAG GL_OUT_OF_MEMORY
#include "error_check.h"
#else
gl_fatal_error("GL_OUT_OF_MEMORY");
#endif
}
/* no GLinterpolation is done here to respect the original image aliasing ! */
gl_resizeImageNoInterpolate(pixels1, TGL_FEATURE_TEXTURE_DIM, TGL_FEATURE_TEXTURE_DIM, pixels, width, height);
do_free = 1;
width = TGL_FEATURE_TEXTURE_DIM;
height = TGL_FEATURE_TEXTURE_DIM;
} else {
pixels1 = pixels;
}
im = &c->current_texture->images[level];
im->xsize = width;
im->ysize = height;
#if TGL_FEATURE_RENDER_BITS == 32
gl_convertRGB_to_8A8R8G8B(im->pixmap, pixels1, width, height);
#elif TGL_FEATURE_RENDER_BITS == 16
gl_convertRGB_to_5R6G5B(im->pixmap, pixels1, width, height);
#else
#error Bad TGL_FEATURE_RENDER_BITS
#endif
if (do_free)
gl_free(pixels1);
}
/* TODO: not all tests are done */
/*
void glopTexEnv(GLContext* c, GLParam* p) {
GLint target = p[1].i;
GLint pname = p[2].i;
GLint param = p[3].i;
if (target != GL_TEXTURE_ENV) {
error:
#if TGL_FEATURE_ERROR_CHECK == 1
#define ERROR_FLAG GL_INVALID_ENUM
#include "error_check.h"
#else
gl_fatal_error("glTexParameter: unsupported option");
#endif
}
if (pname != GL_TEXTURE_ENV_MODE)
goto error;
if (param != GL_DECAL)
goto error;
}
*/
/* TODO: not all tests are done */
/*
void glopTexParameter(GLContext* c, GLParam* p) {
GLint target = p[1].i;
GLint pname = p[2].i;
GLint param = p[3].i;
if (target != GL_TEXTURE_2D &&
target != GL_TEXTURE_1D) {
error:
tgl_warning("glTexParameter: unsupported option");
return;
}
switch (pname) {
case GL_TEXTURE_WRAP_S:
case GL_TEXTURE_WRAP_T:
if (param != GL_REPEAT)
goto error;
break;
}
}
*/
/*
void glopPixelStore(GLContext* c, GLParam* p) {
GLint pname = p[1].i;
GLint param = p[2].i;
if (pname != GL_UNPACK_ALIGNMENT || param != 1) {
gl_fatal_error("glPixelStore: unsupported option");
}
}
*/
|
displacement_contact_criteria.h | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_DISPLACEMENT_CONTACT_CRITERIA_H)
#define KRATOS_DISPLACEMENT_CONTACT_CRITERIA_H
/* System includes */
/* External includes */
/* Project includes */
#include "utilities/table_stream_utility.h"
#include "solving_strategies/convergencecriterias/convergence_criteria.h"
#include "utilities/color_utilities.h"
namespace Kratos
{
///@addtogroup ContactStructuralMechanicsApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@name Kratos Classes
///@{
/**
* @class DisplacementContactCriteria
* @ingroup ContactStructuralMechanicsApplication
* @brief Convergence criteria for contact problems
* @details This class implements a convergence control based on nodal displacement (for penalty contact)
* @author Vicente Mataix Ferrandiz
*/
template< class TSparseSpace,
class TDenseSpace >
class DisplacementContactCriteria
: public ConvergenceCriteria< TSparseSpace, TDenseSpace >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of DisplacementContactCriteria
KRATOS_CLASS_POINTER_DEFINITION( DisplacementContactCriteria );
/// The base class definition (and it subclasses)
typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
/// The sparse space used
typedef TSparseSpace SparseSpaceType;
/// The table stream definition TODO: Replace by logger
typedef TableStreamUtility::Pointer TablePrinterPointerType;
/// The index type definition
typedef std::size_t IndexType;
/// The key type definition
typedef std::size_t KeyType;
///@}
///@name Life Cycle
///@{
/// Constructor.
/**
* @param DispRatioTolerance Relative tolerance for displacement error
* @param DispAbsTolerance Absolute tolerance for displacement error
* @param pTable The pointer to the output table
* @param PrintingOutput If the output is going to be printed in a txt file
*/
explicit DisplacementContactCriteria(
const TDataType DispRatioTolerance,
const TDataType DispAbsTolerance,
const bool PrintingOutput = false
)
: ConvergenceCriteria< TSparseSpace, TDenseSpace >(),
mPrintingOutput(PrintingOutput),
mTableIsInitialized(false)
{
// The displacement solution
mDispRatioTolerance = DispRatioTolerance;
mDispAbsTolerance = DispAbsTolerance;
}
/**
* @brief Default constructor (parameters)
* @param ThisParameters The configuration parameters
*/
explicit DisplacementContactCriteria( Parameters ThisParameters = Parameters(R"({})"))
: ConvergenceCriteria< TSparseSpace, TDenseSpace >(),
mTableIsInitialized(false)
{
// The default parameters
Parameters default_parameters = Parameters(R"(
{
"ensure_contact" : false,
"print_convergence_criterion" : false,
"displacement_relative_tolerance" : 1.0e-4,
"displacement_absolute_tolerance" : 1.0e-9
})" );
ThisParameters.ValidateAndAssignDefaults(default_parameters);
// The displacement solution
mDispRatioTolerance = ThisParameters["displacement_relative_tolerance"].GetDouble();
mDispAbsTolerance = ThisParameters["displacement_absolute_tolerance"].GetDouble();
// Additional flags -> NOTE: Replace for a real flag?¿
mPrintingOutput = ThisParameters["print_convergence_criterion"].GetBool();
}
// Copy constructor.
DisplacementContactCriteria( DisplacementContactCriteria const& rOther )
:BaseType(rOther)
,mDispRatioTolerance(rOther.mDispRatioTolerance)
,mDispAbsTolerance(rOther.mDispAbsTolerance)
,mPrintingOutput(rOther.mPrintingOutput)
,mTableIsInitialized(rOther.mTableIsInitialized)
{
}
/// Destructor.
~DisplacementContactCriteria() override = default;
///@}
///@name Operators
///@{
/**
* @brief Compute relative and absolute error.
* @param rModelPart Reference to the ModelPart containing the contact problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
* @return true if convergence is achieved, false otherwise
*/
bool PostCriteria(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
if (SparseSpaceType::Size(rDx) != 0) { //if we are solving for something
// Initialize
TDataType disp_solution_norm = 0.0, disp_increase_norm = 0.0;
IndexType disp_dof_num(0);
// Loop over Dofs
#pragma omp parallel for reduction(+:disp_solution_norm,disp_increase_norm,disp_dof_num)
for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) {
auto it_dof = rDofSet.begin() + i;
std::size_t dof_id;
TDataType dof_value, dof_incr;
if (it_dof->IsFree()) {
dof_id = it_dof->EquationId();
dof_value = it_dof->GetSolutionStepValue(0);
dof_incr = rDx[dof_id];
const auto curr_var = it_dof->GetVariable();
disp_solution_norm += dof_value * dof_value;
disp_increase_norm += dof_incr * dof_incr;
disp_dof_num++;
}
}
if(disp_increase_norm == 0.0) disp_increase_norm = 1.0;
if(disp_solution_norm == 0.0) disp_solution_norm = 1.0;
const TDataType disp_ratio = std::sqrt(disp_increase_norm/disp_solution_norm);
const TDataType disp_abs = std::sqrt(disp_increase_norm)/ static_cast<TDataType>(disp_dof_num);
// The process info of the model part
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// We print the results // TODO: Replace for the new log
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
std::cout.precision(4);
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& Table = p_table->GetTable();
Table << disp_ratio << mDispRatioTolerance << disp_abs << mDispAbsTolerance;
} else {
std::cout.precision(4);
if (mPrintingOutput == false) {
KRATOS_INFO("DisplacementContactCriteria") << BOLDFONT("DoF ONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl;
KRATOS_INFO("DisplacementContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl;
} else {
KRATOS_INFO("DisplacementContactCriteria") << "DoF ONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl;
KRATOS_INFO("DisplacementContactCriteria") << "\tDISPLACEMENT: RATIO = " << disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl;
}
}
}
// We check if converged
const bool disp_converged = (disp_ratio <= mDispRatioTolerance || disp_abs <= mDispAbsTolerance);
if (disp_converged) {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& table = p_table->GetTable();
if (mPrintingOutput == false)
table << BOLDFONT(FGRN(" Achieved"));
else
table << "Achieved";
} else {
if (mPrintingOutput == false)
KRATOS_INFO("DisplacementContactCriteria") << BOLDFONT("\tDoF") << " convergence is " << BOLDFONT(FGRN("achieved")) << std::endl;
else
KRATOS_INFO("DisplacementContactCriteria") << "\tDoF convergence is achieved" << std::endl;
}
}
return true;
} else {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& table = p_table->GetTable();
if (mPrintingOutput == false)
table << BOLDFONT(FRED(" Not achieved"));
else
table << "Not achieved";
} else {
if (mPrintingOutput == false)
KRATOS_INFO("DisplacementContactCriteria") << BOLDFONT("\tDoF") << " convergence is " << BOLDFONT(FRED(" not achieved")) << std::endl;
else
KRATOS_INFO("DisplacementContactCriteria") << "\tDoF convergence is not achieved" << std::endl;
}
}
return false;
}
}
else // In this case all the displacements are imposed!
return true;
}
/**
* @brief This function initialize the convergence criteria
* @param rModelPart Reference to the ModelPart containing the contact problem. (unused)
*/
void Initialize( ModelPart& rModelPart ) override
{
BaseType::mConvergenceCriteriaIsInitialized = true;
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
if (r_process_info.Has(TABLE_UTILITY) && mTableIsInitialized == false) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& table = p_table->GetTable();
table.AddColumn("DP RATIO", 10);
table.AddColumn("EXP. RAT", 10);
table.AddColumn("ABS", 10);
table.AddColumn("EXP. ABS", 10);
table.AddColumn("CONVERGENCE", 15);
mTableIsInitialized = true;
}
}
///@}
///@name Operations
///@{
///@}
///@name Acces
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
bool mPrintingOutput; /// If the colors and bold are printed
bool mTableIsInitialized; /// If the table is already initialized
TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement
TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Unaccessible methods
///@{
///@}
};
///@} // Kratos classes
///@} // Application group
}
#endif /* KRATOS_DISPLACEMENT_CONTACT_CRITERIA_H */
|
concattest2.c | #include <stdlib.h>
#include "concattest2.h"
void concattest2(float* v,int m,int n,float*output){
#pragma omp parallel for
for (int H15 = 0; H15 < 1; H15++) {
for (int H19 = 0; H19 < 1; H19++) {
output[((1 + (m - (1)))) * (H19) + H15] = v[(((m)) * (H19)) + H15];
}
for (int H20 = 1; H20 < n; H20++) {
output[((1 + (m - (1)))) * (((H20 - (1)) + 1)) + H15] = v[(((m)) * (H20)) + H15];
}
}
#pragma omp parallel for
for (int H21 = 1; H21 < m; H21++) {
for (int H22 = 0; H22 < n; H22++) {
output[((1 + (m - (1)))) * (H22) + ((H21 - (1)) + 1)] = v[(((m)) * (H22)) + H21];
}
}
}
|
OpenMPHelper.h | #ifndef PICA_OMPHELPER_H
#define PICA_OMPHELPER_H
/* This file should be included everywhere instead of <omp.h>.
If the code is build with OpenMP it just includes <omp.h>, otherwise it
provides wrappers for OpenMP functions and #pragma omp.
The code including this file can use OpenMP functions and
pragmas independently of whether it will be build with OpenMP or not. */
#ifdef _OPENMP
#include <omp.h>
namespace pica {
inline bool useOpenMP() { return true; }
inline int getNumThreads() {
int numThreads = 0;
#pragma omp parallel
{
#pragma omp master
numThreads = omp_get_num_threads();
}
return numThreads;
}
} // namespace pica
#else
typedef void* omp_lock_t;
inline int omp_get_max_threads() { return 1; }
inline int omp_get_thread_num() { return 0; }
inline int omp_get_num_threads() { return 1; }
inline void omp_set_num_threads(int) {}
inline void omp_init_lock(omp_lock_t *) {}
inline void omp_set_lock(omp_lock_t *) {}
inline void omp_unset_lock(omp_lock_t *) {}
inline void omp_destroy_lock(omp_lock_t *) {}
#pragma omp
namespace pica
{
inline bool useOpenMP() { return false; }
inline int getNumThreads() { return 1; }
} // namespace pica
#endif
#ifdef _MSC_VER
#define collapse(N)
#endif
#endif
|
GB_dense_ewise3_accum_template.c | //------------------------------------------------------------------------------
// GB_dense_ewise3_accum_template: C += A+B where all 3 matrices are dense
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// FUTURE: allow the accum and the 'plus' op to differ (as in C += A-B,
// with PLUS as the accum and MINUS as the operator, so CBLAS can be used
// for this combination.
{
//--------------------------------------------------------------------------
// get A, B, and C
//--------------------------------------------------------------------------
// any matrix may be aliased to any other (C==A, C==B, and/or A==B)
GB_ATYPE *Ax = (GB_ATYPE *) A->x ;
GB_BTYPE *Bx = (GB_BTYPE *) B->x ;
GB_CTYPE *Cx = (GB_CTYPE *) C->x ;
const int64_t cnz = GB_NNZ (C) ;
int64_t p ;
//--------------------------------------------------------------------------
// C += A+B where all 3 matries are dense
//--------------------------------------------------------------------------
if (A == B)
{
//----------------------------------------------------------------------
// C += A+A where A and C are dense
//----------------------------------------------------------------------
// If the op is PLUS, this becomes C += 2*A. If the op is MINUS,
// almost nothing happens since C=C-(A-A) = C, except if A has Infs or
// NaNs. In this case, don't bother to call the CBLAS if the op is
// MINUS.
#if defined ( GB_HAS_CBLAS ) && GB_OP_IS_PLUS_REAL
// C += 2*A via GB_cblas_saxpy or GB_cblas_daxpy
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 2, Ax, Cx, nthreads) ; // C += 2*A
#else
// C += A+A
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < cnz ; p++)
{
GB_GETA (aij, Ax, p) ; // aij = Ax [p]
GB_CTYPE_SCALAR (t) ; // declare scalar t
GB_BINOP (t, aij, aij, 0, 0) ; // t = aij + aij
GB_BINOP (GB_CX (p), GB_CX (p), t, 0, 0) ; // Cx [p] = cij + t
}
#endif
}
else
{
//----------------------------------------------------------------------
// C += A+B where all 3 matrices are dense
//----------------------------------------------------------------------
#if defined ( GB_HAS_CBLAS ) && GB_OP_IS_PLUS_REAL
// C += A+B via GB_cblas_saxpy or GB_cblas_daxpy
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 1, Ax, Cx, nthreads) ; // C += A
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 1, Bx, Cx, nthreads) ; // C += B
#elif defined ( GB_HAS_CBLAS ) && GB_OP_IS_MINUS_REAL
// C -= (A-B) via GB_cblas_saxpy or GB_cblas_daxpy
GB_CBLAS_AXPY (cnz, (GB_CTYPE) -1, Ax, Cx, nthreads) ; // C -= A
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 1, Bx, Cx, nthreads) ; // C += B
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < cnz ; p++)
{
GB_GETA (aij, Ax, p) ; // aij = Ax [p]
GB_GETB (bij, Bx, p) ; // bij = Bx [p]
GB_CTYPE_SCALAR (t) ; // declare scalar t
GB_BINOP (t, aij, bij, 0, 0) ; // t = aij + bij
GB_BINOP (GB_CX (p), GB_CX (p), t, 0, 0) ; // Cx [p] = cij + t
}
#endif
}
}
|
omp50_taskwait_depend.c | // RUN: %libomp-compile-and-run
// UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8
// support for taskwait with depend clause introduced in clang-14
// UNSUPPORTED: clang-5, clang-6, clang-6, clang-8, clang-9, clang-10, clang-11,
// clang-12, clang-13
// icc does not yet support taskwait with depend clause
// XFAIL: icc
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "omp_my_sleep.h"
int a = 0, b = 0;
int task_grabbed = 0, task_can_proceed = 0;
int task2_grabbed = 0, task2_can_proceed = 0;
static void wait_on_flag(int *flag) {
int flag_value;
int timelimit = 30;
int secs = 0;
do {
#pragma omp atomic read
flag_value = *flag;
my_sleep(1.0);
secs++;
if (secs == timelimit) {
fprintf(stderr, "error: timeout in wait_on_flag()\n");
exit(EXIT_FAILURE);
}
} while (flag_value == 0);
}
static void signal_flag(int *flag) {
#pragma omp atomic
(*flag)++;
}
int main(int argc, char** argv) {
// Ensure two threads are running
int num_threads = omp_get_max_threads();
if (num_threads < 2)
omp_set_num_threads(2);
#pragma omp parallel shared(a)
{
int a_value;
// Let us be extra safe here
if (omp_get_num_threads() > 1) {
#pragma omp single nowait
{
// Schedule independent child task that
// waits to be flagged after sebsequent taskwait depend()
#pragma omp task
{
signal_flag(&task_grabbed);
wait_on_flag(&task_can_proceed);
}
// Let another worker thread grab the task to execute
wait_on_flag(&task_grabbed);
// This should be ignored since the task above has
// no dependency information
#pragma omp taskwait depend(inout: a)
// Signal the independent task to proceed
signal_flag(&task_can_proceed);
// Schedule child task with dependencies that taskwait does
// not care about
#pragma omp task depend(inout: b)
{
signal_flag(&task2_grabbed);
wait_on_flag(&task2_can_proceed);
#pragma omp atomic
b++;
}
// Let another worker thread grab the task to execute
wait_on_flag(&task2_grabbed);
// This should be ignored since the task above has
// dependency information on b instead of a
#pragma omp taskwait depend(inout: a)
// Signal the task to proceed
signal_flag(&task2_can_proceed);
// Generate one child task for taskwait
#pragma omp task shared(a) depend(inout: a)
{
my_sleep(1.0);
#pragma omp atomic
a++;
}
#pragma omp taskwait depend(inout: a)
#pragma omp atomic read
a_value = a;
if (a_value != 1) {
fprintf(stderr, "error: dependent task was not executed before "
"taskwait finished\n");
exit(EXIT_FAILURE);
}
} // #pragma omp single
} // if (num_threads > 1)
} // #pragma omp parallel
return EXIT_SUCCESS;
}
|
tsynchtasks.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h> /* OpenMP */
long result=0;
void foo() {
#pragma omp parallel
#pragma omp single
{
int argum = 1;
#pragma omp taskgroup
{
#pragma omp task shared(result) firstprivate(argum)
for (long i = 0; i < 10; i++) {
#pragma omp atomic
result += argum;
}
argum++;
#pragma omp task shared(result) firstprivate(argum)
for (long i = 0; i < 10; i++) {
#pragma omp atomic
result += argum;
}
#pragma omp taskwait
argum = result;
for (long i = 0; i < 10; i++) {
#pragma omp task shared(result) firstprivate(argum)
#pragma omp atomic
result += argum;
}
}
#pragma omp task firstprivate(result) firstprivate(argum)
printf("Hello from third task, up to now result=%ld and argum = %d\n", result, argum);
}
}
int main(int argc, char *argv[]) {
foo();
printf("Back in main ... result = %ld\n", result);
}
|
c-tree.h | /* Definitions for C parsing and type checking.
Copyright (C) 1987, 1993, 1994, 1995, 1997, 1998,
1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to the Free
Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA. */
#ifndef GCC_C_TREE_H
#define GCC_C_TREE_H
#include "c-common.h"
#include "toplev.h"
#include "diagnostic.h"
/* struct lang_identifier is private to c-decl.c, but langhooks.c needs to
know how big it is. This is sanity-checked in c-decl.c. */
#define C_SIZEOF_STRUCT_LANG_IDENTIFIER \
(sizeof (struct c_common_identifier) + 3 * sizeof (void *))
/* Language-specific declaration information. */
struct lang_decl GTY(())
{
char dummy;
};
/* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is read-only. */
#define C_TYPE_FIELDS_READONLY(TYPE) TREE_LANG_FLAG_1 (TYPE)
/* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is volatile. */
#define C_TYPE_FIELDS_VOLATILE(TYPE) TREE_LANG_FLAG_2 (TYPE)
/* In a RECORD_TYPE or UNION_TYPE or ENUMERAL_TYPE
nonzero if the definition of the type has already started. */
#define C_TYPE_BEING_DEFINED(TYPE) TYPE_LANG_FLAG_0 (TYPE)
/* In an incomplete RECORD_TYPE or UNION_TYPE, a list of variable
declarations whose type would be completed by completing that type. */
#define C_TYPE_INCOMPLETE_VARS(TYPE) TYPE_VFIELD (TYPE)
/* In an IDENTIFIER_NODE, nonzero if this identifier is actually a
keyword. C_RID_CODE (node) is then the RID_* value of the keyword,
and C_RID_YYCODE is the token number wanted by Yacc. */
#define C_IS_RESERVED_WORD(ID) TREE_LANG_FLAG_0 (ID)
struct lang_type GTY(())
{
/* In a RECORD_TYPE, a sorted array of the fields of the type. */
struct sorted_fields_type * GTY ((reorder ("resort_sorted_fields"))) s;
/* In an ENUMERAL_TYPE, the min and max values. */
tree enum_min;
tree enum_max;
/* In a RECORD_TYPE, information specific to Objective-C, such
as a list of adopted protocols or a pointer to a corresponding
@interface. See objc/objc-act.h for details. */
tree objc_info;
};
/* Record whether a type or decl was written with nonconstant size.
Note that TYPE_SIZE may have simplified to a constant. */
#define C_TYPE_VARIABLE_SIZE(TYPE) TYPE_LANG_FLAG_1 (TYPE)
#define C_DECL_VARIABLE_SIZE(TYPE) DECL_LANG_FLAG_0 (TYPE)
/* Record whether a typedef for type `int' was actually `signed int'. */
#define C_TYPEDEF_EXPLICITLY_SIGNED(EXP) DECL_LANG_FLAG_1 (EXP)
/* For a FUNCTION_DECL, nonzero if it was defined without an explicit
return type. */
#define C_FUNCTION_IMPLICIT_INT(EXP) DECL_LANG_FLAG_1 (EXP)
/* For a FUNCTION_DECL, nonzero if it was an implicit declaration. */
#define C_DECL_IMPLICIT(EXP) DECL_LANG_FLAG_2 (EXP)
/* For FUNCTION_DECLs, evaluates true if the decl is built-in but has
been declared. */
#define C_DECL_DECLARED_BUILTIN(EXP) \
DECL_LANG_FLAG_3 (FUNCTION_DECL_CHECK (EXP))
/* For FUNCTION_DECLs, evaluates true if the decl is built-in, has a
built-in prototype and does not have a non-built-in prototype. */
#define C_DECL_BUILTIN_PROTOTYPE(EXP) \
DECL_LANG_FLAG_6 (FUNCTION_DECL_CHECK (EXP))
/* Record whether a decl was declared register. This is strictly a
front-end flag, whereas DECL_REGISTER is used for code generation;
they may differ for structures with volatile fields. */
#define C_DECL_REGISTER(EXP) DECL_LANG_FLAG_4 (EXP)
/* Record whether a decl was used in an expression anywhere except an
unevaluated operand of sizeof / typeof / alignof. This is only
used for functions declared static but not defined, though outside
sizeof and typeof it is set for other function decls as well. */
#define C_DECL_USED(EXP) DECL_LANG_FLAG_5 (FUNCTION_DECL_CHECK (EXP))
/* Record whether a label was defined in a statement expression which
has finished and so can no longer be jumped to. */
#define C_DECL_UNJUMPABLE_STMT_EXPR(EXP) \
DECL_LANG_FLAG_6 (LABEL_DECL_CHECK (EXP))
/* Record whether a label was the subject of a goto from outside the
current level of statement expression nesting and so cannot be
defined right now. */
#define C_DECL_UNDEFINABLE_STMT_EXPR(EXP) \
DECL_LANG_FLAG_7 (LABEL_DECL_CHECK (EXP))
/* Record whether a label was defined in the scope of an identifier
with variably modified type which has finished and so can no longer
be jumped to. */
#define C_DECL_UNJUMPABLE_VM(EXP) \
DECL_LANG_FLAG_3 (LABEL_DECL_CHECK (EXP))
/* Record whether a label was the subject of a goto from outside the
current level of scopes of identifiers with variably modified type
and so cannot be defined right now. */
#define C_DECL_UNDEFINABLE_VM(EXP) \
DECL_LANG_FLAG_5 (LABEL_DECL_CHECK (EXP))
/* Record whether a variable has been declared threadprivate by
#pragma omp threadprivate. */
#define C_DECL_THREADPRIVATE_P(DECL) DECL_LANG_FLAG_3 (VAR_DECL_CHECK (DECL))
/* Nonzero for a decl which either doesn't exist or isn't a prototype.
N.B. Could be simplified if all built-in decls had complete prototypes
(but this is presently difficult because some of them need FILE*). */
#define C_DECL_ISNT_PROTOTYPE(EXP) \
(EXP == 0 \
|| (TYPE_ARG_TYPES (TREE_TYPE (EXP)) == 0 \
&& !DECL_BUILT_IN (EXP)))
/* For FUNCTION_TYPE, a hidden list of types of arguments. The same as
TYPE_ARG_TYPES for functions with prototypes, but created for functions
without prototypes. */
#define TYPE_ACTUAL_ARG_TYPES(NODE) TYPE_LANG_SLOT_1 (NODE)
/* Record parser information about an expression that is irrelevant
for code generation alongside a tree representing its value. */
struct c_expr
{
/* The value of the expression. */
tree value;
/* Record the original binary operator of an expression, which may
have been changed by fold, STRING_CST for unparenthesized string
constants, or ERROR_MARK for other expressions (including
parenthesized expressions). */
enum tree_code original_code;
};
/* A kind of type specifier. Note that this information is currently
only used to distinguish tag definitions, tag references and typeof
uses. */
enum c_typespec_kind {
/* A reserved keyword type specifier. */
ctsk_resword,
/* A reference to a tag, previously declared, such as "struct foo".
This includes where the previous declaration was as a different
kind of tag, in which case this is only valid if shadowing that
tag in an inner scope. */
ctsk_tagref,
/* A reference to a tag, not previously declared in a visible
scope. */
ctsk_tagfirstref,
/* A definition of a tag such as "struct foo { int a; }". */
ctsk_tagdef,
/* A typedef name. */
ctsk_typedef,
/* An ObjC-specific kind of type specifier. */
ctsk_objc,
/* A typeof specifier. */
ctsk_typeof
};
/* A type specifier: this structure is created in the parser and
passed to declspecs_add_type only. */
struct c_typespec {
/* What kind of type specifier this is. */
enum c_typespec_kind kind;
/* The specifier itself. */
tree spec;
};
/* A storage class specifier. */
enum c_storage_class {
csc_none,
csc_auto,
csc_extern,
csc_register,
csc_static,
csc_typedef
};
/* A type specifier keyword "void", "_Bool", "char", "int", "float",
"double", or none of these. */
enum c_typespec_keyword {
cts_none,
cts_void,
cts_bool,
cts_char,
cts_int,
cts_float,
cts_double,
cts_dfloat32,
cts_dfloat64,
cts_dfloat128
};
/* A sequence of declaration specifiers in C. */
struct c_declspecs {
/* The type specified, if a single type specifier such as a struct,
union or enum specifier, typedef name or typeof specifies the
whole type, or NULL_TREE if none or a keyword such as "void" or
"char" is used. Does not include qualifiers. */
tree type;
/* The attributes from a typedef decl. */
tree decl_attr;
/* When parsing, the attributes. Outside the parser, this will be
NULL; attributes (possibly from multiple lists) will be passed
separately. */
tree attrs;
/* Any type specifier keyword used such as "int", not reflecting
modifiers such as "short", or cts_none if none. */
enum c_typespec_keyword typespec_word;
/* The storage class specifier, or csc_none if none. */
enum c_storage_class storage_class;
/* Whether any declaration specifiers have been seen at all. */
BOOL_BITFIELD declspecs_seen_p : 1;
/* Whether a type specifier has been seen. */
BOOL_BITFIELD type_seen_p : 1;
/* Whether something other than a storage class specifier or
attribute has been seen. This is used to warn for the
obsolescent usage of storage class specifiers other than at the
start of the list. (Doing this properly would require function
specifiers to be handled separately from storage class
specifiers.) */
BOOL_BITFIELD non_sc_seen_p : 1;
/* Whether the type is specified by a typedef or typeof name. */
BOOL_BITFIELD typedef_p : 1;
/* Whether a struct, union or enum type either had its content
defined by a type specifier in the list or was the first visible
declaration of its tag. */
BOOL_BITFIELD tag_defined_p : 1;
/* Whether the type is explicitly "signed" or specified by a typedef
whose type is explicitly "signed". */
BOOL_BITFIELD explicit_signed_p : 1;
/* Whether the specifiers include a deprecated typedef. */
BOOL_BITFIELD deprecated_p : 1;
/* APPLE LOCAL begin "unavailable" attribute (radar 2809697) */
/* Whether the specifiers include a unavailable typedef. */
BOOL_BITFIELD unavailable_p : 1;
/* APPLE LOCAL end "unavailable" attribute (radar 2809697) */
/* APPLE LOCAL begin private extern */
/* Whether the specifiers include __private_extern. */
BOOL_BITFIELD private_extern_p : 1;
/* APPLE LOCAL end private extern */
/* APPLE LOCAL CW asm blocks */
BOOL_BITFIELD iasm_asm_specbit : 1;
/* Whether the type defaulted to "int" because there were no type
specifiers. */
BOOL_BITFIELD default_int_p;
/* Whether "long" was specified. */
BOOL_BITFIELD long_p : 1;
/* Whether "long" was specified more than once. */
BOOL_BITFIELD long_long_p : 1;
/* Whether "short" was specified. */
BOOL_BITFIELD short_p : 1;
/* Whether "signed" was specified. */
BOOL_BITFIELD signed_p : 1;
/* Whether "unsigned" was specified. */
BOOL_BITFIELD unsigned_p : 1;
/* Whether "complex" was specified. */
BOOL_BITFIELD complex_p : 1;
/* Whether "inline" was specified. */
BOOL_BITFIELD inline_p : 1;
/* Whether "__thread" was specified. */
BOOL_BITFIELD thread_p : 1;
/* Whether "const" was specified. */
BOOL_BITFIELD const_p : 1;
/* Whether "volatile" was specified. */
BOOL_BITFIELD volatile_p : 1;
/* Whether "restrict" was specified. */
BOOL_BITFIELD restrict_p : 1;
};
/* The various kinds of declarators in C. */
enum c_declarator_kind {
/* An identifier. */
cdk_id,
/* A function. */
cdk_function,
/* An array. */
cdk_array,
/* A pointer. */
cdk_pointer,
/* APPLE LOCAL blocks (C++ ch) */
cdk_block_pointer,
/* Parenthesized declarator with nested attributes. */
cdk_attrs
};
/* Information about the parameters in a function declarator. */
struct c_arg_info {
/* A list of parameter decls. */
tree parms;
/* A list of structure, union and enum tags defined. */
tree tags;
/* A list of argument types to go in the FUNCTION_TYPE. */
tree types;
/* A list of non-parameter decls (notably enumeration constants)
defined with the parameters. */
tree others;
/* A list of VLA sizes from the parameters. In a function
definition, these are used to ensure that side-effects in sizes
of arrays converted to pointers (such as a parameter int i[n++])
take place; otherwise, they are ignored. */
tree pending_sizes;
/* True when these arguments had [*]. */
BOOL_BITFIELD had_vla_unspec : 1;
};
/* A declarator. */
struct c_declarator {
/* The kind of declarator. */
enum c_declarator_kind kind;
/* Except for cdk_id, the contained declarator. For cdk_id, NULL. */
struct c_declarator *declarator;
location_t id_loc; /* Currently only set for cdk_id. */
union {
/* For identifiers, an IDENTIFIER_NODE or NULL_TREE if an abstract
declarator. */
tree id;
/* For functions. */
struct c_arg_info *arg_info;
/* For arrays. */
struct {
/* The array dimension, or NULL for [] and [*]. */
tree dimen;
/* The qualifiers inside []. */
int quals;
/* The attributes (currently ignored) inside []. */
tree attrs;
/* Whether [static] was used. */
BOOL_BITFIELD static_p : 1;
/* Whether [*] was used. */
BOOL_BITFIELD vla_unspec_p : 1;
} array;
/* For pointers, the qualifiers on the pointer type. */
int pointer_quals;
/* For attributes. */
tree attrs;
} u;
};
/* A type name. */
struct c_type_name {
/* The declaration specifiers. */
struct c_declspecs *specs;
/* The declarator. */
struct c_declarator *declarator;
};
/* A parameter. */
struct c_parm {
/* The declaration specifiers, minus any prefix attributes. */
struct c_declspecs *specs;
/* The attributes. */
tree attrs;
/* The declarator. */
struct c_declarator *declarator;
};
/* Save and restore the variables in this file and elsewhere
that keep track of the progress of compilation of the current function.
Used for nested functions. */
struct language_function GTY(())
{
struct c_language_function base;
tree x_break_label;
tree x_cont_label;
struct c_switch * GTY((skip)) x_switch_stack;
struct c_arg_info * GTY((skip)) arg_info;
int returns_value;
int returns_null;
int returns_abnormally;
int warn_about_return_type;
/* APPLE LOCAL begin mainline 4.3 2006-10-31 4134307 */
/* APPLE LOCAL end mainline 4.3 2006-10-31 4134307 */
};
/* Save lists of labels used or defined in particular contexts.
Allocated on the parser obstack. */
struct c_label_list
{
/* The label at the head of the list. */
tree label;
/* The rest of the list. */
struct c_label_list *next;
};
/* Statement expression context. */
struct c_label_context_se
{
/* The labels defined at this level of nesting. */
struct c_label_list *labels_def;
/* The labels used at this level of nesting. */
struct c_label_list *labels_used;
/* The next outermost context. */
struct c_label_context_se *next;
};
/* Context of variably modified declarations. */
struct c_label_context_vm
{
/* The labels defined at this level of nesting. */
struct c_label_list *labels_def;
/* The labels used at this level of nesting. */
struct c_label_list *labels_used;
/* The scope of this context. Multiple contexts may be at the same
numbered scope, since each variably modified declaration starts a
new context. */
unsigned scope;
/* The next outermost context. */
struct c_label_context_vm *next;
};
/* in c-parser.c */
extern void c_parse_init (void);
/* in c-aux-info.c */
extern void gen_aux_info_record (tree, int, int, int);
/* in c-decl.c */
extern struct obstack parser_obstack;
extern tree c_break_label;
extern tree c_cont_label;
extern int global_bindings_p (void);
extern void push_scope (void);
extern tree pop_scope (void);
extern void insert_block (tree);
extern void c_expand_body (tree);
extern void c_init_decl_processing (void);
extern void c_dup_lang_specific_decl (tree);
extern void c_print_identifier (FILE *, tree, int);
extern int quals_from_declspecs (const struct c_declspecs *);
extern struct c_declarator *build_array_declarator (tree, struct c_declspecs *,
bool, bool);
extern tree build_enumerator (tree, tree);
extern tree check_for_loop_decls (void);
extern void mark_forward_parm_decls (void);
extern void declare_parm_level (void);
extern void undeclared_variable (tree, location_t);
extern tree declare_label (tree);
extern tree define_label (location_t, tree);
extern void c_maybe_initialize_eh (void);
extern void finish_decl (tree, tree, tree);
extern tree finish_enum (tree, tree, tree);
extern void finish_function (void);
extern tree finish_struct (tree, tree, tree);
extern struct c_arg_info *get_parm_info (bool);
extern tree grokfield (struct c_declarator *, struct c_declspecs *, tree);
extern tree groktypename (struct c_type_name *);
/* APPLE LOCAL blocks 6339747 */
extern tree grokblockdecl (struct c_declspecs *, struct c_declarator *);
extern tree grokparm (const struct c_parm *);
extern tree implicitly_declare (tree);
extern void keep_next_level (void);
extern void pending_xref_error (void);
extern void c_push_function_context (struct function *);
extern void c_pop_function_context (struct function *);
extern void push_parm_decl (const struct c_parm *);
extern struct c_declarator *set_array_declarator_inner (struct c_declarator *,
struct c_declarator *,
bool);
extern tree builtin_function (const char *, tree, int, enum built_in_class,
const char *, tree);
extern void shadow_tag (const struct c_declspecs *);
extern void shadow_tag_warned (const struct c_declspecs *, int);
extern tree start_enum (tree);
extern int start_function (struct c_declspecs *, struct c_declarator *, tree);
extern tree start_decl (struct c_declarator *, struct c_declspecs *, bool,
tree);
extern tree start_struct (enum tree_code, tree);
extern void store_parm_decls (void);
extern void store_parm_decls_from (struct c_arg_info *);
extern tree xref_tag (enum tree_code, tree);
extern struct c_typespec parser_xref_tag (enum tree_code, tree);
extern int c_expand_decl (tree);
extern struct c_parm *build_c_parm (struct c_declspecs *, tree,
struct c_declarator *);
extern struct c_declarator *build_attrs_declarator (tree,
struct c_declarator *);
extern struct c_declarator *build_function_declarator (struct c_arg_info *,
struct c_declarator *);
extern struct c_declarator *build_id_declarator (tree);
extern struct c_declarator *make_pointer_declarator (struct c_declspecs *,
struct c_declarator *);
/* APPLE LOCAL begin radar 5814025 - blocks (C++ cg) */
extern struct c_declarator *make_block_pointer_declarator (struct c_declspecs *,
struct c_declarator *);
/* APPLE LOCAL end radar 5814025 - blocks (C++ cg) */
extern struct c_declspecs *build_null_declspecs (void);
extern struct c_declspecs *declspecs_add_qual (struct c_declspecs *, tree);
extern struct c_declspecs *declspecs_add_type (struct c_declspecs *,
struct c_typespec);
extern struct c_declspecs *declspecs_add_scspec (struct c_declspecs *, tree);
extern struct c_declspecs *declspecs_add_attrs (struct c_declspecs *, tree);
extern struct c_declspecs *finish_declspecs (struct c_declspecs *);
/* in c-objc-common.c */
extern int c_disregard_inline_limits (tree);
extern int c_cannot_inline_tree_fn (tree *);
extern bool c_objc_common_init (void);
extern bool c_missing_noreturn_ok_p (tree);
extern tree c_objc_common_truthvalue_conversion (tree expr);
extern bool c_warn_unused_global_decl (tree);
extern void c_initialize_diagnostics (diagnostic_context *);
extern bool c_vla_unspec_p (tree x, tree fn);
#define c_build_type_variant(TYPE, CONST_P, VOLATILE_P) \
c_build_qualified_type ((TYPE), \
((CONST_P) ? TYPE_QUAL_CONST : 0) | \
((VOLATILE_P) ? TYPE_QUAL_VOLATILE : 0))
/* in c-typeck.c */
extern int in_alignof;
extern int in_sizeof;
extern int in_typeof;
extern struct c_switch *c_switch_stack;
extern struct c_label_context_se *label_context_stack_se;
extern struct c_label_context_vm *label_context_stack_vm;
extern tree require_complete_type (tree);
extern int same_translation_unit_p (tree, tree);
extern int comptypes (tree, tree);
extern bool c_vla_type_p (tree);
extern bool c_mark_addressable (tree);
extern void c_incomplete_type_error (tree, tree);
extern tree c_type_promotes_to (tree);
extern struct c_expr default_function_array_conversion (struct c_expr);
extern tree composite_type (tree, tree);
extern tree build_component_ref (tree, tree);
extern tree build_array_ref (tree, tree);
extern tree build_external_ref (tree, int, location_t);
extern void pop_maybe_used (bool);
extern struct c_expr c_expr_sizeof_expr (struct c_expr);
extern struct c_expr c_expr_sizeof_type (struct c_type_name *);
extern struct c_expr parser_build_unary_op (enum tree_code, struct c_expr);
extern struct c_expr parser_build_binary_op (enum tree_code, struct c_expr,
struct c_expr);
extern tree build_conditional_expr (tree, tree, tree);
extern tree build_compound_expr (tree, tree);
extern tree c_cast_expr (struct c_type_name *, tree);
extern tree build_c_cast (tree, tree);
extern void store_init_value (tree, tree);
extern void error_init (const char *);
extern void pedwarn_init (const char *);
extern void maybe_warn_string_init (tree, struct c_expr);
extern void start_init (tree, tree, int);
extern void finish_init (void);
extern void really_start_incremental_init (tree);
extern void push_init_level (int);
extern struct c_expr pop_init_level (int);
extern void set_init_index (tree, tree);
extern void set_init_label (tree);
extern void process_init_element (struct c_expr);
extern tree build_compound_literal (tree, tree);
extern tree c_start_case (tree);
extern void c_finish_case (tree);
extern tree build_asm_expr (tree, tree, tree, tree, bool);
extern tree build_asm_stmt (tree, tree);
extern tree c_convert_parm_for_inlining (tree, tree, tree, int);
extern int c_types_compatible_p (tree, tree);
extern tree c_begin_compound_stmt (bool);
extern tree c_end_compound_stmt (tree, bool);
extern void c_finish_if_stmt (location_t, tree, tree, tree, bool);
/* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \
extern void c_finish_loop (location_t, tree, tree, tree, tree, tree, tree,
bool);
/* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \
extern tree c_begin_stmt_expr (void);
extern tree c_finish_stmt_expr (tree);
extern tree c_process_expr_stmt (tree);
extern tree c_finish_expr_stmt (tree);
extern tree c_finish_return (tree);
extern tree c_finish_bc_stmt (tree *, bool);
extern tree c_finish_goto_label (tree);
extern tree c_finish_goto_ptr (tree);
extern void c_begin_vm_scope (unsigned int);
extern void c_end_vm_scope (unsigned int);
extern tree c_expr_to_decl (tree, bool *, bool *, bool *);
extern tree c_begin_omp_parallel (void);
extern tree c_finish_omp_parallel (tree, tree);
extern tree c_finish_omp_clauses (tree);
/* APPLE LOCAL begin CW asm blocks */
extern tree get_structure_offset (tree, tree);
extern tree lookup_struct_or_union_tag (tree);
/* APPLE LOCAL end CW asm blocks */
/* Set to 0 at beginning of a function definition, set to 1 if
a return statement that specifies a return value is seen. */
extern int current_function_returns_value;
/* Set to 0 at beginning of a function definition, set to 1 if
a return statement with no argument is seen. */
extern int current_function_returns_null;
/* Set to 0 at beginning of a function definition, set to 1 if
a call to a noreturn function is seen. */
extern int current_function_returns_abnormally;
/* Nonzero means we are reading code that came from a system header file. */
extern int system_header_p;
/* True means global_bindings_p should return false even if the scope stack
says we are in file scope. */
extern bool c_override_global_bindings_to_false;
/* True means we've initialized exception handling. */
extern bool c_eh_initialized_p;
/* In c-decl.c */
extern void c_finish_incomplete_decl (tree);
extern void c_write_global_declarations (void);
/* APPLE LOCAL radar 5741070 */
extern tree c_return_interface_record_type (tree);
/* In order for the format checking to accept the C frontend
diagnostic framework extensions, you must include this file before
toplev.h, not after. */
#if GCC_VERSION >= 4001
#define ATTRIBUTE_GCC_CDIAG(m, n) __attribute__ ((__format__ (GCC_DIAG_STYLE, m ,n))) ATTRIBUTE_NONNULL(m)
#else
#define ATTRIBUTE_GCC_CDIAG(m, n) ATTRIBUTE_NONNULL(m)
#endif
extern void pedwarn_c90 (const char *, ...) ATTRIBUTE_GCC_CDIAG(1,2);
extern void pedwarn_c99 (const char *, ...) ATTRIBUTE_GCC_CDIAG(1,2);
#endif /* ! GCC_C_TREE_H */
|
paint.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP AAA IIIII N N TTTTT %
% P P A A I NN N T %
% PPPP AAAAA I N N N T %
% P A A I N NN T %
% P A A IIIII N N T %
% %
% %
% Methods to Paint on an Image %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% 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 "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/resource_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l o o d f i l l P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FloodfillPaintImage() changes the color value of any pixel that matches
% target and is an immediate neighbor. If the method FillToBorderMethod is
% specified, the color value is changed for any neighbor pixel that does not
% match the bordercolor member of image.
%
% By default target must match a particular pixel color exactly. However,
% in many cases two colors may differ by a small amount. The fuzz member of
% image defines how much tolerance is acceptable to consider two colors as
% the same. For example, set fuzz to 10 and the color red at intensities of
% 100 and 102 respectively are now interpreted as the same color for the
% purposes of the floodfill.
%
% The format of the FloodfillPaintImage method is:
%
% MagickBooleanType FloodfillPaintImage(Image *image,
% const DrawInfo *draw_info,const PixelInfo target,
% const ssize_t x_offset,const ssize_t y_offset,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o target: the RGB value of the target color.
%
% o x_offset,y_offset: the starting location of the operation.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType FloodfillPaintImage(Image *image,
const DrawInfo *draw_info,const PixelInfo *target,const ssize_t x_offset,
const ssize_t y_offset,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define MaxStacksize 524288UL
#define PushSegmentStack(up,left,right,delta) \
{ \
if (s >= (segment_stack+MaxStacksize)) \
ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \
else \
{ \
if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \
{ \
s->x1=(double) (left); \
s->y1=(double) (up); \
s->x2=(double) (right); \
s->y2=(double) (delta); \
s++; \
} \
} \
}
CacheView
*floodplane_view,
*image_view;
Image
*floodplane_image;
MagickBooleanType
skip,
status;
MemoryInfo
*segment_info;
PixelInfo
fill_color,
pixel;
register SegmentInfo
*s;
SegmentInfo
*segment_stack;
ssize_t
offset,
start,
x1,
x2,
y;
/*
Check boundary conditions.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
return(MagickFalse);
if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows))
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
if ((image->alpha_trait == UndefinedPixelTrait) &&
(draw_info->fill.alpha_trait != UndefinedPixelTrait))
(void) SetImageAlpha(image,OpaqueAlpha,exception);
/*
Set floodfill state.
*/
floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (floodplane_image == (Image *) NULL)
return(MagickFalse);
floodplane_image->alpha_trait=UndefinedPixelTrait;
floodplane_image->colorspace=GRAYColorspace;
(void) QueryColorCompliance("#000",AllCompliance,
&floodplane_image->background_color,exception);
(void) SetImageBackgroundColor(floodplane_image,exception);
segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack));
if (segment_info == (MemoryInfo *) NULL)
{
floodplane_image=DestroyImage(floodplane_image);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info);
/*
Push initial segment on stack.
*/
status=MagickTrue;
start=0;
s=segment_stack;
PushSegmentStack(y_offset,x_offset,x_offset,1);
PushSegmentStack(y_offset+1,x_offset,x_offset,-1);
GetPixelInfo(image,&pixel);
image_view=AcquireVirtualCacheView(image,exception);
floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception);
while (s > segment_stack)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
/*
Pop segment off stack.
*/
s--;
x1=(ssize_t) s->x1;
x2=(ssize_t) s->x2;
offset=(ssize_t) s->y2;
y=(ssize_t) s->y1+offset;
/*
Recolor neighboring pixels.
*/
p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception);
q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
p+=x1*GetPixelChannels(image);
q+=x1*GetPixelChannels(floodplane_image);
for (x=x1; x >= 0; x--)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
break;
SetPixelGray(floodplane_image,QuantumRange,q);
p-=GetPixelChannels(image);
q-=GetPixelChannels(floodplane_image);
}
if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse)
break;
skip=x >= x1 ? MagickTrue : MagickFalse;
if (skip == MagickFalse)
{
start=x+1;
if (start < x1)
PushSegmentStack(y,start,x1-1,-offset);
x=x1+1;
}
do
{
if (skip == MagickFalse)
{
if (x < (ssize_t) image->columns)
{
p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1,
exception);
q=GetCacheViewAuthenticPixels(floodplane_view,x,y,image->columns-
x,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for ( ; x < (ssize_t) image->columns; x++)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
break;
SetPixelGray(floodplane_image,QuantumRange,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(floodplane_image);
}
status=SyncCacheViewAuthenticPixels(floodplane_view,exception);
if (status == MagickFalse)
break;
}
PushSegmentStack(y,start,x-1,offset);
if (x > (x2+1))
PushSegmentStack(y,x2+1,x-1,-offset);
}
skip=MagickFalse;
x++;
if (x <= x2)
{
p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1,
exception);
q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for ( ; x <= x2; x++)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
break;
p+=GetPixelChannels(image);
q+=GetPixelChannels(floodplane_image);
}
}
start=x;
} while (x <= x2);
}
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(floodplane_image,image,floodplane_image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
/*
Tile fill color onto floodplane.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelGray(floodplane_image,p) != 0)
{
GetFillColor(draw_info,x,y,&fill_color,exception);
SetPixelViaPixelInfo(image,&fill_color,q);
}
p+=GetPixelChannels(floodplane_image);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
floodplane_view=DestroyCacheView(floodplane_view);
image_view=DestroyCacheView(image_view);
segment_info=RelinquishVirtualMemory(segment_info);
floodplane_image=DestroyImage(floodplane_image);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GradientImage() applies a continuously smooth color transitions along a
% vector from one color to another.
%
% Note, the interface of this method will change in the future to support
% more than one transistion.
%
% The format of the GradientImage method is:
%
% MagickBooleanType GradientImage(Image *image,const GradientType type,
% const SpreadMethod method,const PixelInfo *start_color,
% const PixelInfo *stop_color,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the gradient type: linear or radial.
%
% o spread: the gradient spread meathod: pad, reflect, or repeat.
%
% o start_color: the start color.
%
% o stop_color: the stop color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GradientImage(Image *image,
const GradientType type,const SpreadMethod method,const StopInfo *stops,
const size_t number_stops,ExceptionInfo *exception)
{
const char
*artifact;
DrawInfo
*draw_info;
GradientInfo
*gradient;
MagickBooleanType
status;
/*
Set gradient start-stop end points.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(stops != (const StopInfo *) NULL);
assert(number_stops > 0);
draw_info=AcquireDrawInfo();
gradient=(&draw_info->gradient);
gradient->type=type;
gradient->bounding_box.width=image->columns;
gradient->bounding_box.height=image->rows;
artifact=GetImageArtifact(image,"gradient:bounding-box");
if (artifact != (const char *) NULL)
(void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box);
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=(double) image->rows-1;
artifact=GetImageArtifact(image,"gradient:direction");
if (artifact != (const char *) NULL)
{
GravityType
direction;
direction=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,artifact);
switch (direction)
{
case NorthWestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case NorthGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case NorthEastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=0.0;
break;
}
case WestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case EastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=0.0;
break;
}
case SouthWestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=(double) image->rows-1;
break;
}
case SouthGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=(double) image->columns-1;
break;
}
case SouthEastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=(double) image->rows-1;
break;
}
default:
break;
}
}
artifact=GetImageArtifact(image,"gradient:angle");
if (artifact != (const char *) NULL)
gradient->angle=StringToDouble(artifact,(char **) NULL);
artifact=GetImageArtifact(image,"gradient:vector");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf",
&gradient->gradient_vector.x1,&gradient->gradient_vector.y1,
&gradient->gradient_vector.x2,&gradient->gradient_vector.y2);
if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:direction") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:extent") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:vector") == (const char *) NULL))
if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0))
gradient->gradient_vector.x2=0.0;
gradient->center.x=(double) gradient->gradient_vector.x2/2.0;
gradient->center.y=(double) gradient->gradient_vector.y2/2.0;
artifact=GetImageArtifact(image,"gradient:center");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x,
&gradient->center.y);
artifact=GetImageArtifact(image,"gradient:angle");
if ((type == LinearGradient) && (artifact != (const char *) NULL))
{
double
sine,
cosine,
distance;
/*
Reference https://drafts.csswg.org/css-images-3/#linear-gradients.
*/
sine=sin((double) DegreesToRadians(gradient->angle-90.0));
cosine=cos((double) DegreesToRadians(gradient->angle-90.0));
distance=fabs((double) image->columns*cosine)+
fabs((double) image->rows*sine);
gradient->gradient_vector.x1=0.5*(image->columns-distance*cosine);
gradient->gradient_vector.y1=0.5*(image->rows-distance*sine);
gradient->gradient_vector.x2=0.5*(image->columns+distance*cosine);
gradient->gradient_vector.y2=0.5*(image->rows+distance*sine);
}
gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
gradient->radii.y=gradient->radii.x;
artifact=GetImageArtifact(image,"gradient:extent");
if (artifact != (const char *) NULL)
{
if (LocaleCompare(artifact,"Circle") == 0)
{
gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Diagonal") == 0)
{
gradient->radii.x=(double) (sqrt(image->columns*image->columns+
image->rows*image->rows))/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Ellipse") == 0)
{
gradient->radii.x=(double) image->columns/2.0;
gradient->radii.y=(double) image->rows/2.0;
}
if (LocaleCompare(artifact,"Maximum") == 0)
{
gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Minimum") == 0)
{
gradient->radii.x=(double) (MagickMin(image->columns,image->rows))/
2.0;
gradient->radii.y=gradient->radii.x;
}
}
artifact=GetImageArtifact(image,"gradient:radii");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x,
&gradient->radii.y);
gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y);
gradient->spread=method;
/*
Define the gradient to fill between the stops.
*/
gradient->number_stops=number_stops;
gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops,
sizeof(*gradient->stops));
if (gradient->stops == (StopInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
(void) CopyMagickMemory(gradient->stops,stops,(size_t) number_stops*
sizeof(*stops));
/*
Draw a gradient on the image.
*/
status=DrawGradientImage(image,draw_info,exception);
draw_info=DestroyDrawInfo(draw_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O i l P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OilPaintImage() applies a special effect filter that simulates an oil
% painting. Each pixel is replaced by the most frequent color occurring
% in a circular region defined by radius.
%
% The format of the OilPaintImage method is:
%
% Image *OilPaintImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the circular neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t **DestroyHistogramThreadSet(size_t **histogram)
{
register ssize_t
i;
assert(histogram != (size_t **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (histogram[i] != (size_t *) NULL)
histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]);
histogram=(size_t **) RelinquishMagickMemory(histogram);
return(histogram);
}
static size_t **AcquireHistogramThreadSet(const size_t count)
{
register ssize_t
i;
size_t
**histogram,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
histogram=(size_t **) AcquireQuantumMemory(number_threads,sizeof(*histogram));
if (histogram == (size_t **) NULL)
return((size_t **) NULL);
(void) ResetMagickMemory(histogram,0,number_threads*sizeof(*histogram));
for (i=0; i < (ssize_t) number_threads; i++)
{
histogram[i]=(size_t *) AcquireQuantumMemory(count,sizeof(**histogram));
if (histogram[i] == (size_t *) NULL)
return(DestroyHistogramThreadSet(histogram));
}
return(histogram);
}
MagickExport Image *OilPaintImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
#define NumberPaintBins 256
#define OilPaintImageTag "OilPaint/Image"
CacheView
*image_view,
*paint_view;
Image
*linear_image,
*paint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
**histograms,
width;
ssize_t
center,
y;
/*
Initialize painted image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
width=GetOptimalKernelWidth2D(radius,sigma);
linear_image=CloneImage(image,0,0,MagickTrue,exception);
paint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL))
{
if (linear_image != (Image *) NULL)
linear_image=DestroyImage(linear_image);
if (paint_image != (Image *) NULL)
linear_image=DestroyImage(paint_image);
return((Image *) NULL);
}
if (SetImageStorageClass(paint_image,DirectClass,exception) == MagickFalse)
{
linear_image=DestroyImage(linear_image);
paint_image=DestroyImage(paint_image);
return((Image *) NULL);
}
histograms=AcquireHistogramThreadSet(NumberPaintBins);
if (histograms == (size_t **) NULL)
{
linear_image=DestroyImage(linear_image);
paint_image=DestroyImage(paint_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Oil paint image.
*/
status=MagickTrue;
progress=0;
center=(ssize_t) GetPixelChannels(linear_image)*(linear_image->columns+width)*
(width/2L)+GetPixelChannels(linear_image)*(width/2L);
image_view=AcquireVirtualCacheView(linear_image,exception);
paint_view=AcquireAuthenticCacheView(paint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(linear_image,paint_image,linear_image->rows,1)
#endif
for (y=0; y < (ssize_t) linear_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register size_t
*histogram;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(width/2L),linear_image->columns+width,width,exception);
q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
histogram=histograms[GetOpenMPThreadId()];
for (x=0; x < (ssize_t) linear_image->columns; x++)
{
register ssize_t
i,
u;
size_t
count;
ssize_t
j,
k,
n,
v;
/*
Assign most frequent color.
*/
k=0;
j=0;
count=0;
(void) ResetMagickMemory(histogram,0,NumberPaintBins* sizeof(*histogram));
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
n=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(
linear_image,p+GetPixelChannels(linear_image)*(u+k))));
histogram[n]++;
if (histogram[n] > count)
{
j=k+u;
count=histogram[n];
}
}
k+=(ssize_t) (linear_image->columns+width);
}
for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++)
{
PixelChannel channel=GetPixelChannelChannel(linear_image,i);
PixelTrait traits=GetPixelChannelTraits(linear_image,channel);
PixelTrait paint_traits=GetPixelChannelTraits(paint_image,channel);
if ((traits == UndefinedPixelTrait) ||
(paint_traits == UndefinedPixelTrait))
continue;
if (((paint_traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(linear_image,p) == 0))
{
SetPixelChannel(paint_image,channel,p[center+i],q);
continue;
}
SetPixelChannel(paint_image,channel,p[j*GetPixelChannels(linear_image)+
i],q);
}
p+=GetPixelChannels(linear_image);
q+=GetPixelChannels(paint_image);
}
if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse)
status=MagickFalse;
if (linear_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_OilPaintImage)
#endif
proceed=SetImageProgress(linear_image,OilPaintImageTag,progress++,
linear_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
paint_view=DestroyCacheView(paint_view);
image_view=DestroyCacheView(image_view);
histograms=DestroyHistogramThreadSet(histograms);
linear_image=DestroyImage(linear_image);
if (status == MagickFalse)
paint_image=DestroyImage(paint_image);
return(paint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O p a q u e P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OpaquePaintImage() changes any pixel that matches color with the color
% defined by fill argument.
%
% By default color must match a particular pixel color exactly. However, in
% many cases two colors may differ by a small amount. Fuzz defines how much
% tolerance is acceptable to consider two colors as the same. For example,
% set fuzz to 10 and the color red at intensities of 100 and 102 respectively
% are now interpreted as the same color.
%
% The format of the OpaquePaintImage method is:
%
% MagickBooleanType OpaquePaintImage(Image *image,const PixelInfo *target,
% const PixelInfo *fill,const MagickBooleanType invert,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o target: the RGB value of the target color.
%
% o fill: the replacement color.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OpaquePaintImage(Image *image,
const PixelInfo *target,const PixelInfo *fill,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define OpaquePaintImageTag "Opaque/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
conform_fill,
conform_target,
zero;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(target != (PixelInfo *) NULL);
assert(fill != (PixelInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
ConformPixelInfo(image,fill,&conform_fill,exception);
ConformPixelInfo(image,target,&conform_target,exception);
/*
Make image color opaque.
*/
status=MagickTrue;
progress=0;
GetPixelInfo(image,&zero);
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++)
{
PixelInfo
pixel;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&conform_target) != invert)
SetPixelViaPixelInfo(image,&conform_fill,q);
q+=GetPixelChannels(image);
}
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_OpaquePaintImage)
#endif
proceed=SetImageProgress(image,OpaquePaintImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p a r e n t P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransparentPaintImage() changes the opacity value associated with any pixel
% that matches color to the value defined by opacity.
%
% By default color must match a particular pixel color exactly. However, in
% many cases two colors may differ by a small amount. Fuzz defines how much
% tolerance is acceptable to consider two colors as the same. For example,
% set fuzz to 10 and the color red at intensities of 100 and 102 respectively
% are now interpreted as the same color.
%
% The format of the TransparentPaintImage method is:
%
% MagickBooleanType TransparentPaintImage(Image *image,
% const PixelInfo *target,const Quantum opacity,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o target: the target color.
%
% o opacity: the replacement opacity value.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransparentPaintImage(Image *image,
const PixelInfo *target,const Quantum opacity,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define TransparentPaintImageTag "Transparent/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
zero;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(target != (PixelInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Make image color transparent.
*/
status=MagickTrue;
progress=0;
GetPixelInfo(image,&zero);
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++)
{
PixelInfo
pixel;
register ssize_t
x;
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;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
SetPixelAlpha(image,opacity,q);
q+=GetPixelChannels(image);
}
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_TransparentPaintImage)
#endif
proceed=SetImageProgress(image,TransparentPaintImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p a r e n t P a i n t I m a g e C h r o m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransparentPaintImageChroma() changes the opacity value associated with any
% pixel that matches color to the value defined by opacity.
%
% As there is one fuzz value for the all the channels, TransparentPaintImage()
% is not suitable for the operations like chroma, where the tolerance for
% similarity of two color component (RGB) can be different. Thus we define
% this method to take two target pixels (one low and one high) and all the
% pixels of an image which are lying between these two pixels are made
% transparent.
%
% The format of the TransparentPaintImageChroma method is:
%
% MagickBooleanType TransparentPaintImageChroma(Image *image,
% const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o low: the low target color.
%
% o high: the high target color.
%
% o opacity: the replacement opacity value.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image,
const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
const MagickBooleanType invert,ExceptionInfo *exception)
{
#define TransparentPaintImageTag "Transparent/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(high != (PixelInfo *) NULL);
assert(low != (PixelInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Make image color transparent.
*/
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++)
{
MagickBooleanType
match;
PixelInfo
pixel;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,q,&pixel);
match=((pixel.red >= low->red) && (pixel.red <= high->red) &&
(pixel.green >= low->green) && (pixel.green <= high->green) &&
(pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue :
MagickFalse;
if (match != invert)
SetPixelAlpha(image,opacity,q);
q+=GetPixelChannels(image);
}
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_TransparentPaintImageChroma)
#endif
proceed=SetImageProgress(image,TransparentPaintImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
|
spacetime_heat_adl_kernel_antiderivative.h | /*
Copyright (c) 2020, VSB - Technical University of Ostrava and Graz University of
Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the names of VSB - Technical University of Ostrava and Graz
University of Technology nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL VSB - TECHNICAL UNIVERSITY OF OSTRAVA AND
GRAZ UNIVERSITY OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file spacetime_heat_adl_kernel_antiderivative.h
* @brief Kernel for uniform_spacetime_tensor_mesh.h.
*/
#ifndef INCLUDE_BESTHEA_SPACETIME_HEAT_ADL_KERNEL_ANTIDERIVATIVE_H_
#define INCLUDE_BESTHEA_SPACETIME_HEAT_ADL_KERNEL_ANTIDERIVATIVE_H_
#include <besthea/spacetime_heat_kernel_antiderivative.h>
#include "besthea/settings.h"
#include <vector>
namespace besthea {
namespace bem {
class spacetime_heat_adl_kernel_antiderivative;
}
}
/**
* Class representing a first and second antiderivative of the double-layer
* spacetime kernel.
*/
class besthea::bem::spacetime_heat_adl_kernel_antiderivative
: public besthea::bem::spacetime_heat_kernel_antiderivative<
spacetime_heat_adl_kernel_antiderivative > {
public:
/**
* Constructor.
* @param[in] alpha Heat conductivity.
*/
spacetime_heat_adl_kernel_antiderivative( sc alpha )
: spacetime_heat_kernel_antiderivative<
spacetime_heat_adl_kernel_antiderivative >( alpha ) {
}
/**
* Destructor.
*/
virtual ~spacetime_heat_adl_kernel_antiderivative( ) {
}
/**
* Evaluates the second antiderivative.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
* @param[in] ttau `t-tau`.
*/
#pragma omp declare simd uniform( this, nx, ny, ttau ) simdlen( DATA_WIDTH )
sc do_anti_tau_anti_t( sc xy1, sc xy2, sc xy3, const sc * nx,
[[maybe_unused]] const sc * ny, sc ttau ) const {
sc value;
sc norm2 = xy1 * xy1 + xy2 * xy2 + xy3 * xy3;
sc norm = std::sqrt( norm2 );
sc dot = -xy1 * nx[ 0 ] - xy2 * nx[ 1 ] - xy3 * nx[ 2 ];
sc sqrt_d = std::sqrt( ttau );
if ( ttau > _eps ) {
if ( std::abs( dot ) > _eps ) { // delta > 0, norm > 0
value = -dot / ( _four * _pi * norm )
* ( ( _one / ( _two * _alpha ) - ttau / norm2 )
* std::erf( norm / ( _two * sqrt_d * _sqrt_alpha ) )
+ sqrt_d / ( _sqrt_pi * _sqrt_alpha * norm )
* std::exp( -norm2 / ( _four * _alpha * ttau ) ) );
} else { // ttau > 0, limit for norm -> 0
value = 0.0;
}
} else { // limit for ttau -> 0, assuming norm > 0
value = -dot / ( _eight * _pi * norm * _alpha );
}
return value;
}
/**
* Evaluates the second antiderivative.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
* @param[in] ttau `t-tau`.
*/
#pragma omp declare simd uniform( this, nx, ny, ttau ) simdlen( DATA_WIDTH )
sc do_anti_tau_anti_t_regular_in_time( sc xy1, sc xy2, sc xy3, const sc * nx,
[[maybe_unused]] const sc * ny, sc ttau ) const {
sc value;
sc norm2 = xy1 * xy1 + xy2 * xy2 + xy3 * xy3;
sc norm = std::sqrt( norm2 );
sc dot = -xy1 * nx[ 0 ] - xy2 * nx[ 1 ] - xy3 * nx[ 2 ];
sc sqrt_d = std::sqrt( ttau );
if ( std::abs( dot ) > _eps ) { // ttau > 0, norm > 0
value = -dot / ( _four * _pi * norm )
* ( ( _one / ( _two * _alpha ) - ttau / norm2 )
* std::erf( norm / ( _two * sqrt_d * _sqrt_alpha ) )
+ sqrt_d / ( _sqrt_pi * _sqrt_alpha * norm )
* std::exp( -norm2 / ( _four * _alpha * ttau ) ) );
} else { // ttau > 0, limit for norm -> 0
value = 0.0;
}
return value;
}
/**
* Evaluates the second antiderivative.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
* @param[in] ttau `t-tau`.
*/
#pragma omp declare simd uniform( this, nx, ny, ttau ) simdlen( DATA_WIDTH )
sc do_anti_tau_anti_t_regular_in_time_regular_in_space( sc xy1, sc xy2,
sc xy3, const sc * nx, [[maybe_unused]] const sc * ny, sc ttau ) const {
sc norm2 = xy1 * xy1 + xy2 * xy2 + xy3 * xy3;
sc norm = std::sqrt( norm2 );
sc dot = -xy1 * nx[ 0 ] - xy2 * nx[ 1 ] - xy3 * nx[ 2 ];
sc sqrt_d = std::sqrt( ttau );
// ttau > 0, norm > 0
sc value = -dot / ( _four * _pi * norm )
* ( ( _one / ( _two * _alpha ) - ttau / norm2 )
* std::erf( norm / ( _two * sqrt_d * _sqrt_alpha ) )
+ sqrt_d / ( _sqrt_pi * _sqrt_alpha * norm )
* std::exp( -norm2 / ( _four * _alpha * ttau ) ) );
return value;
}
/**
* Evaluates the second antiderivative.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
*/
#pragma omp declare simd uniform( this, nx, ny ) simdlen( DATA_WIDTH )
sc do_anti_tau_anti_t_limit_in_time_regular_in_space( sc xy1, sc xy2, sc xy3,
const sc * nx, [[maybe_unused]] const sc * ny ) const {
sc norm2 = xy1 * xy1 + xy2 * xy2 + xy3 * xy3;
sc norm = std::sqrt( norm2 );
sc dot = -xy1 * nx[ 0 ] - xy2 * nx[ 1 ] - xy3 * nx[ 2 ];
// limit for ttau -> 0, assuming norm > 0
sc value = -dot / ( _eight * _pi * norm * _alpha );
return value;
}
/**
* Evaluates the first antiderivative.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
* @param[in] ttau `t-tau`.
*/
#pragma omp declare simd uniform( this, nx, ny, ttau ) simdlen( DATA_WIDTH )
sc do_anti_tau_regular( [[maybe_unused]] sc xy1, [[maybe_unused]] sc xy2,
[[maybe_unused]] sc xy3, [[maybe_unused]] const sc * nx,
[[maybe_unused]] const sc * ny, [[maybe_unused]] sc ttau ) const {
return _zero;
}
/**
* Evaluates the first antiderivative.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
*/
#pragma omp declare simd uniform( this, nx, ny ) simdlen( DATA_WIDTH )
sc do_anti_tau_limit( sc xy1, sc xy2, sc xy3, const sc * nx,
[[maybe_unused]] const sc * ny ) const {
sc norm2 = xy1 * xy1 + xy2 * xy2 + xy3 * xy3;
sc norm = std::sqrt( norm2 );
sc dot = -xy1 * nx[ 0 ] - xy2 * nx[ 1 ] - xy3 * nx[ 2 ];
sc value = dot / ( _four * _pi * norm2 * norm );
return value;
}
/**
* Evaluates the definite integral over the same time interval.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
* @param[in] t0 Start of interval.
* @param[in] t1 End of interval.
*/
#pragma omp declare simd uniform( this, nx, ny, t0, t1 ) simdlen( DATA_WIDTH )
sc do_definite_integral_over_same_interval(
sc xy1, sc xy2, sc xy3, const sc * nx, const sc * ny, sc t0, sc t1 ) const {
sc value = ( t1 - t0 ) * do_anti_tau_limit( xy1, xy2, xy3, nx, ny )
- do_anti_tau_anti_t_regular_in_time( xy1, xy2, xy3, nx, ny, t1 - t0 )
+ do_anti_tau_anti_t_limit_in_time_regular_in_space(
xy1, xy2, xy3, nx, ny );
return value;
}
/**
* Evaluates the definite integral over the different time intervals.
* @param[in] xy1 First coordinate of `x - y`.
* @param[in] xy2 Second coordinate of `x - y`.
* @param[in] xy3 Third coordinate of `x - y`.
* @param[in] nx Normal in the `x` variable.
* @param[in] ny Normal in the `y` variable.
* @param[in] t0 Start of interval in `t`.
* @param[in] t1 End of interval in `t`.
* @param[in] tau0 Start of interval in `tau`.
* @param[in] tau1 End of interval in `tau`.
*/
#pragma omp declare simd uniform( this, nx, ny, t0, t1, tau0, tau1 ) \
simdlen( DATA_WIDTH )
sc do_definite_integral_over_different_intervals( sc xy1, sc xy2, sc xy3,
const sc * nx, const sc * ny, sc t0, sc t1, sc tau0, sc tau1 ) const {
sc value = do_anti_tau_anti_t( xy1, xy2, xy3, nx, ny, t1 - tau1 )
- do_anti_tau_anti_t( xy1, xy2, xy3, nx, ny, t1 - tau0 )
- do_anti_tau_anti_t( xy1, xy2, xy3, nx, ny, t0 - tau1 )
+ do_anti_tau_anti_t( xy1, xy2, xy3, nx, ny, t0 - tau0 );
return value;
}
};
#endif /* INCLUDE_BESTHEA_SPACETIME_HEAT_ADL_KERNEL_ANTIDERIVATIVE_H_ \
*/
|
query-veb.h | /*
* Copyright 2018-2021 Kyle Berney, Ben Karsin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef QUERY_VEB_H
#define QUERY_VEB_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <omp.h>
#include <time.h>
#include "params.h"
#include "common.h"
struct vEB_table {
uint64_t L; //size of the bottom/leaf tree
uint64_t R; //size of the corresponding top/root tree
uint32_t D; //depth of the root of the corresponding top/root tree
};
void buildTable(vEB_table *table, uint64_t n, uint32_t d, uint32_t root_depth);
//Searches given perfect vEB tree layout for the query'd element using the table composed of L, R, and D
//Assumes L, R, and D have been initialized via buildTable()
//pos is an array of size d which is used to store the 1-indexed position of the node visited during the query at current depth in the vEB tree
//Returns index of query'd element (if found)
//Otherwise, returns n (element not found)
template<typename TYPE>
uint64_t searchvEB(TYPE *A, vEB_table *table, uint64_t n, uint32_t d, TYPE query, uint64_t *pos, uint64_t tid) {
TYPE current;
uint32_t current_d = 0;
uint64_t i = 1; //1-indexed position of the current node in a BFS (i.e, level order) binary search tree
pos[0] = 1;
uint64_t index = 0; //0-indexed position of the current node in the vEB tree
while (index < n) {
current = A[index];
if (query == current) {
return index;
}
i = 2*i + (query > current);
current_d++;
pos[current_d] = pos[table[current_d].D] + table[current_d].R + (i & table[current_d].R) * table[current_d].L;
index = pos[current_d] - 1;
}
return n;
}
//Performs all of the queries given in the array queries
//index in A of the queried items are saved in the answers array
template<typename TYPE>
void searchAll(TYPE *A, vEB_table *table, uint64_t n, uint32_t d, TYPE *queries, uint64_t *answers, uint64_t numQueries, uint32_t p) {
#pragma omp parallel shared(A, table, n, d, queries, answers, numQueries, p) num_threads(p)
{
uint64_t pos[d];
uint64_t tid = omp_get_thread_num();
for (uint64_t i = tid; i < numQueries; i += p) {
answers[i] = searchvEB<TYPE>(A, table, n, d, queries[i], pos, tid);
}
}
}
//Generates numQueries random queries and returns the milliseconds needed to perform the queries on the given vEB tree layout
template<typename TYPE>
double timeQueryvEB(TYPE *A, vEB_table *table, uint64_t n, uint32_t d, uint64_t numQueries, uint32_t p) {
struct timespec start, end;
TYPE *queries = createRandomQueries<TYPE>(A, n, numQueries); //array to store random queries to perform
uint64_t *answers = (uint64_t *)malloc(numQueries * sizeof(uint64_t)); //array to store the answers (i.e., index of the queried item)
clock_gettime(CLOCK_MONOTONIC, &start);
searchAll<TYPE>(A, table, n, d, queries, answers, numQueries, p);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = ((end.tv_sec*1000000000. + end.tv_nsec) - (start.tv_sec*1000000000. + start.tv_nsec)) / 1000000.; //millisecond
#ifdef VERIFY
bool correct = true;
for (uint64_t i = 0; i < numQueries; i++) {
if (answers[i] == n || A[answers[i]] != queries[i] || answers[i] == n) {
#ifdef DEBUG
printf("query = %lu; A[%lu] = %lu\n", queries[i], answers[i], A[answers[i]]);
#endif
correct = false;
}
}
if (correct == false) printf("Searches failed!\n");
else printf("Searches succeeded!\n");
#endif
free(queries);
free(answers);
return ms;
}
//Searches given non-perfect vEB layout for the query'd element using the tables composed of L, R, and D
//tables is an array of size num_tables pointing to each vEB table used for querying
//E.g., tables[0] is used to query the full root and leaf subtrees
//and tables[1] is used to query the first incomplete leaf subtree
//Each subsequent entry in queries is used to query the next recursive incomplete leaf subtree
//idx is and array of size num_tables which gives the index of where the next incomplete leaf subtree starts
//Assumes all tables L, R, and D have been initialized via buildTable()
//pos is an array of size d which is used to store the 1-indexed position of the node visited during the query at current depth in the vEB tree
//Returns index of query'd element (if found)
//Otherwise, returns n (element not found)
template<typename TYPE>
uint64_t searchvEB_nonperfect(TYPE *A, vEB_table **tables, uint64_t *idx, uint32_t num_tables, TYPE query, uint64_t *pos, uint64_t tid) {
TYPE current;
uint32_t current_d;
uint64_t i, index;
TYPE *a = A;
uint64_t offset = 0;
uint32_t j = 0;
while (j < num_tables) {
current_d = 0;
i = 1; //1-indexed position of the current node in a BFS (i.e, level order) binary search tree
pos[0] = 1;
index = 0; //0-indexed position of the current node in the vEB tree
while (index + offset < idx[j]) {
current = a[index];
if (query == current) {
return offset + index;
}
i = 2*i + (query > current);
current_d++;
pos[current_d] = pos[tables[j][current_d].D] + tables[j][current_d].R + (i & tables[j][current_d].R) * tables[j][current_d].L;
index = pos[current_d] - 1;
}
a = &A[idx[j]];
offset = idx[j];
++j;
}
return idx[num_tables-1]; //return n
}
//Performs all of the queries given in the array queries
//index in A of the queried items are saved in the answers array
template<typename TYPE>
void searchAll_nonperfect(TYPE *A, vEB_table **tables, uint64_t *idx, uint32_t num_tables, uint32_t d, TYPE *queries, uint64_t *answers, uint64_t numQueries, uint32_t p) {
#pragma omp parallel shared(A, tables, idx, num_tables, d, queries, answers, numQueries, p) num_threads(p)
{
uint64_t pos[d];
uint64_t tid = omp_get_thread_num();
for (uint64_t i = tid; i < numQueries; i += p) {
answers[i] = searchvEB_nonperfect<TYPE>(A, tables, idx, num_tables, queries[i], pos, tid);
}
}
}
//Generates numQueries random queries and returns the milliseconds needed to perform the queries on the given vEB tree layout
template<typename TYPE>
double timeQueryvEB_nonperfect(TYPE *A, vEB_table **tables, uint64_t *idx, uint32_t num_tables, uint64_t n, uint32_t d, uint64_t numQueries, uint32_t p) {
struct timespec start, end;
TYPE *queries = createRandomQueries<TYPE>(A, n, numQueries); //array to store random queries to perform
uint64_t *answers = (uint64_t *)malloc(numQueries * sizeof(uint64_t)); //array to store the answers (i.e., index of the queried item)
clock_gettime(CLOCK_MONOTONIC, &start);
searchAll_nonperfect<TYPE>(A, tables, idx, num_tables, d, queries, answers, numQueries, p);
clock_gettime(CLOCK_MONOTONIC, &end);
double ms = ((end.tv_sec*1000000000. + end.tv_nsec) - (start.tv_sec*1000000000. + start.tv_nsec)) / 1000000.; //millisecond
#ifdef VERIFY
bool correct = true;
for (uint64_t i = 0; i < numQueries; i++) {
if (answers[i] == n || A[answers[i]] != queries[i] || answers[i] == n) {
#ifdef DEBUG
printf("query = %lu; A[%lu] = %lu\n", queries[i], answers[i], A[answers[i]]);
#endif
correct = false;
}
}
if (correct == false) printf("Searches failed!\n");
else printf("Searches succeeded!\n");
#endif
free(queries);
free(answers);
return ms;
}
#endif |
plex.c | /*
* compute the duplex structure of two RNA strands,
* allowing only inter-strand base pairs.
* see cofold() for computing hybrid structures without
* restriction.
* Ivo Hofacker
* Vienna RNA package
*
*/
/*
* library containing the function used in rnaplex
* the program rnaplex uses the following function
* Lduplexfold: finds high scoring segments
* it stores the end-position of these segments in an array
* and call then for each of these positions the duplexfold function
* which allows one to make backtracking for each of the high scoring position
* It allows one to find suboptimal partially overlapping (depends on a a parameter)
* duplexes between a long RNA and a shorter one.
* Contrarly to RNAduplex, the energy model is not in E~log(N),
* where N is the length of an interial loop but used an affine model,
* where the extension and begin parameter are fitted to the energy
* parameter used by RNAduplex. This allows one to check for duplex between a short RNA(20nt)
* and a long one at the speed of 1Mnt/s. At this speed the whole genome (3Gnt) can be analyzed for one siRNA
* in about 50 minutes.
* The algorithm is based on an idea by Durbin and Eddy:when the alginment reach a value larger than a
* given threshold this value is stored in an array. When the alignment score goes
* then under this threshold, the alignemnent begin from this value, in that way the backtracking allow us
* to find all non-overlapping high-scoring segments.
* For more information check "durbin, biological sequence analysis"
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include "ViennaRNA/utils/basic.h"
#include "ViennaRNA/params/default.h"
#include "ViennaRNA/fold_vars.h"
#include "ViennaRNA/fold.h"
#include "ViennaRNA/pair_mat.h"
#include "ViennaRNA/params/basic.h"
#include "ViennaRNA/plex.h"
#include "ViennaRNA/ali_plex.h"
#include "ViennaRNA/loops/all.h"
/* #################SIMD############### */
/* int subopt_sorted=0; */
#define PUBLIC
#define PRIVATE static
#define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */
#define NEW_NINIO 1 /* new asymetry penalty */
#define ARRAY 32 /*array size*/
#define UNIT 100
#define MINPSCORE -2 * UNIT
/**
*** Macro that define indices for the Single Array approach defined in FLduplexfold_XS->gain of 20% in runtime
*** so that everything is done in a 1D array.
*** input is idx for i, j for j and the length of the query RNA
*** 1D is divided in 6 subarrays, one for each number of allowed state
*** The length of each subarray is 5*L. 5 the maximal stored distance on the target sequence,
*** L is the length of the query sequence
**/
#define LCI(i, j, l) ((i) * l + j)
#define LINI(i, j, l) ((i + 5) * l + j)
#define LBXI(i, j, l) ((i + 10) * l + j)
#define LBYI(i, j, l) ((i + 15) * l + j)
#define LINIX(i, j, l) ((i + 20) * l + j)
#define LINIY(i, j, l) ((i + 25) * l + j)
PRIVATE void
encode_seqs(const char *s1,
const char *s2);
PRIVATE short *
encode_seq(const char *seq);
PRIVATE void
update_dfold_params(void);
/**
*** duplexfold(_XS)/backtrack(_XS) computes duplex interaction with standard energy and considers extension_cost
*** find_max(_XS)/plot_max(_XS) find suboptimals and MFE
*** fduplexfold(_XS) computes duplex in a plex way
**/
PRIVATE duplexT
duplexfold(const char *s1,
const char *s2,
const int extension_cost);
PRIVATE char *
backtrack(int i,
int j,
const int extension_cost);
PRIVATE void
find_max(const int *position,
const int *position_j,
const int delta,
const int threshold,
const int length,
const char *s1,
const char *s2,
const int extension_cost,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b);
PRIVATE void
plot_max(const int max,
const int max_pos,
const int max_pos_j,
const int alignment_length,
const char *s1,
const char *s2,
const int extension_cost,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b);
/* PRIVATE duplexT duplexfold_XS(const char *s1, const char *s2,const int **access_s1, const int **access_s2, const int i_pos, const int j_pos, const int threshold); */
PRIVATE duplexT
duplexfold_XS(const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int i_pos,
const int j_pos,
const int threshold,
const int i_flag,
const int j_flag);
/* PRIVATE char * backtrack_XS(int i, int j, const int** access_s1, const int** access_s2); */
PRIVATE char *
backtrack_XS(int i,
int j,
const int **access_s1,
const int **access_s2,
const int i_flag,
const int j_flag);
PRIVATE void
find_max_XS(const int *position,
const int *position_j,
const int delta,
const int threshold,
const int alignment_length,
const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b);
PRIVATE void
plot_max_XS(const int max,
const int max_pos,
const int max_pos_j,
const int alignment_length,
const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b);
PRIVATE duplexT
fduplexfold(const char *s1,
const char *s2,
const int extension_cost,
const int il_a,
const int il_b,
const int b_a,
const int b_b);
PRIVATE char *
fbacktrack(int i,
int j,
const int extension_cost,
const int il_a,
const int il_b,
const int b_a,
const int b_b,
int *dG);
PRIVATE duplexT
fduplexfold_XS(const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int i_pos,
const int j_pos,
const int threshold,
const int il_a,
const int il_b,
const int b_a,
const int b_b);
PRIVATE char *
fbacktrack_XS(int i,
int j,
const int **access_s1,
const int **access_s2,
const int i_pos,
const int j_pos,
const int il_a,
const int il_b,
const int b_a,
const int b_b,
int *dGe,
int *dGeplex,
int *dGx,
int *dGy);
/*@unused@*/
#define MAXSECTORS 500 /* dimension for a backtrack array */
#define LOCALITY 0. /* locality parameter for base-pairs */
PRIVATE vrna_param_t *P = NULL;
/**
*** energy array used in fduplexfold and fduplexfold_XS
*** We do not use the 1D array here as it is not time critical
*** It also makes the code more readable
*** c -> stack;in -> interior loop;bx/by->bulge;inx/iny->1xn loops
**/
PRIVATE int **c = NULL, **in = NULL, **bx = NULL, **by = NULL, **inx = NULL, **iny = NULL;
/**
*** S1, SS1, ... contains the encoded sequence for target and query
*** n1, n2, n3, n4 contains target and query length
**/
PRIVATE short *S1 = NULL, *SS1 = NULL, *S2 = NULL, *SS2 = NULL; /*contains the sequences*/
PRIVATE int n1, n2; /* sequence lengths */
PRIVATE int n3, n4; /*sequence length for the duplex*/;
/*-----------------------------------------------------------------------duplexfold_XS---------------------------------------------------------------------------*/
/**
*** duplexfold_XS is the pendant to the duplex function as defined in duplex.c
*** but takes the accessibility into account. It is similar to the MFE version of RNAup
*** The only approximation made is that target 3' end - query 5' end base pair is known
*** s1,s2 are the query and target sequence; access_s1, access_s2 are the accessibility
*** profiles, i_pos, j_pos are the coordinates of the closing pair.
**/
PRIVATE duplexT
duplexfold_XS(const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int i_pos,
const int j_pos,
const int threshold,
const int i_flag,
const int j_flag)
{
int i, j, p, q, Emin = INF, l_min = 0, k_min = 0;
char *struc;
vrna_md_t md;
struc = NULL;
duplexT mfe;
n3 = (int)strlen(s1);
n4 = (int)strlen(s2);
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
update_fold_params();
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
c = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
for (i = 0; i <= n3; i++)
c[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
for (i = 0; i <= n3; i++)
for (j = 0; j <= n4; j++)
c[i][j] = INF;
encode_seqs(s1, s2);
int type, type2, type3, E, k, l;
i = n3 - i_flag;
j = 1 + j_flag;
type = pair[S1[i]][S2[j]];
if (!type) {
printf("Error during initialization of the duplex in duplexfold_XS\n");
mfe.structure = NULL;
mfe.energy = INF;
return mfe;
}
c[i][j] = P->DuplexInit;
/** if (type>2) c[i][j] += P->TerminalAU;
*** c[i][j]+=P->dangle3[rtype[type]][SS1[i+1]];
*** c[i][j]+=P->dangle5[rtype[type]][SS2[j-1]];
*** The three above lines are replaced by the line below
**/
c[i][j] +=
vrna_E_ext_stem(rtype[type], (j_flag ? SS2[j - 1] : -1), (i_flag ? SS1[i + 1] : -1), P);
/*
* if(j_flag ==0 && i_flag==0){
* c[i][j] += vrna_E_ext_stem(rtype[type], -1 , -1 , P);
* }else if(j_flag ==0 && i_flag==1){
* c[i][j] += vrna_E_ext_stem(rtype[type], -1 , SS1[i+1], P);
* }else if(j_flag ==1 && i_flag==0){
* c[i][j] += vrna_E_ext_stem(rtype[type], SS2[j-1] , -1, P);
* }else {
* c[i][j] += vrna_E_ext_stem(rtype[type], SS2[j-1] , SS1[i+1], P);
* }
* Just in case we have only one bp, we initialize ...
* k_min, l_min and Emin
*/
k_min = i;
l_min = j;
Emin = c[i][j];
for (k = i; k > 1; k--) {
if (k < i)
c[k + 1][0] = INF;
for (l = j; l <= n4 - 1; l++) {
if (!(k == i && l == j))
c[k][l] = INF;
type2 = pair[S1[k]][S2[l]];
if (!type2)
continue;
for (p = k + 1; p <= n3 - i_flag && p < k + MAXLOOP - 1; p++) {
for (q = l - 1; q >= 1 + j_flag; q--) {
if (p - k + l - q - 2 > MAXLOOP)
break;
type3 = pair[S1[p]][S2[q]];
if (!type3)
continue;
E = E_IntLoop(p - k - 1,
l - q - 1,
type2,
rtype[type3],
SS1[k + 1],
SS2[l - 1],
SS1[p - 1],
SS2[q + 1],
P);
c[k][l] = MIN2(c[k][l], c[p][q] + E);
}
}
E = c[k][l];
E += access_s1[i - k + 1][i_pos] + access_s2[l - 1][j_pos + (l - 1) - 1];
/**if (type2>2) E += P->TerminalAU;
***if (k>1) E += P->dangle5[type2][SS1[k-1]];
***if (l<n4) E += P->dangle3[type2][SS2[l+1]];
*** Replaced by the line below
**/
E += vrna_E_ext_stem(type2, (k > 1) ? SS1[k - 1] : -1, (l < n4) ? SS2[l + 1] : -1, P);
if (E < Emin) {
Emin = E;
k_min = k;
l_min = l;
}
}
}
if (Emin > threshold) {
mfe.energy = INF;
mfe.ddG = INF;
mfe.structure = NULL;
for (i = 0; i <= n3; i++)
free(c[i]);
free(c);
free(S1);
free(S2);
free(SS1);
free(SS2);
return mfe;
} else {
struc = backtrack_XS(k_min, l_min, access_s1, access_s2, i_flag, j_flag);
}
/**
*** find best dangles combination
**/
int dx_5, dx_3, dy_5, dy_3, dGx, dGy, bonus_x;
dx_5 = 0;
dx_3 = 0;
dy_5 = 0;
dy_3 = 0;
dGx = 0;
dGy = 0;
bonus_x = 0;
/*
* x--------x
* ||||||||
* x--------x
*/
dGx = access_s1[i - k_min + 1][i_pos];
dx_3 = 0;
dx_5 = 0;
bonus_x = 0;
dGy = access_s2[l_min - j + 1][j_pos + (l_min - 1)];
mfe.tb = i_pos - 9 - i + k_min - 1 - dx_5;
mfe.te = i_pos - 9 - 1 + dx_3;
mfe.qb = j_pos - 9 - 1 - dy_5;
mfe.qe = j_pos + l_min - 3 - 9 + dy_3;
mfe.ddG = (double)Emin * 0.01;
mfe.dG1 = (double)dGx * 0.01;
mfe.dG2 = (double)dGy * 0.01;
mfe.energy = mfe.ddG - mfe.dG1 - mfe.dG2;
mfe.structure = struc;
for (i = 0; i <= n3; i++)
free(c[i]);
free(c);
free(S1);
free(S2);
free(SS1);
free(SS2);
return mfe;
}
PRIVATE char *
backtrack_XS(int i,
int j,
const int **access_s1,
const int **access_s2,
const int i_flag,
const int j_flag)
{
/* backtrack structure going backwards from i, and forwards from j
* return structure in bracket notation with & as separator */
int k, l, type, type2, E, traced, i0, j0;
char *st1, *st2, *struc;
st1 = (char *)vrna_alloc(sizeof(char) * (n3 + 1));
st2 = (char *)vrna_alloc(sizeof(char) * (n4 + 1));
i0 = i; /*MAX2(i-1,1);*/ j0 = j;/*MIN2(j+1,n4);*/
while (i <= n3 - i_flag && j >= 1 + j_flag) {
E = c[i][j];
traced = 0;
st1[i - 1] = '(';
st2[j - 1] = ')';
type = pair[S1[i]][S2[j]];
if (!type)
vrna_message_error("backtrack failed in fold duplex bli");
for (k = i + 1; k <= n3 && k > i - MAXLOOP - 2; k++) {
for (l = j - 1; l >= 1; l--) {
int LE;
if (i - k + l - j - 2 > MAXLOOP)
break;
type2 = pair[S1[k]][S2[l]];
if (!type2)
continue;
LE = E_IntLoop(k - i - 1,
j - l - 1,
type,
rtype[type2],
SS1[i + 1],
SS2[j - 1],
SS1[k - 1],
SS2[l + 1],
P);
if (E == c[k][l] + LE) {
traced = 1;
i = k;
j = l;
break;
}
}
if (traced)
break;
}
if (!traced) {
#if 0
if (i < n3)
E -= P->dangle3[rtype[type]][SS1[i + 1]]; /* +access_s1[1][i+1]; */
if (j > 1)
E -= P->dangle5[rtype[type]][SS2[j - 1]]; /* +access_s2[1][j+1]; */
if (type > 2)
E -= P->TerminalAU;
#endif
E -= vrna_E_ext_stem(rtype[type], SS2[j - 1], SS1[i + 1], P);
break;
if (E != P->DuplexInit)
vrna_message_error("backtrack failed in fold duplex bal");
else
break;
}
}
/*
* if (i<n3) i++;
* if (j>1) j--;
*/
struc = (char *)vrna_alloc(i - i0 + 1 + j0 - j + 1 + 2);
for (k = MAX2(i0, 1); k <= i; k++)
if (!st1[k - 1])
st1[k - 1] = '.';
for (k = j; k <= j0; k++)
if (!st2[k - 1])
st2[k - 1] = '.';
strcpy(struc, st1 + MAX2(i0 - 1, 0));
strcat(struc, "&");
strcat(struc, st2 + j - 1);
free(st1);
free(st2);
return struc;
}
/**
*** fduplexfold(_XS) computes the interaction based on the plex energy model.
*** Faster than duplex approach, but not standard model compliant
*** We use the standard matrix (c, in, etc..., because we backtrack)
**/
PRIVATE duplexT
fduplexfold_XS(const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int i_pos,
const int j_pos,
const int threshold,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
/**
*** i,j recursion index
*** Emin, i_min, j_min MFE position and energy
*** mfe struc duplex structure
**/
int i, j, Emin, i_min, j_min, l1;
duplexT mfe;
char *struc;
/**
*** bext=b_a bulge extension parameter for linear model
*** iopen=il_b interior opening for linear model
*** iext_s=2*il_a asymmetric extension for interior loop
*** iext_ass=60+il_a symmetric extension for interior loop
*** min_colonne=INF; max score of a row
*** i_length;
*** max_pos; position of best hit during recursion on target
*** max_pos_j; position of best hit during recursion on query
*** temp; temp variable for min_colonne
*** min_j_colonne; position of the minimum on query in row j
*** max=INF; absolute MFE
*** n3,n4 length of target and query
*** DJ contains the accessibility penalty for the query sequence
*** maxPenalty contains the maximum penalty
**/
int bopen = b_b;
int bext = b_a;
int iopen = il_b;
int iext_s = 2 * il_a; /* iext_s 2 nt nucleotide extension of interior loop, on i and j side */
int iext_ass = 50 + il_a; /* iext_ass assymetric extension of interior loop, either on i or on j side. */
int min_colonne = INF; /* enthaelt das maximum einer kolonne */
int i_length;
int max_pos; /* get position of the best hit */
int max_pos_j;
int temp = INF;
int min_j_colonne;
int max = INF;
int **DJ;
int maxPenalty[4];
vrna_md_t md;
/**
*** variable initialization
**/
n3 = (int)strlen(s1);
n4 = (int)strlen(s2);
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
update_fold_params();
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
/**
*** array initialization
**/
c = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
in = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
bx = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
by = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
inx = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
iny = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
/* #pragma omp parallel for */
for (i = 0; i <= n3; i++) {
c[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
in[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
bx[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
by[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
inx[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
iny[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
}
for (i = 0; i < n3; i++) {
for (j = 0; j < n4; j++) {
in[i][j] = INF; /* no in before 1 */
c[i][j] = INF; /* no bulge and no in before n2 */
bx[i][j] = INF; /* no bulge before 1 */
by[i][j] = INF;
inx[i][j] = INF; /* no bulge before 1 */
iny[i][j] = INF;
}
}
/**
*** sequence encoding
**/
encode_seqs(s1, s2);
/**
*** Compute max accessibility penalty for the query only once
**/
maxPenalty[0] = (int)-1 * P->stack[2][2] / 2;
maxPenalty[1] = (int)-1 * P->stack[2][2];
maxPenalty[2] = (int)-3 * P->stack[2][2] / 2;
maxPenalty[3] = (int)-2 * P->stack[2][2];
DJ = (int **)vrna_alloc(4 * sizeof(int *));
DJ[0] = (int *)vrna_alloc((1 + n4) * sizeof(int));
DJ[1] = (int *)vrna_alloc((1 + n4) * sizeof(int));
DJ[2] = (int *)vrna_alloc((1 + n4) * sizeof(int));
DJ[3] = (int *)vrna_alloc((1 + n4) * sizeof(int));
j = n4 - 9;
while (--j > 9) {
int jdiff = j_pos + j - 11;
/**
*** Depending in which direction (i:1->n vs j:m->1) the accessibility is computed we get slightly different results.
*** We reduce the discrepancies by taking the average of d^i_k and d^j_l
**/
DJ[0][j] = 0.5 *
(access_s2[5][jdiff + 4] - access_s2[4][jdiff + 4] + access_s2[5][jdiff] -
access_s2[4][jdiff - 1]);
DJ[1][j] = 0.5 *
(access_s2[5][jdiff + 5] - access_s2[4][jdiff + 5] + access_s2[5][jdiff + 1] -
access_s2[4][jdiff]) + DJ[0][j];
DJ[2][j] = 0.5 *
(access_s2[5][jdiff + 6] - access_s2[4][jdiff + 6] + access_s2[5][jdiff + 2] -
access_s2[4][jdiff + 1]) + DJ[1][j];
DJ[3][j] = 0.5 *
(access_s2[5][jdiff + 7] - access_s2[4][jdiff + 7] + access_s2[5][jdiff + 3] -
access_s2[4][jdiff + 2]) + DJ[2][j];
/*
* DJ[0][j] = access_s2[5][jdiff+4] - access_s2[4][jdiff+4] ;
* DJ[1][j] = access_s2[5][jdiff+5] - access_s2[4][jdiff+5] + DJ[0][j];
* DJ[2][j] = access_s2[5][jdiff+6] - access_s2[4][jdiff+6] + DJ[1][j];
* DJ[3][j] = access_s2[5][jdiff+7] - access_s2[4][jdiff+7] + DJ[2][j];
* DJ[0][j] = MIN2(DJ[0][j],maxPenalty[0]);
* DJ[1][j] = MIN2(DJ[1][j],maxPenalty[1]);
* DJ[2][j] = MIN2(DJ[2][j],maxPenalty[2]);
* DJ[3][j] = MIN2(DJ[3][j],maxPenalty[3]);
*/
}
/**
*** Start of the recursion
*** first and last 10 nucleotides on target and query are dummy nucleotides
*** allow to reduce number of if test
**/
i = 11;
i_length = n3 - 9;
while (i < i_length) {
int di1, di2, di3, di4;
int idiff = i_pos - (n3 - 10 - i);
di1 = 0.5 *
(access_s1[5][idiff + 4] - access_s1[4][idiff + 4] + access_s1[5][idiff] -
access_s1[4][idiff - 1]);
di2 = 0.5 *
(access_s1[5][idiff + 3] - access_s1[4][idiff + 3] + access_s1[5][idiff - 1] -
access_s1[4][idiff - 2]) + di1;
di3 = 0.5 *
(access_s1[5][idiff + 2] - access_s1[4][idiff + 2] + access_s1[5][idiff - 2] -
access_s1[4][idiff - 3]) + di2;
di4 = 0.5 *
(access_s1[5][idiff + 1] - access_s1[4][idiff + 1] + access_s1[5][idiff - 3] -
access_s1[4][idiff - 4]) + di3;
/*
* di1 = access_s1[5][idiff] - access_s1[4][idiff-1];
* di2 = access_s1[5][idiff-1] - access_s1[4][idiff-2] + di1;
* di3 = access_s1[5][idiff-2] - access_s1[4][idiff-3] + di2;
* di4 = access_s1[5][idiff-3] - access_s1[4][idiff-4] + di3;
* di1=MIN2(di1,maxPenalty[0]);
* di2=MIN2(di2,maxPenalty[1]);
* di3=MIN2(di3,maxPenalty[2]);
* di4=MIN2(di4,maxPenalty[3]);
*/
j = n4 - 9;
min_colonne = INF;
while (10 < --j) {
int dj1, dj2, dj3, dj4;
int jdiff = j_pos + j - 11;
dj1 = DJ[0][j];
dj2 = DJ[1][j];
dj3 = DJ[2][j];
dj4 = DJ[3][j];
int type, type2;
type = pair[S1[i]][S2[j]];
/**
*** Start duplex
**/
/*
* c[i][j]=type ? P->DuplexInit + access_s1[1][idiff]+access_s2[1][jdiff] : INF;
*/
c[i][j] = type ? P->DuplexInit : INF;
/**
*** update lin bx by linx liny matrix
**/
type2 = pair[S2[j + 1]][S1[i - 1]];
/**
*** start/extend interior loop
**/
in[i][j] = MIN2(
c[i - 1][j + 1] + P->mismatchI[type2][SS2[j]][SS1[i]] + iopen + iext_s + di1 + dj1,
in[i - 1][j] + iext_ass + di1);
/**
*** start/extend nx1 target
*** use same type2 as for in
**/
inx[i][j] = MIN2(
c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s + di1 + dj1,
inx[i - 1][j] + iext_ass + di1);
/**
*** start/extend 1xn target
*** use same type2 as for in
**/
iny[i][j] = MIN2(
c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s + di1 + dj1,
iny[i][j + 1] + iext_ass + dj1);
/**
*** extend interior loop
**/
in[i][j] = MIN2(in[i][j], in[i][j + 1] + iext_ass + dj1);
in[i][j] = MIN2(in[i][j], in[i - 1][j + 1] + iext_s + di1 + dj1);
/**
*** start/extend bulge target
**/
type2 = pair[S2[j]][S1[i - 1]];
bx[i][j] =
MIN2(bx[i - 1][j] + bext + di1,
c[i - 1][j] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0) + di1);
/**
*** start/extend bulge query
**/
type2 = pair[S2[j + 1]][S1[i]];
by[i][j] =
MIN2(by[i][j + 1] + bext + dj1,
c[i][j + 1] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0) + dj1);
/**
***end update recursion
***######################## Start stack extension##############################
**/
if (!type)
continue;
c[i][j] += vrna_E_ext_stem(type, SS1[i - 1], SS2[j + 1], P);
/**
*** stack extension
**/
if ((type2 = pair[S1[i - 1]][S2[j + 1]]))
c[i][j] = MIN2(c[i - 1][j + 1] + P->stack[rtype[type]][type2] + di1 + dj1, c[i][j]);
/**
*** 1x0 / 0x1 stack extension
**/
if ((type2 = pair[S1[i - 1]][S2[j + 2]]))
c[i][j] = MIN2(c[i - 1][j + 2] + P->bulge[1] + P->stack[rtype[type]][type2] + di1 + dj2,
c[i][j]);
if ((type2 = pair[S1[i - 2]][S2[j + 1]]))
c[i][j] = MIN2(c[i - 2][j + 1] + P->bulge[1] + P->stack[type2][rtype[type]] + di2 + dj1,
c[i][j]);
/**
*** 1x1 / 2x2 stack extension
**/
if ((type2 = pair[S1[i - 2]][S2[j + 2]]))
c[i][j] = MIN2(
c[i - 2][j + 2] + P->int11[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]] + di2 + dj2,
c[i][j]);
if ((type2 = pair[S1[i - 3]][S2[j + 3]])) {
c[i][j] =
MIN2(c[i - 3][j + 3] +
P->int22[type2][rtype[type]][SS1[i - 2]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + di3 + dj3,
c[i][j]);
}
/**
*** 1x2 / 2x1 stack extension
*** E_IntLoop(1,2,type2, rtype[type],SS1[i-1], SS2[j+2], SS1[i-1], SS2[j+1], P) corresponds to
*** P->int21[rtype[type]][type2][SS2[j+2]][SS1[i-1]][SS1[i-1]]
**/
if ((type2 = pair[S1[i - 3]][S2[j + 2]])) {
c[i][j] =
MIN2(
c[i - 3][j + 2] + P->int21[rtype[type]][type2][SS2[j + 1]][SS1[i - 2]][SS1[i - 1]] + di3 + dj2,
c[i][j]);
}
if ((type2 = pair[S1[i - 2]][S2[j + 3]])) {
c[i][j] =
MIN2(
c[i - 2][j + 3] + P->int21[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + di2 + dj3,
c[i][j]);
}
/**
*** 2x3 / 3x2 stack extension
**/
if ((type2 = pair[S1[i - 4]][S2[j + 3]]))
c[i][j] = MIN2(c[i - 4][j + 3] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 3]][SS2[j + 2]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + di4 + dj3, c[i][j]);
if ((type2 = pair[S1[i - 3]][S2[j + 4]]))
c[i][j] = MIN2(c[i - 3][j + 4] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 2]][SS2[j + 3]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + di3 + dj4, c[i][j]);
/**
*** So now we have to handle 1x3, 3x1, 3x3, and mxn m,n > 3
**/
/**
*** 3x3 or more
**/
c[i][j] = MIN2(
in[i - 3][j + 3] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + 2 * iext_s + di3 + dj3,
c[i][j]);
/**
*** 2xn or more
**/
c[i][j] = MIN2(
in[i - 4][j + 2] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + di4 + dj2,
c[i][j]);
/**
*** nx2 or more
**/
c[i][j] = MIN2(
in[i - 2][j + 4] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + di2 + dj4,
c[i][j]);
/**
*** nx1 n>2
**/
c[i][j] = MIN2(
inx[i - 3][j + 1] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + di3 + dj1,
c[i][j]);
/**
*** 1xn n>2
**/
c[i][j] = MIN2(
iny[i - 1][j + 3] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + dj3 + di1,
c[i][j]);
/**
*** nx0 n>1
**/
int bAU;
bAU = (type > 2 ? P->TerminalAU : 0);
c[i][j] = MIN2(bx[i - 2][j + 1] + di2 + dj1 + bext + bAU, c[i][j]);
/**
*** 0xn n>1
**/
c[i][j] = MIN2(by[i - 1][j + 2] + di1 + dj2 + bext + bAU, c[i][j]);
/*
* remove this line printf("%d\t",c[i][j]);
*/
temp = min_colonne;
min_colonne = MIN2(c[i][j] + vrna_E_ext_stem(rtype[type], SS2[j - 1], SS1[i + 1], P),
min_colonne);
if (temp > min_colonne)
min_j_colonne = j;
/* ---------------------------------------------------------------------end update */
}
if (max >= min_colonne) {
max = min_colonne;
max_pos = i;
max_pos_j = min_j_colonne;
}
i++;
/*
* remove this line printf("\n");
*/
}
Emin = max;
if (Emin > threshold) {
free(S1);
free(S2);
free(SS1);
free(SS2);
for (i = 0; i <= n3; i++) {
free(c[i]);
free(in[i]);
free(bx[i]);
free(by[i]);
free(inx[i]);
free(iny[i]);
}
for (i = 0; i <= 3; i++)
free(DJ[i]);
free(c);
free(in);
free(bx);
free(by);
free(inx);
free(iny);
free(DJ);
mfe.energy = 0;
mfe.structure = NULL;
return mfe;
}
i_min = max_pos;
j_min = max_pos_j;
int dGe, dGeplex, dGx, dGy;
dGe = dGeplex = dGx = dGy = 0;
/* printf("MAX fduplexfold_XS %d\n",Emin); */
struc = fbacktrack_XS(i_min,
j_min,
access_s1,
access_s2,
i_pos,
j_pos,
il_a,
il_b,
b_a,
b_b,
&dGe,
&dGeplex,
&dGx,
&dGy);
l1 = strchr(struc, '&') - struc;
int size;
size = strlen(struc) - 1;
int lengthx;
int endx;
int lengthy;
int endy;
lengthx = l1;
lengthx -= (struc[0] == '.' ? 1 : 0);
lengthx -= (struc[l1 - 1] == '.' ? 1 : 0);
endx = (i_pos - (n3 - i_min));
lengthy = size - l1;
lengthy -= (struc[size] == '.' ? 1 : 0);
lengthy -= (struc[l1 + 1] == '.' ? 1 : 0);
endy = j_pos + j_min + lengthy - 22;
if (i_min < n3 - 10)
i_min++;
if (j_min > 11)
j_min--;
mfe.i = i_min;
mfe.j = j_min;
mfe.ddG = (double)Emin * 0.01;
mfe.structure = struc;
mfe.energy_backtrack = (double)dGe * 0.01;
mfe.energy = (double)dGeplex * 0.01;
mfe.opening_backtrack_x = (double)dGx * 0.01;
mfe.opening_backtrack_y = (double)dGy * 0.01;
mfe.dG1 = 0; /* !remove access to complete access array (double) access_s1[lengthx][endx+10] * 0.01; */
mfe.dG2 = 0; /* !remove access to complete access array (double) access_s2[lengthy][endy+10] * 0.01; */
free(S1);
free(S2);
free(SS1);
free(SS2);
for (i = 0; i <= n3; i++) {
free(c[i]);
free(in[i]);
free(bx[i]);
free(by[i]);
free(inx[i]);
free(iny[i]);
}
for (i = 0; i <= 3; i++)
free(DJ[i]);
free(DJ);
free(c);
free(in);
free(bx);
free(by);
free(iny);
free(inx);
return mfe;
}
PRIVATE char *
fbacktrack_XS(int i,
int j,
const int **access_s1,
const int **access_s2,
const int i_pos,
const int j_pos,
const int il_a,
const int il_b,
const int b_a,
const int b_b,
int *dG,
int *dGplex,
int *dGx,
int *dGy)
{
/* backtrack structure going backwards from i, and forwards from j
* return structure in bracket notation with & as separator */
int k, l, type, type2, E, traced, i0, j0;
char *st1, *st2, *struc;
int bopen = b_b;
int bext = b_a;
int iopen = il_b;
int iext_s = 2 * il_a; /* iext_s 2 nt nucleotide extension of interior loop, on i and j side */
int iext_ass = 50 + il_a; /* iext_ass assymetric extension of interior loop, either on i or on j side. */
st1 = (char *)vrna_alloc(sizeof(char) * (n3 + 1));
st2 = (char *)vrna_alloc(sizeof(char) * (n4 + 1));
i0 = MIN2(i + 1, n3 - 10);
j0 = MAX2(j - 1, 11);
int state;
state = 1; /* we start backtracking from a a pair , i.e. c-matrix */
/* state 1 -> base pair, c
* state 2 -> interior loop, in
* state 3 -> bx loop, bx
* state 4 -> by loop, by
*/
traced = 1;
k = i;
l = j; /* stores the i,j information for subsequence usage see * */
int idiff, jdiff;
/**
*** (type>2?P->TerminalAU:0)+P->dangle3[rtype[type]][SS1[i+1]]+P->dangle5[rtype[type]][SS2[j-1]];
**/
int maxPenalty[4];
vrna_md_t md;
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
update_dfold_params();
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
maxPenalty[0] = (int)-1 * P->stack[2][2] / 2;
maxPenalty[1] = (int)-1 * P->stack[2][2];
maxPenalty[2] = (int)-3 * P->stack[2][2] / 2;
maxPenalty[3] = (int)-2 * P->stack[2][2];
type = pair[S1[i]][S2[j]];
*dG += vrna_E_ext_stem(rtype[type], SS2[j - 1], SS1[i + 1], P);
*dGplex = *dG;
while (i > 10 && j <= n4 - 9 && traced) {
int di1, di2, di3, di4;
idiff = i_pos - (n3 - 10 - i);
di1 = 0.5 *
(access_s1[5][idiff + 4] - access_s1[4][idiff + 4] + access_s1[5][idiff] -
access_s1[4][idiff - 1]);
di2 = 0.5 *
(access_s1[5][idiff + 3] - access_s1[4][idiff + 3] + access_s1[5][idiff - 1] -
access_s1[4][idiff - 2]) + di1;
di3 = 0.5 *
(access_s1[5][idiff + 2] - access_s1[4][idiff + 2] + access_s1[5][idiff - 2] -
access_s1[4][idiff - 3]) + di2;
di4 = 0.5 *
(access_s1[5][idiff + 1] - access_s1[4][idiff + 1] + access_s1[5][idiff - 3] -
access_s1[4][idiff - 4]) + di3;
/*
* di1 = access_s1[5][idiff] - access_s1[4][idiff-1];
* di2 = access_s1[5][idiff-1] - access_s1[4][idiff-2] + di1;
* di3 = access_s1[5][idiff-2] - access_s1[4][idiff-3] + di2;
* di4 = access_s1[5][idiff-3] - access_s1[4][idiff-4] + di3;
* di1=MIN2(di1,maxPenalty[0]);
* di2=MIN2(di2,maxPenalty[1]);
* di3=MIN2(di3,maxPenalty[2]);
* di4=MIN2(di4,maxPenalty[3]);
*/
int dj1, dj2, dj3, dj4;
jdiff = j_pos + j - 11;
dj1 = 0.5 *
(access_s2[5][jdiff + 4] - access_s2[4][jdiff + 4] + access_s2[5][jdiff] -
access_s2[4][jdiff - 1]);
dj2 = 0.5 *
(access_s2[5][jdiff + 5] - access_s2[4][jdiff + 5] + access_s2[5][jdiff + 1] -
access_s2[4][jdiff]) + dj1;
dj3 = 0.5 *
(access_s2[5][jdiff + 6] - access_s2[4][jdiff + 6] + access_s2[5][jdiff + 2] -
access_s2[4][jdiff + 1]) + dj2;
dj4 = 0.5 *
(access_s2[5][jdiff + 7] - access_s2[4][jdiff + 7] + access_s2[5][jdiff + 3] -
access_s2[4][jdiff + 2]) + dj3;
/*
* dj1 = access_s2[5][jdiff+4] - access_s2[4][jdiff+4];
* dj2 = access_s2[5][jdiff+5] - access_s2[4][jdiff+5] + dj1;
* dj3 = access_s2[5][jdiff+6] - access_s2[4][jdiff+6] + dj2;
* dj4 = access_s2[5][jdiff+7] - access_s2[4][jdiff+7] + dj3;
* dj1=MIN2(dj1,maxPenalty[0]);
* dj2=MIN2(dj2,maxPenalty[1]);
* dj3=MIN2(dj3,maxPenalty[2]);
* dj4=MIN2(dj4,maxPenalty[3]);
*/
traced = 0;
switch (state) {
case 1:
type = pair[S1[i]][S2[j]];
int bAU;
bAU = (type > 2 ? P->TerminalAU : 0);
if (!type)
vrna_message_error("backtrack failed in fold duplex");
type2 = pair[S1[i - 1]][S2[j + 1]];
if (type2 && c[i][j] == (c[i - 1][j + 1] + P->stack[rtype[type]][type2] + di1 + dj1)) {
k = i - 1;
l = j + 1;
(*dG) += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di1;
*dGy += dj1;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 1]][S2[j + 2]];
if (type2 &&
c[i][j] == (c[i - 1][j + 2] + P->bulge[1] + P->stack[rtype[type]][type2] + di1 + dj2)) {
k = i - 1;
l = j + 2;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di1;
*dGy += dj2;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 2]][S2[j + 1]];
if (type2 &&
c[i][j] == (c[i - 2][j + 1] + P->bulge[1] + P->stack[type2][rtype[type]] + di2 + dj1)) {
k = i - 2;
l = j + 1;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di2;
*dGy += dj1;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 2]][S2[j + 2]];
if (type2 &&
c[i][j] ==
(c[i - 2][j + 2] + P->int11[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]] + di2 + dj2)) {
k = i - 2;
l = j + 2;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di2;
*dGy += dj2;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 3]][S2[j + 3]];
if (type2 &&
c[i][j] ==
(c[i - 3][j + 3] +
P->int22[type2][rtype[type]][SS1[i - 2]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + di3 +
dj3)) {
k = i - 3;
l = j + 3;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di3;
*dGy += dj3;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 3]][S2[j + 2]];
if (type2 &&
c[i][j] ==
(c[i - 3][j + 2] + P->int21[rtype[type]][type2][SS2[j + 1]][SS1[i - 2]][SS1[i - 1]] +
di3 +
dj2)) {
k = i - 3;
l = j + 2;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di3;
*dGy += dj2;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 2]][S2[j + 3]];
if (type2 &&
c[i][j] ==
(c[i - 2][j + 3] + P->int21[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] +
di2 +
dj3)) {
k = i - 2;
l = j + 3;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di2;
*dGy += dj3;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 4]][S2[j + 3]];
if (type2 && c[i][j] == (c[i - 4][j + 3] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 3]][SS2[j + 2]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + di4 + dj3)) {
k = i - 4;
l = j + 3;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di2;
*dGy += dj3;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 3]][S2[j + 4]];
if (type2 && c[i][j] == (c[i - 3][j + 4] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 2]][SS2[j + 3]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + di3 + dj4)) {
k = i - 3;
l = j + 4;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di2;
*dGy += dj3;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
if (c[i][j] ==
(in[i - 3][j + 3] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + di3 + dj3 + 2 *
iext_s)) {
k = i;
l = j;
*dGplex += P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + 2 * iext_s;
*dGx += di3;
*dGy += dj3;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 3;
j = j + 3;
state = 2;
traced = 1;
break;
}
if (c[i][j] ==
(in[i - 4][j + 2] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + di4 + dj2 +
iext_s +
2 * iext_ass)) {
k = i;
l = j;
*dGplex += P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass;
*dGx += di4;
*dGy += dj2;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 4;
j = j + 2;
state = 2;
traced = 1;
break;
}
if (c[i][j] ==
(in[i - 2][j + 4] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + di2 + dj4 +
iext_s +
2 * iext_ass)) {
k = i;
l = j;
*dGplex += P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass;
*dGx += di2;
*dGy += dj4;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 2;
j = j + 4;
state = 2;
traced = 1;
break;
}
if (c[i][j] ==
(inx[i - 3][j + 1] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass +
iext_ass + di3 + dj1)) {
k = i;
l = j;
*dGplex += P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass +
di3 + dj1;
*dGx += di3;
*dGy += dj1;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 3;
j = j + 1;
state = 5;
traced = 1;
break;
}
if (c[i][j] ==
(iny[i - 1][j + 3] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass +
iext_ass + di1 + dj3)) {
k = i;
l = j;
*dGplex += P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass +
di1 + dj3;
*dGx += di1;
*dGy += dj3;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 1;
j = j + 3;
state = 6;
traced = 1;
break;
}
if (c[i][j] == (bx[i - 2][j + 1] + di2 + dj1 + bext + bAU)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
*dGplex += bext + bAU;
*dGx += di2;
*dGy += dj1;
i = i - 2;
j = j + 1;
state = 3;
traced = 1;
break;
}
if (c[i][j] == (by[i - 1][j + 2] + di1 + dj2 + bext + bAU)) {
k = i;
l = j;
*dGplex += bext + bAU;
*dGx += di1;
*dGy += dj2;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 1;
j = j + 2;
state = 4;
traced = 1;
break;
}
break;
case 2:
if (in[i][j] == (in[i - 1][j + 1] + iext_s + di1 + dj1)) {
i--;
j++;
*dGplex += iext_s;
*dGx += di1;
*dGy += dj1;
state = 2;
traced = 1;
break;
}
if (in[i][j] == (in[i - 1][j] + iext_ass + di1)) {
i = i - 1;
*dGplex += iext_ass;
*dGx += di1;
state = 2;
traced = 1;
break;
}
if (in[i][j] == (in[i][j + 1] + iext_ass + dj1)) {
j++;
state = 2;
*dGy += dj1;
*dGplex += iext_ass;
traced = 1;
break;
}
type2 = pair[SS2[j + 1]][SS1[i - 1]];
if (type2 &&
in[i][j] ==
(c[i - 1][j + 1] + P->mismatchI[type2][SS2[j]][SS1[i]] + iopen + iext_s + di1 + dj1)) {
*dGplex += P->mismatchI[type2][SS2[j]][SS1[i]] + iopen + iext_s;
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di1;
*dGy += dj1;
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 3:
if (bx[i][j] == (bx[i - 1][j] + bext + di1)) {
i--;
*dGplex += bext;
*dGx += di1;
state = 3;
traced = 1;
break;
}
type2 = pair[S2[j]][S1[i - 1]];
if (type2 &&
bx[i][j] == (c[i - 1][j] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0) + di1)) {
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += bopen + bext + (type2 > 2 ? P->TerminalAU : 0);
*dGx += di1;
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 4:
if (by[i][j] == (by[i][j + 1] + bext + dj1)) {
j++;
*dGplex += bext;
state = 4;
traced = 1;
break;
}
type2 = pair[S2[j + 1]][S1[i]];
if (type2 &&
by[i][j] == (c[i][j + 1] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0) + dj1)) {
int temp;
temp = k;
k = i;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGplex += bopen + bext + (type2 > 2 ? P->TerminalAU : 0);
*dGy += dj1;
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 5:
if (inx[i][j] == (inx[i - 1][j] + iext_ass + di1)) {
i--;
*dGplex += iext_ass;
*dGx += di1;
state = 5;
traced = 1;
break;
}
type2 = pair[S2[j + 1]][S1[i - 1]];
if (type2 &&
inx[i][j] ==
(c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s + di1 +
dj1)) {
*dGplex += P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s;
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di1;
*dGy += dj1;
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 6:
if (iny[i][j] == (iny[i][j + 1] + iext_ass + dj1)) {
j++;
*dGplex += iext_ass;
*dGx += dj1;
state = 6;
traced = 1;
break;
}
type2 = pair[S2[j + 1]][S1[i - 1]];
if (type2 &&
iny[i][j] ==
(c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s + di1 +
dj1)) {
*dGplex += P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s;
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
*dGx += di1;
*dGy += dj1;
i = k;
j = l;
state = 1;
traced = 1;
break;
}
}
}
if (!traced) {
idiff = i_pos - (n3 - 10 - i);
jdiff = j_pos + j - 11;
E = c[i][j];
/**
*** if (i>1) {E -= P->dangle5[type][SS1[i-1]]; *dG+=P->dangle5[type][SS1[i-1]];*dGplex+=P->dangle5[type][SS1[i-1]];}
*** if (j<n4){E -= P->dangle3[type][SS2[j+1]]; *dG+=P->dangle3[type][SS2[j+1]];*dGplex+=P->dangle3[type][SS2[j+1]];}
*** if (type>2) {E -= P->TerminalAU; *dG+=P->TerminalAU;*dGplex+=P->TerminalAU;}
**/
int correction;
correction = vrna_E_ext_stem(type, (i > 1) ? SS1[i - 1] : -1, (j < n4) ? SS2[j + 1] : -1, P);
*dG += correction;
*dGplex += correction;
E -= correction;
/*
* if (E != P->DuplexInit+access_s1[1][idiff]+access_s2[1][jdiff]) {
* vrna_message_error("backtrack failed in second fold duplex");
* }
*/
if (E != P->DuplexInit) {
vrna_message_error("backtrack failed in second fold duplex");
} else {
*dG += P->DuplexInit;
*dGplex += P->DuplexInit;
*dGx += 0; /* access_s1[1][idiff]; */
*dGy += 0; /* access_s2[1][jdiff]; */
st1[i - 1] = '(';
st2[j - 1] = ')';
}
}
if (i > 11)
i--;
if (j < n4 - 10)
j++;
struc = (char *)vrna_alloc(i0 - i + 1 + j - j0 + 1 + 2);
for (k = MAX2(i, 1); k <= i0; k++)
if (!st1[k - 1])
st1[k - 1] = '.';
for (k = j0; k <= j; k++)
if (!st2[k - 1])
st2[k - 1] = '.';
strcpy(struc, st1 + MAX2(i - 1, 0));
strcat(struc, "&");
strcat(struc, st2 + j0 - 1);
/* printf("%s %3d,%-3d : %3d,%-3d\n", struc, i,i0,j0,j); */
free(st1);
free(st2);
return struc;
}
duplexT **
Lduplexfold_XS(const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int threshold,
const int alignment_length,
const int delta,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
/**
*** See variable definition in fduplexfold_XS
**/
int i, j;
int bopen = b_b;
int bext = b_a;
int iopen = il_b;
int iext_s = 2 * il_a;
int iext_ass = 50 + il_a;
int min_colonne = INF;
int i_length;
int max_pos;
int max_pos_j;
int min_j_colonne;
int max = INF;
int *position;
int *position_j;
int maxPenalty[4];
int **DJ;
/**
*** 1D array corresponding to the standard 2d recursion matrix
*** Makes the computation 20% faster
**/
int *SA;
vrna_md_t md;
/**
*** variable initialization
**/
n1 = (int)strlen(s1);
n2 = (int)strlen(s2);
/**
*** Sequence encoding
**/
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
update_dfold_params();
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
encode_seqs(s1, s2);
/**
*** Position of the high score on the target and query sequence
**/
position = (int *)vrna_alloc((delta + n1 + 3 + delta) * sizeof(int));
position_j = (int *)vrna_alloc((delta + n1 + 3 + delta) * sizeof(int));
/**
*** extension penalty, computed only once, further reduce the computation time
**/
maxPenalty[0] = (int)-1 * P->stack[2][2] / 2;
maxPenalty[1] = (int)-1 * P->stack[2][2];
maxPenalty[2] = (int)-3 * P->stack[2][2] / 2;
maxPenalty[3] = (int)-2 * P->stack[2][2];
DJ = (int **)vrna_alloc(4 * sizeof(int *));
DJ[0] = (int *)vrna_alloc(n2 * sizeof(int));
DJ[1] = (int *)vrna_alloc(n2 * sizeof(int));
DJ[2] = (int *)vrna_alloc(n2 * sizeof(int));
DJ[3] = (int *)vrna_alloc(n2 * sizeof(int));
j = n2 - 9;
while (--j > 10) {
DJ[0][j] = 0.5 *
(access_s2[5][j + 4] - access_s2[4][j + 4] + access_s2[5][j] - access_s2[4][j - 1]);
DJ[1][j] = 0.5 *
(access_s2[5][j + 5] - access_s2[4][j + 5] + access_s2[5][j + 1] - access_s2[4][j]) +
DJ[0][j];
DJ[2][j] = 0.5 *
(access_s2[5][j + 6] - access_s2[4][j + 6] + access_s2[5][j + 2] -
access_s2[4][j + 1]) +
DJ[1][j];
DJ[3][j] = 0.5 *
(access_s2[5][j + 7] - access_s2[4][j + 7] + access_s2[5][j + 3] -
access_s2[4][j + 2]) +
DJ[2][j];
/*
* DJ[0][j] = access_s2[5][j+4] - access_s2[4][j+4] ;
* DJ[1][j] = access_s2[5][j+5] - access_s2[4][j+5] + DJ[0][j];
* DJ[2][j] = access_s2[5][j+6] - access_s2[4][j+6] + DJ[1][j];
* DJ[3][j] = access_s2[5][j+7] - access_s2[4][j+7] + DJ[2][j];
* DJ[0][j] = MIN2(DJ[0][j],maxPenalty[0]);
* DJ[1][j] = MIN2(DJ[1][j],maxPenalty[1]);
* DJ[2][j] = MIN2(DJ[2][j],maxPenalty[2]);
* DJ[3][j] = MIN2(DJ[3][j],maxPenalty[3]);
*/
}
/**
*** instead of having 4 2-dim arrays we use a unique 1-dim array
*** The mapping 2d -> 1D is done based ont the macro
*** LCI(i,j,l) ((i )*l + j)
*** LINI(i,j,l) ((i + 5)*l + j)
*** LBXI(i,j,l) ((i + 10)*l + j)
*** LBYI(i,j,l) ((i + 15)*l + j)
*** LINIX(i,j,l) ((i + 20)*l + j)
*** LINIY(i,j,l) ((i + 25)*l + j)
***
*** SA has a length of 5 (number of columns we look back) *
*** * 6 (number of structures we look at) *
*** * length of the sequence
**/
SA = (int *)vrna_alloc(sizeof(int) * 5 * 6 * (n2 + 5));
for (j = n2 + 4; j >= 0; j--) {
SA[(j *
30)] =
SA[(j * 30) + 1] = SA[(j * 30) + 2] = SA[(j * 30) + 3] = SA[(j * 30) + 4] = INF;
SA[(j * 30) +
5] =
SA[(j * 30) + 1 +
5] =
SA[(j * 30) + 2 + 5] = SA[(j * 30) + 3 + 5] = SA[(j * 30) + 4 + 5] = INF;
SA[(j * 30) +
10] =
SA[(j * 30) + 1 +
10] =
SA[(j * 30) + 2 + 10] = SA[(j * 30) + 3 + 10] = SA[(j * 30) + 4 + 10] = INF;
SA[(j * 30) +
15] =
SA[(j * 30) + 1 +
15] =
SA[(j * 30) + 2 + 15] = SA[(j * 30) + 3 + 15] = SA[(j * 30) + 4 + 15] = INF;
SA[(j * 30) +
20] =
SA[(j * 30) + 1 +
20] =
SA[(j * 30) + 2 + 20] = SA[(j * 30) + 3 + 20] = SA[(j * 30) + 4 + 20] = INF;
SA[(j * 30) +
25] =
SA[(j * 30) + 1 +
25] =
SA[(j * 30) + 2 + 25] = SA[(j * 30) + 3 + 25] = SA[(j * 30) + 4 + 25] = INF;
}
i = 10;
i_length = n1 - 9;
while (i < i_length) {
int di1, di2, di3, di4;
int idx = i % 5;
int idx_1 = (i - 1) % 5;
int idx_2 = (i - 2) % 5;
int idx_3 = (i - 3) % 5;
int idx_4 = (i - 4) % 5;
di1 = 0.5 * (access_s1[5][i + 4] - access_s1[4][i + 4] + access_s1[5][i] - access_s1[4][i - 1]);
di2 = 0.5 *
(access_s1[5][i + 3] - access_s1[4][i + 3] + access_s1[5][i - 1] - access_s1[4][i - 2]) +
di1;
di3 = 0.5 *
(access_s1[5][i + 2] - access_s1[4][i + 2] + access_s1[5][i - 2] - access_s1[4][i - 3]) +
di2;
di4 = 0.5 *
(access_s1[5][i + 1] - access_s1[4][i + 1] + access_s1[5][i - 3] - access_s1[4][i - 4]) +
di3;
/*
* di1 = access_s1[5][i] - access_s1[4][i-1];
* di2 = access_s1[5][i-1] - access_s1[4][i-2] + di1;
* di3 = access_s1[5][i-2] - access_s1[4][i-3] + di2;
* di4 = access_s1[5][i-3] - access_s1[4][i-4] + di3;
* di1=MIN2(di1,maxPenalty[0]);
* di2=MIN2(di2,maxPenalty[1]);
* di3=MIN2(di3,maxPenalty[2]);
* di4=MIN2(di4,maxPenalty[3]);
*/
j = n2 - 9;
while (--j > 9) {
int dj1, dj2, dj3, dj4;
dj1 = DJ[0][j];
dj2 = DJ[1][j];
dj3 = DJ[2][j];
dj4 = DJ[3][j];
int type2, type, temp;
type = pair[S1[i]][S2[j]];
/**
*** Start duplex
**/
/* SA[LCI(idx,j,n2)] = type ? P->DuplexInit + access_s1[1][i] + access_s2[1][j] : INF; */
SA[LCI(idx, j, n2)] = type ? P->DuplexInit : INF;
/**
*** update lin bx by linx liny matrix
**/
type2 = pair[S2[j + 1]][S1[i - 1]];
/**
*** start/extend interior loop
**/
SA[LINI(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->mismatchI[type2][SS2[j]][SS1[i]] + di1 + dj1 + iopen + iext_s,
SA[LINI(idx_1, j, n2)] + iext_ass + di1);
/**
*** start/extend nx1 target
*** use same type2 as for in
**/
SA[LINIX(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + di1 + dj1 + iopen + iext_s,
SA[LINIX(idx_1, j, n2)] + iext_ass + di1);
/**
*** start/extend 1xn target
*** use same type2 as for in
**/
SA[LINIY(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + di1 + dj1 + iopen + iext_s,
SA[LINIY(idx, j + 1, n2)] + iext_ass + dj1);
/**
*** extend interior loop
**/
SA[LINI(idx, j, n2)] = MIN2(SA[LINI(idx, j, n2)], SA[LINI(idx, j + 1, n2)] + iext_ass + dj1);
SA[LINI(idx, j, n2)] = MIN2(SA[LINI(idx, j, n2)],
SA[LINI(idx_1, j + 1, n2)] + iext_s + di1 + dj1);
/**
*** start/extend bulge target
**/
type2 = pair[S2[j]][S1[i - 1]];
SA[LBXI(idx, j, n2)] = MIN2(SA[LBXI(idx_1, j, n2)] + bext + di1,
SA[LCI(idx_1, j,
n2)] + bopen + bext +
(type2 > 2 ? P->TerminalAU : 0) + di1);
/**
*** start/extend bulge query
**/
type2 = pair[S2[j + 1]][S1[i]];
SA[LBYI(idx, j, n2)] = MIN2(SA[LBYI(idx, j + 1, n2)] + bext + dj1,
SA[LCI(idx, j + 1,
n2)] + bopen + bext +
(type2 > 2 ? P->TerminalAU : 0) + dj1);
/**
***end update recursion
**/
if (!type)
continue; /**
*** stack extension
**/
SA[LCI(idx, j, n2)] += vrna_E_ext_stem(type, SS1[i - 1], SS2[j + 1], P);
/**
*** stack extension
**/
if ((type2 = pair[S1[i - 1]][S2[j + 1]]))
SA[LCI(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->stack[rtype[type]][type2] + di1 + dj1,
SA[LCI(idx, j, n2)]);
/**
*** 1x0 / 0x1 stack extension
**/
if ((type2 = pair[S1[i - 1]][S2[j + 2]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_1, j + 2,
n2)] + P->bulge[1] + P->stack[rtype[type]][type2] + di1 + dj2,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 2]][S2[j + 1]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_2, j + 1,
n2)] + P->bulge[1] + P->stack[type2][rtype[type]] + di2 + dj1,
SA[LCI(idx, j, n2)]);
}
/**
*** 1x1 / 2x2 stack extension
**/
if ((type2 = pair[S1[i - 2]][S2[j + 2]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_2, j + 2,
n2)] + P->int11[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]] + di2 + dj2,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 3]][S2[j + 3]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_3, j + 3,
n2)] +
P->int22[type2][rtype[type]][SS1[i - 2]][SS1[i - 1]][SS2[j + 1]][SS2[j +
2]] + di3 + dj3,
SA[LCI(idx, j, n2)]);
}
/**
*** 1x2 / 2x1 stack extension
*** E_IntLoop(1,2,type2, rtype[type],SS1[i-1], SS2[j+2], SS1[i-1], SS2[j+1], P) corresponds to
*** P->int21[rtype[type]][type2][SS2[j+2]][SS1[i-1]][SS1[i-1]]
**/
if ((type2 = pair[S1[i - 3]][S2[j + 2]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_3, j + 2,
n2)] +
P->int21[rtype[type]][type2][SS2[j + 1]][SS1[i - 2]][SS1[i - 1]] + di3 + dj2,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 2]][S2[j + 3]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_2, j + 3,
n2)] +
P->int21[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + di2 + dj3,
SA[LCI(idx, j, n2)]);
}
/**
*** 2x3 / 3x2 stack extension
**/
if ((type2 = pair[S1[i - 4]][S2[j + 3]])) {
SA[LCI(idx, j, n2)] = MIN2(SA[LCI(idx_4, j + 3, n2)] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 3]][SS2[j + 2]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + di4 + dj3,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 3]][S2[j + 4]])) {
SA[LCI(idx, j, n2)] = MIN2(SA[LCI(idx_3, j + 4, n2)] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 2]][SS2[j + 3]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + di3 + dj4,
SA[LCI(idx, j, n2)]);
}
/**
*** So now we have to handle 1x3, 3x1, 3x3, and mxn m,n > 3
**/
/**
*** 3x3 or more
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINI(idx_3, j + 3,
n2)] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + 2 * iext_s + di3 + dj3,
SA[LCI(idx, j, n2)]);
/**
*** 2xn or more
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINI(idx_4, j + 2,
n2)] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + di4 + dj2,
SA[LCI(idx, j, n2)]);
/**
*** nx2 or more
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINI(idx_2, j + 4,
n2)] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + di2 + dj4,
SA[LCI(idx, j, n2)]);
/**
*** nx1 n>2
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINIX(idx_3, j + 1,
n2)] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + di3 + dj1,
SA[LCI(idx, j, n2)]);
/**
*** 1xn n>2
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINIY(idx_1, j + 3,
n2)] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + dj3 + di1,
SA[LCI(idx, j, n2)]);
/**
*** nx0 n>1
**/
int bAU;
bAU = (type > 2 ? P->TerminalAU : 0);
SA[LCI(idx, j,
n2)] = MIN2(SA[LBXI(idx_2, j + 1, n2)] + di2 + dj1 + bext + bAU, SA[LCI(idx, j, n2)]);
/**
*** 0xn n>1
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LBYI(idx_1, j + 2, n2)] + di1 + dj2 + bext + bAU, SA[LCI(idx, j, n2)]);
temp = min_colonne;
/**
*** (type>2?P->TerminalAU:0)+
*** P->dangle3[rtype[type]][SS1[i+1]]+
*** P->dangle5[rtype[type]][SS2[j-1]],
**/
/*
* remove this line printf("LCI %d:%d %d\t",i,j,SA[LCI(idx,j,n2)]);
* remove this line printf("LI %d:%d %d\t",i,j, SA[LINI(idx,j,n2)]);
*/
min_colonne =
MIN2(SA[LCI(idx, j, n2)] + vrna_E_ext_stem(rtype[type], SS2[j - 1], SS1[i + 1], P),
min_colonne);
if (temp > min_colonne)
min_j_colonne = j;
/* ---------------------------------------------------------------------end update */
}
if (max >= min_colonne) {
max = min_colonne;
max_pos = i;
max_pos_j = min_j_colonne;
}
position[i + delta] = min_colonne;
min_colonne = INF;
position_j[i + delta] = min_j_colonne;
/* remove this line printf("\n"); */
i++;
}
/* printf("MAX: %d",max); */
free(S1);
free(S2);
free(SS1);
free(SS2);
free(SA);
if (max < threshold) {
find_max_XS(position,
position_j,
delta,
threshold,
alignment_length,
s1,
s2,
access_s1,
access_s2,
fast,
il_a,
il_b,
b_a,
b_b);
}
if (max < INF) {
plot_max_XS(max,
max_pos,
max_pos_j,
alignment_length,
s1,
s2,
access_s1,
access_s2,
fast,
il_a,
il_b,
b_a,
b_b);
}
for (i = 0; i <= 3; i++)
free(DJ[i]);
free(DJ);
free(position);
free(position_j);
return NULL;
}
PRIVATE void
find_max_XS(const int *position,
const int *position_j,
const int delta,
const int threshold,
const int alignment_length,
const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
int pos = n1 - 9;
if (fast == 1) {
while (10 < pos--) {
int temp_min = 0;
if (position[pos + delta] < (threshold)) {
int search_range;
search_range = delta + 1;
while (--search_range)
if (position[pos + delta - search_range] <= position[pos + delta - temp_min])
temp_min = search_range;
pos -= temp_min;
int max_pos_j;
max_pos_j = position_j[pos + delta];
int max;
max = position[pos + delta];
printf("target upper bound %d: query lower bound %d (%5.2f) \n",
pos - 10,
max_pos_j - 10,
((double)max) / 100);
pos = MAX2(10, pos + temp_min - delta);
}
}
} else if (fast == 2) {
pos = n1 - 9;
while (10 < pos--) {
int temp_min = 0;
if (position[pos + delta] < (threshold)) {
int search_range;
search_range = delta + 1;
while (--search_range)
if (position[pos + delta - search_range] <= position[pos + delta - temp_min])
temp_min = search_range;
pos -= temp_min;
int max_pos_j;
max_pos_j = position_j[pos + delta];
/* max_pos_j und pos entsprechen die realen position
* in der erweiterten sequenz.
* pos=1 -> position 1 in the sequence (and not 0 like in C)
* max_pos_j -> position 1 in the sequence ( not 0 like in C)
*/
int alignment_length2;
alignment_length2 = MIN2(n1, n2);
int begin_t = MAX2(11, pos - alignment_length2 + 1); /* 10 */
int end_t = MIN2(n1 - 10, pos + 1);
int begin_q = MAX2(11, max_pos_j - 1); /* 10 */
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length2 - 1);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2 + 20));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2 + 20));
strcpy(s3, "NNNNNNNNNN");
strcpy(s4, "NNNNNNNNNN");
strncat(s3, (s1 + begin_t - 1), end_t - begin_t + 1);
strncat(s4, (s2 + begin_q - 1), end_q - begin_q + 1);
strcat(s3, "NNNNNNNNNN");
strcat(s4, "NNNNNNNNNN");
s3[end_t - begin_t + 1 + 20] = '\0';
s4[end_q - begin_q + 1 + 20] = '\0';
duplexT test;
test = fduplexfold_XS(s3,
s4,
access_s1,
access_s2,
end_t,
begin_q,
threshold,
il_a,
il_b,
b_a,
b_b);
if (test.energy * 100 < threshold) {
int l1 = strchr(test.structure, '&') - test.structure;
printf(
" %s %3d,%-3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f) [%5.2f] i:%d,j:%d <%5.2f>\n",
test.structure,
begin_t - 10 + test.i - l1 - 10,
begin_t - 10 + test.i - 1 - 10,
begin_q - 10 + test.j - 1 - 10,
(begin_q - 11) + test.j + (int)strlen(test.structure) - l1 - 2 - 10,
test.ddG,
test.energy,
test.opening_backtrack_x,
test.opening_backtrack_y,
test.energy_backtrack,
pos - 10,
max_pos_j - 10,
((double)position[pos + delta]) / 100);
pos = MAX2(10, pos + temp_min - delta);
free(test.structure);
}
free(s3);
free(s4);
}
}
} else {
pos = n1 - 9;
while (pos-- > 10) {
int temp_min = 0;
if (position[pos + delta] < (threshold)) {
int search_range;
search_range = delta + 1;
while (--search_range)
if (position[pos + delta - search_range] <= position[pos + delta - temp_min])
temp_min = search_range;
pos -= temp_min; /* position on i */
int max_pos_j;
max_pos_j = position_j[pos + delta]; /* position on j */
int begin_t = MAX2(11, pos - alignment_length);
int end_t = MIN2(n1 - 10, pos + 1);
int begin_q = MAX2(11, max_pos_j - 1);
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length - 1);
int i_flag;
int j_flag;
i_flag = (end_t == pos + 1 ? 1 : 0);
j_flag = (begin_q == max_pos_j - 1 ? 1 : 0);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2));
strncpy(s3, (s1 + begin_t), end_t - begin_t + 1);
strncpy(s4, (s2 + begin_q), end_q - begin_q + 1);
s3[end_t - begin_t + 1] = '\0';
s4[end_q - begin_q + 1] = '\0';
duplexT test;
test =
duplexfold_XS(s3, s4, access_s1, access_s2, pos, max_pos_j, threshold, i_flag, j_flag);
if (test.energy * 100 < threshold) {
printf("%s %3d,%-3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f) i:%d,j:%d <%5.2f>\n",
test.structure,
test.tb,
test.te,
test.qb,
test.qe,
test.ddG,
test.energy,
test.dG1,
test.dG2,
pos - 10,
max_pos_j - 10,
((double)position[pos + delta]) / 100);
pos = MAX2(10, pos + temp_min - delta);
}
free(s3);
free(s4);
free(test.structure);
}
}
}
}
#if 0
PRIVATE int
compare(const void *sub1,
const void *sub2)
{
int d;
if (((duplexT *)sub1)->ddG > ((duplexT *)sub2)->ddG)
return 1;
if (((duplexT *)sub1)->ddG < ((duplexT *)sub2)->ddG)
return -1;
d = ((duplexT *)sub1)->i - ((duplexT *)sub2)->i;
if (d != 0)
return d;
return ((duplexT *)sub1)->j - ((duplexT *)sub2)->j;
}
#endif
PRIVATE void
plot_max_XS(const int max,
const int max_pos,
const int max_pos_j,
const int alignment_length,
const char *s1,
const char *s2,
const int **access_s1,
const int **access_s2,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
if (fast == 1) {
printf("target upper bound %d: query lower bound %d (%5.2f)\n", max_pos - 3, max_pos_j,
((double)max) / 100);
} else if (fast == 2) {
int alignment_length2;
alignment_length2 = MIN2(n1, n2);
int begin_t = MAX2(11, max_pos - alignment_length2 + 1); /* 10 */
int end_t = MIN2(n1 - 10, max_pos + 1);
int begin_q = MAX2(11, max_pos_j - 1); /* 10 */
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length2 - 1);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2 + 20));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2 + 20));
strcpy(s3, "NNNNNNNNNN");
strcpy(s4, "NNNNNNNNNN");
strncat(s3, (s1 + begin_t - 1), end_t - begin_t + 1);
strncat(s4, (s2 + begin_q - 1), end_q - begin_q + 1);
strcat(s3, "NNNNNNNNNN");
strcat(s4, "NNNNNNNNNN");
s3[end_t - begin_t + 1 + 20] = '\0';
s4[end_q - begin_q + 1 + 20] = '\0';
duplexT test;
test = fduplexfold_XS(s3, s4, access_s1, access_s2, end_t, begin_q, INF, il_a, il_b, b_a, b_b);
int l1 = strchr(test.structure, '&') - test.structure;
printf("%s %3d,%-3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f) [%5.2f] i:%d,j:%d <%5.2f>\n",
test.structure,
begin_t - 10 + test.i - l1 - 10,
begin_t - 10 + test.i - 1 - 10,
begin_q - 10 + test.j - 1 - 10,
(begin_q - 11) + test.j + (int)strlen(test.structure) - l1 - 2 - 10,
test.ddG,
test.energy,
test.opening_backtrack_x,
test.opening_backtrack_y,
test.energy_backtrack,
max_pos - 10,
max_pos_j - 10,
(double)max / 100);
free(s3);
free(s4);
free(test.structure);
} else {
int begin_t = MAX2(11, max_pos - alignment_length);
int end_t = MIN2(n1 - 10, max_pos + 1);
int begin_q = MAX2(11, max_pos_j - 1);
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length - 1);
int i_flag;
int j_flag;
i_flag = (end_t == max_pos + 1 ? 1 : 0);
j_flag = (begin_q == max_pos_j - 1 ? 1 : 0);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2)); /* +1 for \0 +1 for distance */
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2));
strncpy(s3, (s1 + begin_t - 1), end_t - begin_t + 1); /* -1 to go from */
strncpy(s4, (s2 + begin_q - 1), end_q - begin_q + 1); /* -1 to go from */
s3[end_t - begin_t + 1] = '\0'; /* */
s4[end_q - begin_q + 1] = '\0';
duplexT test;
test = duplexfold_XS(s3, s4, access_s1, access_s2, max_pos, max_pos_j, INF, i_flag, j_flag);
printf("%s %3d,%-3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f) i:%d,j:%d <%5.2f>\n",
test.structure,
test.tb,
test.te,
test.qb,
test.qe,
test.ddG,
test.energy,
test.dG1,
test.dG2,
max_pos - 10,
max_pos_j - 10,
(double)max / 100);
free(s3);
free(s4);
free(test.structure);
}
}
/*---------------------------------------------------------duplexfold----------------------------------------------------------------------------------*/
PRIVATE duplexT
duplexfold(const char *s1,
const char *s2,
const int extension_cost)
{
int i, j, l1, Emin = INF, i_min = 0, j_min = 0;
char *struc;
duplexT mfe;
vrna_md_t md;
n3 = (int)strlen(s1);
n4 = (int)strlen(s2);
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
update_fold_params();
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
c = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
for (i = 0; i <= n3; i++)
c[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
encode_seqs(s1, s2);
for (i = 1; i <= n3; i++) {
for (j = n4; j > 0; j--) {
int type, type2, E, k, l;
type = pair[S1[i]][S2[j]];
c[i][j] = type ? P->DuplexInit + 2 * extension_cost : INF;
if (!type)
continue;
/**
*** if (i>1) c[i][j] += P->dangle5[type][SS1[i-1]]+ extension_cost;
*** if (j<n4) c[i][j] += P->dangle3[type][SS2[j+1]]+ extension_cost;
*** if (type>2) c[i][j] += P->TerminalAU;
**/
c[i][j] += vrna_E_ext_stem(type, (i > 1) ? SS1[i - 1] : -1, (j < n4) ? SS2[j + 1] : -1, P);
for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) {
for (l = j + 1; l <= n4; l++) {
if (i - k + l - j - 2 > MAXLOOP)
break;
type2 = pair[S1[k]][S2[l]];
if (!type2)
continue;
E = E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type],
SS1[k + 1], SS2[l - 1], SS1[i - 1], SS2[j + 1],
P) + (i - k + l - j) * extension_cost;
c[i][j] = MIN2(c[i][j], c[k][l] + E);
}
}
E = c[i][j];
/**
*** if (i<n3) E += P->dangle3[rtype[type]][SS1[i+1]]+extension_cost;
*** if (j>1) E += P->dangle5[rtype[type]][SS2[j-1]]+extension_cost;
*** if (type>2) E += P->TerminalAU;
***
**/
E += vrna_E_ext_stem(rtype[type], (j > 1) ? SS2[j - 1] : -1, (i < n3) ? SS1[i + 1] : -1, P);
if (E < Emin) {
Emin = E;
i_min = i;
j_min = j;
}
}
}
struc = backtrack(i_min, j_min, extension_cost);
if (i_min < n3)
i_min++;
if (j_min > 1)
j_min--;
l1 = strchr(struc, '&') - struc;
int size;
size = strlen(struc) - 1;
Emin -= size * (extension_cost);
mfe.i = i_min;
mfe.j = j_min;
mfe.energy = (double)Emin / 100.;
mfe.structure = struc;
for (i = 0; i <= n3; i++)
free(c[i]);
free(c);
free(S1);
free(S2);
free(SS1);
free(SS2);
return mfe;
}
PRIVATE char *
backtrack(int i,
int j,
const int extension_cost)
{
/* backtrack structure going backwards from i, and forwards from j
* return structure in bracket notation with & as separator */
int k, l, type, type2, E, traced, i0, j0;
char *st1, *st2, *struc;
st1 = (char *)vrna_alloc(sizeof(char) * (n3 + 1));
st2 = (char *)vrna_alloc(sizeof(char) * (n4 + 1));
i0 = MIN2(i + 1, n3);
j0 = MAX2(j - 1, 1);
while (i > 0 && j <= n4) {
E = c[i][j];
traced = 0;
st1[i - 1] = '(';
st2[j - 1] = ')';
type = pair[S1[i]][S2[j]];
if (!type)
vrna_message_error("backtrack failed in fold duplex");
for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) {
for (l = j + 1; l <= n4; l++) {
int LE;
if (i - k + l - j - 2 > MAXLOOP)
break;
type2 = pair[S1[k]][S2[l]];
if (!type2)
continue;
LE = E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type],
SS1[k + 1], SS2[l - 1], SS1[i - 1], SS2[j + 1],
P) + (i - k + l - j) * extension_cost;
if (E == c[k][l] + LE) {
traced = 1;
i = k;
j = l;
break;
}
}
if (traced)
break;
}
if (!traced) {
E -= vrna_E_ext_stem(type, (i > 1) ? SS1[i - 1] : -1, (j < n4) ? SS2[j + 1] : -1, P);
/**
*** if (i>1) E -= P->dangle5[type][SS1[i-1]]+extension_cost;
*** if (j<n4) E -= P->dangle3[type][SS2[j+1]]+extension_cost;
*** if (type>2) E -= P->TerminalAU;
**/
if (E != P->DuplexInit + 2 * extension_cost)
vrna_message_error("backtrack failed in fold duplex");
else
break;
}
}
if (i > 1)
i--;
if (j < n4)
j++;
struc = (char *)vrna_alloc(i0 - i + 1 + j - j0 + 1 + 2);
for (k = MAX2(i, 1); k <= i0; k++)
if (!st1[k - 1])
st1[k - 1] = '.';
for (k = j0; k <= j; k++)
if (!st2[k - 1])
st2[k - 1] = '.';
strcpy(struc, st1 + MAX2(i - 1, 0));
strcat(struc, "&");
strcat(struc, st2 + j0 - 1);
/* printf("%s %3d,%-3d : %3d,%-3d\n", struc, i,i0,j0,j); */
free(st1);
free(st2);
return struc;
}
PRIVATE duplexT
fduplexfold(const char *s1,
const char *s2,
const int extension_cost,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
int i, j, Emin, i_min, j_min, l1;
duplexT mfe;
char *struc;
int bopen = b_b;
int bext = b_a + extension_cost;
int iopen = il_b;
int iext_s = 2 * (il_a + extension_cost); /* iext_s 2 nt nucleotide extension of interior loop, on i and j side */
int iext_ass = 50 + il_a + extension_cost; /* iext_ass assymetric extension of interior loop, either on i or on j side. */
int min_colonne = INF; /* enthaelt das maximum einer kolonne */
int i_length;
int max_pos; /* get position of the best hit */
int max_pos_j;
int temp = INF;
int min_j_colonne;
int max = INF;
vrna_md_t md;
/* FOLLOWING NEXT 4 LINE DEFINES AN ARRAY CONTAINING POSITION OF THE SUBOPT IN S1 */
n3 = (int)strlen(s1);
n4 = (int)strlen(s2);
/*
* delta_check is the minimal distance allowed for two hits to be accepted
* if both hits are closer, reject the smaller ( in term of position) hits
* i want to implement a function that, given a position in a long sequence and a small sequence,
* duplexfold them at this position and report the result at the command line
* for this i first need to rewrite backtrack in order to remove the printf functio
* END OF DEFINITION FOR NEEDED SUBOPT DATA
*/
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
update_fold_params();
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
/*local c array initialization---------------------------------------------*/
c = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
in = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
bx = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
by = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
inx = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
iny = (int **)vrna_alloc(sizeof(int *) * (n3 + 1));
for (i = 0; i <= n3; i++) {
c[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
in[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
bx[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
by[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
inx[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
iny[i] = (int *)vrna_alloc(sizeof(int) * (n4 + 1));
}
/*
* -------------------------------------------------------------------------
* end of array initialisation----------------------------------
*maybe int *** would be better
*/
encode_seqs(s1, s2);
/* ------------------------------------------matrix initialisierung */
for (i = 0; i < n3; i++) {
for (j = 0; j < n4; j++) {
in[i][j] = INF; /* no in before 1 */
c[i][j] = INF; /* no bulge and no in before n2 */
bx[i][j] = INF; /* no bulge before 1 */
by[i][j] = INF;
inx[i][j] = INF; /* no bulge before 1 */
iny[i][j] = INF;
}
}
/*--------------------------------------------------------local array*/
/* -------------------------------------------------------------matrix initialisierung */
i = 11;
i_length = n3 - 9;
while (i < i_length) {
j = n4 - 9;
min_colonne = INF;
while (10 < --j) {
int type, type2;
type = pair[S1[i]][S2[j]];
/**
*** Start duplex
**/
c[i][j] = type ? P->DuplexInit + 2 * extension_cost : INF;
/**
*** update lin bx by linx liny matrix
**/
type2 = pair[S2[j + 1]][S1[i - 1]];
/**
*** start/extend interior loop
**/
in[i][j] =
MIN2(c[i - 1][j + 1] + P->mismatchI[type2][SS2[j]][SS1[i]] + iopen + iext_s,
in[i - 1][j] + iext_ass);
/**
*** start/extend nx1 target
*** use same type2 as for in
**/
inx[i][j] = MIN2(c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s,
inx[i - 1][j] + iext_ass);
/**
*** start/extend 1xn target
*** use same type2 as for in
**/
iny[i][j] = MIN2(c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s,
iny[i][j + 1] + iext_ass);
/**
*** extend interior loop
**/
in[i][j] = MIN2(in[i][j], in[i][j + 1] + iext_ass);
in[i][j] = MIN2(in[i][j], in[i - 1][j + 1] + iext_s);
/**
*** start/extend bulge target
**/
type2 = pair[S2[j]][S1[i - 1]];
bx[i][j] =
MIN2(bx[i - 1][j] + bext, c[i - 1][j] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0));
/**
*** start/extend bulge query
**/
type2 = pair[S2[j + 1]][S1[i]];
by[i][j] =
MIN2(by[i][j + 1] + bext, c[i][j + 1] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0));
/**
***end update recursion
***######################## Start stack extension##############################
**/
if (!type)
continue;
c[i][j] += vrna_E_ext_stem(type, SS1[i - 1], SS2[j + 1], P) + 2 * extension_cost;
/**
*** stack extension
**/
if ((type2 = pair[S1[i - 1]][S2[j + 1]]))
c[i][j] =
MIN2(c[i - 1][j + 1] + P->stack[rtype[type]][type2] + 2 * extension_cost, c[i][j]);
/**
*** 1x0 / 0x1 stack extension
**/
type2 = pair[S1[i - 1]][S2[j + 2]];
c[i][j] = MIN2(
c[i - 1][j + 2] + P->bulge[1] + P->stack[rtype[type]][type2] + 3 * extension_cost,
c[i][j]);
type2 = pair[S1[i - 2]][S2[j + 1]];
c[i][j] = MIN2(
c[i - 2][j + 1] + P->bulge[1] + P->stack[type2][rtype[type]] + 3 * extension_cost,
c[i][j]);
/**
*** 1x1 / 2x2 stack extension
**/
type2 = pair[S1[i - 2]][S2[j + 2]];
c[i][j] = MIN2(
c[i - 2][j + 2] + P->int11[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]] + 4 * extension_cost,
c[i][j]);
type2 = pair[S1[i - 3]][S2[j + 3]];
c[i][j] =
MIN2(c[i - 3][j + 3] +
P->int22[type2][rtype[type]][SS1[i - 2]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + 6 * extension_cost,
c[i][j]);
/**
*** 1x2 / 2x1 stack extension
*** E_IntLoop(1,2,type2, rtype[type],SS1[i-1], SS2[j+2], SS1[i-1], SS2[j+1], P) corresponds to
*** P->int21[rtype[type]][type2][SS2[j+2]][SS1[i-1]][SS1[i-1]]
**/
type2 = pair[S1[i - 3]][S2[j + 2]];
c[i][j] =
MIN2(
c[i - 3][j + 2] + P->int21[rtype[type]][type2][SS2[j + 1]][SS1[i - 2]][SS1[i - 1]] + 5 * extension_cost,
c[i][j]);
type2 = pair[S1[i - 2]][S2[j + 3]];
c[i][j] =
MIN2(
c[i - 2][j + 3] + P->int21[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + 5 * extension_cost,
c[i][j]);
/**
*** 2x3 / 3x2 stack extension
**/
if ((type2 = pair[S1[i - 4]][S2[j + 3]])) {
c[i][j] = MIN2(c[i - 4][j + 3] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 3]][SS2[j + 2]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + 7 * extension_cost,
c[i][j]);
}
if ((type2 = pair[S1[i - 3]][S2[j + 4]])) {
c[i][j] = MIN2(c[i - 3][j + 4] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 2]][SS2[j + 3]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + 7 * extension_cost,
c[i][j]);
}
/**
*** So now we have to handle 1x3, 3x1, 3x3, and mxn m,n > 3
**/
/**
*** 3x3 or more
**/
c[i][j] = MIN2(
in[i - 3][j + 3] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + 2 * iext_s + 2 * extension_cost,
c[i][j]);
/**
*** 2xn or more
**/
c[i][j] = MIN2(
in[i - 4][j + 2] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + 2 * extension_cost,
c[i][j]);
/**
*** nx2 or more
**/
c[i][j] = MIN2(
in[i - 2][j + 4] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + 2 * extension_cost,
c[i][j]);
/**
*** nx1 n>2
**/
c[i][j] = MIN2(
inx[i - 3][j + 1] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + 2 * extension_cost,
c[i][j]);
/**
*** 1xn n>2
**/
c[i][j] = MIN2(
iny[i - 1][j + 3] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + 2 * extension_cost,
c[i][j]);
/**
*** nx0 n>1
**/
int bAU;
bAU = (type > 2 ? P->TerminalAU : 0);
c[i][j] = MIN2(bx[i - 2][j + 1] + 2 * extension_cost + bext + bAU, c[i][j]);
/**
*** 0xn n>1
**/
c[i][j] = MIN2(by[i - 1][j + 2] + 2 * extension_cost + bext + bAU, c[i][j]);
temp = min_colonne;
min_colonne = MIN2(c[i][j] + vrna_E_ext_stem(rtype[type], SS2[j - 1], SS1[i + 1],
P) + 2 * extension_cost,
min_colonne);
if (temp > min_colonne)
min_j_colonne = j;
/* ---------------------------------------------------------------------end update */
}
if (max >= min_colonne) {
max = min_colonne;
max_pos = i;
max_pos_j = min_j_colonne;
}
i++;
}
Emin = max;
i_min = max_pos;
j_min = max_pos_j;
int dGe;
dGe = 0;
struc = fbacktrack(i_min, j_min, extension_cost, il_a, il_b, b_a, b_b, &dGe);
if (i_min < n3 - 10)
i_min++;
if (j_min > 11)
j_min--;
l1 = strchr(struc, '&') - struc;
int size;
size = strlen(struc) - 1;
Emin -= size * (extension_cost);
mfe.i = i_min;
mfe.j = j_min;
mfe.energy = (double)Emin / 100.;
mfe.energy_backtrack = (double)dGe / 100.;
mfe.structure = struc;
free(S1);
free(S2);
free(SS1);
free(SS2);
for (i = 0; i <= n3; i++) {
free(c[i]);
free(in[i]);
free(bx[i]);
free(by[i]);
free(inx[i]);
free(iny[i]);
}
free(c);
free(in);
free(bx);
free(by);
free(inx);
free(iny);
return mfe;
}
PRIVATE char *
fbacktrack(int i,
int j,
const int extension_cost,
const int il_a,
const int il_b,
const int b_a,
const int b_b,
int *dG)
{
/* backtrack structure going backwards from i, and forwards from j
* return structure in bracket notation with & as separator */
int k, l, type, type2, E, traced, i0, j0;
char *st1, *st2, *struc;
int bopen = b_b;
int bext = b_a + extension_cost;
int iopen = il_b;
int iext_s = 2 * (il_a + extension_cost); /* iext_s 2 nt nucleotide extension of interior loop, on i and j side */
int iext_ass = 50 + il_a + extension_cost; /* iext_ass assymetric extension of interior loop, either on i or on j side. */
st1 = (char *)vrna_alloc(sizeof(char) * (n3 + 1));
st2 = (char *)vrna_alloc(sizeof(char) * (n4 + 1));
i0 = MIN2(i + 1, n3 - 10);
j0 = MAX2(j - 1, 11);
int state;
state = 1; /* we start backtracking from a a pair , i.e. c-matrix */
/* state 1 -> base pair, c
* state 2 -> interior loop, in
* state 3 -> bx loop, bx
* state 4 -> by loop, by
*/
traced = 1;
k = i;
l = j;
type = pair[S1[i]][S2[j]];
*dG += vrna_E_ext_stem(rtype[type], SS2[j - 1], SS1[i + 1], P);
/* (type>2?P->TerminalAU:0)+P->dangle3[rtype[type]][SS1[i+1]]+P->dangle5[rtype[type]][SS2[j-1]]; */
while (i > 10 && j <= n4 - 9 && traced) {
traced = 0;
switch (state) {
case 1:
type = pair[S1[i]][S2[j]];
int bAU;
bAU = (type > 2 ? P->TerminalAU : 0);
if (!type)
vrna_message_error("backtrack failed in fold duplex");
type2 = pair[S1[i - 1]][S2[j + 1]];
if (type2 &&
c[i][j] == (c[i - 1][j + 1] + P->stack[rtype[type]][type2] + 2 * extension_cost)) {
k = i - 1;
l = j + 1;
(*dG) += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 1]][S2[j + 2]];
if (type2 &&
c[i][j] ==
(c[i - 1][j + 2] + P->bulge[1] + P->stack[rtype[type]][type2] + 3 * extension_cost)) {
k = i - 1;
l = j + 2;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 2]][S2[j + 1]];
if (type2 &&
c[i][j] ==
(c[i - 2][j + 1] + P->bulge[1] + P->stack[type2][rtype[type]] + 3 * extension_cost)) {
k = i - 2;
l = j + 1;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 2]][S2[j + 2]];
if (type2 &&
c[i][j] ==
(c[i - 2][j + 2] + P->int11[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]] + 4 *
extension_cost)) {
k = i - 2;
l = j + 2;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 3]][S2[j + 3]];
if (type2 &&
c[i][j] ==
(c[i - 3][j + 3] +
P->int22[type2][rtype[type]][SS1[i - 2]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + 6 *
extension_cost)) {
k = i - 3;
l = j + 3;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 3]][S2[j + 2]];
if (type2 &&
c[i][j] ==
(c[i - 3][j + 2] + P->int21[rtype[type]][type2][SS2[j + 1]][SS1[i - 2]][SS1[i - 1]] +
5 *
extension_cost)) {
k = i - 3;
l = j + 2;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 2]][S2[j + 3]];
if (type2 &&
c[i][j] ==
(c[i - 2][j + 3] + P->int21[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] +
5 *
extension_cost)) {
k = i - 2;
l = j + 3;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 4]][S2[j + 3]];
if (type2 && c[i][j] == (c[i - 4][j + 3] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 3]][SS2[j + 2]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + 7 *
extension_cost)) {
k = i - 4;
l = j + 3;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
type2 = pair[S1[i - 3]][S2[j + 4]];
if (type2 && c[i][j] == (c[i - 3][j + 4] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 2]][SS2[j + 3]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + 7 *
extension_cost)) {
k = i - 3;
l = j + 4;
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
st1[i - 1] = '(';
st2[j - 1] = ')';
i = k;
j = l;
state = 1;
traced = 1;
break;
}
if (c[i][j] ==
(in[i - 3][j + 3] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + 2 *
extension_cost +
2 * iext_s)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 3;
j = j + 3;
state = 2;
traced = 1;
break;
}
if (c[i][j] ==
(in[i - 4][j + 2] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 *
iext_ass + 2 * extension_cost)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 4;
j = j + 2;
state = 2;
traced = 1;
break;
}
if (c[i][j] ==
(in[i - 2][j + 4] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 *
iext_ass + 2 * extension_cost)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 2;
j = j + 4;
state = 2;
traced = 1;
break;
}
if (c[i][j] ==
(inx[i - 3][j + 1] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass +
iext_ass + 2 * extension_cost)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 3;
j = j + 1;
state = 5;
traced = 1;
break;
}
if (c[i][j] ==
(iny[i - 1][j + 3] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass +
iext_ass + 2 * extension_cost)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 1;
j = j + 3;
state = 6;
traced = 1;
break;
}
if (c[i][j] == (bx[i - 2][j + 1] + 2 * extension_cost + bext + bAU)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 2;
j = j + 1;
state = 3;
traced = 1;
break;
}
if (c[i][j] == (by[i - 1][j + 2] + 2 * extension_cost + bext + bAU)) {
k = i;
l = j;
st1[i - 1] = '(';
st2[j - 1] = ')';
i = i - 1;
j = j + 2;
state = 4;
traced = 1;
break;
}
break;
case 2:
if (in[i][j] == (in[i - 1][j + 1] + iext_s)) {
i--;
j++;
state = 2;
traced = 1;
break;
}
if (in[i][j] == (in[i - 1][j] + iext_ass)) {
i = i - 1;
state = 2;
traced = 1;
break;
}
if (in[i][j] == (in[i][j + 1] + iext_ass)) {
j++;
state = 2;
traced = 1;
break;
}
type2 = pair[S2[j + 1]][S1[i - 1]];
if (type2 &&
in[i][j] == (c[i - 1][j + 1] + P->mismatchI[type2][SS2[j]][SS1[i]] + iopen + iext_s)) {
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 3:
if (bx[i][j] == (bx[i - 1][j] + bext)) {
i--;
state = 3;
traced = 1;
break;
}
type2 = pair[S2[j]][S1[i - 1]];
if (type2 && bx[i][j] == (c[i - 1][j] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0))) {
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 4:
if (by[i][j] == (by[i][j + 1] + bext)) {
j++;
state = 4;
traced = 1;
break;
}
type2 = pair[S2[j + 1]][S1[i]];
if (type2 && by[i][j] == (c[i][j + 1] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0))) {
int temp;
temp = k;
k = i;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 5:
if (inx[i][j] == (inx[i - 1][j] + iext_ass)) {
i--;
state = 5;
traced = 1;
break;
}
type2 = pair[S2[j + 1]][S1[i - 1]];
if (type2 &&
inx[i][j] ==
(c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s)) {
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
i = k;
j = l;
state = 1;
traced = 1;
break;
}
case 6:
if (iny[i][j] == (iny[i][j + 1] + iext_ass)) {
j++;
state = 6;
traced = 1;
break;
}
type2 = pair[S2[j + 1]][S1[i - 1]];
if (type2 &&
iny[i][j] ==
(c[i - 1][j + 1] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s)) {
int temp;
temp = k;
k = i - 1;
i = temp;
temp = l;
l = j + 1;
j = temp;
type = pair[S1[i]][S2[j]];
*dG += E_IntLoop(i - k - 1,
l - j - 1,
type2,
rtype[type],
SS1[k + 1],
SS2[l - 1],
SS1[i - 1],
SS2[j + 1],
P);
i = k;
j = l;
state = 1;
traced = 1;
break;
}
}
}
if (!traced) {
E = c[i][j];
/**
*** if (i>1) {E -= P->dangle5[type][SS1[i-1]]+extension_cost; *dG+=P->dangle5[type][SS1[i-1]];}
*** if (j<n4){E -= P->dangle3[type][SS2[j+1]]+extension_cost; *dG+=P->dangle3[type][SS2[j+1]];}
*** if (type>2) {E -= P->TerminalAU; *dG+=P->TerminalAU;}
**/
int correction;
correction = vrna_E_ext_stem(type, (i > 1) ? SS1[i - 1] : -1, (j < n4) ? SS2[j + 1] : -1, P);
*dG += correction;
E -= correction + 2 * extension_cost;
if (E != P->DuplexInit + 2 * extension_cost) {
vrna_message_error("backtrack failed in second fold duplex");
} else {
*dG += P->DuplexInit;
st1[i - 1] = '(';
st2[j - 1] = ')';
}
}
if (i > 11)
i--;
if (j < n4 - 10)
j++;
struc = (char *)vrna_alloc(i0 - i + 1 + j - j0 + 1 + 2);
for (k = MAX2(i, 1); k <= i0; k++)
if (!st1[k - 1])
st1[k - 1] = '.';
for (k = j0; k <= j; k++)
if (!st2[k - 1])
st2[k - 1] = '.';
strcpy(struc, st1 + MAX2(i - 1, 0));
strcat(struc, "&");
strcat(struc, st2 + j0 - 1);
/* printf("%s %3d,%-3d : %3d,%-3d\n", struc, i,i0,j0,j); */
free(st1);
free(st2);
return struc;
}
duplexT **
Lduplexfold(const char *s1,
const char *s2,
const int threshold,
const int extension_cost,
const int alignment_length,
const int delta,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
/**
*** See variable definition in fduplexfold_XS
**/
int i, j;
int bopen = b_b;
int bext = b_a + extension_cost;
int iopen = il_b;
int iext_s = 2 * (il_a + extension_cost); /* iext_s 2 nt nucleotide extension of interior loop, on i and j side */
int iext_ass = 50 + il_a + extension_cost; /* iext_ass assymetric extension of interior loop, either on i or on j side. */
int min_colonne = INF; /* enthaelt das maximum einer kolonne */
int i_length;
int max_pos; /* get position of the best hit */
int max_pos_j;
int temp = INF;
int min_j_colonne;
int max = INF;
int *position; /* contains the position of the hits with energy > E */
int *position_j;
/**
*** 1D array corresponding to the standard 2d recursion matrix
*** Makes the computation 20% faster
**/
int *SA;
vrna_md_t md;
/**
*** variable initialization
**/
n1 = (int)strlen(s1);
n2 = (int)strlen(s2);
/**
*** Sequence encoding
**/
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
update_fold_params();
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
encode_seqs(s1, s2);
/**
*** Position of the high score on the target and query sequence
**/
position = (int *)vrna_alloc((delta + n1 + 3 + delta) * sizeof(int));
position_j = (int *)vrna_alloc((delta + n1 + 3 + delta) * sizeof(int));
/**
*** instead of having 4 2-dim arrays we use a unique 1-dim array
*** The mapping 2d -> 1D is done based ont the macro
*** LCI(i,j,l) ((i )*l + j)
*** LINI(i,j,l) ((i + 5)*l + j)
*** LBXI(i,j,l) ((i + 10)*l + j)
*** LBYI(i,j,l) ((i + 15)*l + j)
*** LINIX(i,j,l) ((i + 20)*l + j)
*** LINIY(i,j,l) ((i + 25)*l + j)
***
*** SA has a length of 5 (number of columns we look back) *
*** * 6 (number of structures we look at) *
*** * length of the sequence
**/
SA = (int *)vrna_alloc(sizeof(int) * 5 * 6 * (n2 + 5));
for (j = n2 + 4; j >= 0; j--) {
SA[(j *
30)] =
SA[(j * 30) + 1] = SA[(j * 30) + 2] = SA[(j * 30) + 3] = SA[(j * 30) + 4] = INF;
SA[(j * 30) +
5] =
SA[(j * 30) + 1 +
5] =
SA[(j * 30) + 2 + 5] = SA[(j * 30) + 3 + 5] = SA[(j * 30) + 4 + 5] = INF;
SA[(j * 30) +
10] =
SA[(j * 30) + 1 +
10] =
SA[(j * 30) + 2 + 10] = SA[(j * 30) + 3 + 10] = SA[(j * 30) + 4 + 10] = INF;
SA[(j * 30) +
15] =
SA[(j * 30) + 1 +
15] =
SA[(j * 30) + 2 + 15] = SA[(j * 30) + 3 + 15] = SA[(j * 30) + 4 + 15] = INF;
SA[(j * 30) +
20] =
SA[(j * 30) + 1 +
20] =
SA[(j * 30) + 2 + 20] = SA[(j * 30) + 3 + 20] = SA[(j * 30) + 4 + 20] = INF;
SA[(j * 30) +
25] =
SA[(j * 30) + 1 +
25] =
SA[(j * 30) + 2 + 25] = SA[(j * 30) + 3 + 25] = SA[(j * 30) + 4 + 25] = INF;
}
i = 10;
i_length = n1 - 9;
while (i < i_length) {
int idx = i % 5;
int idx_1 = (i - 1) % 5;
int idx_2 = (i - 2) % 5;
int idx_3 = (i - 3) % 5;
int idx_4 = (i - 4) % 5;
j = n2 - 9;
while (9 < --j) {
int type, type2;
type = pair[S1[i]][S2[j]];
/**
*** Start duplex
**/
SA[LCI(idx, j, n2)] = type ? P->DuplexInit + 2 * extension_cost : INF;
/**
*** update lin bx by linx liny matrix
**/
type2 = pair[S2[j + 1]][S1[i - 1]];
/**
*** start/extend interior loop
**/
SA[LINI(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->mismatchI[type2][SS2[j]][SS1[i]] + iopen + iext_s,
SA[LINI(idx_1, j, n2)] + iext_ass);
/**
*** start/extend nx1 target
*** use same type2 as for in
**/
SA[LINIX(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s,
SA[LINIX(idx_1, j, n2)] + iext_ass);
/**
*** start/extend 1xn target
*** use same type2 as for in
**/
SA[LINIY(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->mismatch1nI[type2][SS2[j]][SS1[i]] + iopen + iext_s,
SA[LINIY(idx, j + 1, n2)] + iext_ass);
/**
*** extend interior loop
**/
SA[LINI(idx, j, n2)] = MIN2(SA[LINI(idx, j, n2)], SA[LINI(idx, j + 1, n2)] + iext_ass);
SA[LINI(idx, j, n2)] = MIN2(SA[LINI(idx, j, n2)], SA[LINI(idx_1, j + 1, n2)] + iext_s);
/**
*** start/extend bulge target
**/
type2 = pair[S2[j]][S1[i - 1]];
SA[LBXI(idx, j, n2)] = MIN2(SA[LBXI(idx_1, j, n2)] + bext,
SA[LCI(idx_1, j,
n2)] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0));
/**
*** start/extend bulge query
**/
type2 = pair[S2[j + 1]][S1[i]];
SA[LBYI(idx, j, n2)] = MIN2(SA[LBYI(idx, j + 1, n2)] + bext,
SA[LCI(idx, j + 1,
n2)] + bopen + bext + (type2 > 2 ? P->TerminalAU : 0));
/**
***end update recursion
***##################### Start stack extension ######################
**/
if (!type)
continue; /**
*** stack extension
**/
SA[LCI(idx, j, n2)] += vrna_E_ext_stem(type, SS1[i - 1], SS2[j + 1], P) + 2 * extension_cost;
/**
*** stack extension
**/
if ((type2 = pair[S1[i - 1]][S2[j + 1]]))
SA[LCI(idx, j, n2)] = MIN2(SA[LCI(idx_1, j + 1,
n2)] + P->stack[rtype[type]][type2] + 2 * extension_cost,
SA[LCI(idx, j, n2)]);
/**
*** 1x0 / 0x1 stack extension
**/
if ((type2 = pair[S1[i - 1]][S2[j + 2]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_1, j + 2,
n2)] + P->bulge[1] + P->stack[rtype[type]][type2] + 3 * extension_cost,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 2]][S2[j + 1]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_2, j + 1,
n2)] + P->bulge[1] + P->stack[type2][rtype[type]] + 3 * extension_cost,
SA[LCI(idx, j, n2)]);
}
/**
*** 1x1 / 2x2 stack extension
**/
if ((type2 = pair[S1[i - 2]][S2[j + 2]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_2, j + 2,
n2)] + P->int11[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]] + 4 * extension_cost,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 3]][S2[j + 3]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_3, j + 3,
n2)] +
P->int22[type2][rtype[type]][SS1[i - 2]][SS1[i - 1]][SS2[j + 1]][SS2[j +
2]] + 6 * extension_cost,
SA[LCI(idx, j, n2)]);
}
/**
*** 1x2 / 2x1 stack extension
*** E_IntLoop(1,2,type2, rtype[type],SS1[i-1], SS2[j+2], SS1[i-1], SS2[j+1], P) corresponds to
*** P->int21[rtype[type]][type2][SS2[j+2]][SS1[i-1]][SS1[i-1]]
**/
if ((type2 = pair[S1[i - 3]][S2[j + 2]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_3, j + 2,
n2)] +
P->int21[rtype[type]][type2][SS2[j + 1]][SS1[i - 2]][SS1[i - 1]] + 5 * extension_cost,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 2]][S2[j + 3]])) {
SA[LCI(idx, j,
n2)] = MIN2(SA[LCI(idx_2, j + 3,
n2)] +
P->int21[type2][rtype[type]][SS1[i - 1]][SS2[j + 1]][SS2[j + 2]] + 5 * extension_cost,
SA[LCI(idx, j, n2)]);
}
/**
*** 2x3 / 3x2 stack extension
**/
if ((type2 = pair[S1[i - 4]][S2[j + 3]])) {
SA[LCI(idx, j, n2)] = MIN2(SA[LCI(idx_4, j + 3,
n2)] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 3]][SS2[j + 2]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + 7 * extension_cost,
SA[LCI(idx, j, n2)]);
}
if ((type2 = pair[S1[i - 3]][S2[j + 4]])) {
SA[LCI(idx, j, n2)] = MIN2(SA[LCI(idx_3, j + 4,
n2)] + P->internal_loop[5] + P->ninio[2] +
P->mismatch23I[type2][SS1[i - 2]][SS2[j + 3]] +
P->mismatch23I[rtype[type]][SS2[j + 1]][SS1[i - 1]] + 7 * extension_cost,
SA[LCI(idx, j, n2)]);
}
/**
*** So now we have to handle 1x3, 3x1, 3x3, and mxn m,n > 3
**/
/**
*** 3x3 or more
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINI(idx_3, j + 3,
n2)] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + 2 * iext_s + 2 * extension_cost,
SA[LCI(idx, j, n2)]);
/**
*** 2xn or more
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINI(idx_4, j + 2,
n2)] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + 2 * extension_cost,
SA[LCI(idx, j, n2)]);
/**
*** nx2 or more
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINI(idx_2, j + 4,
n2)] + P->mismatchI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_s + 2 * iext_ass + 2 * extension_cost,
SA[LCI(idx, j, n2)]);
/**
*** nx1 n>2
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINIX(idx_3, j + 1,
n2)] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + 2 * extension_cost,
SA[LCI(idx, j, n2)]);
/**
*** 1xn n>2
**/
SA[LCI(idx, j,
n2)] = MIN2(SA[LINIY(idx_1, j + 3,
n2)] + P->mismatch1nI[rtype[type]][SS1[i - 1]][SS2[j + 1]] + iext_ass + iext_ass + 2 * extension_cost,
SA[LCI(idx, j, n2)]);
/**
*** nx0 n>1
**/
int bAU;
bAU = (type > 2 ? P->TerminalAU : 0);
SA[LCI(idx, j,
n2)] =
MIN2(SA[LBXI(idx_2, j + 1, n2)] + 2 * extension_cost + bext + bAU, SA[LCI(idx, j, n2)]);
/**
*** 0xn n>1
**/
SA[LCI(idx, j,
n2)] =
MIN2(SA[LBYI(idx_1, j + 2, n2)] + 2 * extension_cost + bext + bAU, SA[LCI(idx, j, n2)]);
temp = min_colonne;
min_colonne = MIN2(SA[LCI(idx, j, n2)] + vrna_E_ext_stem(rtype[type], SS2[j - 1], SS1[i + 1],
P) + 2 * extension_cost,
min_colonne);
if (temp > min_colonne)
min_j_colonne = j;
}
if (max >= min_colonne) {
max = min_colonne;
max_pos = i;
max_pos_j = min_j_colonne;
}
position[i + delta] = min_colonne;
min_colonne = INF;
position_j[i + delta] = min_j_colonne;
i++;
}
/* printf("MAX: %d",max); */
free(S1);
free(S2);
free(SS1);
free(SS2);
if (max < threshold) {
find_max(position,
position_j,
delta,
threshold,
alignment_length,
s1,
s2,
extension_cost,
fast,
il_a,
il_b,
b_a,
b_b);
}
if (max < INF) {
plot_max(max,
max_pos,
max_pos_j,
alignment_length,
s1,
s2,
extension_cost,
fast,
il_a,
il_b,
b_a,
b_b);
}
free(SA);
free(position);
free(position_j);
return NULL;
}
PRIVATE void
find_max(const int *position,
const int *position_j,
const int delta,
const int threshold,
const int alignment_length,
const char *s1,
const char *s2,
const int extension_cost,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
int pos = n1 - 9;
if (fast == 1) {
while (10 < pos--) {
int temp_min = 0;
if (position[pos + delta] < (threshold)) {
int search_range;
search_range = delta + 1;
while (--search_range)
if (position[pos + delta - search_range] <= position[pos + delta - temp_min])
temp_min = search_range;
pos -= temp_min;
int max_pos_j;
max_pos_j = position_j[pos + delta];
int max;
max = position[pos + delta];
printf("target upper bound %d: query lower bound %d (%5.2f) \n",
pos - 10,
max_pos_j - 10,
((double)max) / 100);
pos = MAX2(10, pos + temp_min - delta);
}
}
} else if (fast == 2) {
pos = n1 - 9;
while (10 < pos--) {
int temp_min = 0;
if (position[pos + delta] < (threshold)) {
int search_range;
search_range = delta + 1;
while (--search_range)
if (position[pos + delta - search_range] <= position[pos + delta - temp_min])
temp_min = search_range;
pos -= temp_min;
int max_pos_j;
max_pos_j = position_j[pos + delta];
/* max_pos_j und pos entsprechen die realen position
* in der erweiterten sequenz.
* pos=1 -> position 1 in the sequence (and not 0 like in C)
* max_pos_j -> position 1 in the sequence ( not 0 like in C)
*/
int alignment_length2;
alignment_length2 = MIN2(n1, n2);
int begin_t = MAX2(11, pos - alignment_length2 + 1); /* 10 */
int end_t = MIN2(n1 - 10, pos + 1);
int begin_q = MAX2(11, max_pos_j - 1); /* 10 */
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length2 - 1);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2 + 20));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2 + 20));
strcpy(s3, "NNNNNNNNNN");
strcpy(s4, "NNNNNNNNNN");
strncat(s3, (s1 + begin_t - 1), end_t - begin_t + 1);
strncat(s4, (s2 + begin_q - 1), end_q - begin_q + 1);
strcat(s3, "NNNNNNNNNN");
strcat(s4, "NNNNNNNNNN");
s3[end_t - begin_t + 1 + 20] = '\0';
s4[end_q - begin_q + 1 + 20] = '\0';
duplexT test;
test = fduplexfold(s3, s4, extension_cost, il_a, il_b, b_a, b_b);
if (test.energy * 100 < threshold) {
int l1 = strchr(test.structure, '&') - test.structure;
printf("%s %3d,%-3d : %3d,%-3d (%5.2f) [%5.2f] i:%d,j:%d <%5.2f>\n", test.structure,
begin_t - 10 + test.i - l1 - 10,
begin_t - 10 + test.i - 1 - 10,
begin_q - 10 + test.j - 1 - 10,
(begin_q - 11) + test.j + (int)strlen(test.structure) - l1 - 2 - 10,
test.energy, test.energy_backtrack, pos - 10, max_pos_j - 10,
((double)position[pos + delta]) / 100);
pos = MAX2(10, pos + temp_min - delta);
}
free(s3);
free(s4);
free(test.structure);
}
}
}
#if 0
else if (fast == 3) {
pos = n1 - 9;
while (10 < pos--) {
int temp_min = 0;
if (position[pos + delta] < (threshold)) {
int search_range;
search_range = delta + 1;
while (--search_range)
if (position[pos + delta - search_range] <= position[pos + delta - temp_min])
temp_min = search_range;
pos -= temp_min;
int max_pos_j;
max_pos_j = position_j[pos + delta];
/* max_pos_j und pos entsprechen die realen position
* in der erweiterten sequenz.
* pos=1 -> position 1 in the sequence (and not 0 like in C)
* max_pos_j -> position 1 in the sequence ( not 0 like in C)
*/
//Here we can start the reverse recursion for the
//Starting from the reported pos / max_pos_j we start the recursion
//We have to be careful with the fact that all energies are inverted.
int alignment_length2;
//Select the smallest interaction length in order to define the new interaction length
alignment_length2 = MIN2(n1 - pos + 1, max_pos_j - 1 + 1);
//
int begin_t = MAX2(11, pos - alignment_length2 + 1); /* 10 */
int end_t = MIN2(n1 - 10, pos + 1);
int begin_q = MAX2(11, max_pos_j - 1); /* 10 */
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length2 - 1);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2 + 20));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2 + 20));
strcpy(s3, "NNNNNNNNNN");
strcpy(s4, "NNNNNNNNNN");
strncat(s3, (s1 + begin_t - 1), end_t - begin_t + 1);
strncat(s4, (s2 + begin_q - 1), end_q - begin_q + 1);
strcat(s3, "NNNNNNNNNN");
strcat(s4, "NNNNNNNNNN");
s3[end_t - begin_t + 1 + 20] = '\0';
s4[end_q - begin_q + 1 + 20] = '\0';
duplexT test;
test = fduplexfold(s4, s3, extension_cost, il_a, il_b, b_a, b_b);
if (test.energy * 100 < threshold) {
int structureLength = strlen(test.structure);
int l1 = strchr(test.structure, '&') - test.structure;
int start_t, end_t, start_q, end_q;
/*reverse structure string*/
char *reverseStructure = (char *)vrna_alloc(sizeof(char) * (structureLength + 1));
int posStructure;
for (posStructure = l1 + 1; posStructure < structureLength; posStructure++) {
if (test.structure[posStructure] == ')')
reverseStructure[posStructure - l1 - 1] = '(';
else
reverseStructure[posStructure - l1 - 1] = test.structure[posStructure];
}
reverseStructure[structureLength - 1 - l1] = '&';
for (posStructure = 0; posStructure < l1; posStructure++) {
if (test.structure[posStructure] == '(')
reverseStructure[structureLength + posStructure - l1] = ')';
else
reverseStructure[structureLength + posStructure - l1] = test.structure[posStructure];
}
reverseStructure[structureLength] = '\0';
// l1=strchr(reverse.structure, '&')-test.structure;
printf("%s %3d,%-3d : %3d,%-3d (%5.2f) [%5.2f] i:%d,j:%d <%5.2f>\n",
reverseStructure,
begin_t - 10 + test.j - 1 - 10,
(begin_t - 11) + test.j + strlen(test.structure) - l1 - 2 - 10,
begin_q - 10 + test.i - l1 - 10,
begin_q - 10 + test.i - 1 - 10,
test.energy,
test.energy_backtrack,
pos,
max_pos_j,
((double)position[pos + delta]) / 100);
pos = MAX2(10, pos + temp_min - delta);
}
free(s3);
free(s4);
free(test.structure);
}
}
}
#endif
else {
pos = n1 - 9;
while (10 < pos--) {
int temp_min = 0;
if (position[pos + delta] < (threshold)) {
int search_range;
search_range = delta + 1;
while (--search_range)
if (position[pos + delta - search_range] <= position[pos + delta - temp_min])
temp_min = search_range;
pos -= temp_min;
int max_pos_j;
max_pos_j = position_j[pos + delta];
/* max_pos_j und pos entsprechen die realen position
* in der erweiterten sequenz.
* pos=1 -> position 1 in the sequence (and not 0 like in C)
* max_pos_j -> position 1 in the sequence ( not 0 like in C)
*/
int alignment_length2;
alignment_length2 = MIN2(n1, n2);
int begin_t = MAX2(11, pos - alignment_length2 + 1); /* 10 */
int end_t = MIN2(n1 - 10, pos + 1);
int begin_q = MAX2(11, max_pos_j - 1); /* 10 */
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length2 - 1);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2));
strncpy(s3, (s1 + begin_t - 1), end_t - begin_t + 1);
strncpy(s4, (s2 + begin_q - 1), end_q - begin_q + 1);
s3[end_t - begin_t + 1] = '\0';
s4[end_q - begin_q + 1] = '\0';
duplexT test;
test = duplexfold(s3, s4, extension_cost);
if (test.energy * 100 < threshold) {
int l1 = strchr(test.structure, '&') - test.structure;
printf("%s %3d,%-3d : %3d,%-3d (%5.2f) i:%d,j:%d <%5.2f>\n", test.structure,
begin_t - 10 + test.i - l1,
begin_t - 10 + test.i - 1,
begin_q - 10 + test.j - 1,
(begin_q - 11) + test.j + (int)strlen(test.structure) - l1 - 2,
test.energy, pos - 10, max_pos_j - 10, ((double)position[pos + delta]) / 100);
pos = MAX2(10, pos + temp_min - delta);
}
free(s3);
free(s4);
free(test.structure);
}
}
}
}
PRIVATE void
plot_max(const int max,
const int max_pos,
const int max_pos_j,
const int alignment_length,
const char *s1,
const char *s2,
const int extension_cost,
const int fast,
const int il_a,
const int il_b,
const int b_a,
const int b_b)
{
if (fast == 1) {
printf("target upper bound %d: query lower bound %d (%5.2f)\n", max_pos - 10, max_pos_j - 10,
((double)max) / 100);
} else if (fast == 2) {
int alignment_length2;
alignment_length2 = MIN2(n1, n2);
int begin_t = MAX2(11, max_pos - alignment_length2 + 1); /* 10 */
int end_t = MIN2(n1 - 10, max_pos + 1);
int begin_q = MAX2(11, max_pos_j - 1); /* 10 */
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length2 - 1);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2 + 20));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2 + 20));
strcpy(s3, "NNNNNNNNNN");
strcpy(s4, "NNNNNNNNNN");
strncat(s3, (s1 + begin_t - 1), end_t - begin_t + 1);
strncat(s4, (s2 + begin_q - 1), end_q - begin_q + 1);
strcat(s3, "NNNNNNNNNN");
strcat(s4, "NNNNNNNNNN");
s3[end_t - begin_t + 1 + 20] = '\0';
s4[end_q - begin_q + 1 + 20] = '\0';
duplexT test;
test = fduplexfold(s3, s4, extension_cost, il_a, il_b, b_a, b_b);
int l1 = strchr(test.structure, '&') - test.structure;
printf("%s %3d,%-3d : %3d,%-3d (%5.2f) [%5.2f] i:%d,j:%d <%5.2f>\n", test.structure,
begin_t - 10 + test.i - l1 - 10,
begin_t - 10 + test.i - 1 - 10,
begin_q - 10 + test.j - 1 - 10,
(begin_q - 11) + test.j + (int)strlen(test.structure) - l1 - 2 - 10,
test.energy, test.energy_backtrack, max_pos - 10, max_pos_j - 10, ((double)max) / 100);
free(s3);
free(s4);
free(test.structure);
} else {
duplexT test;
int alignment_length2;
alignment_length2 = MIN2(n1, n2);
int begin_t = MAX2(11, max_pos - alignment_length2 + 1);
int end_t = MIN2(n1 - 10, max_pos + 1);
int begin_q = MAX2(11, max_pos_j - 1);
int end_q = MIN2(n2 - 10, max_pos_j + alignment_length2 - 1);
char *s3 = (char *)vrna_alloc(sizeof(char) * (end_t - begin_t + 2));
char *s4 = (char *)vrna_alloc(sizeof(char) * (end_q - begin_q + 2));
strncpy(s3, (s1 + begin_t - 1), end_t - begin_t + 1);
strncpy(s4, (s2 + begin_q - 1), end_q - begin_q + 1);
s3[end_t - begin_t + 1] = '\0';
s4[end_q - begin_q + 1] = '\0';
test = duplexfold(s3, s4, extension_cost);
int l1 = strchr(test.structure, '&') - test.structure;
printf("%s %3d,%-3d : %3d,%-3d (%5.2f) i:%d,j:%d <%5.2f>\n", test.structure,
begin_t - 10 + test.i - l1,
begin_t - 10 + test.i - 1,
begin_q - 10 + test.j - 1,
(begin_q - 11) + test.j + (int)strlen(test.structure) - l1 - 2,
test.energy, max_pos - 10, max_pos_j - 10, ((double)max) / 100);
free(s3);
free(s4);
free(test.structure);
}
}
PRIVATE void
update_dfold_params(void)
{
vrna_md_t md;
if (P)
free(P);
set_model_details(&md);
P = vrna_params(&md);
make_pair_matrix();
}
PRIVATE void
encode_seqs(const char *s1,
const char *s2)
{
unsigned int i, l;
l = strlen(s1);
S1 = encode_seq(s1);
SS1 = (short *)vrna_alloc(sizeof(short) * (l + 1));
/* SS1 exists only for the special X K and I bases and energy_set!=0 */
for (i = 1; i <= l; i++) /* make numerical encoding of sequence */
SS1[i] = alias[S1[i]]; /* for mismatches of nostandard bases */
l = strlen(s2);
S2 = encode_seq(s2);
SS2 = (short *)vrna_alloc(sizeof(short) * (l + 1));
/* SS2 exists only for the special X K and I bases and energy_set!=0 */
for (i = 1; i <= l; i++) /* make numerical encoding of sequence */
SS2[i] = alias[S2[i]]; /* for mismatches of nostandard bases */
}
PRIVATE short *
encode_seq(const char *sequence)
{
unsigned int i, l;
short *S;
l = strlen(sequence);
S = (short *)vrna_alloc(sizeof(short) * (l + 2));
S[0] = (short)l;
/* make numerical encoding of sequence */
for (i = 1; i <= l; i++)
S[i] = (short)encode_char(toupper(sequence[i - 1]));
/* for circular folding add first base at position n+1 */
S[l + 1] = S[1];
return S;
}
int
arraySize(duplexT **array)
{
int site_count = 0;
while (array[site_count] != NULL)
site_count++;
return site_count;
}
void
freeDuplexT(duplexT **array)
{
int size = arraySize(array);
while (--size) {
free(array[size]->structure);
free(array[size]);
}
free(array[0]->structure);
free(array);
}
|
eigenproblem.h | // Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file eigenproblem.h
*
* \brief Contains definition and implementaiton of various eigenvalue solver interfaces.
*/
#ifndef __EIGENPROBLEM_H__
#define __EIGENPROBLEM_H__
#include "constants.h"
#include "linalg.hpp"
/// Type of the solver to use for the standard or generalized eigen-value problem
enum ev_solver_t
{
/// use LAPACK
ev_lapack,
/// use ScaLAPACK
ev_scalapack,
/// use ELPA1 solver
ev_elpa1,
/// use ELPA2 (2-stage) solver
ev_elpa2,
/// use MAGMA
ev_magma,
/// use PLASMA
ev_plasma,
ev_rs_gpu,
ev_rs_cpu
};
/// Base class for eigen-value problems.
class Eigenproblem
{
public:
virtual ~Eigenproblem()
{
}
/// Complex generalized Hermitian-definite eigenproblem.
virtual int solve(int32_t matrix_size,
int32_t nevec,
double_complex* A,
int32_t lda,
double_complex* B,
int32_t ldb,
double* eval,
double_complex* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
TERMINATE("solver is not implemented");
return -1;
}
/// Real generalized symmetric-definite eigenproblem.
virtual int solve(int32_t matrix_size,
int32_t nevec,
double* A,
int32_t lda,
double* B,
int32_t ldb,
double* eval,
double* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
TERMINATE("solver is not implemented");
return -1;
}
/// Complex standard Hermitian-definite eigenproblem with with N lowest eigen-vectors.
virtual int solve(int32_t matrix_size,
int32_t nevec,
double_complex* A,
int32_t lda,
double* eval,
double_complex* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
TERMINATE("solver is not implemented");
return -1;
}
/// Real standard symmetric-definite eigenproblem with N lowest eigen-vectors.
virtual int solve(int32_t matrix_size,
int32_t nevec,
double* A,
int32_t lda,
double* eval,
double* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
TERMINATE("solver is not implemented");
return -1;
}
/// Complex standard Hermitian-definite eigenproblem with all eigen-vectors.
virtual int solve(int32_t matrix_size,
double_complex* A,
int32_t lda,
double* eval,
double_complex* Z,
int32_t ldz) const
{
TERMINATE("standard eigen-value solver is not configured");
return -1;
}
/// Real standard symmetric-definite eigenproblem with all eigen-vectors.
virtual int solve(int32_t matrix_size,
double* A,
int32_t lda,
double* eval,
double* Z,
int32_t ldz) const
{
TERMINATE("standard eigen-value solver is not configured");
return -1;
}
virtual bool parallel() const = 0;
virtual ev_solver_t type() const = 0;
};
/// Interface for LAPACK eigen-value solvers.
class Eigenproblem_lapack: public Eigenproblem
{
private:
double abstol_;
std::vector<int32_t> get_work_sizes(int32_t matrix_size) const
{
std::vector<int32_t> work_sizes(3);
work_sizes[0] = 2 * matrix_size + matrix_size * matrix_size;
work_sizes[1] = 1 + 5 * matrix_size + 2 * matrix_size * matrix_size;
work_sizes[2] = 3 + 5 * matrix_size;
return work_sizes;
}
public:
Eigenproblem_lapack(double abstol__ = 1e-12) : abstol_(abstol__)
{
}
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double_complex* B, int32_t ldb,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int nb = linalg_base::ilaenv(1, "ZHETRD", "U", matrix_size, 0, 0, 0);
int lwork = (nb + 1) * matrix_size;
int lrwork = 7 * matrix_size;
int liwork = 5 * matrix_size;
std::vector<double_complex> work(lwork);
std::vector<double> rwork(lrwork);
std::vector<int32_t> iwork(liwork);
std::vector<int32_t> ifail(matrix_size);
std::vector<double> w(matrix_size);
double vl = 0.0;
double vu = 0.0;
int32_t m;
int32_t info;
int32_t ione = 1;
FORTRAN(zhegvx)(&ione, "V", "I", "U", &matrix_size, A, &lda, B, &ldb, &vl, &vu, &ione, &nevec, const_cast<double*>(&abstol_), &m,
&w[0], Z, &ldz, &work[0], &lwork, &rwork[0], &iwork[0], &ifail[0], &info, (int32_t)1,
(int32_t)1, (int32_t)1);
if (m != nevec)
{
std::stringstream s;
s << "not all eigen-values are found" << std::endl
<< "target number of eign-values: " << nevec << std::endl
<< "number of eign-values found: " << m << std::endl
<< "matrix size: " << matrix_size;
WARNING(s);
return 1;
}
if (info)
{
std::stringstream s;
s << "zhegvx returned " << info;
TERMINATE(s);
}
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* B, int32_t ldb,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int nb = linalg_base::ilaenv(1, "DSYTRD", "U", matrix_size, 0, 0, 0);
int lwork = (nb + 3) * matrix_size + 1024;
int liwork = 5 * matrix_size;
std::vector<double> work(lwork);
std::vector<int32_t> iwork(liwork);
std::vector<int32_t> ifail(matrix_size);
std::vector<double> w(matrix_size);
double vl = 0.0;
double vu = 0.0;
int32_t m;
int32_t info;
int32_t ione = 1;
FORTRAN(dsygvx)(&ione, "V", "I", "U", &matrix_size, A, &lda, B, &ldb, &vl, &vu, &ione, &nevec, const_cast<double*>(&abstol_), &m,
&w[0], Z, &ldz, &work[0], &lwork, &iwork[0], &ifail[0], &info, (int32_t)1,
(int32_t)1, (int32_t)1);
if (m != nevec)
{
//== std::stringstream s;
//== s << "not all eigen-values are found" << std::endl
//== << "target number of eign-values: " << nevec << std::endl
//== << "number of eign-values found: " << m;
//== WARNING(s);
return 1;
}
if (info)
{
std::stringstream s;
s << "dsygvx returned " << info;
TERMINATE(s);
}
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
int solve(int32_t matrix_size, double_complex* A, int32_t lda, double* eval, double_complex* Z, int32_t ldz) const
{
std::vector<int32_t> work_sizes = get_work_sizes(matrix_size);
std::vector<double_complex> work(work_sizes[0]);
std::vector<double> rwork(work_sizes[1]);
std::vector<int32_t> iwork(work_sizes[2]);
int32_t info;
FORTRAN(zheevd)("V", "U", &matrix_size, A, &lda, eval, &work[0], &work_sizes[0], &rwork[0], &work_sizes[1],
&iwork[0], &work_sizes[2], &info, (int32_t)1, (int32_t)1);
for (int i = 0; i < matrix_size; i++)
std::memcpy(&Z[ldz * i], &A[lda * i], matrix_size * sizeof(double_complex));
if (info)
{
std::stringstream s;
s << "zheevd returned " << info;
TERMINATE(s);
}
return 0;
}
int solve(int32_t matrix_size, double* A, int32_t lda, double* eval, double* Z, int32_t ldz) const
{
std::vector<int32_t> work_sizes = get_work_sizes(matrix_size);
int32_t lwork = 1 + 6 * matrix_size + 2 * matrix_size * matrix_size;
int32_t liwork = 3 + 5 * matrix_size;
std::vector<double> work(lwork);
std::vector<int32_t> iwork(liwork);
int32_t info;
FORTRAN(dsyevd)("V", "U", &matrix_size, A, &lda, eval, &work[0], &lwork,
&iwork[0], &liwork, &info, (int32_t)1, (int32_t)1);
for (int i = 0; i < matrix_size; i++)
std::memcpy(&Z[ldz * i], &A[lda * i], matrix_size * sizeof(double));
if (info)
{
std::stringstream s;
s << "dsyevd returned " << info;
TERMINATE(s);
}
return 0;
}
int solve(int32_t matrix_size,
int nevec,
double* A,
int32_t lda,
double* eval,
double* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
int32_t lwork = -1;
double lwork1, vl, vu;
int32_t il, iu, m, info;
std::vector<double> w(matrix_size);
std::vector<int32_t> iwork(5 * matrix_size);
std::vector<int32_t> ifail(matrix_size);
il = 1;
iu = nevec;
FORTRAN(dsyevx)("V", "I", "U", &matrix_size, A, &lda, &vl, &vu, &il, &iu, const_cast<double*>(&abstol_), &m,
&w[0], Z, &ldz, &lwork1, &lwork, &iwork[0], &ifail[0], &info, (int32_t)1, (int32_t)1, (int32_t)1);
lwork = static_cast<int32_t>(lwork1 + 1);
std::vector<double> work(lwork);
FORTRAN(dsyevx)("V", "I", "U", &matrix_size, A, &lda, &vl, &vu, &il, &iu, const_cast<double*>(&abstol_), &m,
&w[0], Z, &ldz, &work[0], &lwork, &iwork[0], &ifail[0], &info, (int32_t)1, (int32_t)1, (int32_t)1);
if (m != nevec)
{
std::stringstream s;
s << "not all eigen-values are found" << std::endl
<< "target number of eign-values: " << nevec << std::endl
<< "number of eign-values found: " << m;
WARNING(s);
return 1;
}
if (info)
{
std::stringstream s;
s << "dsyevx returned " << info;
TERMINATE(s);
}
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
int solve(int32_t matrix_size,
int nevec,
double_complex* A,
int32_t lda,
double* eval,
double_complex* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
int32_t lwork = -1;
double vl, vu;
int32_t il, iu, m, info;
std::vector<double> w(matrix_size);
std::vector<int32_t> iwork(5 * matrix_size);
std::vector<int32_t> ifail(matrix_size);
std::vector<double> rwork(7 * matrix_size);
std::vector<double_complex> work(3);
il = 1;
iu = nevec;
FORTRAN(zheevx)("V", "I", "U", &matrix_size, A, &lda, &vl, &vu, &il, &iu, const_cast<double*>(&abstol_), &m,
&w[0], Z, &ldz, &work[0], &lwork, &rwork[0], &iwork[0], &ifail[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
lwork = static_cast<int32_t>(work[0].real()) + 1;
work.resize(lwork);
FORTRAN(zheevx)("V", "I", "U", &matrix_size, A, &lda, &vl, &vu, &il, &iu, const_cast<double*>(&abstol_), &m,
&w[0], Z, &ldz, &work[0], &lwork, &rwork[0], &iwork[0], &ifail[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
if (m != nevec) {
std::stringstream s;
s << "not all eigen-values are found" << std::endl
<< "target number of eign-values: " << nevec << std::endl
<< "number of eign-values found: " << m;
WARNING(s);
return 1;
}
if (info) {
std::stringstream s;
s << "dsyevx returned " << info;
TERMINATE(s);
}
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
bool parallel() const
{
return false;
}
ev_solver_t type() const
{
return ev_lapack;
}
};
#ifdef __PLASMA
extern "C" void plasma_zheevd_wrapper(int32_t matrix_size, void* a, int32_t lda, void* z,
int32_t ldz, double* eval);
#endif
/// Interface for PLASMA eigen-value solvers.
class Eigenproblem_plasma: public Eigenproblem
{
public:
Eigenproblem_plasma()
{
}
#ifdef __PLASMA
void solve(int32_t matrix_size, double_complex* A, int32_t lda, double* eval, double_complex* Z, int32_t ldz) const
{
//plasma_set_num_threads(1);
//omp_set_num_threads(1);
//printf("before call to plasma_zheevd_wrapper\n");
plasma_zheevd_wrapper(matrix_size, a, lda, z, lda, eval);
//printf("after call to plasma_zheevd_wrapper\n");
//plasma_set_num_threads(8);
//omp_set_num_threads(8);
}
#endif
bool parallel() const
{
return false;
}
ev_solver_t type() const
{
return ev_plasma;
}
};
#ifdef __MAGMA
extern "C" void magma_zhegvdx_2stage_wrapper(int32_t matrix_size, int32_t nv, void* a, int32_t lda,
void* b, int32_t ldb, double* eval);
extern "C" void magma_dsygvdx_2stage_wrapper(int32_t matrix_size, int32_t nv, void* a, int32_t lda, void* b,
int32_t ldb, double* eval);
extern "C" void magma_dsyevdx_wrapper(int32_t matrix_size, int32_t nv, double* a, int32_t lda, double* eval);
extern "C" int magma_zheevdx_wrapper(int32_t matrix_size, int32_t nv, double_complex* a, int32_t lda, double* eval);
extern "C" int magma_zheevdx_2stage_wrapper(int32_t matrix_size, int32_t nv, cuDoubleComplex* a, int32_t lda, double* eval);
#endif
/// Interface for MAGMA eigen-value solvers.
class Eigenproblem_magma: public Eigenproblem
{
public:
Eigenproblem_magma()
{
}
#ifdef __MAGMA
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double_complex* B, int32_t ldb,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int nt = omp_get_max_threads();
magma_zhegvdx_2stage_wrapper(matrix_size, nevec, A, lda, B, ldb, eval);
if (nt != omp_get_max_threads()) {
TERMINATE("magma has changed the number of threads");
}
#pragma omp parallel for
for (int i = 0; i < nevec; i++) {
std::memcpy(&Z[ldz * i], &A[lda * i], matrix_size * sizeof(double_complex));
}
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* B, int32_t ldb,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int nt = omp_get_max_threads();
magma_dsygvdx_2stage_wrapper(matrix_size, nevec, A, lda, B, ldb, eval);
if (nt != omp_get_max_threads()) {
TERMINATE("magma has changed the number of threads");
}
#pragma omp parallel for
for (int i = 0; i < nevec; i++) {
std::memcpy(&Z[ldz * i], &A[lda * i], matrix_size * sizeof(double));
}
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int nt = omp_get_max_threads();
magma_dsyevdx_wrapper(matrix_size, nevec, A, lda, eval);
if (nt != omp_get_max_threads()) {
TERMINATE("magma has changed the number of threads");
}
#pragma omp parallel for
for (int i = 0; i < nevec; i++) {
std::memcpy(&Z[ldz * i], &A[lda * i], matrix_size * sizeof(double));
}
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int nt = omp_get_max_threads();
//int result = magma_zheevdx_2stage_wrapper(matrix_size, nevec, A, lda, eval);
int result = magma_zheevdx_wrapper(matrix_size, nevec, A, lda, eval);
if (nt != omp_get_max_threads()) {
TERMINATE("magma has changed the number of threads");
}
if (result == 0) {
#pragma omp parallel for
for (int i = 0; i < nevec; i++) {
std::memcpy(&Z[ldz * i], &A[lda * i], matrix_size * sizeof(double_complex));
}
return 0;
}
return 1;
}
#endif
bool parallel() const
{
return false;
}
ev_solver_t type() const
{
return ev_magma;
}
};
/// Interface for ScaLAPACK eigen-value solvers.
class Eigenproblem_scalapack: public Eigenproblem
{
private:
int32_t bs_row_;
int32_t bs_col_;
int num_ranks_row_;
int num_ranks_col_;
int blacs_context_;
double abstol_;
//== #ifdef __SCALAPACK
//== std::vector<int32_t> get_work_sizes(int32_t matrix_size, int32_t nb, int32_t nprow, int32_t npcol,
//== int blacs_context) const
//== {
//== std::vector<int32_t> work_sizes(3);
//==
//== int32_t nn = std::max(matrix_size, std::max(nb, 2));
//==
//== int32_t np0 = linalg_base::numroc(nn, nb, 0, 0, nprow);
//== int32_t mq0 = linalg_base::numroc(nn, nb, 0, 0, npcol);
//==
//== work_sizes[0] = matrix_size + (np0 + mq0 + nb) * nb;
//==
//== work_sizes[1] = 1 + 9 * matrix_size + 3 * np0 * mq0;
//==
//== work_sizes[2] = 7 * matrix_size + 8 * npcol + 2;
//==
//== return work_sizes;
//== }
//== std::vector<int32_t> get_work_sizes_gevp(int32_t matrix_size, int32_t nb, int32_t nprow, int32_t npcol,
//== int blacs_context) const
//== {
//== std::vector<int32_t> work_sizes(3);
//==
//== int32_t nn = std::max(matrix_size, std::max(nb, 2));
//==
//== int32_t neig = std::max(1024, nb);
//== int32_t nmax3 = std::max(neig, std::max(nb, 2));
//==
//== int32_t np = nprow * npcol;
//== // due to the mess in the documentation, take the maximum of np0, nq0, mq0
//== int32_t nmpq0 = std::max(linalg_base::numroc(nn, nb, 0, 0, nprow),
//== std::max(linalg_base::numroc(nn, nb, 0, 0, npcol),
//== linalg_base::numroc(nmax3, nb, 0, 0, npcol)));
//== int32_t anb = linalg_base::pjlaenv(blacs_context, 3, "PZHETTRD", "L", 0, 0, 0, 0);
//== int32_t sqnpc = (int32_t)pow(double(np), 0.5);
//== int32_t nps = std::max(linalg_base::numroc(nn, 1, 0, 0, sqnpc), 2 * anb);
//== work_sizes[0] = matrix_size + (2 * nmpq0 + nb) * nb;
//== work_sizes[0] = std::max(work_sizes[0], matrix_size + 2 * (anb + 1) * (4 * nps + 2) + (nps + 1) * nps);
//== work_sizes[0] = std::max(work_sizes[0], 3 * nmpq0 * nb + nb * nb);
//== work_sizes[1] = 4 * matrix_size + std::max(5 * matrix_size, nmpq0 * nmpq0) +
//== linalg_base::iceil(neig, np) * nn + neig * matrix_size;
//== int32_t nnp = std::max(matrix_size, std::max(np + 1, 4));
//== work_sizes[2] = 6 * nnp;
//== return work_sizes;
//== }
//== #endif
public:
Eigenproblem_scalapack(BLACS_grid const& blacs_grid__, int32_t bs_row__, int32_t bs_col__, double abstol__ = 1e-12)
: bs_row_(bs_row__),
bs_col_(bs_col__),
num_ranks_row_(blacs_grid__.num_ranks_row()),
num_ranks_col_(blacs_grid__.num_ranks_col()),
blacs_context_(blacs_grid__.context()),
abstol_(abstol__)
{
}
#ifdef __SCALAPACK
int solve(int32_t matrix_size,
double_complex* A,
int32_t lda,
double* eval,
double_complex* Z,
int32_t ldz) const
{
int desca[9];
linalg_base::descinit(desca, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, lda);
int descz[9];
linalg_base::descinit(descz, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, ldz);
int32_t info;
int32_t ione = 1;
int32_t lwork = -1;
int32_t lrwork = -1;
int32_t liwork = -1;
std::vector<double_complex> work(1);
std::vector<double> rwork(1);
std::vector<int32_t> iwork(1);
/* work size query */
FORTRAN(pzheevd)("V", "U", &matrix_size, A, &ione, &ione, desca, eval, Z, &ione, &ione, descz, &work[0],
&lwork, &rwork[0], &lrwork, &iwork[0], &liwork, &info, (int32_t)1,
(int32_t)1);
lwork = static_cast<int32_t>(work[0].real()) + 1;
lrwork = static_cast<int32_t>(rwork[0]) + 1;
liwork = iwork[0];
work = std::vector<double_complex>(lwork);
rwork = std::vector<double>(lrwork);
iwork = std::vector<int32_t>(liwork);
FORTRAN(pzheevd)("V", "U", &matrix_size, A, &ione, &ione, desca, eval, Z, &ione, &ione, descz, &work[0],
&lwork, &rwork[0], &lrwork, &iwork[0], &liwork, &info, (int32_t)1,
(int32_t)1);
if (info)
{
std::stringstream s;
s << "pzheevd returned " << info;
TERMINATE(s);
}
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double_complex* B, int32_t ldb,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int32_t desca[9];
linalg_base::descinit(desca, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, lda);
int32_t descb[9];
linalg_base::descinit(descb, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, ldb);
int32_t descz[9];
linalg_base::descinit(descz, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, ldz);
//std::vector<int32_t> work_sizes = get_work_sizes_gevp(matrix_size, std::max(bs_row_, bs_col_),
// num_ranks_row_, num_ranks_col_, blacs_context_);
//
std::vector<int32_t> ifail(matrix_size);
std::vector<int32_t> iclustr(2 * num_ranks_row_ * num_ranks_col_);
std::vector<double> gap(num_ranks_row_ * num_ranks_col_);
std::vector<double> w(matrix_size);
double orfac = 1e-6;
int32_t ione = 1;
int32_t m;
int32_t nz;
double d1;
int32_t info;
int32_t lwork = -1;
int32_t lrwork = -1;
int32_t liwork = -1;
std::vector<double_complex> work(1);
std::vector<double> rwork(3);
std::vector<int32_t> iwork(1);
/* work size query */
FORTRAN(pzhegvx)(&ione, "V", "I", "U", &matrix_size, A, &ione, &ione, desca, B, &ione, &ione, descb, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work[0], &lwork,
&rwork[0], &lrwork, &iwork[0], &liwork, &ifail[0], &iclustr[0], &gap[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
lwork = static_cast<int32_t>(work[0].real()) + 4096;
lrwork = static_cast<int32_t>(rwork[0]) + 4096;
liwork = iwork[0] + 4096;
work = std::vector<double_complex>(lwork);
rwork = std::vector<double>(lrwork);
iwork = std::vector<int32_t>(liwork);
FORTRAN(pzhegvx)(&ione, "V", "I", "U", &matrix_size, A, &ione, &ione, desca, B, &ione, &ione, descb, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work[0], &lwork,
&rwork[0], &lrwork, &iwork[0], &liwork, &ifail[0], &iclustr[0], &gap[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
if (info)
{
if ((info / 2) % 2)
{
std::stringstream s;
s << "eigenvectors corresponding to one or more clusters of eigenvalues" << std::endl
<< "could not be reorthogonalized because of insufficient workspace" << std::endl;
int k = num_ranks_row_ * num_ranks_col_;
for (int i = 0; i < num_ranks_row_ * num_ranks_col_ - 1; i++)
{
if ((iclustr[2 * i + 1] != 0) && (iclustr[2 * (i + 1)] == 0))
{
k = i + 1;
break;
}
}
s << "number of eigenvalue clusters : " << k << std::endl;
for (int i = 0; i < k; i++) s << iclustr[2 * i] << " : " << iclustr[2 * i + 1] << std::endl;
TERMINATE(s);
}
std::stringstream s;
s << "pzhegvx returned " << info;
TERMINATE(s);
}
if ((m != nevec) || (nz != nevec))
TERMINATE("Not all eigen-vectors or eigen-values are found.");
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* B, int32_t ldb,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int32_t desca[9];
linalg_base::descinit(desca, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, lda);
int32_t descb[9];
linalg_base::descinit(descb, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, ldb);
int32_t descz[9];
linalg_base::descinit(descz, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, ldz);
int32_t lwork = -1;
int32_t liwork;
double work1;
double orfac = 1e-6;
int32_t ione = 1;
int32_t m;
int32_t nz;
double d1;
int32_t info;
std::vector<int32_t> ifail(matrix_size);
std::vector<int32_t> iclustr(2 * num_ranks_row_ * num_ranks_col_);
std::vector<double> gap(num_ranks_row_ * num_ranks_col_);
std::vector<double> w(matrix_size);
/* work size query */
FORTRAN(pdsygvx)(&ione, "V", "I", "U", &matrix_size, A, &ione, &ione, desca, B, &ione, &ione, descb, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work1, &lwork,
&liwork, &lwork, &ifail[0], &iclustr[0], &gap[0], &info, (int32_t)1, (int32_t)1, (int32_t)1);
lwork = static_cast<int32_t>(work1) + 4 * (1 << 20);
std::vector<double> work(lwork);
std::vector<int32_t> iwork(liwork);
FORTRAN(pdsygvx)(&ione, "V", "I", "U", &matrix_size, A, &ione, &ione, desca, B, &ione, &ione, descb, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work[0], &lwork,
&iwork[0], &liwork, &ifail[0], &iclustr[0], &gap[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
if (info)
{
if ((info / 2) % 2)
{
std::stringstream s;
s << "eigenvectors corresponding to one or more clusters of eigenvalues" << std::endl
<< "could not be reorthogonalized because of insufficient workspace" << std::endl;
int k = num_ranks_row_ * num_ranks_col_;
for (int i = 0; i < num_ranks_row_ * num_ranks_col_ - 1; i++)
{
if ((iclustr[2 * i + 1] != 0) && (iclustr[2 * (i + 1)] == 0))
{
k = i + 1;
break;
}
}
s << "number of eigenvalue clusters : " << k << std::endl;
for (int i = 0; i < k; i++) s << iclustr[2 * i] << " : " << iclustr[2 * i + 1] << std::endl;
TERMINATE(s);
}
std::stringstream s;
s << "pzhegvx returned " << info;
TERMINATE(s);
}
if ((m != nevec) || (nz != nevec))
TERMINATE("Not all eigen-vectors or eigen-values are found.");
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
int solve(int32_t matrix_size,
int32_t nevec,
double* A,
int32_t lda,
double* eval,
double* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int32_t desca[9];
linalg_base::descinit(desca, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, lda);
int32_t descz[9];
linalg_base::descinit(descz, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, ldz);
double orfac = 1e-6;
int32_t ione = 1;
int32_t m;
int32_t nz;
double d1;
int32_t info;
std::vector<int32_t> ifail(matrix_size);
std::vector<int32_t> iclustr(2 * num_ranks_row_ * num_ranks_col_);
std::vector<double> gap(num_ranks_row_ * num_ranks_col_);
std::vector<double> w(matrix_size);
/* work size query */
std::vector<double> work(3);
std::vector<int32_t> iwork(1);
int32_t lwork = -1;
int32_t liwork = -1;
FORTRAN(pdsyevx)("V", "I", "U", &matrix_size, A, &ione, &ione, desca, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work[0], &lwork,
&iwork[0], &liwork, &ifail[0], &iclustr[0], &gap[0], &info, (int32_t)1, (int32_t)1, (int32_t)1);
lwork = static_cast<int32_t>(work[0]) + 4 * (1 << 20);
liwork = iwork[0];
work = std::vector<double>(lwork);
iwork = std::vector<int32_t>(liwork);
FORTRAN(pdsyevx)("V", "I", "U", &matrix_size, A, &ione, &ione, desca, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work[0], &lwork,
&iwork[0], &liwork, &ifail[0], &iclustr[0], &gap[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
if (info)
{
if ((info / 2) % 2)
{
std::stringstream s;
s << "eigenvectors corresponding to one or more clusters of eigenvalues" << std::endl
<< "could not be reorthogonalized because of insufficient workspace" << std::endl;
int k = num_ranks_row_ * num_ranks_col_;
for (int i = 0; i < num_ranks_row_ * num_ranks_col_ - 1; i++)
{
if ((iclustr[2 * i + 1] != 0) && (iclustr[2 * (i + 1)] == 0))
{
k = i + 1;
break;
}
}
s << "number of eigenvalue clusters : " << k << std::endl;
for (int i = 0; i < k; i++) s << iclustr[2 * i] << " : " << iclustr[2 * i + 1] << std::endl;
TERMINATE(s);
}
std::stringstream s;
s << "pdsyevx returned " << info;
TERMINATE(s);
}
if ((m != nevec) || (nz != nevec))
TERMINATE("Not all eigen-vectors or eigen-values are found.");
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
int solve(int32_t matrix_size,
int32_t nevec,
double_complex* A,
int32_t lda,
double* eval,
double_complex* Z,
int32_t ldz,
int32_t num_rows_loc = 0,
int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
int32_t desca[9];
linalg_base::descinit(desca, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, lda);
int32_t descz[9];
linalg_base::descinit(descz, matrix_size, matrix_size, bs_row_, bs_col_, 0, 0, blacs_context_, ldz);
double orfac = 1e-6;
int32_t ione = 1;
int32_t m;
int32_t nz;
double d1;
int32_t info;
std::vector<int32_t> ifail(matrix_size);
std::vector<int32_t> iclustr(2 * num_ranks_row_ * num_ranks_col_);
std::vector<double> gap(num_ranks_row_ * num_ranks_col_);
std::vector<double> w(matrix_size);
/* work size query */
std::vector<double_complex> work(3);
std::vector<double> rwork(3);
std::vector<int32_t> iwork(1);
int32_t lwork = -1;
int32_t lrwork = -1;
int32_t liwork = -1;
FORTRAN(pzheevx)("V", "I", "U", &matrix_size, A, &ione, &ione, desca, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work[0], &lwork,
&rwork[0], &lrwork, &iwork[0], &liwork, &ifail[0], &iclustr[0], &gap[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
lwork = static_cast<int32_t>(work[0].real()) + (1 << 16);
lrwork = static_cast<int32_t>(rwork[0]) + (1 << 16);
liwork = iwork[0];
work = std::vector<double_complex>(lwork);
rwork = std::vector<double>(lrwork);
iwork = std::vector<int32_t>(liwork);
FORTRAN(pzheevx)("V", "I", "U", &matrix_size, A, &ione, &ione, desca, &d1, &d1,
&ione, &nevec, const_cast<double*>(&abstol_), &m, &nz, &w[0], &orfac, Z, &ione, &ione, descz, &work[0], &lwork,
&rwork[0], &lrwork, &iwork[0], &liwork, &ifail[0], &iclustr[0], &gap[0], &info,
(int32_t)1, (int32_t)1, (int32_t)1);
if (info)
{
if ((info / 2) % 2)
{
std::stringstream s;
s << "eigenvectors corresponding to one or more clusters of eigenvalues" << std::endl
<< "could not be reorthogonalized because of insufficient workspace" << std::endl;
int k = num_ranks_row_ * num_ranks_col_;
for (int i = 0; i < num_ranks_row_ * num_ranks_col_ - 1; i++)
{
if ((iclustr[2 * i + 1] != 0) && (iclustr[2 * (i + 1)] == 0))
{
k = i + 1;
break;
}
}
s << "number of eigenvalue clusters : " << k << std::endl;
for (int i = 0; i < k; i++) s << iclustr[2 * i] << " : " << iclustr[2 * i + 1] << std::endl;
TERMINATE(s);
}
std::stringstream s;
s << "pzheevx returned " << info;
TERMINATE(s);
}
if ((m != nevec) || (nz != nevec))
TERMINATE("Not all eigen-vectors or eigen-values are found.");
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
#endif
bool parallel() const
{
return true;
}
ev_solver_t type() const
{
return ev_scalapack;
}
};
#ifdef __ELPA
extern "C" {
void FORTRAN(elpa_cholesky_complex_wrapper)(ftn_int const* na,
ftn_double_complex* a,
ftn_int const* lda,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols);
void FORTRAN(elpa_cholesky_real_wrapper)(ftn_int const* na,
ftn_double* a,
ftn_int const* lda,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols);
void FORTRAN(elpa_invert_trm_complex_wrapper)(ftn_int const* na,
ftn_double_complex* a,
ftn_int const* lda,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols);
void FORTRAN(elpa_invert_trm_real_wrapper)(ftn_int const* na,
ftn_double* a,
ftn_int const* lda,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols);
void FORTRAN(elpa_mult_ah_b_complex_wrapper)(ftn_char uplo_a,
ftn_char uplo_c,
ftn_int const* na,
ftn_int const* ncb,
ftn_double_complex* a,
ftn_int const* lda,
ftn_double_complex* b,
ftn_int const* ldb,
ftn_int const* nblk,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols,
ftn_double_complex* c,
ftn_int const* ldc,
ftn_len uplo_a_len,
ftn_len uplo_c_len);
void FORTRAN(elpa_mult_at_b_real_wrapper)(ftn_char uplo_a,
ftn_char uplo_c,
ftn_int const* na,
ftn_int const* ncb,
ftn_double* a,
ftn_int const* lda,
ftn_double* b,
ftn_int const* ldb,
ftn_int const* nblk,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols,
ftn_double* c,
ftn_int const* ldc,
ftn_len uplo_a_len,
ftn_len uplo_c_len);
void FORTRAN(elpa_solve_evp_complex)(ftn_int const* na,
ftn_int const* nev,
ftn_double_complex* a,
ftn_int const* lda,
ftn_double* ev,
ftn_double_complex* q,
ftn_int const* ldq,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols);
void FORTRAN(elpa_solve_evp_real)(ftn_int const* na,
ftn_int const* nev,
ftn_double* a,
ftn_int const* lda,
ftn_double* ev,
ftn_double* q,
ftn_int const* ldq,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols);
void FORTRAN(elpa_solve_evp_complex_2stage)(ftn_int const* na,
ftn_int const* nev,
ftn_double_complex* a,
ftn_int const* lda,
ftn_double* ev,
ftn_double_complex* q,
ftn_int const* ldq,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols,
ftn_int const* mpi_comm_all);
void FORTRAN(elpa_solve_evp_real_2stage)(ftn_int const* na,
ftn_int const* nev,
ftn_double* a,
ftn_int const* lda,
ftn_double* ev,
ftn_double* q,
ftn_int const* ldq,
ftn_int const* nblk,
ftn_int const* matrixCols,
ftn_int const* mpi_comm_rows,
ftn_int const* mpi_comm_cols,
ftn_int const* mpi_comm_all);
}
#endif
class Eigenproblem_elpa: public Eigenproblem
{
protected:
int32_t block_size_;
int32_t num_ranks_row_;
int32_t rank_row_;
int32_t num_ranks_col_;
int32_t rank_col_;
int blacs_context_;
Communicator const& comm_row_;
Communicator const& comm_col_;
Communicator const& comm_all_;
int32_t mpi_comm_rows_;
int32_t mpi_comm_cols_;
int32_t mpi_comm_all_;
public:
Eigenproblem_elpa(BLACS_grid const& blacs_grid__, int32_t block_size__)
: block_size_(block_size__),
num_ranks_row_(blacs_grid__.num_ranks_row()),
rank_row_(blacs_grid__.rank_row()),
num_ranks_col_(blacs_grid__.num_ranks_col()),
rank_col_(blacs_grid__.rank_col()),
blacs_context_(blacs_grid__.context()),
comm_row_(blacs_grid__.comm_row()),
comm_col_(blacs_grid__.comm_col()),
comm_all_(blacs_grid__.comm())
{
mpi_comm_rows_ = MPI_Comm_c2f(comm_row_.mpi_comm());
mpi_comm_cols_ = MPI_Comm_c2f(comm_col_.mpi_comm());
mpi_comm_all_ = MPI_Comm_c2f(comm_all_.mpi_comm());
}
void transform_to_standard(int32_t matrix_size__,
double_complex* A__, int32_t lda__,
double_complex* B__, int32_t ldb__,
int32_t num_rows_loc__, int32_t num_cols_loc__,
matrix<double_complex>& tmp1__,
matrix<double_complex>& tmp2__) const
{
PROFILE("Eigenproblem_elpa:transform_to_standard");
/* compute Cholesky decomposition of B: B=L*L^H; overwrite B with L */
FORTRAN(elpa_cholesky_complex_wrapper)(&matrix_size__, B__, &ldb__, &block_size_, &num_cols_loc__, &mpi_comm_rows_, &mpi_comm_cols_);
/* invert L */
FORTRAN(elpa_invert_trm_complex_wrapper)(&matrix_size__, B__, &ldb__, &block_size_, &num_cols_loc__, &mpi_comm_rows_, &mpi_comm_cols_);
FORTRAN(elpa_mult_ah_b_complex_wrapper)("U", "L", &matrix_size__, &matrix_size__, B__, &ldb__, A__, &lda__, &block_size_,
&mpi_comm_rows_, &mpi_comm_cols_, tmp1__.at<CPU>(), &num_rows_loc__, (int32_t)1,
(int32_t)1);
int32_t descc[9];
linalg_base::descinit(descc, matrix_size__, matrix_size__, block_size_, block_size_, 0, 0, blacs_context_, lda__);
linalg_base::pztranc(matrix_size__, matrix_size__, linalg_const<double_complex>::one(), tmp1__.at<CPU>(), 1, 1, descc,
linalg_const<double_complex>::zero(), tmp2__.at<CPU>(), 1, 1, descc);
FORTRAN(elpa_mult_ah_b_complex_wrapper)("U", "U", &matrix_size__, &matrix_size__, B__, &ldb__, tmp2__.at<CPU>(), &num_rows_loc__,
&block_size_, &mpi_comm_rows_, &mpi_comm_cols_, A__, &lda__, (int32_t)1,
(int32_t)1);
linalg_base::pztranc(matrix_size__, matrix_size__, linalg_const<double_complex>::one(), A__, 1, 1, descc, linalg_const<double_complex>::zero(),
tmp1__.at<CPU>(), 1, 1, descc);
for (int i = 0; i < num_cols_loc__; i++)
{
int32_t n_col = linalg_base::indxl2g(i + 1, block_size_, rank_col_, 0, num_ranks_col_);
int32_t n_row = linalg_base::numroc(n_col, block_size_, rank_row_, 0, num_ranks_row_);
for (int j = n_row; j < num_rows_loc__; j++)
{
A__[j + i * lda__] = tmp1__(j, i);
}
}
}
void transform_to_standard(int32_t matrix_size__,
double* A__, int32_t lda__,
double* B__, int32_t ldb__,
int32_t num_rows_loc__, int32_t num_cols_loc__,
matrix<double>& tmp1__,
matrix<double>& tmp2__) const
{
PROFILE("Eigenproblem_elpa:transform_to_standard");
/* compute Cholesky decomposition of B: B=L*L^H; overwrite B with L */
FORTRAN(elpa_cholesky_real_wrapper)(&matrix_size__, B__, &ldb__, &block_size_, &num_cols_loc__, &mpi_comm_rows_, &mpi_comm_cols_);
/* invert L */
FORTRAN(elpa_invert_trm_real_wrapper)(&matrix_size__, B__, &ldb__, &block_size_, &num_cols_loc__, &mpi_comm_rows_, &mpi_comm_cols_);
FORTRAN(elpa_mult_at_b_real_wrapper)("U", "L", &matrix_size__, &matrix_size__, B__, &ldb__, A__, &lda__, &block_size_,
&mpi_comm_rows_, &mpi_comm_cols_, tmp1__.at<CPU>(), &num_rows_loc__, (int32_t)1,
(int32_t)1);
int32_t descc[9];
linalg_base::descinit(descc, matrix_size__, matrix_size__, block_size_, block_size_, 0, 0, blacs_context_, lda__);
linalg_base::pdtran(matrix_size__, matrix_size__, 1.0, tmp1__.at<CPU>(), 1, 1, descc, 0.0,
tmp2__.at<CPU>(), 1, 1, descc);
FORTRAN(elpa_mult_at_b_real_wrapper)("U", "U", &matrix_size__, &matrix_size__, B__, &ldb__, tmp2__.at<CPU>(), &num_rows_loc__,
&block_size_, &mpi_comm_rows_, &mpi_comm_cols_, A__, &lda__, (int32_t)1,
(int32_t)1);
linalg_base::pdtran(matrix_size__, matrix_size__, 1.0, A__, 1, 1, descc, 0.0, tmp1__.at<CPU>(), 1, 1, descc);
for (int i = 0; i < num_cols_loc__; i++)
{
int32_t n_col = linalg_base::indxl2g(i + 1, block_size_, rank_col_, 0, num_ranks_col_);
int32_t n_row = linalg_base::numroc(n_col, block_size_, rank_row_, 0, num_ranks_row_);
for (int j = n_row; j < num_rows_loc__; j++)
{
A__[j + i * lda__] = tmp1__(j, i);
}
}
}
void transform_back(int32_t matrix_size__, int32_t nevec__,
double_complex* B__, int32_t ldb__,
double_complex* Z__, int32_t ldz__,
int32_t num_rows_loc__, int32_t num_cols_loc__,
matrix<double_complex>& tmp1__,
matrix<double_complex>& tmp2__) const
{
PROFILE("Eigenproblem_elpa:transform_back");
int32_t descb[9];
linalg_base::descinit(descb, matrix_size__, matrix_size__, block_size_, block_size_, 0, 0, blacs_context_, ldb__);
linalg_base::pztranc(matrix_size__, matrix_size__, linalg_const<double_complex>::one(), B__, 1, 1, descb, linalg_const<double_complex>::zero(),
tmp2__.at<CPU>(), 1, 1, descb);
FORTRAN(elpa_mult_ah_b_complex_wrapper)("L", "N", &matrix_size__, &nevec__, tmp2__.at<CPU>(), &num_rows_loc__, tmp1__.at<CPU>(),
&num_rows_loc__, &block_size_, &mpi_comm_rows_, &mpi_comm_cols_, Z__, &ldz__,
(int32_t)1, (int32_t)1);
}
void transform_back(int32_t matrix_size__, int32_t nevec__,
double* B__, int32_t ldb__,
double* Z__, int32_t ldz__,
int32_t num_rows_loc__, int32_t num_cols_loc__,
matrix<double>& tmp1__,
matrix<double>& tmp2__) const
{
PROFILE("Eigenproblem_elpa:transform_back");
int32_t descb[9];
linalg_base::descinit(descb, matrix_size__, matrix_size__, block_size_, block_size_, 0, 0, blacs_context_, ldb__);
linalg_base::pdtran(matrix_size__, matrix_size__, 1.0, B__, 1, 1, descb, 0.0, tmp2__.at<CPU>(), 1, 1, descb);
FORTRAN(elpa_mult_at_b_real_wrapper)("L", "N", &matrix_size__, &nevec__, tmp2__.at<CPU>(), &num_rows_loc__, tmp1__.at<CPU>(),
&num_rows_loc__, &block_size_, &mpi_comm_rows_, &mpi_comm_cols_, Z__, &ldz__,
(int32_t)1, (int32_t)1);
}
};
class Eigenproblem_elpa1: public Eigenproblem_elpa
{
public:
Eigenproblem_elpa1(BLACS_grid const& blacs_grid__, int32_t block_size__)
: Eigenproblem_elpa(blacs_grid__, block_size__)
{
}
#ifdef __ELPA
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double_complex* B, int32_t ldb,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
matrix<double_complex> tmp1(num_rows_loc, num_cols_loc);
matrix<double_complex> tmp2(num_rows_loc, num_cols_loc);
transform_to_standard(matrix_size, A, lda, B, ldb, num_rows_loc, num_cols_loc, tmp1, tmp2);
std::vector<double> w(matrix_size);
sddk::timer t("Eigenproblem_elpa1|diag");
FORTRAN(elpa_solve_evp_complex)(&matrix_size, &nevec, A, &lda, &w[0], tmp1.at<CPU>(), &num_rows_loc,
&block_size_, &num_cols_loc, &mpi_comm_rows_, &mpi_comm_cols_);
t.stop();
std::memcpy(eval, &w[0], nevec * sizeof(double));
transform_back(matrix_size, nevec, B, ldb, Z, ldz, num_rows_loc, num_cols_loc, tmp1, tmp2);
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* B, int32_t ldb,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
matrix<double> tmp1(num_rows_loc, num_cols_loc);
matrix<double> tmp2(num_rows_loc, num_cols_loc);
transform_to_standard(matrix_size, A, lda, B, ldb, num_rows_loc, num_cols_loc, tmp1, tmp2);
std::vector<double> w(matrix_size);
sddk::timer t("Eigenproblem_elpa1|diag");
FORTRAN(elpa_solve_evp_real)(&matrix_size, &nevec, A, &lda, &w[0], tmp1.at<CPU>(), &num_rows_loc,
&block_size_, &num_cols_loc, &mpi_comm_rows_, &mpi_comm_cols_);
t.stop();
std::memcpy(eval, &w[0], nevec * sizeof(double));
transform_back(matrix_size, nevec, B, ldb, Z, ldz, num_rows_loc, num_cols_loc, tmp1, tmp2);
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc, int32_t num_cols_loc) const
{
assert(nevec <= matrix_size);
std::vector<double> w(matrix_size);
sddk::timer t("Eigenproblem_elpa1|diag");
FORTRAN(elpa_solve_evp_real)(&matrix_size, &nevec, A, &lda, &w[0], Z, &ldz,
&block_size_, &num_cols_loc, &mpi_comm_rows_, &mpi_comm_cols_);
t.stop();
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc, int32_t num_cols_loc) const
{
assert(nevec <= matrix_size);
std::vector<double> w(matrix_size);
sddk::timer t("Eigenproblem_elpa1|diag");
FORTRAN(elpa_solve_evp_complex)(&matrix_size, &nevec, A, &lda, &w[0], Z, &ldz,
&block_size_, &num_cols_loc, &mpi_comm_rows_, &mpi_comm_cols_);
t.stop();
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
#endif
bool parallel() const
{
return true;
}
ev_solver_t type() const
{
return ev_elpa1;
}
};
class Eigenproblem_elpa2: public Eigenproblem_elpa
{
public:
Eigenproblem_elpa2(BLACS_grid const& blacs_grid__, int32_t block_size__)
: Eigenproblem_elpa(blacs_grid__, block_size__)
{
}
#ifdef __ELPA
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double_complex* B, int32_t ldb,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
matrix<double_complex> tmp1(num_rows_loc, num_cols_loc);
matrix<double_complex> tmp2(num_rows_loc, num_cols_loc);
transform_to_standard(matrix_size, A, lda, B, ldb, num_rows_loc, num_cols_loc, tmp1, tmp2);
std::vector<double> w(matrix_size);
sddk::timer t("Eigenproblem_elpa2|diag");
FORTRAN(elpa_solve_evp_complex_2stage)(&matrix_size, &nevec, A, &lda, &w[0], tmp1.at<CPU>(), &num_rows_loc,
&block_size_, &num_cols_loc, &mpi_comm_rows_, &mpi_comm_cols_, &mpi_comm_all_);
t.stop();
std::memcpy(eval, &w[0], nevec * sizeof(double));
transform_back(matrix_size, nevec, B, ldb, Z, ldz, num_rows_loc, num_cols_loc, tmp1, tmp2);
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* B, int32_t ldb,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc = 0, int32_t num_cols_loc = 0) const
{
assert(nevec <= matrix_size);
matrix<double> tmp1(num_rows_loc, num_cols_loc);
matrix<double> tmp2(num_rows_loc, num_cols_loc);
transform_to_standard(matrix_size, A, lda, B, ldb, num_rows_loc, num_cols_loc, tmp1, tmp2);
std::vector<double> w(matrix_size);
sddk::timer t("Eigenproblem_elpa2|diag");
FORTRAN(elpa_solve_evp_real_2stage)(&matrix_size, &nevec, A, &lda, &w[0], tmp1.at<CPU>(), &num_rows_loc,
&block_size_, &num_cols_loc, &mpi_comm_rows_, &mpi_comm_cols_, &mpi_comm_all_);
t.stop();
std::memcpy(eval, &w[0], nevec * sizeof(double));
transform_back(matrix_size, nevec, B, ldb, Z, ldz, num_rows_loc, num_cols_loc, tmp1, tmp2);
return 0;
}
int solve(int32_t matrix_size, int32_t nevec,
double* A, int32_t lda,
double* eval,
double* Z, int32_t ldz,
int32_t num_rows_loc, int32_t num_cols_loc) const
{
assert(nevec <= matrix_size);
std::vector<double> w(matrix_size);
sddk::timer t("Eigenproblem_elpa2|diag");
FORTRAN(elpa_solve_evp_real_2stage)(&matrix_size, &nevec, A, &lda, &w[0], Z, &ldz,
&block_size_, &num_cols_loc, &mpi_comm_rows_, &mpi_comm_cols_, &mpi_comm_all_);
t.stop();
std::memcpy(eval, &w[0], nevec * sizeof(double));
return 0;
}
#endif
bool parallel() const
{
return true;
}
ev_solver_t type() const
{
return ev_elpa2;
}
};
#ifdef __RS_GEN_EIG
void my_gen_eig(char uplo, int n, int nev, double_complex* a, int ia, int ja, int* desca,
double_complex* b, int ib, int jb, int* descb, double* d,
double_complex* q, int iq, int jq, int* descq, int* info);
void my_gen_eig_cpu(char uplo, int n, int nev, double_complex* a, int ia, int ja, int* desca,
double_complex* b, int ib, int jb, int* descb, double* d,
double_complex* q, int iq, int jq, int* descq, int* info);
#endif
class Eigenproblem_RS_CPU: public Eigenproblem
{
private:
int32_t bs_row_;
int32_t bs_col_;
int num_ranks_row_;
int rank_row_;
int num_ranks_col_;
int rank_col_;
int blacs_context_;
public:
Eigenproblem_RS_CPU(BLACS_grid const& blacs_grid__, int32_t bs_row__, int32_t bs_col__)
: bs_row_(bs_row__),
bs_col_(bs_col__),
num_ranks_row_(blacs_grid__.num_ranks_row()),
rank_row_(blacs_grid__.rank_row()),
num_ranks_col_(blacs_grid__.num_ranks_col()),
rank_col_(blacs_grid__.rank_col()),
blacs_context_(blacs_grid__.context())
{
}
#ifdef __RS_GEN_EIG
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double_complex* B, int32_t ldb,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc, int32_t num_cols_loc) const
{
assert(nevec <= matrix_size);
int32_t desca[9];
lin_alg<scalapack>::descinit(desca, matrix_size, matrix_size, block_size_, block_size_, 0, 0,
blacs_context_, lda);
int32_t descb[9];
lin_alg<scalapack>::descinit(descb, matrix_size, matrix_size, block_size_, block_size_, 0, 0,
blacs_context_, ldb);
mdarray<double_complex, 2> ztmp(num_rows_loc, num_cols_loc);
int32_t descz[9];
lin_alg<scalapack>::descinit(descz, matrix_size, matrix_size, block_size_, block_size_, 0, 0,
blacs_context_, num_rows_loc);
std::vector<double> eval_tmp(matrix_size);
int info;
my_gen_eig_cpu('L', matrix_size, nevec, a, 1, 1, desca, b, 1, 1, descb, &eval_tmp[0], ztmp.ptr(), 1, 1, descz, &info);
if (info)
{
std::stringstream s;
s << "my_gen_eig " << info;
TERMINATE(s);
}
for (int i = 0; i < lin_alg<scalapack>::numroc(nevec, block_size_, rank_col_, 0, num_ranks_col_); i++)
memcpy(&z[ldz * i], &ztmp(0, i), num_rows_loc * sizeof(double_complex));
memcpy(eval, &eval_tmp[0], nevec * sizeof(double));
return 0;
}
#endif
bool parallel() const
{
return true;
}
ev_solver_t type() const
{
return ev_rs_cpu;
}
};
class Eigenproblem_RS_GPU: public Eigenproblem
{
private:
int32_t bs_row_;
int32_t bs_col_;
int num_ranks_row_;
int rank_row_;
int num_ranks_col_;
int rank_col_;
int blacs_context_;
public:
Eigenproblem_RS_GPU(BLACS_grid const& blacs_grid__, int32_t bs_row__, int32_t bs_col__)
: bs_row_(bs_row__),
bs_col_(bs_col__),
num_ranks_row_(blacs_grid__.num_ranks_row()),
rank_row_(blacs_grid__.rank_row()),
num_ranks_col_(blacs_grid__.num_ranks_col()),
rank_col_(blacs_grid__.rank_col()),
blacs_context_(blacs_grid__.context())
{
}
#ifdef __RS_GEN_EIG
int solve(int32_t matrix_size, int32_t nevec,
double_complex* A, int32_t lda,
double_complex* B, int32_t ldb,
double* eval,
double_complex* Z, int32_t ldz,
int32_t num_rows_loc, int32_t num_cols_loc) const
{
assert(nevec <= matrix_size);
int32_t desca[9];
lin_alg<scalapack>::descinit(desca, matrix_size, matrix_size, block_size_, block_size_, 0, 0,
blacs_context_, lda);
int32_t descb[9];
lin_alg<scalapack>::descinit(descb, matrix_size, matrix_size, block_size_, block_size_, 0, 0,
blacs_context_, ldb);
mdarray<double_complex, 2> ztmp(nullptr, num_rows_loc, num_cols_loc);
ztmp.allocate(1);
int32_t descz[9];
lin_alg<scalapack>::descinit(descz, matrix_size, matrix_size, block_size_, block_size_, 0, 0,
blacs_context_, num_rows_loc);
std::vector<double> eval_tmp(matrix_size);
int info;
my_gen_eig('L', matrix_size, nevec, a, 1, 1, desca, b, 1, 1, descb, &eval_tmp[0], ztmp.ptr(), 1, 1, descz, &info);
if (info)
{
std::stringstream s;
s << "my_gen_eig " << info;
TERMINATE(s);
}
for (int i = 0; i < lin_alg<scalapack>::numroc(nevec, block_size_, rank_col_, 0, num_ranks_col_); i++)
std::memcpy(&Z[ldz * i], &ztmp(0, i), num_rows_loc * sizeof(double_complex));
std::memcpy(eval, &eval_tmp[0], nevec * sizeof(double));
return 0;
}
#endif
bool parallel() const
{
return true;
}
ev_solver_t type() const
{
return ev_rs_gpu;
}
};
#endif // __EIGENPROBLEM_H__
|
GB_binop__rminus_uint32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__rminus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_08__rminus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__rminus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_04__rminus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_uint32)
// A*D function (colscale): GB (_AxD__rminus_uint32)
// D*A function (rowscale): GB (_DxB__rminus_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__rminus_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__rminus_uint32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_uint32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_uint32)
// C=scalar+B GB (_bind1st__rminus_uint32)
// C=scalar+B' GB (_bind1st_tran__rminus_uint32)
// C=A+scalar GB (_bind2nd__rminus_uint32)
// C=A'+scalar GB (_bind2nd_tran__rminus_uint32)
// C type: uint32_t
// A type: uint32_t
// A pattern? 0
// B type: uint32_t
// B pattern? 0
// BinaryOp: cij = (bij - aij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
uint32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint32_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint32_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (y - x) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_RMINUS || GxB_NO_UINT32 || GxB_NO_RMINUS_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__rminus_uint32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint32_t
uint32_t bwork = (*((uint32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__rminus_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint32_t alpha_scalar ;
uint32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint32_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__rminus_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__rminus_uint32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__rminus_uint32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_t bij = GBX (Bx, p, false) ;
Cx [p] = (bij - x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rminus_uint32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint32_t aij = GBX (Ax, p, false) ;
Cx [p] = (y - aij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij - x) ; \
}
GrB_Info GB (_bind1st_tran__rminus_uint32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (y - aij) ; \
}
GrB_Info GB (_bind2nd_tran__rminus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
critical-2.c | /* { dg-do compile } */
void f1(void)
{
#pragma omp critical a /* { dg-error "expected" } */
;
#pragma omp critical ( /* { dg-error "expected identifier" } */
;
#pragma omp critical (a /* { dg-error "expected .\\)." } */
;
#pragma omp critical (a b) /* { dg-error "expected .\\)." } */
} /* { dg-error "expected expression" } */
|
arithmetic.c |
int min(int a, int b) { return a < b ? a : b; }
int max(int a, int b) { return a > b ? a : b; }
// Traditional vertical calculation like algorithm, O(n^2)
/*
* Input:
* int *a, int *b: ptr to multicands
* int *c: ptr to result array
* int m, int n: length of mlticands
*
*/
void multiply(int *a, int *b, int *c, int m, int n)
{
int i, j;
// Multiply digit by digit
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
c[i + j] += a[i] * b[j];
}
}
// Handles carries
for (i = 0; i < n + m; i++)
{
if (c[i] >= 10)
{
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
}
}
void bigadd(int *a, int *b, int *c, int lengthA, int lengthB)
{
int i;
int carry = 0;
// Copy A to C
memcpy(c, a, lengthA * sizeof(int));
// Add B to C digit by digit
for (i = 0; i < lengthB; i++)
{
c[i] = (a[i] + b[i] + carry);
carry = c[i] / 10;
c[i] %= 10;
}
// Handles the last carry
c[lengthB] += carry;
}
void bigsub(int *a, int *b, int *c, int lengthA, int lengthB)
{
int i;
// Copy a to c
memcpy(c, a, lengthA * sizeof(int));
// Substract digit by digit
for (i = 0; i < lengthB; ++i)
{
c[i] = c[i] - b[i];
if (c[i] < 0)
{
c[i + 1] -= 1;
c[i] += 10;
}
}
// Handles borrows
for (i = lengthB; i < lengthA; ++i)
{
if (c[i] < 0)
{
c[i + 1] -= 1;
c[i] += 10;
}
}
}
void bigjoin(int *var, int *result, int length)
{
int i;
int carry = 0;
for (i = 0; i < length; ++i)
{
result[i] += var[i] + carry;
carry = result[i] / 10;
result[i] %= 10;
}
// Handles the last carry
result[length] += carry;
}
// Traditional vertical calculation like algorithm,
// With openmp
void multiplyMP(int *a, int *b, int *c, int m, int n)
{
int i, j;
// Multiply digit by digit
#pragma omp parallel for num_threads(4)
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
c[i + j] += a[i] * b[j];
}
}
// Handles carries
for (i = 0; i < n + m; i++)
{
if (c[i] >= 10)
{
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
}
}
|
mkl_quantized_conv_ops.h | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_KERNELS_MKL_QUANTIZED_CONV_OPS_H_
#define TENSORFLOW_CORE_KERNELS_MKL_QUANTIZED_CONV_OPS_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor.h"
#ifdef INTEL_MKL
namespace tensorflow {
template <class T>
float MklFloatForOneQuantizedLevel(float range_min, float range_max) {
int64 highest = static_cast<int64>(Eigen::NumTraits<T>::highest());
int64 lowest = static_cast<int64>(Eigen::NumTraits<T>::lowest());
// Adjusting for having a symmetric range.
// for example: for 8-bit [-127, 127] as opposed to [-128, 127].
if (lowest < -highest) ++lowest;
const float float_for_one_quantized_level =
(range_max - range_min) / (highest - lowest);
return float_for_one_quantized_level;
}
template <class T1, class T2, class T3>
void MklQuantizationRangeForMultiplication(float min_a, float max_a,
float min_b, float max_b,
float* min_c, float* max_c) {
const float a_float_for_one_quant_level =
MklFloatForOneQuantizedLevel<T1>(min_a, max_a);
const float b_float_for_one_quant_level =
MklFloatForOneQuantizedLevel<T2>(min_b, max_b);
const int64 c_highest = static_cast<int64>(Eigen::NumTraits<T3>::highest());
const int64 c_lowest = static_cast<int64>(Eigen::NumTraits<T3>::lowest());
const float c_float_for_one_quant_level =
a_float_for_one_quant_level * b_float_for_one_quant_level;
*min_c = c_float_for_one_quant_level * c_lowest;
*max_c = c_float_for_one_quant_level * c_highest;
}
template <class T1, class T2, class T3>
void MklQuantizationRangeForMultiplication(float min_a, float max_a,
const Tensor& min_b_vector,
const Tensor& max_b_vector,
Tensor** min_c_vector,
Tensor** max_c_vector) {
DCHECK(min_b_vector.NumElements() == (*min_c_vector)->NumElements());
DCHECK(max_b_vector.NumElements() == (*max_c_vector)->NumElements());
size_t n_channel = min_b_vector.NumElements();
const int64 c_highest = static_cast<int64>(Eigen::NumTraits<T3>::highest());
const int64 c_lowest = static_cast<int64>(Eigen::NumTraits<T3>::lowest());
const float* min_b = min_b_vector.flat<float>().data();
const float* max_b = max_b_vector.flat<float>().data();
float* min_c = (*min_c_vector)->flat<float>().data();
float* max_c = (*max_c_vector)->flat<float>().data();
#ifndef ENABLE_DNNL_THREADPOOL
#pragma omp parallel for
#endif // !ENABLE_DNNL_THREADPOOL
// TODO: Add eigen parallel_for
for (size_t n = 0; n < n_channel; ++n) {
float a_float_for_one_quant_level =
MklFloatForOneQuantizedLevel<T1>(min_a, max_a);
float b_float_for_one_quant_level =
MklFloatForOneQuantizedLevel<T2>(min_b[n], max_b[n]);
float c_float_for_one_quant_level =
a_float_for_one_quant_level * b_float_for_one_quant_level;
min_c[n] = c_float_for_one_quant_level * c_lowest;
max_c[n] = c_float_for_one_quant_level * c_highest;
}
}
} // namespace tensorflow
#endif // INTEL_MKL
#endif // TENSORFLOW_CORE_KERNELS_MKL_QUANTIZED_CONV_OPS_H_
|
GB_binop__rdiv_fc32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_08__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_02__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_04__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_fc32)
// A*D function (colscale): GB (_AxD__rdiv_fc32)
// D*A function (rowscale): GB (_DxB__rdiv_fc32)
// C+=B function (dense accum): GB (_Cdense_accumB__rdiv_fc32)
// C+=b function (dense accum): GB (_Cdense_accumb__rdiv_fc32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_fc32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_fc32)
// C=scalar+B GB (_bind1st__rdiv_fc32)
// C=scalar+B' GB (_bind1st_tran__rdiv_fc32)
// C=A+scalar GB (_bind2nd__rdiv_fc32)
// C=A'+scalar GB (_bind2nd_tran__rdiv_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// A pattern? 0
// B type: GxB_FC32_t
// B pattern? 0
// BinaryOp: cij = GB_FC32_div (bij, aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_BTYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
GxB_FC32_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) \
GxB_FC32_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) \
GxB_FC32_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_FC32_div (y, x) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_RDIV || GxB_NO_FC32 || GxB_NO_RDIV_FC32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type GxB_FC32_t
GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__rdiv_fc32)
(
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
GxB_FC32_t *restrict Cx = (GxB_FC32_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__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *restrict Cx = (GxB_FC32_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__rdiv_fc32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
GxB_FC32_t alpha_scalar ;
GxB_FC32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((GxB_FC32_t *) alpha_scalar_in)) ;
beta_scalar = (*((GxB_FC32_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__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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__rdiv_fc32)
(
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
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ;
GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
GxB_FC32_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_FC32_div (bij, x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rdiv_fc32)
(
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 ;
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ;
GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC32_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_FC32_div (y, aij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_div (aij, x) ; \
}
GrB_Info GB (_bind1st_tran__rdiv_fc32)
(
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 \
GxB_FC32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_t
}
//------------------------------------------------------------------------------
// 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) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_div (y, aij) ; \
}
GrB_Info GB (_bind2nd_tran__rdiv_fc32)
(
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
GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
3d7pt_var.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 7 point stencil with variable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*7);
for(m=0; m<7;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 16;
tile_size[1] = 16;
tile_size[2] = 4;
tile_size[3] = 32;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<7; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) {
for (t1=-1;t1<=floord(Nt-2,8);t1++) {
lbp=max(ceild(t1,2),ceild(16*t1-Nt+3,16));
ubp=min(floord(Nt+Nz-4,16),floord(8*t1+Nz+5,16));
#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(16*t2-Nz,4)),2*t1);t3<=min(min(min(floord(Nt+Ny-4,4),floord(8*t1+Ny+13,4)),floord(16*t2+Ny+12,4)),floord(16*t1-16*t2+Nz+Ny+11,4));t3++) {
for (t4=max(max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-28,32)),ceild(4*t3-Ny-28,32));t4<=min(min(min(min(floord(4*t3+Nx,32),floord(Nt+Nx-4,32)),floord(8*t1+Nx+13,32)),floord(16*t2+Nx+12,32)),floord(16*t1-16*t2+Nz+Nx+11,32));t4++) {
for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),4*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),4*t3+2),32*t4+30),16*t1-16*t2+Nz+13);t5++) {
for (t6=max(max(16*t2,t5+1),-16*t1+16*t2+2*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(4*t3,t5+1);t7<=min(4*t3+3,t5+Ny-2);t7++) {
lbv=max(32*t4,t5+1);
ubv=min(32*t4+31,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "variable no-symmetry")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<7;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
DRB019-plusplus-var-yes.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Race condition on outLen due to unprotected writes.
Adding private (outLen) can avoid race condition. But it is wrong semantically.
Data race pairs: we allow two pair to preserve the original code pattern.
1. outLen@72:12 vs. outLen@72:12
2. output[]@72:5 vs. output[]@72:5
*/
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
int main(int argc,char *argv[])
{
int i;
int inLen = 1000;
int outLen = 0;
if (argc > 1)
inLen = atoi(argv[1]);
int input[inLen];
int output[inLen];
#pragma omp parallel for private (i)
for (i = 0; i <= inLen - 1; i += 1) {
input[i] = i;
}
for (i = 0; i <= inLen - 1; i += 1) {
output[outLen++] = input[i];
}
printf("output[0]=%d\n",output[0]);
return 0;
}
|
GB_subassign_08s_and_16.c | //------------------------------------------------------------------------------
// GB_subassign_08s_and_16: C(I,J)<M or !M> += A ; using S
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Method 08s: C(I,J)<M> += A ; using S
// Method 16: C(I,J)<!M> += A ; using S
// M: present
// Mask_comp: true or false
// C_replace: false
// accum: present
// A: matrix
// S: constructed
// C: not bitmap: use GB_bitmap_assign instead
// M, A: any sparsity structure.
#include "GB_subassign_methods.h"
GrB_Info GB_subassign_08s_and_16
(
GrB_Matrix C,
// input:
const GrB_Index *I,
const int64_t ni,
const int64_t nI,
const int Ikind,
const int64_t Icolon [3],
const GrB_Index *J,
const int64_t nj,
const int64_t nJ,
const int Jkind,
const int64_t Jcolon [3],
const GrB_Matrix M,
const bool Mask_struct, // if true, use the only structure of M
const bool Mask_comp, // if true, !M, else use M
const GrB_BinaryOp accum,
const GrB_Matrix A,
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (!GB_IS_BITMAP (C)) ;
ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M
ASSERT (!GB_aliased (C, A)) ; // NO ALIAS of C==A
//--------------------------------------------------------------------------
// S = C(I,J)
//--------------------------------------------------------------------------
GB_EMPTY_TASKLIST ;
GB_CLEAR_STATIC_HEADER (S, &S_header) ;
GB_OK (GB_subassign_symbolic (S, C, I, ni, J, nj, true, Context)) ;
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
GB_MATRIX_WAIT_IF_JUMBLED (M) ;
GB_MATRIX_WAIT_IF_JUMBLED (A) ;
GB_GET_C ; // C must not be bitmap
GB_GET_MASK ;
GB_GET_A ;
GB_GET_S ;
GB_GET_ACCUM ;
//--------------------------------------------------------------------------
// Method 16: C(I,J)<!M> += A ; using S
//--------------------------------------------------------------------------
// Time: Close to optimal. All entries in A+S must be traversed.
//--------------------------------------------------------------------------
// Method 08s: C(I,J)<M> += A ; using S
//--------------------------------------------------------------------------
// Time: Only entries in A must be traversed, and the corresponding entries
// in C located. This method constructs S and traverses all of it in the
// worst case. Compare with method 08n, which does not construct S but
// instead uses a binary search for entries in C, but it only traverses
// entries in A.*M.
//--------------------------------------------------------------------------
// Parallel: A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20)
//--------------------------------------------------------------------------
if (A_is_bitmap)
{
// all of IxJ must be examined
GB_SUBASSIGN_IXJ_SLICE ;
}
else
{
// traverse all A+S
GB_SUBASSIGN_TWO_SLICE (A, S) ;
}
//--------------------------------------------------------------------------
// phase 1: create zombies, update entries, and count pending tuples
//--------------------------------------------------------------------------
if (A_is_bitmap)
{
//----------------------------------------------------------------------
// phase1: A is bitmap
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iA_start, iA_end) ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//--------------------------------------------------------------
// get S(iA_start:iA_end,j)
//--------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iA_start) ;
int64_t pA_start = j * Avlen ;
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j)
//--------------------------------------------------------------
for (int64_t iA = iA_start ; iA < iA_end ; iA++)
{
int64_t pA = pA_start + iA ;
bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ;
bool Afound = Ab [pA] ;
if (Sfound && !Afound)
{
// S (i,j) is present but A (i,j) is not
// ----[C . 1] or [X . 1]-------------------------------
// [C . 1]: action: ( C ): no change, with accum
// [X . 1]: action: ( X ): still a zombie
// ----[C . 0] or [X . 0]-------------------------------
// [C . 0]: action: ( C ): no change, with accum
// [X . 0]: action: ( X ): still a zombie
GB_NEXT (S) ;
}
else if (!Sfound && Afound)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
}
else if (Sfound && Afound)
{
// both S (i,j) and A (i,j) present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[C A 1] or [X A 1]---------------------------
// [C A 1]: action: ( =A ): A to C no accum
// [C A 1]: action: ( =C+A ): apply accum
// [X A 1]: action: ( undelete ): zombie lives
GB_C_S_LOOKUP ;
GB_withaccum_C_A_1_matrix ;
}
GB_NEXT (S) ;
}
}
}
GB_PHASE1_TASK_WRAPUP ;
}
}
else
{
//----------------------------------------------------------------------
// phase1: A is hypersparse, sparse, or full
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE1 ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//--------------------------------------------------------------
// get A(:,j) and S(:,j)
//--------------------------------------------------------------
int64_t j = GBH (Zh, k) ;
GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen);
GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen);
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
// int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = GBI (Si, pS, Svlen) ;
int64_t iA = GBI (Ai, pA, Avlen) ;
if (iS < iA)
{
// S (i,j) is present but A (i,j) is not
// ----[C . 1] or [X . 1]-------------------------------
// [C . 1]: action: ( C ): no change, with accum
// [X . 1]: action: ( X ): still a zombie
// ----[C . 0] or [X . 0]-------------------------------
// [C . 0]: action: ( C ): no change, with accum
// [X . 0]: action: ( X ): still a zombie
GB_NEXT (S) ;
}
else if (iA < iS)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (A) ;
}
else
{
// both S (i,j) and A (i,j) present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[C A 1] or [X A 1]---------------------------
// [C A 1]: action: ( =A ): A to C no accum
// [C A 1]: action: ( =C+A ): apply accum
// [X A 1]: action: ( undelete ): zombie lives
GB_C_S_LOOKUP ;
GB_withaccum_C_A_1_matrix ;
}
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// ignore the remainder of S(:,j)
// while list A (:,j) has entries. List S (:,j) exhausted.
while (pA < pA_end)
{
// S (i,j) is not present, A (i,j) is present
int64_t iA = GBI (Ai, pA, Avlen) ;
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (A) ;
}
}
GB_PHASE1_TASK_WRAPUP ;
}
}
//--------------------------------------------------------------------------
// phase 2: insert pending tuples
//--------------------------------------------------------------------------
GB_PENDING_CUMSUM ;
if (A_is_bitmap)
{
//----------------------------------------------------------------------
// phase2: A is bitmap
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iA_start, iA_end) ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//--------------------------------------------------------------
// get S(iA_start:iA_end,j)
//--------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iA_start) ;
int64_t pA_start = j * Avlen ;
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
for (int64_t iA = iA_start ; iA < iA_end ; iA++)
{
int64_t pA = pA_start + iA ;
bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ;
bool Afound = Ab [pA] ;
if (!Sfound && Afound)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT_aij ;
}
}
else if (Sfound)
{
// S (i,j) present
GB_NEXT (S) ;
}
}
}
GB_PHASE2_TASK_WRAPUP ;
}
}
else
{
//----------------------------------------------------------------------
// phase2: A is hypersparse, sparse, or full
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE2 ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//--------------------------------------------------------------
// get A(:,j) and S(:,j)
//--------------------------------------------------------------
int64_t j = GBH (Zh, k) ;
GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen);
GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen);
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = GBI (Si, pS, Svlen) ;
int64_t iA = GBI (Ai, pA, Avlen) ;
if (iS < iA)
{
// S (i,j) is present but A (i,j) is not
GB_NEXT (S) ;
}
else if (iA < iS)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT_aij ;
}
GB_NEXT (A) ;
}
else
{
// both S (i,j) and A (i,j) present
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// while list A (:,j) has entries. List S (:,j) exhausted.
while (pA < pA_end)
{
// S (i,j) is not present, A (i,j) is present
int64_t iA = GBI (Ai, pA, Avlen) ;
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT_aij ;
}
GB_NEXT (A) ;
}
}
GB_PHASE2_TASK_WRAPUP ;
}
}
//--------------------------------------------------------------------------
// finalize the matrix and return result
//--------------------------------------------------------------------------
GB_SUBASSIGN_WRAPUP ;
}
|
GB_unop__cos_fc32_fc32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__cos_fc32_fc32
// op(A') function: GB_unop_tran__cos_fc32_fc32
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = aij
// unaryop: cij = ccosf (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = ccosf (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = aij ; \
Cx [pC] = ccosf (z) ; \
}
// 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_COS || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__cos_fc32_fc32
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = ccosf (z) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = ccosf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__cos_fc32_fc32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *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
|
GB_binop__band_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__band_int8
// A.*B function (eWiseMult): GB_AemultB__band_int8
// A*D function (colscale): (none)
// D*A function (rowscale): (node)
// C+=B function (dense accum): GB_Cdense_accumB__band_int8
// C+=b function (dense accum): GB_Cdense_accumb__band_int8
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__band_int8
// C=scalar+B GB_bind1st__band_int8
// C=scalar+B' GB_bind1st_tran__band_int8
// C=A+scalar GB_bind2nd__band_int8
// C=A'+scalar GB_bind2nd_tran__band_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_BAND || GxB_NO_INT8 || GxB_NO_BAND_INT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (none)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__band_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__band_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__band_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
//------------------------------------------------------------------------------
#if 0
GrB_Info (none)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t *GB_RESTRICT Cx = (int8_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info (node)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t *GB_RESTRICT Cx = (int8_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
#undef GB_FREE_ALL
#define GB_FREE_ALL \
{ \
GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \
GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \
GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \
}
GrB_Info GB_AaddB__band_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__band_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__band_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__band_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__band_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__band_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
|
kvstore_dist_server.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file mxnet_node.h
* \brief implement mxnet nodes
*/
#ifndef MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_
#define MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_
#include <mxnet/c_api.h>
#include <mxnet/kvstore.h>
#include <ps/ps.h>
#include <queue>
#include <string>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <functional>
#include <future>
#include <vector>
#include "../profiler/profiler.h"
#include "../operator/tensor/elemwise_binary_op-inl.h"
#include "../operator/tensor/init_op.h"
namespace mxnet {
namespace kvstore {
// maintain same order in frontend.
enum class CommandType {
kController,
kSetMultiPrecision,
kStopServer,
kSyncMode,
kSetGradientCompression,
kSetProfilerParams
};
enum class RequestType { kDefaultPushPull, kRowSparsePushPull, kCompressedPushPull };
struct DataHandleType {
RequestType requestType;
int dtype;
};
/*!
* Uses Cantor pairing function to generate a unique number given two numbers.
* This number can also be inverted to find the unique pair whose Cantor value is this number.
* Ref: https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function
* \param requestType RequestType
* \param dtype integer
* \return Cantor value of arguments
*/
static int GetCommandType(RequestType requestType, int d) {
int m = static_cast<int>(requestType);
return (((m + d) * (m + d + 1)) / 2) + d;
}
/*!
* Unpairs Cantor value and finds the two integers used to pair.
* Then returns DataHandleType object with those numbers.
* \param cmd DataHandleCommand generated by GetCommandType function
* \return DataHandleType
*/
static DataHandleType DepairDataHandleType(int cmd) {
int w = std::floor((std::sqrt(8 * cmd + 1) - 1) / 2);
int t = ((w * w) + w) / 2;
int y = cmd - t;
int x = w - y;
CHECK_GE(x, 0);
CHECK_GE(y, 0);
DataHandleType type;
type.requestType = static_cast<RequestType>(x);
type.dtype = y;
return type;
}
/**
* \brief executor runs a function using the thread called \ref Start
*/
class Executor {
public:
/**
* \brief start the executor
*/
void Start() {
std::unique_lock<std::mutex> lk(mu_);
while (true) {
cond_.wait(lk, [this] { return !queue_.empty(); });
Block blk = std::move(queue_.front());
queue_.pop();
lk.unlock();
if (blk.f) {
blk.f();
blk.p->set_value();
} else {
blk.p->set_value();
break;
}
lk.lock();
}
}
/**
* \brief function
*/
typedef std::function<void()> Func;
/**
* \brief let the thread called \ref Start to exec a function. threadsafe
*/
void Exec(const Func& func) {
Block blk(func);
auto fut = blk.p->get_future();
{
std::lock_guard<std::mutex> lk(mu_);
queue_.push(std::move(blk));
cond_.notify_one();
}
fut.wait();
}
/**
* \brief stop the thread, threadsafe
*/
void Stop() {
Exec(Func());
}
private:
struct Block {
explicit Block(const Func& func) : f(func), p(std::make_shared<std::promise<void>>()) {}
Func f;
std::shared_ptr<std::promise<void>> p;
};
std::queue<Block> queue_;
std::mutex mu_;
std::condition_variable cond_;
};
class KVStoreDistServer {
public:
KVStoreDistServer() {
using namespace std::placeholders;
ps_server_ = new ps::KVServer<char>(0);
static_cast<ps::SimpleApp*>(ps_server_)
->set_request_handle(std::bind(&KVStoreDistServer::CommandHandle, this, _1, _2));
ps_server_->set_request_handle(std::bind(&KVStoreDistServer::DataHandleEx, this, _1, _2, _3));
sync_mode_ = false;
gradient_compression_ = std::make_shared<GradientCompression>();
log_verbose_ = dmlc::GetEnv("MXNET_KVSTORE_DIST_ROW_SPARSE_VERBOSE", false);
}
~KVStoreDistServer() {
profiler::Profiler::Get()->SetState(profiler::Profiler::ProfilerState(0));
delete ps_server_;
}
void set_controller(const KVStore::Controller& controller) {
CHECK(controller);
controller_ = controller;
}
void set_updater(const KVStore::Updater& updater) {
CHECK(updater);
updater_ = updater;
}
/**
* \brief blocked until received the command \a kSyncMode
*/
void Run() {
exec_.Start();
}
private:
struct UpdateBuf {
std::vector<ps::KVMeta> request;
NDArray merged;
// temp_array is used to cast received values as float32 for computation if required
NDArray temp_array;
};
void CommandHandle(const ps::SimpleData& recved, ps::SimpleApp* app) {
CommandType recved_type = static_cast<CommandType>(recved.head);
switch (recved_type) {
case CommandType::kStopServer:
exec_.Stop();
break;
case CommandType::kSyncMode:
sync_mode_ = true;
break;
case CommandType::kSetGradientCompression:
gradient_compression_->DecodeParams(recved.body);
break;
case CommandType::kSetProfilerParams:
// last char is the type of profiler command
ProcessServerProfilerCommands(
static_cast<KVStoreServerProfilerCommand>(recved.body.back() - '0'), recved.body);
break;
case CommandType::kSetMultiPrecision:
// uses value 1 for message id from frontend
if (!multi_precision_) {
multi_precision_ = true;
CreateMultiPrecisionCopies();
}
break;
case CommandType::kController:
// this uses value 0 for message id from frontend
// let the main thread to execute ctrl, which is necessary for python
exec_.Exec([this, recved]() {
CHECK(controller_);
controller_(recved.head, recved.body);
});
break;
}
app->Response(recved);
}
/*
* For keys already initialized, if necessary create stored_realt.
* This will only be used if by some wrong usage of kvstore,
* some keys are initialized before optimizer is set.
*/
void CreateMultiPrecisionCopies() {
for (auto const& stored_entry : store_) {
const int key = stored_entry.first;
const NDArray& stored = stored_entry.second;
if (stored.dtype() != mshadow::kFloat32) {
auto& stored_realt = store_realt_[key];
if (stored.storage_type() == kRowSparseStorage) {
stored_realt =
NDArray(kRowSparseStorage, stored.shape(), stored.ctx(), true, mshadow::kFloat32);
} else {
stored_realt = NDArray(stored.shape(), stored.ctx(), false, mshadow::kFloat32);
}
auto& update = update_buf_[key];
if (!update.merged.is_none()) {
if (update.merged.storage_type() == kRowSparseStorage) {
update.merged = NDArray(kRowSparseStorage,
update.merged.shape(),
update.merged.ctx(),
true,
mshadow::kFloat32);
} else {
update.merged =
NDArray(update.merged.shape(), update.merged.ctx(), false, mshadow::kFloat32);
}
}
CHECK(update.request.size() == 0)
<< ps::MyRank() << "Multiprecision mode can not be set while pushes are underway."
<< "Please set optimizer before pushing keys." << key << " " << update.request.size();
CopyFromTo(stored, stored_realt);
}
}
for (auto const& stored_realt_entry : store_realt_) {
stored_realt_entry.second.WaitToRead();
}
}
void ProcessServerProfilerCommands(KVStoreServerProfilerCommand type, const std::string& body) {
switch (type) {
case KVStoreServerProfilerCommand::kSetConfig:
SetProfilerConfig(body.substr(0, body.size() - 1));
break;
case KVStoreServerProfilerCommand::kState:
MXSetProfilerState(static_cast<int>(body.front() - '0'));
break;
case KVStoreServerProfilerCommand::kPause:
MXProfilePause(static_cast<int>(body.front() - '0'));
break;
case KVStoreServerProfilerCommand::kDump:
MXDumpProfile(static_cast<int>(body.front() - '0'));
break;
}
}
void SetProfilerConfig(std::string params_str) {
std::vector<std::string> elems;
mxnet::kvstore::split(params_str, ',', std::back_inserter(elems));
std::vector<const char*> ckeys;
std::vector<const char*> cvals;
ckeys.reserve(elems.size());
cvals.reserve(elems.size());
for (size_t i = 0; i < elems.size(); i++) {
std::vector<std::string> parts;
mxnet::kvstore::split(elems[i], ':', std::back_inserter(parts));
CHECK_EQ(parts.size(), 2) << "Improper profiler config passed from worker";
CHECK(!parts[0].empty()) << "ProfilerConfig parameter is empty";
CHECK(!parts[1].empty()) << "ProfilerConfig value is empty for parameter " << parts[0];
if (parts[0] == "filename") {
parts[1] = "rank" + std::to_string(ps::MyRank()) + "_" + parts[1];
}
char* ckey = new char[parts[0].length() + 1];
std::snprintf(ckey, parts[0].length() + 1, "%s", parts[0].c_str());
ckeys.push_back(ckey);
char* cval = new char[parts[1].length() + 1];
std::snprintf(cval, parts[1].length() + 1, "%s", parts[1].c_str());
cvals.push_back(cval);
}
MXSetProfilerConfig(elems.size(), &ckeys[0], &cvals[0]);
for (size_t i = 0; i < ckeys.size(); i++) {
delete[] ckeys[i];
delete[] cvals[i];
}
}
void DataHandleEx(const ps::KVMeta& req_meta,
const ps::KVPairs<char>& req_data,
ps::KVServer<char>* server) {
DataHandleType type = DepairDataHandleType(req_meta.cmd);
switch (type.requestType) {
case RequestType::kRowSparsePushPull:
DataHandleRowSparse(type, req_meta, req_data, server);
break;
case RequestType::kCompressedPushPull:
DataHandleCompressed(type, req_meta, req_data, server);
break;
case RequestType::kDefaultPushPull:
DataHandleDefault(type, req_meta, req_data, server);
break;
}
}
inline bool has_multi_precision_copy(const DataHandleType type) {
return multi_precision_ && type.dtype != mshadow::kFloat32;
}
inline void ApplyUpdates(const DataHandleType type,
const int key,
const ps::KVPairs<char>& req_data,
UpdateBuf* update_buf,
ps::KVServer<char>* server) {
if (!sync_mode_ || update_buf->request.size() == (size_t)ps::NumWorkers()) {
// let the main thread to execute updater_, which is necessary for python
auto& stored = has_multi_precision_copy(type) ? store_realt_[key] : store_[key];
auto& update = sync_mode_ ? update_buf->merged : update_buf->temp_array;
if (updater_) {
exec_.Exec([this, key, &update, &stored]() {
CHECK(updater_);
updater_(key, update, &stored);
});
} else {
CHECK(sync_mode_) << "Updater needs to be set for async mode";
// if no updater, just copy
CopyFromTo(update_buf->merged, &stored);
}
if (log_verbose_) {
LOG(INFO) << "sent response to " << update_buf->request.size() << " workers";
}
/**
* Request can be for either push, pull or pushpull
* If pull flag is set, respond immediately with the updated values
* Otherwise, only send the notification
*/
bool has_pull = false;
for (const auto& req : update_buf->request) {
has_pull = has_pull || req.pull;
}
if (has_pull) {
// if there is a pull request, perform WaitToRead() once before DefaultStorageResponse
if (has_multi_precision_copy(type))
CopyFromTo(stored, store_[key]);
stored.WaitToRead();
for (const auto& req : update_buf->request) {
if (req.pull) {
DefaultStorageResponse(type, key, req, req_data, server);
}
}
update_buf->request.clear();
} else {
// otherwise, send response directly
for (const auto& req : update_buf->request) {
server->Response(req);
}
update_buf->request.clear();
if (has_multi_precision_copy(type))
CopyFromTo(stored, store_[key]);
stored.WaitToRead();
}
} else {
update_buf->merged.WaitToRead();
}
}
void DecodeRowIds(const ps::SArray<ps::Key>& keys,
int64_t* indices,
const int64_t master_key,
const int64_t num_rows) {
indices[0] = 0;
for (int64_t i = 1; i <= num_rows; i++) {
int key = DecodeKey(keys[i]);
auto row_id = key - master_key;
indices[i - 1] = row_id;
}
}
void AccumulateRowSparseGrads(const DataHandleType type,
const NDArray& recved,
UpdateBuf* updateBuf) {
NDArray out(kRowSparseStorage,
updateBuf->merged.shape(),
Context(),
true,
has_multi_precision_copy(type) ? mshadow::kFloat32 : type.dtype);
if (has_multi_precision_copy(type))
CopyFromTo(recved, updateBuf->temp_array);
const NDArray& to_merge = has_multi_precision_copy(type) ? updateBuf->temp_array : recved;
// accumulate row_sparse gradients
using namespace mshadow;
Engine::Get()->PushAsync(
[to_merge, updateBuf, out](RunContext ctx, Engine::CallbackOnComplete on_complete) {
op::ElemwiseBinaryOp::ComputeEx<cpu, op::mshadow_op::plus>(
{}, {}, {to_merge, updateBuf->merged}, {kWriteTo}, {out});
on_complete();
},
to_merge.ctx(),
{to_merge.var(), updateBuf->merged.var()},
{out.var()},
FnProperty::kNormal,
0,
PROFILER_MESSAGE_FUNCNAME);
CopyFromTo(out, &(updateBuf->merged), 0);
updateBuf->merged.WaitToRead();
}
void RowSparsePullResponse(const DataHandleType type,
const int master_key,
const size_t num_rows,
const ps::KVMeta& req_meta,
const ps::KVPairs<char>& req_data,
ps::KVServer<char>* server) {
if (log_verbose_)
LOG(INFO) << "pull: " << master_key;
ps::KVPairs<char> response;
if (num_rows == 0) {
std::vector<int> lens(req_data.keys.size(), 0);
response.keys = req_data.keys;
response.lens.CopyFrom(lens.begin(), lens.end());
server->Response(req_meta, response);
return;
}
const NDArray& stored = store_[master_key];
if (has_multi_precision_copy(type))
stored.WaitToRead();
CHECK(!stored.is_none()) << "init " << master_key << " first";
auto shape = stored.shape();
auto unit_len = shape.ProdShape(1, shape.ndim());
const int num_bytes = mshadow::mshadow_sizeof(type.dtype);
const int unit_size = unit_len * num_bytes;
const char* data = static_cast<char*>(stored.data().dptr_);
auto len = num_rows * unit_size;
// concat values
response.vals.resize(len);
#pragma omp parallel for
for (size_t i = 1; i <= num_rows; i++) {
int key = DecodeKey(req_data.keys[i]);
int64_t row_id = key - master_key;
const auto src = data + row_id * unit_size;
auto begin = (i - 1) * unit_size;
auto end = i * unit_size;
response.vals.segment(begin, end).CopyFrom(src, unit_size);
}
// setup response
response.keys = req_data.keys;
std::vector<int> lens(req_data.keys.size(), unit_len);
lens[0] = 0;
response.lens.CopyFrom(lens.begin(), lens.end());
server->Response(req_meta, response);
}
void InitRowSparseStored(const DataHandleType type,
const int master_key,
const size_t num_rows,
const ps::KVMeta& req_meta,
const ps::KVPairs<char>& req_data,
ps::KVServer<char>* server) {
auto& stored = has_multi_precision_copy(type) ? store_realt_[master_key] : store_[master_key];
int dtype = type.dtype;
int num_bytes = mshadow::mshadow_sizeof(dtype);
auto unit_len = req_data.lens[1] / num_bytes;
CHECK_GT(unit_len, 0);
size_t ds[] = {num_rows, (size_t)unit_len};
mxnet::TShape dshape(ds, ds + 2);
CHECK_EQ(req_data.vals.size(), num_rows * unit_len * num_bytes);
TBlob recv_blob;
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
recv_blob = TBlob(reinterpret_cast<DType*>(req_data.vals.data()), dshape, cpu::kDevMask);
})
NDArray recved = NDArray(recv_blob, 0);
stored = NDArray(kRowSparseStorage,
dshape,
Context(),
true,
has_multi_precision_copy(type) ? mshadow::kFloat32 : type.dtype);
if (has_multi_precision_copy(type)) {
store_[master_key] = NDArray(kRowSparseStorage, dshape, Context(), true, type.dtype);
}
Engine::Get()->PushAsync(
[this, recved, stored, type](RunContext ctx, Engine::CallbackOnComplete on_complete) {
NDArray rsp = stored;
stored.CheckAndAlloc({mshadow::Shape1(recved.shape()[0])});
mshadow::Stream<cpu>* s = ctx.get_stream<cpu>();
using namespace mxnet::op;
nnvm::dim_t nnr = rsp.shape()[0];
MSHADOW_IDX_TYPE_SWITCH(rsp.aux_type(rowsparse::kIdx), IType, {
IType* idx = rsp.aux_data(rowsparse::kIdx).dptr<IType>();
mxnet_op::Kernel<PopulateFullIdxRspKernel, cpu>::Launch(s, nnr, idx);
});
TBlob rsp_data = rsp.data();
// copies or casts as appropriate
ndarray::Copy<cpu, cpu>(recved.data(), &rsp_data, Context(), Context(), RunContext());
on_complete();
},
recved.ctx(),
{recved.var()},
{stored.var()},
FnProperty::kNormal,
0,
PROFILER_MESSAGE_FUNCNAME);
if (has_multi_precision_copy(type)) {
CopyFromTo(stored, store_[master_key]);
store_[master_key].WaitToRead();
}
stored.WaitToRead();
server->Response(req_meta);
}
void DataHandleRowSparse(const DataHandleType type,
const ps::KVMeta& req_meta,
const ps::KVPairs<char>& req_data,
ps::KVServer<char>* server) {
int master_key = DecodeKey(req_data.keys[0]);
auto num_rows = req_data.keys.size() - 1;
auto& stored = store_[master_key];
if (req_meta.push) {
CHECK_GT(req_data.lens.size(), 0) << "req_data.lens cannot be empty";
CHECK_EQ(req_data.lens[0], 0);
if (stored.is_none()) {
if (log_verbose_)
LOG(INFO) << "initial push: " << master_key;
// initialization
CHECK_GT(num_rows, 0) << "init with empty data is not supported";
InitRowSparseStored(type, master_key, num_rows, req_meta, req_data, server);
return;
} else {
if (log_verbose_)
LOG(INFO) << "push: " << master_key << " " << req_data.keys;
auto& updates = update_buf_[master_key];
if (sync_mode_ && updates.merged.is_none()) {
updates.merged = NDArray(kRowSparseStorage,
stored.shape(),
Context(),
true,
has_multi_precision_copy(type) ? mshadow::kFloat32 : type.dtype);
}
if (has_multi_precision_copy(type) && updates.temp_array.is_none()) {
updates.temp_array =
NDArray(kRowSparseStorage, stored.shape(), Context(), false, mshadow::kFloat32);
}
if (num_rows == 0) {
if (sync_mode_) {
if (updates.request.empty()) {
// reset to zeros
int merged_dtype = has_multi_precision_copy(type) ? mshadow::kFloat32 : type.dtype;
updates.merged =
NDArray(kRowSparseStorage, stored.shape(), Context(), true, merged_dtype);
} // else nothing to aggregate
updates.request.push_back(req_meta);
ApplyUpdates(type, master_key, req_data, &updates, server);
} else {
server->Response(req_meta);
}
} else {
auto unit_len = req_data.lens[1] / mshadow::mshadow_sizeof(type.dtype);
CHECK_GT(unit_len, 0);
// indices
std::vector<int64_t> indices(num_rows);
DecodeRowIds(req_data.keys, indices.data(), master_key, num_rows);
// data
TBlob idx_blob(indices.data(), mshadow::Shape1(num_rows), cpu::kDevMask);
size_t ds[] = {(size_t)num_rows, (size_t)unit_len};
mxnet::TShape dshape(ds, ds + 2);
TBlob recv_blob;
MSHADOW_REAL_TYPE_SWITCH(type.dtype, DType, {
recv_blob =
TBlob(reinterpret_cast<DType*>(req_data.vals.data()), dshape, cpu::kDevMask);
})
// row_sparse NDArray
NDArray recved(kRowSparseStorage, stored.shape(), recv_blob, {idx_blob}, 0);
if (updates.request.empty()) {
if (sync_mode_) {
CopyFromTo(recved, updates.merged);
} else {
if (has_multi_precision_copy(type)) {
CopyFromTo(recved, updates.temp_array);
} else {
updates.temp_array = recved;
}
}
} else {
CHECK(sync_mode_);
AccumulateRowSparseGrads(type, recved, &updates);
}
updates.request.push_back(req_meta);
ApplyUpdates(type, master_key, req_data, &updates, server);
}
}
} else {
// pull
RowSparsePullResponse(type, master_key, num_rows, req_meta, req_data, server);
}
}
void DefaultStorageResponse(const DataHandleType type,
const int key,
const ps::KVMeta& req_meta,
const ps::KVPairs<char>& req_data,
ps::KVServer<char>* server) {
ps::KVPairs<char> response;
const NDArray& stored = store_[key];
CHECK(!stored.is_none()) << "init " << key << " first";
// as server returns when store_realt is ready in this case
if (has_multi_precision_copy(type))
stored.WaitToRead();
auto len = stored.shape().Size() * mshadow::mshadow_sizeof(stored.dtype());
response.keys = req_data.keys;
response.lens = {len};
// TODO(mli) try to remove this CopyFrom
response.vals.CopyFrom(static_cast<const char*>(stored.data().dptr_), len);
server->Response(req_meta, response);
}
void DataHandleCompressed(const DataHandleType type,
const ps::KVMeta& req_meta,
const ps::KVPairs<char>& req_data,
ps::KVServer<char>* server) {
CHECK_EQ(type.dtype, mshadow::kFloat32)
<< "Gradient compression is currently supported for fp32 only";
if (req_meta.push) {
// there used several WaitToRead, this is because \a recved's memory
// could be deallocated when this function returns. so we need to make sure
// the operators with \a NDArray are actually finished
// first for dummy key which represents original size of array, whose len is 0
CHECK_EQ(req_data.keys.size(), (size_t)2);
CHECK_EQ(req_data.lens.size(), (size_t)2);
CHECK_EQ(req_data.vals.size(), (size_t)req_data.lens[1]);
int original_size = DecodeKey(req_data.keys[0]);
int key = DecodeKey(req_data.keys[1]);
auto& stored = store_[key];
size_t ds[] = {(size_t)req_data.lens[1] / mshadow::mshadow_sizeof(type.dtype)};
mxnet::TShape dshape(ds, ds + 1);
TBlob recv_blob(reinterpret_cast<real_t*>(req_data.vals.data()), dshape, cpu::kDevMask);
NDArray recved = NDArray(recv_blob, 0);
NDArray decomp_buf = decomp_buf_[key];
dshape = mxnet::TShape{(int64_t)original_size};
if (decomp_buf.is_none()) {
decomp_buf = NDArray(dshape, Context());
}
if (stored.is_none()) {
stored = NDArray(dshape, Context());
gradient_compression_->Dequantize(recved, &stored, 0);
server->Response(req_meta);
stored.WaitToRead();
} else if (sync_mode_) {
// synced push
auto& merged = update_buf_[key];
if (merged.merged.is_none()) {
merged.merged = NDArray(dshape, Context());
}
if (merged.request.size() == 0) {
gradient_compression_->Dequantize(recved, &merged.merged, 0);
} else {
gradient_compression_->Dequantize(recved, &decomp_buf, 0);
merged.merged += decomp_buf;
}
merged.request.push_back(req_meta);
ApplyUpdates(type, key, req_data, &merged, server);
} else {
// async push
gradient_compression_->Dequantize(recved, &decomp_buf, 0);
exec_.Exec([this, key, &decomp_buf, &stored]() {
CHECK(updater_);
updater_(key, decomp_buf, &stored);
});
server->Response(req_meta);
stored.WaitToRead();
}
} else { // pull
CHECK_EQ(req_data.keys.size(), (size_t)1);
CHECK_EQ(req_data.lens.size(), (size_t)0);
int key = DecodeKey(req_data.keys[0]);
DefaultStorageResponse(type, key, req_meta, req_data, server);
}
}
void DataHandleDefault(const DataHandleType type,
const ps::KVMeta& req_meta,
const ps::KVPairs<char>& req_data,
ps::KVServer<char>* server) {
// do some check
CHECK_EQ(req_data.keys.size(), (size_t)1);
if (req_meta.push) {
CHECK_EQ(req_data.lens.size(), (size_t)1);
CHECK_EQ(req_data.vals.size(), (size_t)req_data.lens[0]);
}
int key = DecodeKey(req_data.keys[0]);
auto& stored = has_multi_precision_copy(type) ? store_realt_[key] : store_[key];
// there used several WaitToRead, this is because \a recved's memory
// could be deallocated when this function returns. so we need to make sure
// the operators with \a NDArray are actually finished
if (req_meta.push) {
size_t ds[] = {(size_t)req_data.lens[0] / mshadow::mshadow_sizeof(type.dtype)};
mxnet::TShape dshape(ds, ds + 1);
TBlob recv_blob;
MSHADOW_REAL_TYPE_SWITCH(type.dtype, DType, {
recv_blob = TBlob(reinterpret_cast<DType*>(req_data.vals.data()), dshape, cpu::kDevMask);
})
NDArray recved = NDArray(recv_blob, 0);
if (stored.is_none()) {
// initialization
stored = NDArray(dshape,
Context(),
false,
has_multi_precision_copy(type) ? mshadow::kFloat32 : type.dtype);
CopyFromTo(recved, &stored, 0);
server->Response(req_meta);
if (has_multi_precision_copy(type)) {
auto& stored_dtype = store_[key];
stored_dtype = NDArray(dshape, Context(), false, type.dtype);
CopyFromTo(stored, stored_dtype);
stored_dtype.WaitToRead();
}
stored.WaitToRead();
} else {
auto& updates = update_buf_[key];
if (sync_mode_ && updates.merged.is_none()) {
updates.merged = NDArray(dshape,
Context(),
false,
has_multi_precision_copy(type) ? mshadow::kFloat32 : type.dtype);
}
if (has_multi_precision_copy(type) && updates.temp_array.is_none()) {
updates.temp_array = NDArray(dshape, Context(), false, mshadow::kFloat32);
}
if (updates.request.empty()) {
if (sync_mode_) {
CopyFromTo(recved, updates.merged);
} else {
if (has_multi_precision_copy(type)) {
CopyFromTo(recved, updates.temp_array);
} else {
updates.temp_array = recved;
}
}
} else {
CHECK(sync_mode_);
if (has_multi_precision_copy(type)) {
CopyFromTo(recved, updates.temp_array);
updates.merged += updates.temp_array;
} else {
updates.merged += recved;
}
}
updates.request.push_back(req_meta);
ApplyUpdates(type, key, req_data, &updates, server);
}
} else {
DefaultStorageResponse(type, key, req_meta, req_data, server);
}
}
int DecodeKey(ps::Key key) {
auto kr = ps::Postoffice::Get()->GetServerKeyRanges()[ps::MyRank()];
return key - kr.begin();
}
/**
* \brief user defined mode for push
*/
bool sync_mode_;
KVStore::Controller controller_;
KVStore::Updater updater_;
/**
* \brief store_ contains the value at kvstore for each key
*/
std::unordered_map<int, NDArray> store_;
std::unordered_map<int, NDArray> store_realt_;
/**
* \brief merge_buf_ is a buffer used if sync_mode is true. It represents
* values from different workers being merged. The store will be updated
* to this value when values from all workers are pushed into this buffer.
*/
std::unordered_map<int, UpdateBuf> update_buf_;
/**
* \brief decomp_buf_ is a buffer into which compressed values are
* decompressed before merging to the store. used when compress_!='none'
*/
std::unordered_map<int, NDArray> decomp_buf_;
Executor exec_;
ps::KVServer<char>* ps_server_;
// whether to LOG verbose information
bool log_verbose_;
/*
* \brief whether to use multi precision mode.
* in multi precision mode, all weights are stored as float32.
* any gradient received will be cast to float32 before accumulation and updating of weights.
*/
bool multi_precision_;
/**
* \brief gradient compression object.
* starts with none, used after SetGradientCompression sets the type
* currently there is no support for unsetting gradient compression
*/
std::shared_ptr<kvstore::GradientCompression> gradient_compression_;
};
} // namespace kvstore
} // namespace mxnet
#endif // MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_
|
strassen-task.c | /**********************************************************************************************/
/* This program is part of the Barcelona OpenMP Tasks Suite */
/* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */
/* Copyright (C) 2009 Universitat Politecnica de Catalunya */
/* */
/**********************************************************************************************/
/*
* Copyright (c) 1996 Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to use, copy, modify, and distribute the Software without
* restriction, provided the Software, including any modified copies made
* under this license, is not distributed for a fee, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* 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 MASSACHUSETTS INSTITUTE OF TECHNOLOGY 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.
*
* Except as contained in this notice, the name of the Massachusetts
* Institute of Technology shall not be used in advertising or otherwise
* to promote the sale, use or other dealings in this Software without
* prior written authorization from the Massachusetts Institute of
* Technology.
*
*/
#include <stdlib.h>
#include "strassen.h"
/*****************************************************************************
**
** OptimizedStrassenMultiply
**
** For large matrices A, B, and C of size MatrixSize * MatrixSize this
** function performs the operation C = A x B efficiently.
**
** INPUT:
** C = (*C WRITE) Address of top left element of matrix C.
** A = (*A IS READ ONLY) Address of top left element of matrix A.
** B = (*B IS READ ONLY) Address of top left element of matrix B.
** MatrixSize = Size of matrices (for n*n matrix, MatrixSize = n)
** RowWidthA = Number of elements in memory between A[x,y] and A[x,y+1]
** RowWidthB = Number of elements in memory between B[x,y] and B[x,y+1]
** RowWidthC = Number of elements in memory between C[x,y] and C[x,y+1]
**
** OUTPUT:
** C = (*C WRITE) Matrix C contains A x B. (Initial value of *C undefined.)
**
*****************************************************************************/
static void OptimizedStrassenMultiply_par(double *C, double *A, double *B,
unsigned MatrixSize, unsigned RowWidthC, unsigned RowWidthA,
unsigned RowWidthB, unsigned int Depth, unsigned int cutoff_depth,
unsigned cutoff_size)
{
unsigned QuadrantSize = MatrixSize >> 1; /* MatixSize / 2 */
unsigned QuadrantSizeInBytes = sizeof(double) * QuadrantSize * QuadrantSize;
unsigned Column, Row;
/************************************************************************
** For each matrix A, B, and C, we'll want pointers to each quandrant
** in the matrix. These quandrants will be addressed as follows:
** -- --
** | A A12 |
** | |
** | A21 A22 |
** -- --
************************************************************************/
double /* *A, *B, *C, */ *A12, *B12, *C12,
*A21, *B21, *C21, *A22, *B22, *C22;
double *S1,*S2,*S3,*S4,*S5,*S6,*S7,*S8,*M2,*M5,*T1sMULT;
#define T2sMULT C22
#define NumberOfVariables 11
char *Heap;
void *StartHeap;
if (MatrixSize <= cutoff_size) {
MultiplyByDivideAndConquer(C, A, B, MatrixSize, RowWidthC, RowWidthA, RowWidthB, 0);
return;
}
/* Initialize quandrant matrices */
A12 = A + QuadrantSize;
B12 = B + QuadrantSize;
C12 = C + QuadrantSize;
A21 = A + (RowWidthA * QuadrantSize);
B21 = B + (RowWidthB * QuadrantSize);
C21 = C + (RowWidthC * QuadrantSize);
A22 = A21 + QuadrantSize;
B22 = B21 + QuadrantSize;
C22 = C21 + QuadrantSize;
/* Allocate Heap Space Here */
StartHeap = Heap = malloc(QuadrantSizeInBytes * NumberOfVariables);
/* Distribute the heap space over the variables */
S1 = (double*) Heap; Heap += QuadrantSizeInBytes;
S2 = (double*) Heap; Heap += QuadrantSizeInBytes;
S3 = (double*) Heap; Heap += QuadrantSizeInBytes;
S4 = (double*) Heap; Heap += QuadrantSizeInBytes;
S5 = (double*) Heap; Heap += QuadrantSizeInBytes;
S6 = (double*) Heap; Heap += QuadrantSizeInBytes;
S7 = (double*) Heap; Heap += QuadrantSizeInBytes;
S8 = (double*) Heap; Heap += QuadrantSizeInBytes;
M2 = (double*) Heap; Heap += QuadrantSizeInBytes;
M5 = (double*) Heap; Heap += QuadrantSizeInBytes;
T1sMULT = (double*) Heap; Heap += QuadrantSizeInBytes;
if (Depth < cutoff_depth)
{
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S1[Row * QuadrantSize + Column] = A21[RowWidthA * Row + Column] + A22[RowWidthA * Row + Column];
#pragma omp taskwait
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S2[Row * QuadrantSize + Column] = S1[Row * QuadrantSize + Column] - A[RowWidthA * Row + Column];
#pragma omp taskwait
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S4[Row * QuadrantSize + Column] = A12[Row * RowWidthA + Column] - S2[QuadrantSize * Row + Column];
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S5[Row * QuadrantSize + Column] = B12[Row * RowWidthB + Column] - B[Row * RowWidthB + Column];
#pragma omp taskwait
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S6[Row * QuadrantSize + Column] = B22[Row * RowWidthB + Column] - S5[Row * QuadrantSize + Column];
#pragma omp taskwait
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S8[Row * QuadrantSize + Column] = S6[Row * QuadrantSize + Column] - B21[Row * RowWidthB + Column];
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S3[Row * QuadrantSize + Column] = A[RowWidthA * Row + Column] - A21[RowWidthA * Row + Column];
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++)
S7[Row * QuadrantSize + Column] = B22[Row * RowWidthB + Column] - B12[Row * RowWidthB + Column];
#pragma omp taskwait
/* M2 = A x B */
#pragma omp task untied
OptimizedStrassenMultiply_par(M2, A, B, QuadrantSize, QuadrantSize, RowWidthA, RowWidthB, Depth+1, cutoff_depth, cutoff_size);
/* M5 = S1 * S5 */
#pragma omp task untied
OptimizedStrassenMultiply_par(M5, S1, S5, QuadrantSize, QuadrantSize, QuadrantSize, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of T1 = S2 x S6 + M2 */
#pragma omp task untied
OptimizedStrassenMultiply_par(T1sMULT, S2, S6, QuadrantSize, QuadrantSize, QuadrantSize, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of T2 = T1 + S3 x S7 */
#pragma omp task untied
OptimizedStrassenMultiply_par(C22, S3, S7, QuadrantSize, RowWidthC /*FIXME*/, QuadrantSize, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of C = M2 + A12 * B21 */
#pragma omp task untied
OptimizedStrassenMultiply_par(C, A12, B21, QuadrantSize, RowWidthC, RowWidthA, RowWidthB, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of C12 = S4 x B22 + T1 + M5 */
#pragma omp task untied
OptimizedStrassenMultiply_par(C12, S4, B22, QuadrantSize, RowWidthC, QuadrantSize, RowWidthB, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of C21 = T2 - A22 * S8 */
#pragma omp task untied
OptimizedStrassenMultiply_par(C21, A22, S8, QuadrantSize, RowWidthC, RowWidthA, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
#pragma omp taskwait
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column += 1)
C[RowWidthC * Row + Column] += M2[Row * QuadrantSize + Column];
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column += 1)
C12[RowWidthC * Row + Column] += M5[Row * QuadrantSize + Column] + T1sMULT[Row * QuadrantSize + Column] + M2[Row * QuadrantSize + Column];
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column += 1)
C21[RowWidthC * Row + Column] = -C21[RowWidthC * Row + Column] + C22[RowWidthC * Row + Column] + T1sMULT[Row * QuadrantSize + Column] + M2[Row * QuadrantSize + Column];
#pragma omp taskwait
#pragma omp task private(Row, Column)
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column += 1)
C22[RowWidthC * Row + Column] += M5[Row * QuadrantSize + Column] + T1sMULT[Row * QuadrantSize + Column] + M2[Row * QuadrantSize + Column];
#pragma omp taskwait
}
else
{
for (Row = 0; Row < QuadrantSize; Row++)
for (Column = 0; Column < QuadrantSize; Column++) {
S1[Row * QuadrantSize + Column] = A21[RowWidthA * Row + Column] + A22[RowWidthA * Row + Column];
S2[Row * QuadrantSize + Column] = S1[Row * QuadrantSize + Column] - A[RowWidthA * Row + Column];
S4[Row * QuadrantSize + Column] = A12[Row * RowWidthA + Column] - S2[QuadrantSize * Row + Column];
S5[Row * QuadrantSize + Column] = B12[Row * RowWidthB + Column] - B[Row * RowWidthB + Column];
S6[Row * QuadrantSize + Column] = B22[Row * RowWidthB + Column] - S5[Row * QuadrantSize + Column];
S8[Row * QuadrantSize + Column] = S6[Row * QuadrantSize + Column] - B21[Row * RowWidthB + Column];
S3[Row * QuadrantSize + Column] = A[RowWidthA * Row + Column] - A21[RowWidthA * Row + Column];
S7[Row * QuadrantSize + Column] = B22[Row * RowWidthB + Column] - B12[Row * RowWidthB + Column];
}
/* M2 = A x B */
OptimizedStrassenMultiply_par(M2, A, B, QuadrantSize, QuadrantSize, RowWidthA, RowWidthB, Depth+1, cutoff_depth, cutoff_size);
/* M5 = S1 * S5 */
OptimizedStrassenMultiply_par(M5, S1, S5, QuadrantSize, QuadrantSize, QuadrantSize, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of T1 = S2 x S6 + M2 */
OptimizedStrassenMultiply_par(T1sMULT, S2, S6, QuadrantSize, QuadrantSize, QuadrantSize, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of T2 = T1 + S3 x S7 */
OptimizedStrassenMultiply_par(C22, S3, S7, QuadrantSize, RowWidthC /*FIXME*/, QuadrantSize, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of C = M2 + A12 * B21 */
OptimizedStrassenMultiply_par(C, A12, B21, QuadrantSize, RowWidthC, RowWidthA, RowWidthB, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of C12 = S4 x B22 + T1 + M5 */
OptimizedStrassenMultiply_par(C12, S4, B22, QuadrantSize, RowWidthC, QuadrantSize, RowWidthB, Depth+1, cutoff_depth, cutoff_size);
/* Step 1 of C21 = T2 - A22 * S8 */
OptimizedStrassenMultiply_par(C21, A22, S8, QuadrantSize, RowWidthC, RowWidthA, QuadrantSize, Depth+1, cutoff_depth, cutoff_size);
for (Row = 0; Row < QuadrantSize; Row++) {
for (Column = 0; Column < QuadrantSize; Column += 1) {
C[RowWidthC * Row + Column] += M2[Row * QuadrantSize + Column];
C12[RowWidthC * Row + Column] += M5[Row * QuadrantSize + Column] + T1sMULT[Row * QuadrantSize + Column] + M2[Row * QuadrantSize + Column];
C21[RowWidthC * Row + Column] = -C21[RowWidthC * Row + Column] + C22[RowWidthC * Row + Column] + T1sMULT[Row * QuadrantSize + Column] + M2[Row * QuadrantSize + Column];
C22[RowWidthC * Row + Column] += M5[Row * QuadrantSize + Column] + T1sMULT[Row * QuadrantSize + Column] + M2[Row * QuadrantSize + Column];
}
}
}
free(StartHeap);
}
void strassen_main_par(double *A, double *B, double *C, int n, unsigned int cutoff_size, unsigned int cutoff_depth)
{
#pragma omp parallel
#pragma omp master
OptimizedStrassenMultiply_par(C, A, B, n, n, n, n, 1, cutoff_depth, cutoff_size);
}
|
openmp-util.h |
/*
* OpenMP multithreading setup util for VMD tcl plugins.
*
* Copyright (c) 2006-2009 akohlmey@cmm.chem.upenn.edu
*/
#ifndef OPENMP_UTIL_H
#define OPENMP_UTIL_H
#include <tcl.h>
#if defined(_OPENMP)
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
static int nthr = 0;
#endif
/* this results in an empty function without OpenMP */
static void check_thread_count(Tcl_Interp *interp, const char *name)
{
#if defined(_OPENMP)
char *forcecount, buffer[256];
int newcpucount = nthr;
/* Handle VMD's way to allow the user to override the number
* of CPUs for use in scalability testing, debugging, etc. */
forcecount = getenv("VMDFORCECPUCOUNT");
if (forcecount != NULL) {
if (sscanf(forcecount, "%d", &newcpucount) != 1) {
newcpucount=1;
}
omp_set_num_threads(newcpucount);
}
/* first time setup */
if (newcpucount < 1) {
#pragma omp parallel shared(nthr)
{
#pragma omp master
{ newcpucount = omp_get_num_threads(); }
}
}
/* print a message to the console, whenever the number of threads changes. */
if (nthr!=newcpucount) {
nthr=newcpucount;
sprintf(buffer,"vmdcon -info \"'%s' will use %d thread%s through OpenMP.\"\n", name, nthr, (nthr>1)? "s":"");
Tcl_Eval(interp,buffer);
}
#endif
}
#endif /* OPENMP_UTIL_H */
|
fec.c | #include<stdio.h>
#include "gdal.h"
#include<omp.h>
void usage()
{
printf( "-----------------------------------------\n");
printf( "--Modis Processing chain--OpenMP code----\n");
printf( "-----------------------------------------\n");
printf( "./fc inEmis31 inEmis32 outFC\n");
printf( "-----------------------------------------\n");
printf( "inEmis31\t\tModis MOD11A2 Emis 31 1Km\n");
printf( "inEmis32\t\tModis MOD11A2 Emis 32 1Km\n");
printf( "outFC\t\t\tFraction emissivity Cover output [-x100]\n");
return;
}
int main( int argc, char *argv[] )
{
if( argc < 3 ) {
usage();
return 1;
}
//Loading the input files names
//-----------------------------
char *inB2 = argv[1]; //Emis31
char *inB3 = argv[2]; //Emis32
char *fcF = argv[3];
//Loading the input files
//-----------------------
GDALAllRegister();
GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//Emis31
GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//Emis32
if(hD2==NULL||hD3==NULL){
printf("One or more input files ");
printf("could not be loaded\n");
exit(1);
}
//Loading the file infos
//----------------------
GDALDriverH hDr2 = GDALGetDatasetDriver(hD2);
char **options = NULL;
options = CSLSetNameValue( options, "TILED", "YES" );
options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" );
options = CSLSetNameValue( options, "PREDICTOR", "2" );
GDALDatasetH hDOut = GDALCreateCopy(hDr2,fcF,hD2,FALSE,options,NULL,NULL);
GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1);
GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//Emis31
GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//Emis32
int nX = GDALGetRasterBandXSize(hB2);
int nY = GDALGetRasterBandYSize(hB2);
int N = nX*nY;
float *l2 = (float *) malloc(sizeof(float)*N);
float *l3 = (float *) malloc(sizeof(float)*N);
float *lOut = (float *) malloc(sizeof(float)*N);
int rowcol;
float tempval, minval=100, maxval=0;
GDALRasterIO(hB2,GF_Read,0,0,nX,nY,l2,nX,nY,GDT_Float32,0,0);
GDALRasterIO(hB3,GF_Read,0,0,nX,nY,l3,nX,nY,GDT_Float32,0,0);
#pragma omp parallel for default(none) \
private (rowcol, tempval) shared (N, minval, maxval, l2, l3)
for(rowcol=0;rowcol<N;rowcol++){
if( l2[rowcol] == 0 || l3[rowcol] == 0) {}
else
{
tempval = 0.49 + 0.001 * (l2[rowcol]+l3[rowcol]);
if( tempval < minval ) minval = tempval;
else if ( tempval > maxval && tempval < 1.0 ) maxval = tempval;
}
}
#pragma omp barrier
printf("\t\tminval=%.3f\tmaxval=%.3f\n",minval,maxval);
#pragma omp parallel for default(none) \
private (rowcol, tempval) shared (N, minval, maxval, l2, l3, lOut)
for(rowcol=0;rowcol<N;rowcol++){
if( l2[rowcol] == 0 || l3[rowcol] == 0){
lOut[rowcol] = 0;
}
else
{
tempval = 0.49 + 0.001 * (l2[rowcol]+l3[rowcol]);
if( tempval < minval ) lOut[rowcol] = 0;
else if ( tempval > maxval ) lOut[rowcol] = 0;
else lOut[rowcol] = 100.0 * (float) (tempval-minval)/(maxval-minval);
}
}
#pragma omp barrier
GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,lOut,nX,nY,GDT_Float32,0,0);
if( l2 != NULL ) free( l2 );
if( l3 != NULL ) free( l3 );
GDALClose(hD2);
GDALClose(hD3);
GDALClose(hDOut);
return(EXIT_SUCCESS);
}
|
oneWayFunction.c | // Copyright (c) 2016-2018 The Ulord Core Foundation
#include "oneWayFunction.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifndef MAC_OSX
#include <omp.h>
#endif
#include "my_time.h"
#include "common.h"
// OpenSSL Library
#include "c_sha1.h"
#include "c_sha256.h"
#include "c_sha512.h"
#include "c_sha3_256.h"
#include "c_whirlpool.h"
#include "c_ripemd160.h"
#include "c_blake2s256.h"
#include "c_aes128.h"
#include "c_des.h"
#include "c_crc32.h"
#include "c_hmac_md5.h"
#include "c_rc4.h"
#include "c_camellia128.h"
// JTR source code
#include "c_gost.h"
#include "c_haval5_256.h"
#include "c_skein512_256.h"
OneWayFunctionInfor funcInfor[FUNCTION_NUM] = {
"SHA3-256", crypto_sha3_256,
"SHA1", crypto_sha1,
"SHA256", crypto_sha256,
"SHA512", crypto_sha512,
"Whirlpool", crypto_whirlpool,
"RIPEMD-160", crypto_ripemd160,
"BLAKE2s(256bits)", crypto_blake2s256,
"AES(128bits)", crypto_aes128,
"DES", crypto_des,
"RC4", crypto_rc4,
"Camellia(128bits)", crypto_camellia128,
"CRC32", crypto_crc32,
"HMAC(MD5)", crypto_hmac_md5,
"GOST R 34.11-94", crypto_gost,
"HAVAL-256/5", crypto_haval5_256,
"Skein-512(256bits)", crypto_skein512_256
};
void initOneWayFunction() {
gost_init_table();
CRC32_Table_Init();
}
void testOneWayFunction(const char *mess, uint32_t messLen, const int64_t iterNum) {
/*
int64_t j;
uint32_t messLen = (uint32_t)strlen(mess);
uint8_t input[INPUT_LEN], output[FUNCTION_NUM][OUTPUT_LEN];
memset(input, 0, INPUT_LEN*sizeof(uint8_t));
memcpy(input, mess, messLen*sizeof(char));
printf("**************************** Correctness test (One way function) ****************************\n");
printf("Test message: %s\n", mess);
for (int i = 0; i < FUNCTION_NUM; ++i) {
printf("%02d ", i);
funcInfor[i].func(input, messLen, output[i]);
view_data_u8(funcInfor[i].funcName, output[i], OUTPUT_LEN);
}
printf("*********************************************************************************************\n");
printf("************************************************* Performance test (One way function) *************************************************\n");
uint8_t *result = (uint8_t *)malloc(iterNum * OUTPUT_LEN * sizeof(uint8_t));
assert(NULL != result);
memset(result, 0, iterNum * OUTPUT_LEN * sizeof(uint8_t));
uint32_t threadNumArr[] = {1, 4, 8, 12, 16, 20, 24, 32, 48, 64};
uint32_t threadNumTypes = sizeof(threadNumArr) / sizeof(uint32_t);
printf(" %-18s", "Algorithm");
for (uint32_t ix = 0; ix < threadNumTypes; ++ix)
printf("%12d", threadNumArr[ix]);
printf("\n");
for (int i = 0; i < FUNCTION_NUM; ++i) {
printf("%02d %-18s\t", i, funcInfor[i].funcName);
for (uint32_t ix = 0; ix < threadNumTypes; ++ix) {
omp_set_num_threads(threadNumArr[ix]);
double startTime = get_wall_time();
if (threadNumArr[ix] == 1) {
for (j = 0; j < iterNum; ++j) {
funcInfor[i].func(input, messLen, result + j * OUTPUT_LEN);
}
} else {
#pragma omp parallel for firstprivate(input), private(j) shared(result)
for (j = 0; j < iterNum; ++j) {
funcInfor[i].func(input, messLen, result + j * OUTPUT_LEN);
}
}
double endTime = get_wall_time();
double costTime = endTime - startTime;
printf("%5.0f Kps ", iterNum / 1000 / costTime); fflush(stdout);
// Check result
for (j = 0; j < iterNum; j += 1) {
if (memcmp(output[i], result + j * OUTPUT_LEN, OUTPUT_LEN)) {
printf("Thread num: %u, j: %ld\n", threadNumArr[ix], j);
view_data_u8("output", output[i], OUTPUT_LEN);
view_data_u8("result", result + j * OUTPUT_LEN, OUTPUT_LEN);
abort();
}
}
}
printf("\n");
}
if (NULL != result) {
free(result);
result = NULL;
}
*/
printf("***************************************************************************************************************************************\n");
}
|
gmapper.c | #define _MODULE_GMAPPER
#ifndef CXXFLAGS
#define CXXFLAGS "?"
#endif
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <zlib.h>
#include <omp.h> // OMP multithreading
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <getopt.h>
#include "../gmapper/gmapper.h"
#include "../gmapper/seeds.h"
#include "../gmapper/genome.h"
#include "../gmapper/mapping.h"
#include "../common/hash.h"
#include "../common/fasta.h"
#include "../common/util.h"
#include "../common/version.h"
#include "../common/sw-full-common.h"
#include "../common/sw-full-cs.h"
#include "../common/sw-full-ls.h"
#include "../common/sw-vector.h"
#include "../common/output.h"
#include "../common/input.h"
#include "../common/read_hit_heap.h"
#include "../common/sw-post.h"
/* heaps */
/*
typedef struct ptr_and_sz {
void * ptr;
size_t sz;
} ptr_and_sz;
*/
//DEF_HEAP(uint32_t, char *, out)
DEF_HEAP(uint32_t, struct ptr_and_sz, out)
/*
Get hit stats
*/
int
hit_edit_distance(struct read_hit * rh) {
//find how many perfect matches, off by 1 matches and off by 2 matches
// int matches; /* # of matches */
// int mismatches; /* # of substitutions */
// int insertions; /* # of insertions */
// int deletions; /* # of deletions */
int edit_distance=0;
edit_distance+=rh->sfrp->mismatches;
edit_distance+=rh->sfrp->insertions;
edit_distance+=rh->sfrp->deletions;
assert(edit_distance>=0);
return edit_distance;
}
/*
* Free memory allocated by this read.
*/
void
read_free(struct read_entry * re)
{
free(re->name);
free(re->seq);
if (re->orig_seq!=re->seq) {
free(re->orig_seq);
}
if (Qflag) {
assert(re->qual!=NULL);
free(re->qual);
if (re->qual!=re->orig_qual) {
free(re->orig_qual);
}
assert(re->plus_line!=NULL);
free(re->plus_line);
}
}
void
read_free_full(struct read_entry * re, count_t * counter)
{
if (shrimp_mode == MODE_COLOUR_SPACE && Qflag) {
if (re->crossover_score != NULL) {
free(re->crossover_score);
re->crossover_score = NULL;
}
}
if (re->mapidx[0] != NULL)
my_free(re->mapidx[0], n_seeds * re->max_n_kmers * sizeof(re->mapidx[0][0]), counter, "mapidx [%s]", re->name);
if (re->mapidx[1] != NULL)
my_free(re->mapidx[1], n_seeds * re->max_n_kmers * sizeof(re->mapidx[0][0]), counter, "mapidx [%s]", re->name);
read_free_hit_list(re, counter);
read_free_anchor_list(re, counter);
if (re->n_ranges > 0)
free(re->ranges);
if (re->n_final_unpaired_hits > 0) {
int i;
for (i = 0; i < re->n_final_unpaired_hits; i++)
free_sfrp(&re->final_unpaired_hits[i].sfrp, re, counter);
my_free(re->final_unpaired_hits, re->n_final_unpaired_hits * sizeof(re->final_unpaired_hits[0]),
counter, "final_unpaired_hits [%s]", re->name);
re->n_final_unpaired_hits = 0;
re->final_unpaired_hits = NULL;
}
free(re->read[0]);
free(re->read[1]);
read_free(re);
}
void
readpair_free_full(pair_entry * peP, count_t * counterP)
{
int nip, i;
if (peP->n_final_paired_hits > 0) {
my_free(peP->final_paired_hits, peP->n_final_paired_hits * sizeof(peP->final_paired_hits[0]),
counterP, "final_paired_hits [%s,%s]", peP->re[0]->name, peP->re[1]->name);
peP->n_final_paired_hits = 0;
peP->final_paired_hits = NULL;
}
for (nip = 0; nip < 2; nip++) {
if (peP->final_paired_hit_pool_size[nip] > 0) {
for (i = 0; i < peP->final_paired_hit_pool_size[nip]; i++) {
free_sfrp(&peP->final_paired_hit_pool[nip][i].sfrp, peP->re[nip], counterP);
if (peP->final_paired_hit_pool[nip][i].n_paired_hit_idx > 0) {
my_free(peP->final_paired_hit_pool[nip][i].paired_hit_idx, peP->final_paired_hit_pool[nip][i].n_paired_hit_idx * sizeof(peP->final_paired_hit_pool[nip][i].paired_hit_idx[0]),
counterP, "paired_hit_idx [%s]", peP->re[nip]->name);
peP->final_paired_hit_pool[nip][i].n_paired_hit_idx = 0;
peP->final_paired_hit_pool[nip][i].paired_hit_idx = NULL;
}
}
my_free(peP->final_paired_hit_pool[nip], peP->final_paired_hit_pool_size[nip] * sizeof(peP->final_paired_hit_pool[nip][0]),
counterP, "final_paired_hit_pool[%d] [%s,%s]", nip, peP->re[0]->name, peP->re[1]->name);
peP->final_paired_hit_pool_size[nip] = 0;
peP->final_paired_hit_pool[nip] = NULL;
}
}
read_free_full(peP->re[0], counterP);
read_free_full(peP->re[1], counterP);
}
/*
* Reverse read.
*
* This is useful for dealing with the various possibilities for matepair orientation in a unified way.
*/
static void
read_reverse(struct read_entry * re) {
uint32_t * tmp1 = re->read[0];
re->read[0] = re->read[1];
re->read[1] = tmp1;
int tmp2 = re->initbp[0];
re->initbp[0] = re->initbp[1];
re->initbp[1] = tmp2;
re->input_strand = 1 - re->input_strand;
}
/*
static uint
get_contig_number_from_name(char const * c)
{
int cn;
// hack: accept '>' for cn=0
if (*c == '>')
return 0;
for (cn = 0; cn < num_contigs; cn++) {
if (!strcmp(c, contig_names[cn]))
break;
}
return cn;
}
*/
/*
* Compute range limitations for this read.
*/
/*
static void
read_compute_ranges(struct read_entry * re)
{
char * r, * r_save, * c, * c_save;
uint g_start, g_end;
int cn, st;
assert(re->range_string != NULL);
for (r = strtok_r(re->range_string, " ", &r_save); r != NULL; r = strtok_r(NULL, " ", &r_save))
{
c = strtok_r(r, ",", &c_save); // contig name
if (c == NULL)
continue;
cn = get_contig_number_from_name(c);
if (cn >= num_contigs)
continue;
c = strtok_r(NULL, ",", &c_save); // strand
if (c == NULL)
continue;
if (*c == '+')
st = 0;
else if (*c == '-')
st = 1;
else
continue;
c = strtok_r(NULL, ",", &c_save); // g_start
if (c == NULL)
continue;
g_start = (uint)atoll(c);
if (g_start == 0)
continue;
g_start--;
c = strtok_r(NULL, ",", &c_save); // g_end
if (c == NULL)
continue;
g_end = (uint)atoll(c);
if (g_end == 0)
continue;
g_end--;
re->n_ranges++;
re->ranges = (struct range_restriction *)xrealloc(re->ranges, re->n_ranges * sizeof(re->ranges[0]));
re->ranges[re->n_ranges - 1].cn = cn;
re->ranges[re->n_ranges - 1].st = st;
re->ranges[re->n_ranges - 1].g_start = g_start;
re->ranges[re->n_ranges - 1].g_end = g_end;
}
}
*/
/* Trim a read */
static void trim_read(struct read_entry * re) {
re->orig_seq=strdup(re->seq);
if (Qflag) {
re->orig_qual=strdup(re->qual);
}
//handle colour space too!
int length=strlen(re->seq);
int i;
for (i=0; i<length-trim_end-trim_front; i++) {
re->seq[i]=re->seq[i+trim_front];
if (Qflag) {
re->qual[i]=re->qual[i+trim_front];
}
}
re->seq[i] = '\0';
if (Qflag) {
re->qual[i] = '\0';
}
return;
}
/*
* Launch the threads that will scan the reads
*/
static bool
launch_scan_threads(fasta_t fasta, fasta_t left_fasta, fasta_t right_fasta)
{
llint last_nreads, last_time_usecs;
bool read_more = true, more_in_left_file = true, more_in_right_file=true;
/* initiate the thread buffers */
//thread_output_buffer_sizes = (size_t *)xcalloc_m(sizeof(size_t) * num_threads, "thread_output_buffer_sizes");
thread_output_buffer_sizes = (size_t *)
my_calloc(num_threads * sizeof(size_t),
&mem_thread_buffer, "thread_output_buffer_sizes");
//thread_output_buffer_filled = (char * *)xcalloc_m(sizeof(char *) * num_threads, "thread_output_buffer_filled");
thread_output_buffer_filled = (char * *)
my_calloc(num_threads * sizeof(char *),
&mem_thread_buffer, "thread_output_buffer_filled");
//thread_output_buffer = (char * *)xcalloc_m(sizeof(char *) * num_threads, "thread_output_buffer");
thread_output_buffer = (char * *)
my_calloc(num_threads * sizeof(char *),
&mem_thread_buffer, "thread_output_buffer");
//thread_output_buffer_chunk = (unsigned int *)xcalloc_m(sizeof(unsigned int) * num_threads, "thread_output_buffer_chunk");
thread_output_buffer_chunk = (unsigned int *)
my_calloc(num_threads * sizeof(unsigned int),
&mem_thread_buffer, "thread_output_buffer_chunk");
unsigned int current_thread_chunk = 1;
unsigned int next_chunk_to_print = 1;
struct heap_out h;
heap_out_init(&h, thread_output_heap_capacity );
if (progress > 0) {
fprintf(stderr, "done r/hr r/core-hr\n");
last_nreads = 0;
last_time_usecs = gettimeinusecs();
}
#pragma omp parallel shared(read_more,more_in_left_file,more_in_right_file, fasta) num_threads(num_threads)
{
int thread_id = omp_get_thread_num();
struct read_entry * re_buffer;
int load, i;
//llint before, after;
//re_buffer = (struct read_entry *)xmalloc_m(chunk_size * sizeof(re_buffer[0]), "re_buffer");
re_buffer = (read_entry *)my_malloc(chunk_size * sizeof(re_buffer[0]), &mem_thread_buffer, "re_buffer");
while (read_more) {
memset(re_buffer, 0, chunk_size * sizeof(re_buffer[0]));
//before = rdtsc();
TIME_COUNTER_START(tpg.wait_tc);
//Read in this threads 'chunk'
#pragma omp critical (fill_reads_buffer)
{
//after = rdtsc();
//tpg.wait_ticks += MAX(after - before, 0);
TIME_COUNTER_STOP(tpg.wait_tc);
thread_output_buffer_chunk[thread_id]=current_thread_chunk++;
load = 0;
assert(chunk_size>2);
while (read_more && ((single_reads_file && load < chunk_size) || (!single_reads_file && load < chunk_size-1))) {
//if (!fasta_get_next_with_range(fasta, &re_buffer[load].name, &re_buffer[load].seq, &re_buffer[load].is_rna,
// &re_buffer[load].range_string, &re_buffer[load].qual))
if (single_reads_file) {
if (fasta_get_next_read_with_range(fasta, &re_buffer[load])) {
load++;
} else {
read_more = false;
}
} else {
//read from the left file
if (fasta_get_next_read_with_range(left_fasta, &re_buffer[load])) {
load++;
} else {
more_in_left_file = false;
}
//read from the right file
if (fasta_get_next_read_with_range(right_fasta, &re_buffer[load])) {
load++;
} else {
more_in_right_file = false;
}
//make sure that one is not smaller then the other
if (more_in_left_file != more_in_right_file) {
fprintf(stderr,"error: when using options -1 and -2, both files specified must have the same number of entries\n");
exit(1);
}
//keep reading?
read_more = more_in_left_file && more_in_right_file;
}
}
nreads += load;
// progress reporting
if (progress > 0) {
nreads_mod += load;
if (nreads_mod >= progress) {
llint time_usecs = gettimeinusecs();
#pragma omp critical (cs_stderr)
{
fprintf(stderr, "%lld %d %d.\r", nreads,
(int)(((double)(nreads - last_nreads)/(double)(time_usecs - last_time_usecs)) * 3600.0 * 1.0e6),
(int)(((double)(nreads - last_nreads)/(double)(time_usecs - last_time_usecs)) * 3600.0 * 1.0e6 * (1/(double)num_threads)) );
}
last_nreads = nreads;
last_time_usecs = time_usecs;
}
nreads_mod %= progress;
}
} // end critical section
if (pair_mode != PAIR_NONE)
assert(load % 2 == 0); // read even number of reads
thread_output_buffer_sizes[thread_id] = thread_output_buffer_initial;
//thread_output_buffer[thread_id] = (char *)xmalloc_m(sizeof(char) * thread_output_buffer_sizes[thread_id], "thread_buffer");
thread_output_buffer[thread_id] = (char *)
my_malloc(thread_output_buffer_sizes[thread_id] * sizeof(char),
&mem_thread_buffer, "thread_output_buffer[]");
thread_output_buffer_filled[thread_id] = thread_output_buffer[thread_id];
thread_output_buffer[thread_id][0] = '\0';
for (i = 0; i < load; i++) {
// if running in paired mode and first foot is ignored, ignore this one, too
if (pair_mode != PAIR_NONE && i % 2 == 1 && re_buffer[i-1].ignore) {
//read_free(&re_buffer[i-1]);
read_free(&re_buffer[i]);
continue;
}
//if (!(strcspn(re_buffer[i].seq, "nNxX.") == strlen(re_buffer[i].seq))) {
// if (pair_mode != PAIR_NONE && i % 2 == 1) {
// read_free(re_buffer+i-1);
// read_free(re_buffer+i);
// }
// continue;
//}
//Trim the reads
if (trim) {
if (pair_mode == PAIR_NONE) {
trim_read(&re_buffer[i]);
} else if (i % 2 == 1){
if (trim_first) {
trim_read(&re_buffer[i-1]);
}
if (trim_second) {
trim_read(&re_buffer[i]);
}
}
}
if (shrimp_mode == MODE_LETTER_SPACE && trim_illumina) {
int trailing_Bs=0;
for (int j=0; j<(int)strlen(re_buffer[i].qual); j++) {
if (re_buffer[i].qual[j]!='B') {
trailing_Bs=0;
} else {
trailing_Bs+=1;
}
}
if (trailing_Bs>0) {
re_buffer[i].seq[strlen(re_buffer[i].seq)-trailing_Bs]='\0';
re_buffer[i].qual[strlen(re_buffer[i].qual)-trailing_Bs]='\0';
}
}
//compute average quality value
re_buffer[i].read_len = strlen(re_buffer[i].seq);
if (Qflag && !ignore_qvs && min_avg_qv >= 0) {
//fprintf(stderr, "read:[%s] qual:[%s]", re_buffer[i].name, re_buffer[i].qual);
re_buffer[i].avg_qv = 0;
for (char * c = re_buffer[i].qual; *c != 0; c++) {
re_buffer[i].avg_qv += (*c - qual_delta);
}
//fprintf(stderr, " avg_qv:%d\n", re_buffer[i].avg_qv);
}
if (Qflag && !ignore_qvs && !no_qv_check) {
for (char * c =re_buffer[i].qual; *c !=0; c++) {
int qual_value=(*c-qual_delta);
if (qual_value<-10 || qual_value>50) {
fprintf(stderr,"The qv-offset might be set incorrectly! Currenty qvs are interpreted as PHRED+%d\
and a qv of %d was observed. To disable this error, etiher set the offset correctly or disable this check (see README).\n",qual_delta,qual_value);
exit(1);
}
}
}
re_buffer[i].max_n_kmers = re_buffer[i].read_len - min_seed_span + 1;
re_buffer[i].read[0] = fasta_sequence_to_bitfield(fasta, re_buffer[i].seq);
if (shrimp_mode == MODE_COLOUR_SPACE) {
re_buffer[i].read_len--;
re_buffer[i].max_n_kmers -= 2; // 1st color always discarded from kmers
re_buffer[i].min_kmer_pos = 1;
re_buffer[i].initbp[0] = fasta_get_initial_base(shrimp_mode,re_buffer[i].seq);
re_buffer[i].initbp[1] = re_buffer[i].initbp[0];
re_buffer[i].read[1] = reverse_complement_read_cs(re_buffer[i].read[0], (int8_t)re_buffer[i].initbp[0],
(int8_t)re_buffer[i].initbp[1],
re_buffer[i].read_len, re_buffer[i].is_rna);
} else {
re_buffer[i].read[1] = reverse_complement_read_ls(re_buffer[i].read[0], re_buffer[i].read_len, re_buffer[i].is_rna);
}
if (re_buffer[i].max_n_kmers < 0)
re_buffer[i].max_n_kmers = 0;
if (re_buffer[i].read_len > 0)
re_buffer[i].avg_qv /= re_buffer[i].read_len;
//Check if we can actually use this read
if (//re_buffer[i].max_n_kmers <= 0
//||
re_buffer[i].read_len > longest_read_len
|| (Qflag && !ignore_qvs && re_buffer[i].avg_qv < min_avg_qv) // ignore reads with low avg qv
) {
if (re_buffer[i].max_n_kmers <= 0) {
fprintf(stderr, "warning: skipping read [%s]; smaller then any seed!\n",
re_buffer[i].name);
re_buffer[i].max_n_kmers=1;
} else if (re_buffer[i].read_len > longest_read_len) {
fprintf(stderr, "warning: skipping read [%s]; it has length %d, maximum allowed is %d. Use --longest-read ?\n",
re_buffer[i].name, re_buffer[i].read_len, longest_read_len);
} else {
//fprintf(stderr, "skipping read [%s] with avg_qv:%g\n", re_buffer[i].name, (double)re_buffer[i].avg_qv);
}
if (pair_mode == PAIR_NONE) {
#pragma omp atomic
total_reads_dropped++;
read_free_full(&re_buffer[i], &mem_mapping);
} else {
#pragma omp atomic
total_pairs_dropped++;
if (i%2 == 1) {
read_free_full(&re_buffer[i-1], &mem_mapping);
read_free_full(&re_buffer[i], &mem_mapping);
} else {
read_free_full(&re_buffer[i], &mem_mapping);
re_buffer[i].ignore = true;
}
}
continue;
}
re_buffer[i].window_len = (uint16_t)abs_or_pct(window_len,re_buffer[i].read_len);
// compute position-based crossover scores based on qvs
if (shrimp_mode == MODE_COLOUR_SPACE && Qflag && !ignore_qvs) {
int j;
re_buffer[i].crossover_score = (int *)xmalloc(re_buffer[i].read_len * sizeof(re_buffer[i].crossover_score[0]));
for (j = 0; j < re_buffer[i].read_len; j++) {
re_buffer[i].crossover_score[j] = (int)(score_alpha * log(pr_err_from_qv(re_buffer[i].qual[j] - qual_delta) / 3.0) / log(2.0));
if (re_buffer[i].crossover_score[j] > -1) {
re_buffer[i].crossover_score[j] = -1;
} else if (re_buffer[i].crossover_score[j] < 2*crossover_score) {
re_buffer[i].crossover_score[j] = 2*crossover_score;
}
}
}
if (re_buffer[i].range_string != NULL) {
assert(0); // not maintained
//read_compute_ranges(&re_buffer[i]);
free(re_buffer[i].range_string);
re_buffer[i].range_string = NULL;
}
//free(re_buffer[i].seq);
// time to do some mapping!
if (pair_mode == PAIR_NONE)
{
handle_read(&re_buffer[i], unpaired_mapping_options[0], n_unpaired_mapping_options[0]);
read_free_full(&re_buffer[i], &mem_mapping);
}
else if (i % 2 == 1)
{
pair_entry pe;
memset(&pe, 0, sizeof(pe));
if (pair_reverse[pair_mode][0])
read_reverse(&re_buffer[i-1]);
if (pair_reverse[pair_mode][1])
read_reverse(&re_buffer[i]);
re_buffer[i-1].paired=true;
re_buffer[i-1].first_in_pair=true;
re_buffer[i-1].mate_pair=&re_buffer[i];
re_buffer[i].paired=true;
re_buffer[i].first_in_pair=false;
re_buffer[i].mate_pair=&re_buffer[i-1];
pe.re[0] = &re_buffer[i-1];
pe.re[1] = &re_buffer[i];
handle_readpair(&pe, paired_mapping_options, n_paired_mapping_options);
readpair_free_full(&pe, &mem_mapping);
}
}
// free unused memory while the buffer waits in the output heap
size_t new_size = (thread_output_buffer_filled[thread_id] - thread_output_buffer[thread_id]) + 1;
thread_output_buffer[thread_id] = (char *)
my_realloc(thread_output_buffer[thread_id], new_size, thread_output_buffer_sizes[thread_id],
&mem_thread_buffer, "thread_output_buffer[]");
//fprintf(stdout,"%s",thread_output_buffer[thread_id]);
#pragma omp critical
{
struct heap_out_elem tmp;
tmp.key = thread_output_buffer_chunk[thread_id];
//tmp.rest = thread_output_buffer[thread_id];
tmp.rest.ptr = thread_output_buffer[thread_id];
tmp.rest.sz = new_size; //thread_output_buffer_sizes[thread_id];
thread_output_buffer[thread_id] = NULL;
heap_out_insert(&h, &tmp);
heap_out_get_min(&h, &tmp);
while (h.load > 0 && tmp.key == next_chunk_to_print) {
heap_out_extract_min(&h, &tmp);
//fprintf(stdout, "%s", tmp.rest);
fprintf(stdout, "%s", (char *)tmp.rest.ptr);
//free(tmp.rest);
my_free(tmp.rest.ptr, tmp.rest.sz,
&mem_thread_buffer, "thread_output_buffer[]");
next_chunk_to_print++;
}
}
}
//free(re_buffer);
my_free(re_buffer, chunk_size * sizeof(re_buffer[0]),
&mem_thread_buffer, "re_buffer");
} // end parallel section
if (progress > 0)
fprintf(stderr, "\n");
//assert(h.load == 0);
struct heap_out_elem tmp;
while (h.load>0) {
heap_out_extract_min(&h,&tmp);
fprintf(stdout,"%s",(char *)tmp.rest.ptr);
//free(tmp.rest);
my_free(tmp.rest.ptr, tmp.rest.sz,
&mem_thread_buffer, "thread_output_buffer[]");
}
heap_out_destroy(&h);
//free(thread_output_buffer_sizes);
my_free(thread_output_buffer_sizes, sizeof(size_t) * num_threads,
&mem_thread_buffer, "thread_output_buffer_sizes");
//free(thread_output_buffer_filled);
my_free(thread_output_buffer_filled, sizeof(char *) * num_threads,
&mem_thread_buffer, "thread_output_buffer_filled");
//free(thread_output_buffer);
my_free(thread_output_buffer, sizeof(char *) * num_threads,
&mem_thread_buffer, "thread_output_buffer");
//free(thread_output_buffer_chunk);
my_free(thread_output_buffer_chunk, sizeof(unsigned int) * num_threads,
&mem_thread_buffer, "thread_output_buffer_chunk");
return true;
}
static char *
thres_to_buff(char * buff, double * thres)
{
if (IS_ABSOLUTE(*thres)) {
sprintf(buff, "%u", -(uint)(*thres));
} else {
sprintf(buff, "%.02f%%", *thres);
}
return buff;
}
static char *
bool_to_buff(char * buff, bool * val)
{
sprintf(buff, "%s", *val ? "true" : "false");
return buff;
}
static void
print_insert_histogram()
{
int i;
for (i = 0; i < 100; i++) {
fprintf(stderr, "[%d-%d]: %.2f%%\n",
min_insert_size + i * insert_histogram_bucket_size,
min_insert_size + (i + 1) * insert_histogram_bucket_size - 1,
total_paired_matches == 0? 0 : ((double)insert_histogram[i] / (double)total_paired_matches) * 100);
}
}
typedef struct tp_stats_t {
uint64_t f1_invocs, f1_cells, f1_ticks;
double f1_secs, f1_cellspersec;
uint64_t f2_invocs, f2_cells, f2_ticks;
double f2_secs, f2_cellspersec;
uint64_t fwbw_invocs, fwbw_cells, fwbw_ticks;
double fwbw_secs, fwbw_cellspersec;
double scan_secs, readparse_secs, read_handle_overhead_secs;
double anchor_list_secs, hit_list_secs;
double region_counts_secs, mp_region_counts_secs, duplicate_removal_secs;
double pass1_secs, get_vector_hits_secs, pass2_secs;
} tp_stats_t;
static void
print_statistics()
{
static char const my_tab[] = " ";
//uint64_t f1_invocs[num_threads], f1_cells[num_threads], f1_ticks[num_threads];
//double f1_secs[num_threads], f1_cellspersec[num_threads];
uint64_t f1_total_invocs = 0, f1_total_cells = 0;
double f1_total_secs = 0, f1_total_cellspersec = 0;
uint64_t f1_calls_bypassed = 0;
//uint64_t f2_invocs[num_threads], f2_cells[num_threads], f2_ticks[num_threads];
//double f2_secs[num_threads], f2_cellspersec[num_threads];
uint64_t f2_total_invocs = 0, f2_total_cells = 0;
double f2_total_secs = 0, f2_total_cellspersec = 0;
//uint64_t fwbw_invocs[num_threads], fwbw_cells[num_threads], fwbw_ticks[num_threads];
//double fwbw_secs[num_threads], fwbw_cellspersec[num_threads];
uint64_t fwbw_total_invocs = 0, fwbw_total_cells = 0;
double fwbw_total_secs = 0, fwbw_total_cellspersec = 0;
//double scan_secs[num_threads], readparse_secs[num_threads], read_handle_overhead_secs[num_threads];
//double anchor_list_secs[num_threads], hit_list_secs[num_threads];
//double region_counts_secs[num_threads], mp_region_counts_secs[num_threads], duplicate_removal_secs[num_threads];
//double pass1_secs[num_threads], get_vector_hits_secs[num_threads], pass2_secs[num_threads];
double total_scan_secs = 0, total_wait_secs = 0, total_readparse_secs = 0;
tp_stats_t * tps = (tp_stats_t *)malloc(num_threads * sizeof(tps[0]));
tpg_t * tpgA = (tpg_t *)malloc(num_threads * sizeof(tpgA[0]));
double hz;
double fasta_load_secs;
fasta_stats_t fs;
fs = fasta_stats();
fasta_load_secs = fs->total_secs;
free(fs);
hz = cpuhz();
#pragma omp parallel num_threads(num_threads) shared(hz)
{
int tid = omp_get_thread_num();
memcpy(&tpgA[tid], &tpg, sizeof(tpg_t));
f1_stats(&tps[tid].f1_invocs, &tps[tid].f1_cells, &tps[tid].f1_secs, NULL);
//tps[tid].f1_secs = (double)tps[tid].f1_ticks / hz;
tps[tid].f1_cellspersec = (double)tps[tid].f1_cells / tps[tid].f1_secs;
if (isnan(tps[tid].f1_cellspersec))
tps[tid].f1_cellspersec = 0;
if (shrimp_mode == MODE_COLOUR_SPACE) {
sw_full_cs_stats(&tps[tid].f2_invocs, &tps[tid].f2_cells, &tps[tid].f2_secs);
post_sw_stats(&tps[tid].fwbw_invocs, &tps[tid].fwbw_cells, &tps[tid].fwbw_secs);
} else {
sw_full_ls_stats(&tps[tid].f2_invocs, &tps[tid].f2_cells, &tps[tid].f2_secs);
tps[tid].fwbw_secs = 0;
}
//tps[tid].f2_secs = (double)tps[tid].f2_ticks / hz;
tps[tid].f2_cellspersec = (double)tps[tid].f2_cells / tps[tid].f2_secs;
if (isnan(tps[tid].f2_cellspersec))
tps[tid].f2_cellspersec = 0;
//tps[tid].fwbw_secs = (double)tps[tid].fwbw_ticks / hz;
if (shrimp_mode == MODE_COLOUR_SPACE) {
tps[tid].fwbw_cellspersec = (double)tps[tid].fwbw_cells / tps[tid].fwbw_secs;
if (isnan(tps[tid].fwbw_cellspersec))
tps[tid].fwbw_cellspersec = 0;
}
tps[tid].readparse_secs = ((double)mapping_wallclock_usecs / 1.0e6) - ((double)tpg.read_handle_usecs / 1.0e6) - time_counter_get_secs(&tpg.wait_tc);
tps[tid].scan_secs = ((double)tpg.read_handle_usecs / 1.0e6) - tps[tid].f1_secs - tps[tid].f2_secs - tps[tid].fwbw_secs;
tps[tid].scan_secs = MAX(0, tps[tid].scan_secs);
//tps[tid].anchor_list_secs = (double)tpg.anchor_list_ticks / hz;
tps[tid].anchor_list_secs = time_counter_get_secs(&tpg.anchor_list_tc);
//tps[tid].hit_list_secs = (double)tpg.hit_list_ticks / hz;
tps[tid].hit_list_secs = time_counter_get_secs(&tpg.hit_list_tc);
//tps[tid].duplicate_removal_secs = (double)tpg.duplicate_removal_ticks / hz;
tps[tid].duplicate_removal_secs = time_counter_get_secs(&tpg.duplicate_removal_tc);
//tps[tid].region_counts_secs = (double)tpg.region_counts_ticks / hz;
tps[tid].region_counts_secs = time_counter_get_secs(&tpg.region_counts_tc);
//tps[tid].mp_region_counts_secs = (double)tpg.mp_region_counts_ticks / hz;
tps[tid].mp_region_counts_secs = time_counter_get_secs(&tpg.mp_region_counts_tc);
//tps[tid].pass1_secs = (double)tpg.pass1_ticks / hz;
tps[tid].pass1_secs = time_counter_get_secs(&tpg.pass1_tc);
//tps[tid].get_vector_hits_secs = (double)tpg.get_vector_hits_ticks / hz;
tps[tid].get_vector_hits_secs = time_counter_get_secs(&tpg.get_vector_hits_tc);
//tps[tid].pass2_secs = (double)tpg.pass2_ticks / hz;
tps[tid].pass2_secs = time_counter_get_secs(&tpg.pass2_tc);
/*
tps[tid].anchor_list_secs = (double)anchor_list_usecs[tid] / 1.0e6;
tps[tid].hit_list_secs = (double)hit_list_usecs[tid] / 1.0e6;
tps[tid].duplicate_removal_secs = (double)duplicate_removal_usecs[tid] / 1.0e6;
tps[tid].region_counts_secs = (double)region_counts_usecs[tid] / 1.0e6;
*/
tps[tid].read_handle_overhead_secs = tps[tid].scan_secs
- tps[tid].region_counts_secs - tps[tid].anchor_list_secs - tps[tid].hit_list_secs - tps[tid].duplicate_removal_secs;
}
f1_stats(NULL, NULL, NULL, &f1_calls_bypassed);
fprintf(stderr, "\nStatistics:\n");
fprintf(stderr, "%sOverall:\n", my_tab);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Load Genome Time:", (double)load_genome_usecs / 1.0e6);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Read Mapping Time:", (double)mapping_wallclock_usecs / 1.0e6);
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Reads per hour:", comma_integer((int)(((double)nreads/(double)mapping_wallclock_usecs) * 3600.0 * 1.0e6)));
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Reads per core-hour:", comma_integer((int)(((double)nreads/(double)mapping_wallclock_usecs) * 3600.0 * 1.0e6 * (1/(double)num_threads))));
fprintf(stderr, "\n");
int i;
for(i = 0; i < num_threads; i++){
total_scan_secs += tps[i].scan_secs;
total_readparse_secs += tps[i].readparse_secs;
total_wait_secs += time_counter_get_secs(&tpgA[i].wait_tc);
f1_total_secs += tps[i].f1_secs;
f1_total_invocs += tps[i].f1_invocs;
f1_total_cells += tps[i].f1_cells;
f2_total_secs += tps[i].f2_secs;
f2_total_invocs += tps[i].f2_invocs;
f2_total_cells += tps[i].f2_cells;
if (shrimp_mode == MODE_COLOUR_SPACE) {
fwbw_total_secs += tps[i].fwbw_secs;
fwbw_total_invocs += tps[i].fwbw_invocs;
fwbw_total_cells += tps[i].fwbw_cells;
} else {
fwbw_total_secs = 0;
fwbw_total_invocs = 0;
fwbw_total_cells = 0;
}
}
f1_total_cellspersec = f1_total_secs == 0? 0 : (double)f1_total_cells / f1_total_secs;
f2_total_cellspersec = f2_total_secs == 0? 0 : (double)f2_total_cells / f2_total_secs;
fwbw_total_cellspersec = fwbw_total_secs == 0? 0 : (double)fwbw_total_cells / fwbw_total_secs;
if (Dflag) {
fprintf(stderr, "%sPer-Thread Stats:\n", my_tab);
fprintf(stderr, "%s%s" "%11s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %25s %25s %25s %9s\n", my_tab, my_tab,
"", "ReadParse", "Scan", "Reg Cnts", "MPRegCnt", "Anch List", "Hit List", "Pass1", "Vect Hits", "Pass2", "Dup Remv",
"Vector SW", "Scalar SW", "Post SW", "Wait");
fprintf(stderr, "%s%s" "%11s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %15s %9s %15s %9s %15s %9s %9s\n", my_tab, my_tab,
"", "Time", "Time", "Time", "Time", "Time", "Time", "Time", "Time", "Time", "Time",
"Invocs", "Time", "Invocs", "Time", "Invocs", "Time", "Time");
fprintf(stderr, "\n");
for(i = 0; i < num_threads; i++) {
fprintf(stderr, "%s%s" "Thread %-4d %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %9.2f %15s %9.2f %15s %9.2f %15s %9.2f %9.2f\n", my_tab, my_tab,
i, tps[i].readparse_secs, tps[i].scan_secs,
tps[i].region_counts_secs, tps[i].mp_region_counts_secs, tps[i].anchor_list_secs, tps[i].hit_list_secs,
tps[i].pass1_secs, tps[i].get_vector_hits_secs, tps[i].pass2_secs, tps[i].duplicate_removal_secs,
comma_integer(tps[i].f1_invocs), tps[i].f1_secs,
comma_integer(tps[i].f2_invocs), tps[i].f2_secs,
comma_integer(tps[i].fwbw_invocs), tps[i].fwbw_secs,
time_counter_get_secs(&tpgA[i].wait_tc));
}
for (i = 0; i < num_threads; i++) {
fprintf (stderr, "thrd:%d anchor_list_init_size:(%.2f, %.2f) anchors_discarded:(%.2f, %.2f) big_gaps:(%.2f, %.2f)\n",
i, stat_get_mean(&tpgA[i].anchor_list_init_size), stat_get_sample_stddev(&tpgA[i].anchor_list_init_size),
stat_get_mean(&tpgA[i].n_anchors_discarded), stat_get_sample_stddev(&tpgA[i].n_anchors_discarded),
stat_get_mean(&tpgA[i].n_big_gaps_anchor_list), stat_get_sample_stddev(&tpgA[i].n_big_gaps_anchor_list));
}
fprintf(stderr, "\n");
}
fprintf(stderr, "%sSpaced Seed Scan:\n", my_tab);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Run-time:", total_scan_secs);
fprintf(stderr, "\n");
fprintf(stderr, "%sVector Smith-Waterman:\n", my_tab);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Run-time:", f1_total_secs);
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Invocations:", comma_integer(f1_total_invocs));
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Bypassed Calls:", comma_integer(f1_calls_bypassed));
fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab,
"Cells Computed:", (double)f1_total_cells / 1.0e6);
fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab,
"Cells per Second:", f1_total_cellspersec / 1.0e6);
fprintf(stderr, "\n");
fprintf(stderr, "%sScalar Smith-Waterman:\n", my_tab);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Run-time:", f2_total_secs);
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Invocations:", comma_integer(f2_total_invocs));
fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab,
"Cells Computed:", (double)f2_total_cells / 1.0e6);
fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab,
"Cells per Second:", f2_total_cellspersec / 1.0e6);
fprintf(stderr, "\n");
if (shrimp_mode == MODE_COLOUR_SPACE) {
fprintf(stderr, "%sForward-Backward:\n", my_tab);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Run-time:", fwbw_total_secs);
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Invocations:", comma_integer(fwbw_total_invocs));
fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab,
"Cells Computed:", (double)fwbw_total_cells / 1.0e6);
fprintf(stderr, "%s%s%-24s" "%.2f million\n", my_tab, my_tab,
"Cells per Second:", fwbw_total_cellspersec / 1.0e6);
fprintf(stderr, "\n");
}
fprintf(stderr, "%sMiscellaneous Totals:\n", my_tab);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Fasta Lib Time:", fasta_load_secs);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Read Load Time:", total_readparse_secs);
fprintf(stderr, "%s%s%-24s" "%.2f seconds\n", my_tab, my_tab,
"Wait Time:", total_wait_secs);
fprintf(stderr, "\n");
fprintf(stderr, "%sGeneral:\n", my_tab);
if (pair_mode == PAIR_NONE)
{
fprintf(stderr, "%s%s%-24s" "%s (%.4f%%)\n", my_tab, my_tab,
"Reads Matched:",
comma_integer(total_reads_matched),
(nreads == 0) ? 0 : ((double)total_reads_matched / (double)nreads) * 100);
fprintf(stderr, "%s%s%-24s" "%s (%.4f%%)\n", my_tab, my_tab,
"... with QV >= 10:",
comma_integer(total_reads_matched_conf),
(nreads == 0) ? 0 : ((double)total_reads_matched_conf / (double)nreads) * 100);
fprintf(stderr, "%s%s%-24s" "%s (%.4f%%)\n", my_tab, my_tab,
"Reads Dropped:",
comma_integer(total_reads_dropped),
(nreads == 0) ? 0 : ((double)total_reads_dropped / (double)nreads) * 100);
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Total Matches:",
comma_integer(total_single_matches));
fprintf(stderr, "%s%s%-24s" "%.2f\n", my_tab, my_tab,
"Avg Hits/Matched Read:",
(total_reads_matched == 0) ? 0 : ((double)total_single_matches / (double)total_reads_matched));
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Duplicate Hits Pruned:",
comma_integer(total_dup_single_matches));
}
else // paired hits
{
fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab,
"Pairs Matched:",
comma_integer(total_pairs_matched),
(nreads == 0) ? 0 : ((double)total_pairs_matched / (double)(nreads/2)) * 100);
fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab,
"... with QV >= 10:",
comma_integer(total_pairs_matched_conf),
(nreads == 0) ? 0 : ((double)total_pairs_matched_conf / (double)(nreads/2)) * 100);
fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab,
"Pairs Dropped:",
comma_integer(total_pairs_dropped),
(nreads == 0) ? 0 : ((double)total_pairs_dropped / (double)(nreads/2)) * 100);
fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab,
"Total Paired Matches:",
comma_integer(total_paired_matches));
fprintf(stderr, "%s%s%-40s" "%.2f\n", my_tab, my_tab,
"Avg Matches/Pair Matched:",
(total_pairs_matched == 0) ? 0 : ((double)total_paired_matches / (double)total_pairs_matched));
fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab,
"Duplicate Paired Matches Pruned:",
comma_integer(total_dup_paired_matches));
if (half_paired) {
fprintf(stderr, "\n");
fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab,
"Additional Reads Matched Unpaired:",
comma_integer(total_reads_matched),
(nreads == 0) ? 0 : ((double)total_reads_matched / (double)nreads) * 100);
fprintf(stderr, "%s%s%-40s" "%s (%.4f%%)\n", my_tab, my_tab,
"... with QV >= 10:",
comma_integer(total_reads_matched_conf),
(nreads == 0) ? 0 : ((double)total_reads_matched_conf / (double)nreads) * 100);
fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab,
"Total Unpaired Matches:",
comma_integer(total_single_matches));
fprintf(stderr, "%s%s%-40s" "%.2f\n", my_tab, my_tab,
"Avg Matches/Unpaired Matched Read:",
(total_reads_matched == 0) ? 0 : ((double)total_single_matches / (double)total_reads_matched));
fprintf(stderr, "%s%s%-40s" "%s\n", my_tab, my_tab,
"Duplicate Unpaired Matches Pruned:",
comma_integer(total_dup_single_matches));
}
}
fprintf(stderr, "\n");
fprintf(stderr, "%sMemory usage:\n", my_tab);
fprintf(stderr, "%s%s%-24s" "%s\n", my_tab, my_tab,
"Genomemap:",
comma_integer(count_get_count(&mem_genomemap)));
if (Xflag) {
print_insert_histogram();
}
free(tps);
free(tpgA);
}
static void
usage(char * progname, bool full_usage){
char *slash;
int sn;
if (n_seeds == 0)
load_default_seeds(0);
slash = strrchr(progname, '/');
if (slash != NULL)
progname = slash + 1;
fprintf(stderr,
"usage: %s [options/parameters] { <r> | -1 <r1> -2 <r2> } <g1> <g2>...\n", progname);
fprintf(stderr,
" <r> Reads filename, paired or unpaired\n");
fprintf(stderr,
" <r1> Upstream reads filename\n");
fprintf(stderr,
" <r2> Downstream reads filename\n");
fprintf(stderr,
" <g1> <g2>... Space seperated list of genome filenames\n");
fprintf(stderr,
"Parameters:\n");
fprintf(stderr,
" -s/--seeds Spaced Seed(s) (default: ");
for (sn = 0; sn < n_seeds; sn++) {
if (sn > 0)
fprintf(stderr,
" ");
fprintf(stderr, "%s%s\n", seed_to_string(sn), (sn == n_seeds - 1? ")" : ","));
}
fprintf(stderr,
" -o/--report Maximum Hits per Read (default: %d)\n",
DEF_NUM_OUTPUTS);
fprintf(stderr,
" --max-alignments Max. align. per read (0=all) (default: %d)\n",
DEF_MAX_ALIGNMENTS);
fprintf(stderr,
" -w/--match-window Match Window Length (default: %.02f%%)\n",
DEF_WINDOW_LEN);
fprintf(stderr,
" -n/--cmw-mode Match Mode (default: unpaired:%d paired:%d)\n",
DEF_MATCH_MODE_UNPAIRED, DEF_MATCH_MODE_PAIRED);
if (full_usage) {
fprintf(stderr,
" -l/--cmw-overlap Match Window Overlap Length (default: %.02f%%)\n",
DEF_WINDOW_OVERLAP);
fprintf(stderr,
" -a/--anchor-width Anchor Width Limiting Full SW (default: %d; disable: -1)\n",
DEF_ANCHOR_WIDTH);
fprintf(stderr, "\n");
fprintf(stderr,
" -S/--save Save Genome Proj. in File (default: no)\n");
fprintf(stderr,
" -L/--load Load Genome Proj. from File (default: no)\n");
fprintf(stderr,
" -z/--cutoff Projection List Cut-off Len. (default: %u)\n",
DEF_LIST_CUTOFF);
}
fprintf(stderr, "\n");
fprintf(stderr,
" -m/--match SW Match Score (default: %d)\n",
shrimp_mode == MODE_LETTER_SPACE? DEF_LS_MATCH_SCORE : DEF_CS_MATCH_SCORE);
fprintf(stderr,
" -i/--mismatch SW Mismatch Score (default: %d)\n",
shrimp_mode == MODE_LETTER_SPACE? DEF_LS_MISMATCH_SCORE : DEF_CS_MISMATCH_SCORE);
fprintf(stderr,
" -g/--open-r SW Gap Open Score (Reference) (default: %d)\n",
shrimp_mode == MODE_LETTER_SPACE? DEF_LS_A_GAP_OPEN : DEF_CS_A_GAP_OPEN);
fprintf(stderr,
" -q/--open-q SW Gap Open Score (Query) (default: %d)\n",
shrimp_mode == MODE_LETTER_SPACE? DEF_LS_B_GAP_OPEN : DEF_CS_B_GAP_OPEN);
fprintf(stderr,
" -e/--ext-r SW Gap Extend Score(Reference)(default: %d)\n",
shrimp_mode == MODE_LETTER_SPACE? DEF_LS_A_GAP_EXTEND : DEF_CS_A_GAP_EXTEND);
fprintf(stderr,
" -f/--ext-q SW Gap Extend Score (Query) (default: %d)\n",
shrimp_mode == MODE_LETTER_SPACE? DEF_LS_B_GAP_EXTEND : DEF_CS_B_GAP_EXTEND);
if (shrimp_mode == MODE_COLOUR_SPACE) {
fprintf(stderr,
" -x/--crossover SW Crossover Score (default: %d)\n",
DEF_CS_XOVER_SCORE);
}
fprintf(stderr,
" -r/--cmw-threshold Window Generation Threshold (default: %.02f%%)\n",
DEF_WINDOW_GEN_THRESHOLD);
if (shrimp_mode == MODE_COLOUR_SPACE) {
fprintf(stderr,
" -v/--vec-threshold SW Vector Hit Threshold (default: %.02f%%)\n",
DEF_SW_VECT_THRESHOLD);
}
fprintf(stderr,
" -h/--full-threshold SW Full Hit Threshold (default: %.02f%%)\n",
DEF_SW_FULL_THRESHOLD);
fprintf(stderr, "\n");
fprintf(stderr,
" -N/--threads Number of Threads (default: %d)\n",
DEF_NUM_THREADS);
if (full_usage) {
fprintf(stderr,
" -K/--thread-chunk Thread Chunk Size (default: %d)\n",
DEF_CHUNK_SIZE);
}
fprintf(stderr, "\n");
fprintf(stderr,
" -p/--pair-mode Paired Mode (default: %s)\n",
pair_mode_string[pair_mode]);
fprintf(stderr,
" -I/--isize Min and Max Insert Size (default: %d,%d)\n",
DEF_MIN_INSERT_SIZE, DEF_MAX_INSERT_SIZE);
fprintf(stderr,
" --longest-read Maximum read length (default: %d)\n",
DEF_LONGEST_READ_LENGTH);
fprintf(stderr,
" -1/--upstream Upstream read pair file\n");
fprintf(stderr,
" -2/--downstream Downstream read pair file\n");
fprintf(stderr,
" --un Dump unaligned reads to file\n");
fprintf(stderr,
" --al Dump aligned reads to file\n");
fprintf(stderr,
" --read-group Attach SAM Read Group name\n");
fprintf(stderr,
" --sam-header Use file as SAM header\n");
fprintf(stderr,
" --single-best-mapping Report only the best mapping(s), this is not strata (see README)\n");
fprintf(stderr,
" --all-contigs Report a maximum of 1 mapping for each read.\n");
fprintf(stderr,
" --no-mapping-qualities Do not compute mapping qualities\n");
fprintf(stderr,
" --insert-size-dist Specifies the mean and stddev of the insert sizes\n");
fprintf(stderr,
" --no-improper-mappings (see README)\n");
if (full_usage) {
fprintf(stderr,
" --trim-front Trim front of reads by this amount\n");
fprintf(stderr,
" --trim-end Trim end of reads by this amount\n");
fprintf(stderr,
" --trim-first Trim only first read in pair\n");
fprintf(stderr,
" --trim-second Trim only second read in pair\n");
fprintf(stderr,
" --min-avg-qv The minimum average quality value of a read\n");
fprintf(stderr,
" --progress Display a progress line each <value> reads. (default %d)\n",progress);
fprintf(stderr,
" --save-mmap Save genome projection to shared memory\n");
fprintf(stderr,
" --load-mmap Load genome projection from shared memory\n");
fprintf(stderr,
" --indel-taboo-len Prevent indels from starting or ending in the tail\n");
fprintf(stderr,
" --shrimp-format Output mappings in SHRiMP format (default: %s)\n",Eflag ? "disabled" : "enabled");
fprintf(stderr,
" --qv-offset (see README)\n");
fprintf(stderr,
" --sam-header-hd (see README)\n");
fprintf(stderr,
" --sam-header-sq (see README)\n");
fprintf(stderr,
" --sam-header-rg (see README)\n");
fprintf(stderr,
" --sam-header-pg (see README)\n");
fprintf(stderr,
" --no-autodetect-input (see README)\n");
}
fprintf(stderr, "\n");
fprintf(stderr, "Options:\n");
fprintf(stderr,
" -U/--ungapped Perform Ungapped Alignment (default: %s)\n", gapless_sw ? "enabled" : "disabled");
fprintf(stderr,
" --global Perform full global alignment (default: %s)\n", Gflag ? "enabled" : "disabled");
fprintf(stderr,
" --local Perform local alignment (default: %s)\n", Gflag ? "disabled" : "enabled");
if (shrimp_mode == MODE_COLOUR_SPACE) {
fprintf(stderr,
" --bfast Try to align like bfast (default: %s)\n", Bflag ? "enabled" : "disabled");
} else {
fprintf(stderr,
" --trim-illumina Trim trailing B qual values (default: %s)\n", trim_illumina ? "enabled" : "disabled");
}
fprintf(stderr,
" -C/--negative Negative Strand Aln. Only (default: %s)\n", Cflag ? "enabled" : "disabled");
fprintf(stderr,
" -F/--positive Positive Strand Aln. Only (default: %s)\n", Fflag ? "enabled" : "disabled");
fprintf(stderr,
" -P/--pretty Pretty Print Alignments (default: %s)\n", Pflag ? "enabled" : "disabled");
fprintf(stderr,
" -E/--sam Output SAM Format (default: %s)\n", Eflag ? "enabled" : "disabled");
fprintf(stderr,
" -Q/--fastq Reads are in fastq format (default: %s)\n", Qflag ? "enabled" : "disabled");
if (full_usage) {
fprintf(stderr,
" -R/--print-reads Print Reads in Output (default: %s)\n", Rflag ? "enabled" : "disabled");
// fprintf(stderr,
// " -T (does nothing since default) Reverse Tie-break on Negative Strand (default: enabled)\n");
fprintf(stderr,
" -t/--tiebreak-off Disable Reverse Tie-break\n");
fprintf(stderr,
" on Negative Strand (default: %s)\n",Tflag ? "enabled" : "disabled");
fprintf(stderr,
" -X/--isize-hist Print Insert Size Histogram (default: %s)\n", Xflag ? "enabled" : "disabled");
fprintf(stderr,
" -Y/--proj-hist Print Genome Proj. Histogram (default: %s)\n", Yflag ? "enabled" : "disabled");
fprintf(stderr,
" -Z/--bypass-off Disable Cache Bypass for SW\n");
fprintf(stderr,
" Vector Calls (default: %s)\n", hash_filter_calls ? "enabled" : "disabled");
fprintf(stderr,
" -H/--spaced-kmers Hash Spaced Kmers in Genome\n");
fprintf(stderr,
" Projection (default: %s)\n", Hflag ? "enabled" : "disabled");
fprintf(stderr,
" -D/--thread-stats Individual Thread Statistics (default: %s)\n", Dflag ? "enabled" : "disabled");
fprintf(stderr,
" -V/--trim-off Disable Automatic Genome\n");
fprintf(stderr,
" Index Trimming (default: %s)\n", Vflag ? "enabled" : "disabled");
fprintf(stderr,
" --pr-xover Set the Default Crossover Probability\n");
fprintf(stderr,
" (default: %.1e)\n", pr_xover);
}
fprintf(stderr,
" --sam-unaligned Unaligned reads in SAM output (default: %s)\n", sam_unaligned ? "enabled" : "disabled");
fprintf(stderr,
" --half-paired Output half mapped read pairs (default: %s)\n", half_paired ? "enabled" : "disabled");
fprintf(stderr,
" --strata Print only the best scoring hits\n");
fprintf(stderr,
" -?/--help Full List of Parameters and Options\n");
exit(1);
}
static void
print_pairing_options(struct pairing_options * options)
{
char buff[2][100];
fprintf(stderr, "[\n");
fprintf(stderr, " pairing:%s\n", pair_mode_string[options->pair_mode]);
fprintf(stderr, " min_insert:%d\n", options->min_insert_size);
fprintf(stderr, " max_insert:%d\n", options->max_insert_size);
fprintf(stderr, " pass1_num_outputs:%d\n", options->pass1_num_outputs);
fprintf(stderr, " pass1_threshold:%s\n", thres_to_buff(buff[0], &options->pass1_threshold));
fprintf(stderr, " pass2_num_outputs:%d\n", options->pass2_num_outputs);
fprintf(stderr, " pass2_threshold:%s\n", thres_to_buff(buff[0], &options->pass2_threshold));
fprintf(stderr, " strata:%s\n", bool_to_buff(buff[0], &options->strata));
fprintf(stderr, " save_outputs:%s\n", bool_to_buff(buff[0], &options->save_outputs));
fprintf(stderr, " stop_count:%d\n", options->stop_count);
fprintf(stderr, " stop_threshold:%s\n", thres_to_buff(buff[0], &options->stop_threshold));
fprintf(stderr, "]\n");
}
static void
print_read_mapping_options(struct read_mapping_options_t * options, bool is_paired)
{
char buff[2][100];
fprintf(stderr, "[\n");
fprintf(stderr, " regions:\n");
//fprintf(stderr, " [\n");
fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->regions.recompute));
//if (!options->regions.recompute)
//fprintf(stderr, " ]\n");
//else
// fprintf(stderr, ", min_seed:%d, max_seed:%d]\n",
// options->regions.min_seed, options->regions.max_seed);
fprintf(stderr, " anchor_list:\n");
//fprintf(stderr, " [\n");
fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->anchor_list.recompute));
if (options->anchor_list.recompute) {
fprintf(stderr, " collapse:%s\n", bool_to_buff(buff[0], &options->anchor_list.collapse));
fprintf(stderr, " use_region_counts:%s\n", bool_to_buff(buff[0], &options->anchor_list.use_region_counts));
fprintf(stderr, " use_mp_region_counts:%d\n", options->anchor_list.use_mp_region_counts);
}
//fprintf(stderr, " ]\n");
fprintf(stderr, " hit_list:\n");
//fprintf(stderr, " [\n");
fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->hit_list.recompute));
if (options->hit_list.recompute) {
fprintf(stderr, " gapless:%s\n", bool_to_buff(buff[0], &options->hit_list.gapless));
fprintf(stderr, " match_mode:%d\n", options->hit_list.match_mode);
fprintf(stderr, " threshold:%s\n", thres_to_buff(buff[0], &options->hit_list.threshold));
}
//fprintf(stderr, " ]\n");
fprintf(stderr, " pass1:\n");
//fprintf(stderr, " [\n");
fprintf(stderr, " recompute:%s\n", bool_to_buff(buff[0], &options->pass1.recompute));
if (options->pass1.recompute) {
fprintf(stderr, " threshold:%s\n", thres_to_buff(buff[0], &options->pass1.threshold));
fprintf(stderr, " window_overlap:%s\n", thres_to_buff(buff[1], &options->pass1.window_overlap));
fprintf(stderr, " min_matches:%d\n", options->pass1.min_matches);
fprintf(stderr, " gapless:%s\n", bool_to_buff(buff[0], &options->pass1.gapless));
if (is_paired) {
fprintf(stderr, " only_paired:%s\n", bool_to_buff(buff[0], &options->pass1.only_paired));
}
if (!is_paired) {
fprintf(stderr, " num_outputs:%d\n", options->pass1.num_outputs);
}
}
//fprintf(stderr, " ]\n");
fprintf(stderr, " pass2:\n");
//fprintf(stderr, " [\n");
fprintf(stderr, " threshold:%s\n", thres_to_buff(buff[0], &options->pass2.threshold));
if (!is_paired) {
fprintf(stderr, " strata:%s\n", bool_to_buff(buff[0], &options->pass2.strata));
fprintf(stderr, " save_outputs:%s\n", bool_to_buff(buff[0], &options->pass2.save_outputs));
fprintf(stderr, " num_outputs:%d\n", options->pass2.num_outputs);
}
//fprintf(stderr, " ]\n");
if (!is_paired) {
fprintf(stderr, " stop:\n");
//fprintf(stderr, " [\n");
fprintf(stderr, " stop_count:%d\n", options->pass2.stop_count);
if (options->pass2.stop_count > 0) {
fprintf(stderr, " stop_threshold:%s\n", thres_to_buff(buff[0], &options->pass2.stop_threshold));
}
//fprintf(stderr, " ]\n");
}
fprintf(stderr, "]\n");
}
static void
print_settings() {
char buff[100];
static char const my_tab[] = " ";
int sn, i;
fprintf(stderr, "Settings:\n");
// Seeds
fprintf(stderr, "%s%-40s%s (%d/%d)\n", my_tab,
(n_seeds == 1) ? "Spaced Seed (weight/span)" : "Spaced Seeds (weight/span)",
seed_to_string(0), seed[0].weight, seed[0].span);
for (sn = 1; sn < n_seeds; sn++) {
fprintf(stderr, "%s%-40s%s (%d/%d)\n", my_tab, "",
seed_to_string(sn), seed[sn].weight, seed[sn].span);
}
// Global settings
fprintf(stderr, "\n");
fprintf(stderr, "%s%-40s%d\n", my_tab, "Number of threads:", num_threads);
fprintf(stderr, "%s%-40s%d\n", my_tab, "Thread chunk size:", chunk_size);
fprintf(stderr, "%s%-40s%s\n", my_tab, "Window length:", thres_to_buff(buff, &window_len));
fprintf(stderr, "%s%-40s%s\n", my_tab, "Hash filter calls:", hash_filter_calls? "yes" : "no");
fprintf(stderr, "%s%-40s%d%s\n", my_tab, "Anchor width:", anchor_width,
anchor_width == -1? " (disabled)" : "");
fprintf(stderr, "%s%-40s%d%s\n", my_tab, "Indel taboo Len:", indel_taboo_len,
indel_taboo_len == 0? " (disabled)" : "");
if (list_cutoff < DEF_LIST_CUTOFF) {
fprintf(stderr, "%s%-40s%u\n", my_tab, "Index list cutoff length:", list_cutoff);
}
fprintf(stderr, "%s%-40s%s\n", my_tab, "Gapless mode:", gapless_sw? "yes" : "no");
fprintf(stderr, "%s%-40s%s\n", my_tab, "Global alignment:", Gflag? "yes" : "no");
fprintf(stderr, "%s%-40s%s\n", my_tab, "Region filter:", use_regions? "yes" : "no");
if (use_regions) {
fprintf(stderr, "%s%-40s%d\n", my_tab, "Region size:", (1 << region_bits));
fprintf(stderr, "%s%-40s%d\n", my_tab, "Region overlap:", region_overlap);
}
if (Qflag) {
fprintf(stderr, "%s%-40s%s\n", my_tab, "Ignore QVs:", ignore_qvs? "yes" : "no");
}
if (Qflag && !ignore_qvs) {
fprintf(stderr, "%s%-40s%d%s\n", my_tab, "Minimum average qv:", min_avg_qv, min_avg_qv < 0? " (none)" : "");
//fprintf(stderr, "%s%-40sPHRED+%d\n", my_tab, "QV input encoding:", qual_delta);
}
fprintf(stderr, "%s%-40s%s\n", my_tab, "Compute mapping qualities:", compute_mapping_qualities? "yes" : "no");
if (compute_mapping_qualities)
{
fprintf(stderr, "%s%-40s%s\n", my_tab, "All contigs:", all_contigs? "yes" : "no");
fprintf(stderr, "%s%-40s%s\n", my_tab, "Single best mapping:", single_best_mapping? "yes" : "no");
}
//fprintf(stderr, "%s%-40s%s\n", my_tab, "Hack:", hack? "yes" : "no");
// Scores
fprintf(stderr, "\n");
fprintf(stderr, "%s%-40s%-10d\n", my_tab, "SW Match Score:", match_score);
fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Mismatch Score [Prob]:", mismatch_score, pr_mismatch);
fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Del Open Score [Prob]:", a_gap_open_score, pr_del_open);
fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Ins Open Score [Prob]:", b_gap_open_score, pr_ins_open);
fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Del Extend Score [Prob]:", a_gap_extend_score, pr_del_extend);
fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Ins Extend Score [Prob]:", b_gap_extend_score, pr_ins_extend);
if (shrimp_mode == MODE_COLOUR_SPACE) {
fprintf(stderr, "%s%-40s%-10d\t[%.1e]\n", my_tab, "SW Crossover Score [Prob]:", crossover_score, pr_xover);
}
fprintf(stderr, "\n");
if (n_paired_mapping_options > 0) { // paired mapping
for (i = 0; i < n_paired_mapping_options; i++) {
fprintf(stderr, "Paired mapping options, set [%d]\n", i);
print_pairing_options(&paired_mapping_options[i].pairing);
print_read_mapping_options(&paired_mapping_options[i].read[0], true);
print_read_mapping_options(&paired_mapping_options[i].read[1], true);
}
if (n_unpaired_mapping_options[0] > 0) {
fprintf(stderr, "\n");
for (i = 0; i < n_unpaired_mapping_options[0]; i++) {
fprintf(stderr, "Unpaired mapping options for first read in a pair, set [%d]\n", i);
print_read_mapping_options(&unpaired_mapping_options[0][i], false);
}
}
if (n_unpaired_mapping_options[1] > 0) {
fprintf(stderr, "\n");
for (i = 0; i < n_unpaired_mapping_options[1]; i++) {
fprintf(stderr, "Unpaired mapping options for second read in a pair, set [%d]\n", i);
print_read_mapping_options(&unpaired_mapping_options[1][i], false);
}
}
} else {
for (i = 0; i < n_unpaired_mapping_options[0]; i++) {
fprintf(stderr, "Unpaired mapping options, set [%d]\n", i);
print_read_mapping_options(&unpaired_mapping_options[0][i], false);
}
}
fprintf(stderr, "\n");
return;
fprintf(stderr, "%s%-40s%d\n", my_tab, "Number of Outputs per Read:", num_outputs);
fprintf(stderr, "%s%-40s%d\n", my_tab, "Window Generation Mode:", match_mode);
if (IS_ABSOLUTE(window_overlap)) {
fprintf(stderr, "%s%-40s%u\n", my_tab, "Window Overlap Length:", (uint)-window_overlap);
} else {
fprintf(stderr, "%s%-40s%.02f%%\n", my_tab, "Window Overlap Length:", window_overlap);
}
fprintf(stderr, "\n");
if (IS_ABSOLUTE(window_gen_threshold)) {
fprintf(stderr, "%s%-40s%u\n", my_tab,
"Window Generation Threshold:", (uint)-window_gen_threshold);
} else {
fprintf(stderr, "%s%-40s%.02f%%\n", my_tab,
"Window Generation Threshold:", window_gen_threshold);
}
if (shrimp_mode == MODE_COLOUR_SPACE) {
if (IS_ABSOLUTE(sw_vect_threshold)) {
fprintf(stderr, "%s%-40s%u\n", my_tab, "SW Vector Hit Threshold:", (uint)-sw_vect_threshold);
} else {
fprintf(stderr, "%s%-40s%.02f%%\n", my_tab, "SW Vector Hit Threshold:", sw_vect_threshold);
}
}
if (IS_ABSOLUTE(sw_full_threshold)) {
fprintf(stderr, "%s%-40s%u\n", my_tab,
shrimp_mode == MODE_COLOUR_SPACE? "SW Full Hit Threshold:" : "SW Hit Threshold",
(uint)-sw_full_threshold);
} else {
fprintf(stderr, "%s%-40s%.02f%%\n", my_tab,
shrimp_mode == MODE_COLOUR_SPACE? "SW Full Hit Threshold:" : "SW Hit Threshold",
sw_full_threshold);
}
fprintf(stderr, "\n");
fprintf(stderr, "%s%-40s%s\n", my_tab, "Paired mode:", pair_mode_string[pair_mode]);
if (pair_mode != PAIR_NONE) {
fprintf(stderr, "%s%-40smin:%d max:%d\n", my_tab, "Insert sizes:", min_insert_size, max_insert_size);
if (Xflag) {
fprintf(stderr, "%s%-40s%d\n", my_tab, "Bucket size:", insert_histogram_bucket_size);
}
}
fprintf(stderr, "\n");
}
static int
set_mode_from_string(char const * s) {
if (!strcmp(s, "mirna")) {
mode_mirna = true;
//load_default_mirna_seeds();
Hflag = true;
gapless_sw = true;
anchor_width = 0;
a_gap_open_score = -255;
b_gap_open_score = -255;
hash_filter_calls = false;
match_mode = 1;
window_len = 100.0;
Gflag = false;
compute_mapping_qualities = false;
return 1;
} else {
return 0;
}
}
static void
get_pair_mode(char * c, int * pair_mode)
{
if (c == NULL) {
fprintf(stderr, "error: invalid pair mode\n");
exit(1);
}
if (!strcmp(c, "none")) {
*pair_mode = PAIR_NONE;
} else if (!strcmp(c, "opp-in")) {
*pair_mode = PAIR_OPP_IN;
} else if (!strcmp(c, "opp-out")) {
*pair_mode = PAIR_OPP_OUT;
} else if (!strcmp(c, "col-fw")) {
*pair_mode = PAIR_COL_FW;
} else if (!strcmp(c, "col-bw")) {
*pair_mode = PAIR_COL_BW;
} else {
fprintf(stderr, "error: unrecognized pair mode (%s)\n", c);
exit(1);
}
}
static void
get_int(char * c, int * d)
{
if (c == NULL) {
fprintf(stderr, "error: invalid integer\n");
exit(1);
}
*d = atoi(c);
}
static void
get_threshold(char * c, double * t)
{
if (c == NULL) {
fprintf(stderr, "error: invalid threshold\n");
exit(1);
}
*t = atof(c);
if (*t < 0.0) {
fprintf(stderr, "error: invalid threshold [%s]\n", c);
exit(1);
}
if (strcspn(c, "%.") == strlen(c))
*t = -(*t); //absol.
}
static void
get_bool(char * c, bool * b)
{
if (!strcmp(c, "true") || !strcmp(c, "1")) {
*b = true;
} else if (!strcmp(c, "false") || !strcmp(c, "0")) {
*b = false;
} else {
fprintf(stderr, "error: invalid bool\n");
exit(1);
}
}
static void
get_pairing_options(char * c, struct pairing_options * options)
{
char * p;
if (c == NULL) {
fprintf(stderr, "error: invalid pairing options\n");
exit(1);
}
p = strtok(c, ",");
get_pair_mode(p, &options->pair_mode);
p = strtok(NULL, ",");
get_int(p, &options->min_insert_size);
p = strtok(NULL, ",");
get_int(p, &options->max_insert_size);
p = strtok(NULL, ",");
get_int(p, &options->pass1_num_outputs);
p = strtok(NULL, ",");
get_threshold(p, &options->pass1_threshold);
p = strtok(NULL, ",");
get_int(p, &options->pass2_num_outputs);
p = strtok(NULL, ",");
get_threshold(p, &options->pass2_threshold);
p = strtok(NULL, ",");
get_int(p, &options->stop_count);
p = strtok(NULL, ",");
get_threshold(p, &options->stop_threshold);
p = strtok(NULL, ",");
get_bool(p, &options->strata);
p = strtok(NULL, ",");
get_bool(p, &options->save_outputs);
}
static void
get_read_mapping_options(char * c, struct read_mapping_options_t * options, bool is_paired)
{
char * p, * q;
char * save_ptr;
if (c == NULL) {
fprintf(stderr, "error: invalid read mapping options\n");
exit(1);
}
fprintf(stderr, "parsing read_mapping_options [%s] (%s)\n", c, is_paired? "paired" : "unpaired");
// regions
q = strtok_r(c, "/", &save_ptr);
logit(0, "parsing region options: %s", q);
p = strtok(q, ",");
get_bool(p, &options->regions.recompute);
//if (options->regions.recompute) {
//p = strtok(NULL, ",");
//get_int(p, &options->regions.min_seed);
//p = strtok(NULL, ",");
//get_int(p, &options->regions.max_seed);
//}
// anchor_list
q = strtok_r(NULL, "/", &save_ptr);
logit(0, "parsing anchor_list options: %s", q);
p = strtok(q, ",");
get_bool(p, &options->anchor_list.recompute);
if (options->anchor_list.recompute) {
p = strtok(NULL, ",");
get_bool(p, &options->anchor_list.collapse);
p = strtok(NULL, ",");
get_bool(p, &options->anchor_list.use_region_counts);
if (is_paired) {
p = strtok(NULL, ",");
get_int(p, &options->anchor_list.use_mp_region_counts);
}
}
// hit_list
q = strtok_r(NULL, "/", &save_ptr);
logit(0, "parsing hit_list options: %s", q);
p = strtok(q, ",");
get_bool(p, &options->hit_list.recompute);
if (options->hit_list.recompute) {
p = strtok(NULL, ",");
get_bool(p, &options->hit_list.gapless);
p = strtok(NULL, ",");
get_int(p, &options->hit_list.match_mode);
p = strtok(NULL, ",");
get_threshold(p, &options->hit_list.threshold);
}
// pass1
q = strtok_r(NULL, "/", &save_ptr);
logit(0, "parsing pass1 options: %s", q);
p = strtok(q, ",");
get_bool(p, &options->pass1.recompute);
if (options->pass1.recompute) {
p = strtok(NULL, ",");
get_threshold(p, &options->pass1.threshold);
p = strtok(NULL, ",");
get_threshold(p, &options->pass1.window_overlap);
p = strtok(NULL, ",");
get_int(p, &options->pass1.min_matches);
p = strtok(NULL, ",");
get_bool(p, &options->pass1.gapless);
if (is_paired) {
p = strtok(NULL, ",");
get_bool(p, &options->pass1.only_paired);
}
if (!is_paired) {
p = strtok(NULL, ",");
get_int(p, &options->pass1.num_outputs);
}
}
// pass2
q = strtok_r(NULL, "/", &save_ptr);
logit(0, "parsing pass2 options: %s", q);
p = strtok(q, ",");
get_threshold(p, &options->pass2.threshold);
if (!is_paired) {
p = strtok(NULL, ",");
get_bool(p, &options->pass2.strata);
p = strtok(NULL, ",");
get_bool(p, &options->pass2.save_outputs);
p = strtok(NULL, ",");
get_int(p, &options->pass2.num_outputs);
}
// stop
if (!is_paired) {
q = strtok_r(NULL, "/", &save_ptr);
logit(0, "parsing stop options: %s", q);
p = strtok(q, ",");
get_int(p, &options->pass2.stop_count);
if (options->pass2.stop_count > 0) {
p = strtok(NULL, ",");
get_threshold(p, &options->pass2.stop_threshold);
}
}
}
int main(int argc, char **argv){
char **genome_files = NULL;
int ngenome_files = 0;
char *progname = argv[0];
char const * optstr = NULL;
char *c, *save_c;
int ch;
int i, sn, cn;
llint before;
bool a_gap_open_set, b_gap_open_set;
bool a_gap_extend_set, b_gap_extend_set;
bool match_score_set, mismatch_score_set, xover_score_set;
bool match_mode_set = false;
bool qual_delta_set = false;
fasta_t fasta = NULL, left_fasta = NULL, right_fasta = NULL;
my_alloc_init(64l*1024l*1024l*1024l, 64l*1024l*1024l*1024l);
shrimp_args.argc=argc;
shrimp_args.argv=argv;
set_mode_from_argv(argv, &shrimp_mode);
a_gap_open_set = b_gap_open_set = a_gap_extend_set = b_gap_extend_set = false;
match_score_set = mismatch_score_set = xover_score_set = false;
if (shrimp_mode == MODE_COLOUR_SPACE) {
match_score = DEF_CS_MATCH_SCORE;
mismatch_score = DEF_CS_MISMATCH_SCORE;
a_gap_open_score = DEF_CS_A_GAP_OPEN;
b_gap_open_score = DEF_CS_B_GAP_OPEN;
a_gap_extend_score = DEF_CS_A_GAP_EXTEND;
b_gap_extend_score = DEF_CS_B_GAP_EXTEND;
}
fasta_reset_stats();
fprintf(stderr, "--------------------------------------------------"
"------------------------------\n");
fprintf(stderr, "gmapper: %s.\nSHRiMP %s\n[%s; CXXFLAGS=\"%s\"]\n",
get_mode_string(shrimp_mode),
SHRIMP_VERSION_STRING,
get_compiler(), CXXFLAGS);
fprintf(stderr, "--------------------------------------------------"
"------------------------------\n");
struct option getopt_long_options[standard_entries+MAX(colour_entries,letter_entries)];
memcpy(getopt_long_options,standard_options,sizeof(standard_options));
//TODO -t -9 -d -Z -D -Y
switch(shrimp_mode){
case MODE_COLOUR_SPACE:
optstr = "?1:2:s:n:w:l:o:p:m:i:g:q:e:f:h:r:a:z:DCEFHI:K:L:M:N:PRS:TtUVXYZQx:v:";
memcpy(getopt_long_options+standard_entries,colour_space_options,sizeof(colour_space_options));
break;
case MODE_LETTER_SPACE:
optstr = "?1:2:s:n:w:l:o:p:m:i:g:q:e:f:h:r:a:z:DCEFHI:K:L:M:N:PRS:TtUVXYZQ";
memcpy(getopt_long_options+standard_entries,letter_space_options,sizeof(letter_space_options));
break;
case MODE_HELICOS_SPACE:
fprintf(stderr,"Helicose currently unsupported\n");
exit(1);
break;
}
//get a copy of the command line
size_t size_of_command_line=0;
for (i=0; i<argc; i++) {
size_of_command_line+=strlen(argv[i])+1;
}
size_of_command_line++;
char command_line[size_of_command_line];
size_t offset=0;
for (i=0; i<argc; i++) {
offset+=sprintf(command_line+offset,"%s",argv[i]);
if (i+1!=argc) {
offset+=sprintf(command_line+offset," ");
}
}
assert(offset+1<=size_of_command_line);
while ((ch = getopt_long(argc,argv,optstr,getopt_long_options,NULL)) != -1){
switch (ch) {
case 9:
strata_flag = true;
break;
case 10:
unaligned_reads_file=fopen(optarg,"w");
if (unaligned_reads_file==NULL) {
fprintf(stderr,"error: cannot open file \"%s\" for writting\n",optarg);
}
break;
case 11:
aligned_reads_file=fopen(optarg,"w");
if (aligned_reads_file==NULL) {
fprintf(stderr,"error: cannot open file \"%s\" for writting\n",optarg);
}
break;
case 12:
sam_unaligned=true;
break;
case 13:
longest_read_len=atoi(optarg);
if (longest_read_len<200) {
fprintf(stderr,"error: longest read length must be at least 200\n");
exit(1);
}
break;
case 14:
max_alignments=atoi(optarg);
break;
case 15:
logit(0, "as of v2.2.0, --global is on by default");
Gflag = true;
break;
case 16:
Bflag = true;
Gflag = true;
break;
case 17:
sam_read_group_name=strdup(optarg);
sam_sample_name = strchr(sam_read_group_name,',');
if (sam_sample_name==NULL) {
fprintf(stderr,"error: sam read group needs to be two values, delimited by commas.\n");
fprintf(stderr," the first value is unique read group identifier\n");
fprintf(stderr," the second is the sample (use pool name where a pool is being sequence\n");
exit(1);
}
sam_sample_name[0]='\0';
sam_sample_name++;
break;
case 18:
sam_header_filename=optarg;
break;
case 19:
half_paired = false;
break;
case 20:
sam_r2=true;
break;
case '1':
left_reads_filename = optarg;
break;
case '2':
right_reads_filename = optarg;
break;
case 's':
if (strchr(optarg, ',') == NULL) { // allow comma-separated seeds
if (optarg[0] == 'w') {
int weight = (int)atoi(&optarg[1]);
if (!load_default_seeds(weight)) {
fprintf(stderr, "error: invalid spaced seed weight (%d)\n", weight);
exit(1);
}
} else {
if (!add_spaced_seed(optarg)) {
fprintf(stderr, "error: invalid spaced seed \"%s\"\n", optarg);
exit (1);
}
}
} else {
c = strtok(optarg, ",");
do {
if (c[0] == 'w') {
int weight = (int)atoi(&c[1]);
if (!load_default_seeds(weight)) {
fprintf(stderr, "error: invalid spaced seed weight (%d)\n", weight);
exit(1);
}
} else {
if (!add_spaced_seed(c)) {
fprintf(stderr, "error: invalid spaced seed \"%s\"\n", c);
exit (1);
}
}
c = strtok(NULL, ",");
} while (c != NULL);
}
break;
case 'n':
match_mode = atoi(optarg);
match_mode_set = true;
break;
case 'w':
window_len = atof(optarg);
if (window_len <= 0.0) {
fprintf(stderr, "error: invalid window "
"length\n");
exit(1);
}
if (strcspn(optarg, "%.") == strlen(optarg))
window_len = -window_len; //absol.
break;
case 'o':
num_outputs = atoi(optarg);
num_tmp_outputs = 20 + num_outputs;
break;
case 'm':
match_score = atoi(optarg);
match_score_set = true;
break;
case 'i':
mismatch_score = atoi(optarg);
mismatch_score_set = true;
break;
case 'g':
a_gap_open_score = atoi(optarg);
a_gap_open_set = true;
break;
case 'q':
b_gap_open_score = atoi(optarg);
b_gap_open_set = true;
break;
case 'e':
a_gap_extend_score = atoi(optarg);
a_gap_extend_set = true;
break;
case 'f':
b_gap_extend_score = atoi(optarg);
b_gap_extend_set = true;
break;
case 'x':
assert(shrimp_mode == MODE_COLOUR_SPACE);
crossover_score = atoi(optarg);
xover_score_set = true;
break;
case 'h':
sw_full_threshold = atof(optarg);
if (sw_full_threshold < 0.0) {
fprintf(stderr, "error: invalid s-w full "
"hit threshold\n");
exit(1);
}
if (strcspn(optarg, "%.") == strlen(optarg))
sw_full_threshold = -sw_full_threshold; //absol.
break;
case 'v':
assert(shrimp_mode == MODE_COLOUR_SPACE);
sw_vect_threshold = atof(optarg);
if (sw_vect_threshold < 0.0) {
fprintf(stderr, "error: invalid s-w vector "
"hit threshold\n");
exit(1);
}
if (strcspn(optarg, "%.") == strlen(optarg))
sw_vect_threshold = -sw_vect_threshold; //absol.
break;
case 'r':
window_gen_threshold = atof(optarg);
if (window_gen_threshold < 0.0) {
fprintf(stderr, "error: invalid window generation threshold [%s]\n", optarg);
exit(1);
}
if (strcspn(optarg, "%.") == strlen(optarg))
window_gen_threshold = -window_gen_threshold; //absol.
break;
case 'C':
if (Fflag) {
fprintf(stderr, "error: -C and -F are mutually "
"exclusive\n");
exit(1);
}
Cflag = true;
break;
case 'F':
if (Cflag) {
fprintf(stderr, "error: -C and -F are mutually "
"exclusive\n");
exit(1);
}
Fflag = true;
break;
case 'H':
Hflag = true;
break;
case 'P':
Pflag = true;
Eflag = false;
break;
case 'R':
Rflag = true;
break;
case 't':
Tflag= false;
break;
case 'T':
Tflag = true;
break;
/*
* New options/parameters since SHRiMP 1.2.1
*/
case 'a':
anchor_width = atoi(optarg);
if (anchor_width < -1 || anchor_width >= 100) {
fprintf(stderr, "error: anchor_width requested is invalid (%s)\n",
optarg);
exit(1);
}
break;
case 'X':
Xflag = true;
break;
case 'Y':
Yflag = true;
break;
case 'l':
window_overlap = atof(optarg);
if (window_overlap <= 0.0) {
fprintf(stderr, "error: invalid window overlap\n");
exit(1);
}
if (strcspn(optarg, "%.") == strlen(optarg))
window_overlap = -window_overlap; //absol.
break;
case 'N':
num_threads = atoi(optarg);
break;
case 'K':
chunk_size = atoi(optarg);
break;
case 'S':
save_file = optarg;
break;
case 'L':
load_file = optarg;
break;
case 'D':
Dflag = true;
break;
case '?':
usage(progname, true);
break;
case 'Z':
hash_filter_calls = false;
break;
case 'U':
gapless_sw = true;
anchor_width = 0;
a_gap_open_score = -255;
b_gap_open_score = -255;
hash_filter_calls = false;
break;
case 'p':
if (!strcmp(optarg, "none")) {
pair_mode = PAIR_NONE;
} else if (!strcmp(optarg, "opp-in")) {
pair_mode = PAIR_OPP_IN;
} else if (!strcmp(optarg, "opp-out")) {
pair_mode = PAIR_OPP_OUT;
} else if (!strcmp(optarg, "col-fw")) {
pair_mode = PAIR_COL_FW;
} else if (!strcmp(optarg, "col-bw")) {
pair_mode = PAIR_COL_BW;
} else {
fprintf(stderr, "error: unrecognized pair mode (%s)\n", optarg);
exit(1);
}
break;
case 'I':
c = strtok(optarg, ",");
if (c == NULL)
crash(1, 0, "format for insert sizes is \"-I 200,1000\"\n");
min_insert_size = atoi(c);
if (min_insert_size < 0) {
logit(0, "insert sizes must be nonnegative; check README. resetting min_insert_size from [%s] to 0", optarg);
min_insert_size = 0;
}
c = strtok(NULL, ",");
if (c == NULL)
crash(1, 0, "format for insert sizes is \"-I 200,1000\"\n");
max_insert_size = atoi(c);
if (max_insert_size < 0) {
logit(0, "insert sizes must be nonnegative; check README. resetting max_insert_size from [%s] to 0", optarg);
max_insert_size = 0;
}
if (min_insert_size > max_insert_size)
crash(1, 0, "invalid insert sizes (min:%d,max:%d)\n", min_insert_size, max_insert_size);
break;
case 'E': // on by default; accept option for bw compatibility
logit(0, "as of v2.2.0, -E/--sam is on by default");
Eflag = true;
break;
case 'z':
list_cutoff = atoi(optarg);
if (list_cutoff == 0) {
fprintf(stderr, "error: invalid list cutoff (%s)\n", optarg);
exit(1);
}
break;
case 'V':
Vflag = false;
break;
case 'Q':
Qflag = true;
break;
case 'M':
c = strtok(optarg, ",");
do {
if (!set_mode_from_string(c)) {
fprintf(stderr, "error: unrecognized mode (%s)\n", c);
exit(1);
}
match_mode_set = true;
c = strtok(NULL, ",");
} while (c != NULL);
break;
case 21:
trim_front=atoi(optarg);
if (shrimp_mode == MODE_COLOUR_SPACE) {
fprintf(stderr,"--trim-front cannot be used in colour space mode!\n");
exit(1);
}
if (trim_front<0) {
fprintf(stderr,"--trim-front value must be positive\n");
exit(1);
}
if (trim_front>0)
trim=true;
break;
case 22:
trim_end=atoi(optarg);
if (trim_end<0) {
fprintf(stderr,"--trim-end value must be positive\n");
exit(1);
}
if (trim_end>0)
trim=true;
break;
case 23:
trim=true;
trim_first=true;
trim_second=false;
break;
case 24:
trim=true;
trim_second=true;
trim_first=false;
break;
case 25:
c = strtok(optarg, ",");
if (c == NULL)
crash(1, 0, "argmuent for insert-size-dist should be \"mean,stddev\" [%s]", optarg);
insert_size_mean = atof(c);
c = strtok(NULL, ",");
if (c == NULL)
crash(1, 0, "argmuent for insert-size-dist should be \"mean,stddev\" [%s]", optarg);
insert_size_stddev = atof(c);
break;
case 26:
use_regions = !use_regions;
break;
case 27:
region_overlap = atoi(optarg);
if (region_overlap < 0) {
fprintf(stderr, "region overlap must be non-negative!\n");
exit(1);
}
break;
case 28:
if (n_unpaired_mapping_options[0] > 0 || n_unpaired_mapping_options[1] > 0) {
fprintf(stderr, "warning: unpaired mapping options set before paired mapping options! the latter take precedence.\n");
half_paired = true;
}
n_paired_mapping_options++;
paired_mapping_options = (struct readpair_mapping_options_t *)
//xrealloc(paired_mapping_options, n_paired_mapping_options * sizeof(paired_mapping_options[0]));
my_realloc(paired_mapping_options, n_paired_mapping_options * sizeof(paired_mapping_options[0]), (n_paired_mapping_options - 1) * sizeof(paired_mapping_options[0]),
&mem_small, "paired_mapping_options");
c = strtok_r(optarg, ";", &save_c);
get_pairing_options(c, &paired_mapping_options[n_paired_mapping_options - 1].pairing);
c = strtok_r(NULL, ";", &save_c);
get_read_mapping_options(c, &paired_mapping_options[n_paired_mapping_options - 1].read[0], true);
c = strtok_r(NULL, ";", &save_c);
get_read_mapping_options(c, &paired_mapping_options[n_paired_mapping_options - 1].read[1], true);
// HACK SETTINGS
pair_mode = paired_mapping_options[0].pairing.pair_mode;
break;
case 29:
int nip;
c = strtok(optarg, ";");
if (c == NULL || (*c != '0' && *c != '1')) {
fprintf(stderr, "error: invalid unpaired mapping options:[%s]\n", optarg);
exit(1);
}
if (n_paired_mapping_options > 0)
half_paired = true;
nip = (*c == '0'? 0 : 1);
n_unpaired_mapping_options[nip]++;
unpaired_mapping_options[nip] = (struct read_mapping_options_t *)
//xrealloc(unpaired_mapping_options[nip], n_unpaired_mapping_options[nip] * sizeof(unpaired_mapping_options[nip][0]));
my_realloc(unpaired_mapping_options[nip], n_unpaired_mapping_options[nip] * sizeof(unpaired_mapping_options[nip][0]), (n_unpaired_mapping_options[nip] - 1) * sizeof(unpaired_mapping_options[nip][0]),
&mem_small, "unpaired_mapping_options[%d]", nip);
c = strtok(NULL, ";");
get_read_mapping_options(c, &unpaired_mapping_options[nip][n_unpaired_mapping_options[nip] - 1], false);
break;
case 30:
min_avg_qv = atoi(optarg);
if (min_avg_qv < -2 || min_avg_qv > 40) {
fprintf(stderr, "error: invalid minimum average quality value (%s)\n", optarg);
}
break;
case 31:
extra_sam_fields = true;
break;
case 32:
region_bits = atoi(optarg);
if (region_bits < 8 || region_bits > 20) {
crash(1, 0, "invalid number of region bits: %s; must be between 8 and 20", optarg);
}
n_regions = (1 << (32 - region_bits));
break;
case 33:
progress = atoi(optarg);
break;
case 34:
save_mmap = optarg;
break;
case 35:
load_mmap = optarg;
break;
case 36:
indel_taboo_len = atoi(optarg);
if (indel_taboo_len < 0)
crash(1, 0, "invalid indel taboo len: [%s]", optarg);
break;
case 37:
single_best_mapping = true;
break;
case 38:
all_contigs = true;
break;
case 39:
compute_mapping_qualities = false;
break;
case 40:
Eflag = false;
break;
case 41: // half-paired: accept option for bw compatibility
logit(0, "as of v2.2.0, --half-paired is on by default");
half_paired = true;
break;
case 42: // no-improper-mappings
improper_mappings = false;
break;
case 43: // qual value offset
qual_delta = atoi(optarg);
qual_delta_set = true;
break;
case 44: // sam-header-hd
sam_header_hd = fopen(optarg, "r");
if (sam_header_hd == NULL)
crash(1, 1, "cannot open sam header file with HD lines [%s]", optarg);
break;
case 45: // sam-header-sq
sam_header_sq = fopen(optarg, "r");
if (sam_header_sq == NULL)
crash(1, 1, "cannot open sam header file with SQ lines [%s]", optarg);
break;
case 46: // sam-header-rg
sam_header_rg = fopen(optarg, "r");
if (sam_header_rg == NULL)
crash(1, 1, "cannot open sam header file with RG lines [%s]", optarg);
break;
case 47: // sam-header-pg
sam_header_pg = fopen(optarg, "r");
if (sam_header_pg == NULL)
crash(1, 1, "cannot open sam header file with PG lines [%s]", optarg);
break;
case 48: // no-autodetect-input
autodetect_input = false;
break;
case 3:
trim_illumina=true;
break;
case 123:
no_qv_check=true;
break;
case 124: // local alignment
Gflag = false;
break;
case 125: // --ignore-qvs
ignore_qvs = true;
break;
case 126:
pr_xover = atof(optarg);
break;
default:
usage(progname, false);
}
}
argc -= optind;
argv += optind;
if ((pair_mode != PAIR_NONE || !single_reads_file) && (chunk_size % 2) != 0) {
logit(0, "in paired mode or if using options -1 and -2, the thread chunk size must be even; adjusting it to [%d]", chunk_size + 1);
chunk_size++;
}
if (!Gflag && compute_mapping_qualities) {
logit(0, "mapping qualities are not available in local alignment mode; disabling them");
compute_mapping_qualities = false;
}
if (Gflag && gapless_sw) {
fprintf(stderr,"error: cannot use global (or bfast) and ungapped mode at the same time!\n");
usage(progname,false);
}
if (sam_unaligned && !Eflag) {
fprintf(stderr,"error: when using flag --sam-unaligned must also use -E/--sam\n");
usage(progname,false);
}
if (right_reads_filename != NULL || left_reads_filename !=NULL) {
if (right_reads_filename == NULL || left_reads_filename == NULL ){
fprintf(stderr,"error: when using \"%s\" must also specify \"%s\"\n",
(left_reads_filename != NULL) ? "-1" : "-2",
(left_reads_filename != NULL) ? "-2" : "-1");
usage(progname,false);
}
single_reads_file=false;
if (strcmp(right_reads_filename,"-")==0 && strcmp(left_reads_filename,"-")==0) {
fprintf(stderr,"error: both -1 and -2 arguments cannot be stdin (\"-\")\n");
usage(progname,false);
}
}
if (!match_mode_set) {
match_mode = (pair_mode == PAIR_NONE? DEF_MATCH_MODE_UNPAIRED : DEF_MATCH_MODE_PAIRED);
}
if (pair_mode == PAIR_NONE && (!trim_first || !trim_second)) {
fprintf(stderr,"error: cannot use --trim-first or --trim-second in unpaired mode\n");
usage(progname,false);
}
// set up insert size histogram
if (Xflag && pair_mode == PAIR_NONE) {
fprintf(stderr, "warning: insert histogram not available in unpaired mode; ignoring\n");
Xflag = false;
}
if (pair_mode != PAIR_NONE) {
insert_histogram_bucket_size = ceil_div(max_insert_size - min_insert_size + 1, 100);
for (i = 0; i < 100; i++) {
insert_histogram[i] = 1;
insert_histogram_load += insert_histogram[i];
}
}
if(load_file != NULL && n_seeds != 0){
fprintf(stderr,"error: cannot specify seeds when loading genome map\n");
usage(progname,false);
}
if (n_seeds == 0 && load_file == NULL && load_mmap == NULL) {
if (mode_mirna)
load_default_mirna_seeds();
else
load_default_seeds(0);
}
if (Hflag){
init_seed_hash_mask();
}
if (save_file != NULL && load_file != NULL && list_cutoff == DEF_LIST_CUTOFF){
fprintf(stderr,"error: -L and -S allowed together only if list_cutoff is specified\n");
exit(1);
}
if (load_file != NULL && (save_file != NULL || save_mmap != NULL))
{ // args: none
if (argc != 0) {
fprintf(stderr, "error: when using both -L and -S, no extra files can be given\n");
usage(progname, false);
}
}
else if (load_file != NULL || load_mmap != NULL)
{ // args: reads file
if (argc == 0 && single_reads_file) {
fprintf(stderr,"error: read_file not specified\n");
usage(progname, false);
} else if (argc == 1) {
if (single_reads_file) {
reads_filename = argv[0];
} else {
fprintf(stderr,"error: cannot specify a reads file when using -L, -1 and -2\n");
usage(progname,false);
}
}
}
else if (save_file != NULL)
{ // args: genome file(s)
if (argc == 0){
fprintf(stderr, "error: genome_file(s) not specified\n");
usage(progname,false);
}
genome_files = &argv[0];
ngenome_files = argc;
}
else if (single_reads_file)
{ // args: reads file, genome file(s)
if (argc < 2) {
fprintf(stderr, "error: %sgenome_file(s) not specified\n",
(argc == 0) ? "reads_file, " : "");
usage(progname, false);
}
reads_filename = argv[0];
genome_files = &argv[1];
ngenome_files = argc - 1;
}
else
{
if( argc < 1) {
fprintf(stderr, "error: genome_file(s) not specified\n");
usage(progname, false);
}
genome_files = &argv[0];
ngenome_files = argc;
}
if (!Cflag && !Fflag) {
Cflag = Fflag = true;
}
if (pair_mode != PAIR_NONE && (!Cflag || !Fflag)) {
fprintf(stderr, "warning: in paired mode, both strands must be inspected; ignoring -C and -F\n");
Cflag = Fflag = true;
}
/*
if (pair_mode == PAIR_NONE && half_paired) {
fprintf(stderr, "error: cannot use option half-paired in non-paired mode!\n");
exit(1);
}
*/
if (pair_mode == PAIR_NONE && sam_r2) {
fprintf(stderr, "error: cannot use option sam-r2 in non-paired mode!\n");
exit(1);
}
if (shrimp_mode == MODE_LETTER_SPACE) {
sw_vect_threshold = sw_full_threshold;
}
if (Eflag && Pflag) {
fprintf(stderr,"-E and -P are incompatable\n");
exit(1);
}
if (Eflag && Rflag) {
fprintf(stderr,"-E and -R are incompatable\n");
exit(1);
}
if (!valid_spaced_seeds()) {
fprintf(stderr, "error: invalid spaced seed\n");
if (!Hflag)
fprintf(stderr, " for longer seeds, try using the -H flag\n");
exit(1);
}
if (!IS_ABSOLUTE(window_len) && window_len < 100.0) {
fprintf(stderr, "error: window length < 100%% of read length\n");
exit(1);
}
if (!IS_ABSOLUTE(window_overlap) && window_overlap > 100.0) {
fprintf(stderr, "warning: window overlap length > 100%% of window_length; resetting to 100%%\n");
window_overlap = 100.0;
}
if ((pair_mode == PAIR_NONE && (match_mode < 1 || match_mode > 2))
|| (pair_mode != PAIR_NONE && (match_mode < 2 || match_mode > 4))) {
fprintf(stderr, "error: invalid match mode [pair_mode=%d;match_mode=%d]\n", pair_mode, match_mode);
exit(1);
}
if (num_outputs < 1) {
fprintf(stderr, "error: invalid maximum hits per read\n");
exit(1);
}
if (a_gap_open_score > 0 || b_gap_open_score > 0) {
fprintf(stderr, "error: invalid gap open penalty\n");
exit(1);
}
if (a_gap_extend_score > 0 || b_gap_extend_score > 0) {
fprintf(stderr, "error: invalid gap extend penalty\n");
exit(1);
}
if (!IS_ABSOLUTE(sw_full_threshold) && sw_full_threshold > 100.0) {
fprintf(stderr, "error: invalid s-w full hit threshold\n");
exit(1);
}
if (shrimp_mode == MODE_COLOUR_SPACE && !IS_ABSOLUTE(sw_vect_threshold)
&& sw_vect_threshold > 100.0) {
fprintf(stderr, "error: invalid s-w vector threshold\n");
exit(1);
}
if (!IS_ABSOLUTE(window_gen_threshold) && window_gen_threshold > 100.0) {
fprintf(stderr, "error: invalid window generation threshold\n");
exit(1);
}
if ((IS_ABSOLUTE(window_gen_threshold) && IS_ABSOLUTE(sw_full_threshold)
&& -window_gen_threshold > -sw_full_threshold)
||
(!IS_ABSOLUTE(window_gen_threshold) && !IS_ABSOLUTE(sw_full_threshold)
&& window_gen_threshold > sw_full_threshold)) {
//fprintf(stderr, "warning: window generation threshold is larger than sw threshold\n");
}
if ((a_gap_open_set && !b_gap_open_set) || (a_gap_extend_set && !b_gap_extend_set)) {
fputc('\n', stderr);
}
if (a_gap_open_set && !b_gap_open_set) {
fprintf(stderr, "Notice: Gap open penalty set for reference but not query; assuming symmetry.\n");
b_gap_open_score = a_gap_open_score;
}
if (a_gap_extend_set && !b_gap_extend_set) {
fprintf(stderr, "Notice: Gap extend penalty set for reference but not query; assuming symmetry.\n");
b_gap_extend_score = a_gap_extend_score;
}
if ((a_gap_open_set && !b_gap_open_set) || (a_gap_extend_set && !b_gap_extend_set)) {
fputc('\n', stderr);
}
/* Set probabilities from scores */
if (shrimp_mode == MODE_COLOUR_SPACE) {
// CS: pr_xover ~= .03 => alpha => pr_mismatch => rest
//pr_xover = .03;
score_alpha = (double)crossover_score / (log(pr_xover/3)/log(2.0));
pr_mismatch = 1.0/(1.0 + 1.0/3.0 * pow(2.0, ((double)match_score - (double)mismatch_score)/score_alpha));
} else {
// LS: pr_mismatch ~= .01 => alpha => rest
pr_mismatch = .01;
score_alpha = ((double)match_score - (double)mismatch_score)/(log((1 - pr_mismatch)/(pr_mismatch/3.0))/log(2.0));
}
score_beta = (double)match_score - 2 * score_alpha - score_alpha * log(1 - pr_mismatch)/log(2.0);
pr_del_open = pow(2.0, (double)a_gap_open_score/score_alpha);
pr_ins_open = pow(2.0, (double)b_gap_open_score/score_alpha);
pr_del_extend = pow(2.0, (double)a_gap_extend_score/score_alpha);
pr_ins_extend = pow(2.0, ((double)b_gap_extend_score - score_beta)/score_alpha);
//score_difference_mq_cutoff = (int)rint(10.0 * score_alpha);
#ifdef DEBUG_SCORES
fprintf(stderr, "probabilities from scores:\talpha=%.9g\tbeta=%.9g\n", score_alpha, score_beta);
if (shrimp_mode == MODE_COLOUR_SPACE)
fprintf(stderr, "pr_xover=%.9g\n", pr_xover);
fprintf(stderr, "pr_mismatch=%.9g\npr_del_open=%.9g\tpr_del_extend=%.9g\t(pr_del1=%.9g)\npr_ins_open=%.9g\tpr_ins_extend=%.9g\t(pr_ins1=%.9g)\n",
pr_mismatch,
pr_del_open, pr_del_extend, pr_del_open*pr_del_extend,
pr_ins_open, pr_ins_extend, pr_ins_open*pr_ins_extend);
// sanity check:
fprintf(stderr, "scores from probabilities:\n");
fprintf(stderr, "match_score=%g\nmismatch_score=%g\n",
2 * score_alpha + score_beta + score_alpha * log(1 - pr_mismatch) / log(2.0),
2 * score_alpha + score_beta + score_alpha * log(pr_mismatch/3) / log(2.0));
if (shrimp_mode == MODE_COLOUR_SPACE)
fprintf(stderr, "crossover_score=%g\n", score_alpha * log(pr_xover/3) / log(2.0));
fprintf(stderr, "a_gap_open_score=%g\ta_gap_extend_score=%g\nb_gap_open_score=%g\tb_gap_extend_score=%g\n",
score_alpha * log(pr_del_open) / log(2.0),
score_alpha * log(pr_del_extend) / log(2.0),
score_alpha * log(pr_ins_open) / log(2.0),
score_alpha * log(pr_ins_extend) / log(2.0) + score_beta);
#endif
// set up new options structure
// THIS SHOULD EVENTUALLY BE MERGED INTO OPTION READING
if (n_unpaired_mapping_options[0] == 0 && n_paired_mapping_options == 0) {
if (pair_mode == PAIR_NONE)
{
n_unpaired_mapping_options[0]++;
//unpaired_mapping_options[0] = (struct read_mapping_options_t *)xcalloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]));
unpaired_mapping_options[0] = (struct read_mapping_options_t *)
my_calloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]),
&mem_small, "unpaired_mapping_options[0]");
unpaired_mapping_options[0][0].regions.recompute = (match_mode == 2 && use_regions);
//unpaired_mapping_options[0][0].regions.min_seed = -1;
//unpaired_mapping_options[0][0].regions.max_seed = -1;
unpaired_mapping_options[0][0].anchor_list.recompute = true;
unpaired_mapping_options[0][0].anchor_list.collapse = true;
unpaired_mapping_options[0][0].anchor_list.use_region_counts = (match_mode == 2 && use_regions);
unpaired_mapping_options[0][0].anchor_list.use_mp_region_counts = 0;
unpaired_mapping_options[0][0].hit_list.recompute = true;
unpaired_mapping_options[0][0].hit_list.gapless = gapless_sw;
unpaired_mapping_options[0][0].hit_list.match_mode = match_mode;
unpaired_mapping_options[0][0].hit_list.threshold = window_gen_threshold;
unpaired_mapping_options[0][0].pass1.recompute = true;
unpaired_mapping_options[0][0].pass1.only_paired = false;
unpaired_mapping_options[0][0].pass1.gapless = gapless_sw;
unpaired_mapping_options[0][0].pass1.min_matches = match_mode; // this is 1 or 2 in unpaired mode
unpaired_mapping_options[0][0].pass1.num_outputs = num_tmp_outputs;
unpaired_mapping_options[0][0].pass1.threshold = sw_vect_threshold;
unpaired_mapping_options[0][0].pass1.window_overlap = window_overlap;
unpaired_mapping_options[0][0].pass2.strata = strata_flag;
unpaired_mapping_options[0][0].pass2.save_outputs = false;
unpaired_mapping_options[0][0].pass2.num_outputs = num_outputs;
unpaired_mapping_options[0][0].pass2.threshold = sw_full_threshold;
unpaired_mapping_options[0][0].pass2.stop_count = 0;
}
else
{
n_paired_mapping_options++;
//paired_mapping_options = (struct readpair_mapping_options_t *)xcalloc(n_paired_mapping_options * sizeof(paired_mapping_options[0]));
paired_mapping_options = (struct readpair_mapping_options_t *)
my_calloc(n_paired_mapping_options * sizeof(paired_mapping_options[0]),
&mem_small, "paired_mapping_options");
paired_mapping_options[0].pairing.pair_mode = pair_mode;
paired_mapping_options[0].pairing.min_insert_size = min_insert_size;
paired_mapping_options[0].pairing.max_insert_size = max_insert_size;
paired_mapping_options[0].pairing.strata = strata_flag;
paired_mapping_options[0].pairing.save_outputs = compute_mapping_qualities;
paired_mapping_options[0].pairing.pass1_num_outputs = num_tmp_outputs;
paired_mapping_options[0].pairing.pass2_num_outputs = num_outputs;
paired_mapping_options[0].pairing.pass1_threshold = sw_vect_threshold;
paired_mapping_options[0].pairing.pass2_threshold = sw_full_threshold;
paired_mapping_options[0].read[0].regions.recompute = use_regions && match_mode != 2;
//paired_mapping_options[0].read[0].regions.min_seed = -1;
//paired_mapping_options[0].read[0].regions.max_seed = -1;
paired_mapping_options[0].read[0].anchor_list.recompute = true;
paired_mapping_options[0].read[0].anchor_list.collapse = true;
paired_mapping_options[0].read[0].anchor_list.use_region_counts = use_regions && match_mode != 2;
if (use_regions) {
paired_mapping_options[0].read[0].anchor_list.use_mp_region_counts = (match_mode == 4 && !half_paired? 1
: match_mode == 3 && half_paired? 2
: match_mode == 3 && !half_paired? 3
: 0);
}
paired_mapping_options[0].read[0].hit_list.recompute = true;
paired_mapping_options[0].read[0].hit_list.gapless = gapless_sw;
paired_mapping_options[0].read[0].hit_list.match_mode = (match_mode == 4? 2
: match_mode == 3? 3
: 1);
paired_mapping_options[0].read[0].hit_list.threshold = window_gen_threshold;
paired_mapping_options[0].read[0].pass1.recompute = true;
paired_mapping_options[0].read[0].pass1.only_paired = true;
paired_mapping_options[0].read[0].pass1.gapless = gapless_sw;
paired_mapping_options[0].read[0].pass1.min_matches = (match_mode == 4? 2 : 1);
paired_mapping_options[0].read[0].pass1.threshold = sw_vect_threshold;
paired_mapping_options[0].read[0].pass1.window_overlap = window_overlap;
paired_mapping_options[0].read[0].pass2.strata = strata_flag;
paired_mapping_options[0].read[0].pass2.threshold = sw_full_threshold * 0.5;
paired_mapping_options[0].read[1] = paired_mapping_options[0].read[0];
if (!half_paired)
{
paired_mapping_options[0].pairing.stop_count = 0;
}
else // half_paired
{
paired_mapping_options[0].pairing.stop_count = 1;
paired_mapping_options[0].pairing.stop_threshold = 101.0; //paired_mapping_options[0].pairing.pass2_threshold;
n_unpaired_mapping_options[0]++;
n_unpaired_mapping_options[1]++;
//unpaired_mapping_options[0] = (struct read_mapping_options_t *)xcalloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]));
unpaired_mapping_options[0] = (struct read_mapping_options_t *)
my_calloc(n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]),
&mem_small, "unpaired_mapping_options[0]");
//unpaired_mapping_options[1] = (struct read_mapping_options_t *)xcalloc(n_unpaired_mapping_options[1] * sizeof(unpaired_mapping_options[1][0]));
unpaired_mapping_options[1] = (struct read_mapping_options_t *)
my_calloc(n_unpaired_mapping_options[1] * sizeof(unpaired_mapping_options[1][0]),
&mem_small, "unpaired_mapping_options[1]");
unpaired_mapping_options[0][0].regions.recompute = false;
unpaired_mapping_options[0][0].anchor_list.recompute = false;
unpaired_mapping_options[0][0].hit_list.recompute = false;
unpaired_mapping_options[0][0].pass1.recompute = true;
unpaired_mapping_options[0][0].pass1.gapless = gapless_sw;
unpaired_mapping_options[0][0].pass1.min_matches = 2;
unpaired_mapping_options[0][0].pass1.only_paired = false;
unpaired_mapping_options[0][0].pass1.num_outputs = num_tmp_outputs;
unpaired_mapping_options[0][0].pass1.threshold = sw_vect_threshold;
unpaired_mapping_options[0][0].pass1.window_overlap = window_overlap;
unpaired_mapping_options[0][0].pass2.strata = strata_flag;
unpaired_mapping_options[0][0].pass2.save_outputs = compute_mapping_qualities;
unpaired_mapping_options[0][0].pass2.num_outputs = num_outputs;
unpaired_mapping_options[0][0].pass2.threshold = sw_full_threshold;
unpaired_mapping_options[0][0].pass2.stop_count = 0;
unpaired_mapping_options[1][0] = unpaired_mapping_options[0][0];
}
}
}
if(load_file == NULL && load_mmap == NULL) {
print_settings();
}
if (load_file != NULL && save_mmap != NULL) {
exit(genome_load_map_save_mmap(load_file, save_mmap) == true ? 0 : 1);
}
before = gettimeinusecs();
if (load_mmap != NULL) {
genome_load_mmap(load_mmap);
} else if (load_file != NULL){
if (strchr(load_file, ',') == NULL) {
//use prefix
int buf_size = strlen(load_file) + 20;
//char * genome_name = (char *)xmalloc(sizeof(char)*buf_size);
char genome_name[buf_size];
strncpy(genome_name,load_file,buf_size);
strncat(genome_name,".genome",buf_size);
fprintf(stderr,"Loading genome from %s\n",genome_name);
if (!load_genome_map(genome_name)){
fprintf(stderr, "error: loading from genome file \"%s\"\n", genome_name);
exit (1);
}
//free(genome_name);
int seed_count = 0;
//char * seed_name = (char *)xmalloc(sizeof(char)*buf_size);
char seed_name[buf_size];
//char * buff = (char *)xmalloc(sizeof(char)*buf_size);
char buff[buf_size];
strncpy(seed_name,load_file,buf_size);
strncat(seed_name,".seed.",buf_size);
sprintf(buff,"%d",seed_count);
strncat(seed_name,buff,buf_size);
FILE *f = fopen(seed_name,"r");
while(f != NULL){
fclose(f);
fprintf(stderr,"Loading seed from %s\n",seed_name);
if (!load_genome_map_seed(seed_name)) {
fprintf(stderr, "error: loading from map file \"%s\"\n", seed_name);
exit (1);
}
seed_count++;
strncpy(seed_name,load_file,buf_size);
strncat(seed_name,".seed.",buf_size);
sprintf(buff,"%d",seed_count);
strncat(seed_name,buff,buf_size);
f = fopen(seed_name,"r");
}
//free(seed_name);
//free(buff);
} else {
c = strtok(load_file, ",");
fprintf(stderr,"Loading genome from %s\n",c);
if (!load_genome_map(c)){
fprintf(stderr, "error: loading from genome file \"%s\"\n", c);
exit (1);
}
c = strtok(NULL, ",");
do {
fprintf(stderr,"Loading seed from %s\n",c);
if (!load_genome_map_seed(c)) {
fprintf(stderr, "error: loading from map file \"%s\"\n", c);
exit (1);
}
c = strtok(NULL, ",");
} while (c != NULL);
}
if (Hflag) {
init_seed_hash_mask();
}
//print_settings();
} else {
if (!load_genome(genome_files,ngenome_files)){
exit(1);
}
}
load_genome_usecs += (gettimeinusecs() - before);
// initialize general search tree for contig offsets
gen_st_init(&contig_offsets_gen_st, 17, contig_offsets, num_contigs);
//
// Automatic genome index trimming
//
if (Vflag && save_file == NULL && list_cutoff == DEF_LIST_CUTOFF) {
// this will be a mapping job; enable automatic trimming
long long unsigned int total_genome_len = 0;
int max_seed_weight = 0;
for (i = 0; i < num_contigs; i++) {
total_genome_len += (long long unsigned int)genome_len[i];
}
if (Hflag) {
max_seed_weight = HASH_TABLE_POWER;
} else {
for (sn = 0; sn < n_seeds; sn++) {
if (seed[sn].weight > max_seed_weight) {
max_seed_weight = seed[sn].weight;
}
}
}
// cutoff := max (1000, 100*(total_genome_len/4^max_seed_weight))
list_cutoff = 1000;
if ((uint32_t)((100llu * total_genome_len)/power(4, max_seed_weight)) > list_cutoff) {
list_cutoff = (uint32_t)((100llu * total_genome_len)/power(4, max_seed_weight));
}
//fprintf(stderr, " %-40s%d\n", "Trimming index lists longer than:", list_cutoff);
//fprintf(stderr, "\n");
}
if (load_file != NULL || load_mmap != NULL) {
print_settings();
}
if (Yflag)
print_genomemap_stats();
if (save_file != NULL) {
if (list_cutoff != DEF_LIST_CUTOFF) {
fprintf(stderr, "\nTrimming index lists longer than: %u\n", list_cutoff);
trim_genome();
}
fprintf(stderr,"Saving genome map to %s\n",save_file);
if(!save_genome_map(save_file)){
exit(1);
}
exit(0);
}
// compute total genome size
for (cn = 0; cn < num_contigs; cn++)
total_genome_size += genome_len[cn];
//TODO setup need max window and max read len
//int longest_read_len = 2000;
int max_window_len = (int)abs_or_pct(window_len,longest_read_len);
// open input files, and set Qflag accordingly
if (single_reads_file) {
fasta = fasta_open(reads_filename, shrimp_mode, Qflag, autodetect_input? &Qflag : NULL);
if (fasta == NULL) {
crash(1, 1, "failed to open read file [%s]", reads_filename);
} else {
fprintf(stderr, "- Processing read file [%s]\n", reads_filename);
}
} else {
left_fasta = fasta_open(left_reads_filename, shrimp_mode, Qflag, autodetect_input? &Qflag : NULL);
if (left_fasta == NULL) {
crash(1, 1, "failed to open read file [%s]", left_reads_filename);
}
right_fasta = fasta_open(right_reads_filename, shrimp_mode, Qflag);
if (right_fasta == NULL) {
crash(1, 1, "failed to open read file [%s]", right_reads_filename);
}
// WHY? the code above sets both ->space to shrimp_mode anyhow
//if (right_fasta->space != left_fasta->space) {
// fprintf(stderr,"error: when using -1 and -2, both files must be either only colour space or only letter space!\n");
// return (false);
//}
fasta = left_fasta;
fprintf(stderr, "- Processing read files [%s , %s]\n", left_reads_filename, right_reads_filename);
}
// set default quality value delta
if (Qflag) {
if (!qual_delta_set) {
if (shrimp_mode == MODE_LETTER_SPACE)
qual_delta = DEF_LS_QUAL_DELTA;
else
qual_delta = DEF_CS_QUAL_DELTA;
logit(0, "quality value format not set explicitly; using PHRED+%d", qual_delta);
} else {
logit(0, "quality value format set to PHRED+%d", qual_delta);
}
}
#pragma omp parallel shared(longest_read_len,max_window_len,a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score,\
match_score, mismatch_score,shrimp_mode,crossover_score,anchor_width) num_threads(num_threads)
{
// init thread-private globals
memset(&tpg, 0, sizeof(tpg_t));
tpg.wait_tc.type = DEF_FAST_TIME_COUNTER;
tpg.region_counts_tc.type = DEF_FAST_TIME_COUNTER;
tpg.mp_region_counts_tc.type = DEF_FAST_TIME_COUNTER;
tpg.anchor_list_tc.type = DEF_FAST_TIME_COUNTER;
tpg.hit_list_tc.type = DEF_FAST_TIME_COUNTER;
tpg.get_vector_hits_tc.type = DEF_FAST_TIME_COUNTER;
tpg.pass1_tc.type = DEF_FAST_TIME_COUNTER;
tpg.pass2_tc.type = DEF_FAST_TIME_COUNTER;
tpg.duplicate_removal_tc.type = DEF_FAST_TIME_COUNTER;
/* region handling */
if (use_regions) {
region_map_id = 0;
for (int number_in_pair = 0; number_in_pair < 2; number_in_pair++)
for (int st = 0; st < 2; st++)
//region_map[number_in_pair][st] = (int32_t *)xcalloc(n_regions * sizeof(region_map[0][0][0]));
region_map[number_in_pair][st] = (region_map_t *)
my_calloc(n_regions * sizeof(region_map[0][0][0]),
&mem_mapping, "region_map");
}
if (f1_setup(max_window_len, longest_read_len,
a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score,
match_score, shrimp_mode == MODE_LETTER_SPACE? mismatch_score : match_score + crossover_score,
shrimp_mode == MODE_COLOUR_SPACE, true)) {
fprintf(stderr, "failed to initialise vector Smith-Waterman (%s)\n", strerror(errno));
exit(1);
}
int ret;
if (shrimp_mode == MODE_COLOUR_SPACE) {
/* XXX - a vs. b gap */
ret = sw_full_cs_setup(max_window_len, longest_read_len,
a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score,
match_score, mismatch_score,
crossover_score, true, anchor_width, indel_taboo_len);
} else {
ret = sw_full_ls_setup(max_window_len, longest_read_len,
a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score,
match_score, mismatch_score, true, anchor_width);
}
if (ret) {
fprintf(stderr, "failed to initialise scalar Smith-Waterman (%s)\n", strerror(errno));
exit(1);
}
/* post_sw */
if (shrimp_mode == MODE_COLOUR_SPACE) {
post_sw_setup(max_window_len + longest_read_len,
pr_mismatch, pr_xover, pr_del_open, pr_del_extend, pr_ins_open, pr_ins_extend,
Qflag && !ignore_qvs, use_sanger_qvs, qual_vector_offset, qual_delta, true);
}
}
char * output;
if (Eflag){
int i;
if (sam_header_filename != NULL) {
FILE * sam_header_file = fopen(sam_header_filename, "r");
if (sam_header_file == NULL) {
perror("Failed to open sam header file ");
exit(1);
}
cat(sam_header_file, stdout);
fclose(sam_header_file);
} else {
// HD line
if (sam_header_hd != NULL) {
cat(sam_header_hd, stdout);
} else {
fprintf(stdout,"@HD\tVN:%s\tSO:%s\n","1.0","unsorted");
}
// SQ lines
if (sam_header_sq != NULL) {
cat(sam_header_sq, stdout);
} else {
for(i = 0; i < num_contigs; i++){
fprintf(stdout,"@SQ\tSN:%s\tLN:%u\n",contig_names[i],genome_len[i]);
}
}
// RG lines
if (sam_header_rg != NULL) {
cat(sam_header_rg, stdout);
} else if (sam_read_group_name != NULL) {
fprintf(stdout, "@RG\tID:%s\tSM:%s\n", sam_read_group_name, sam_sample_name);
}
// PG lines
if (sam_header_pg != NULL) {
cat(sam_header_pg, stdout);
} else {
fprintf(stdout, "@PG\tID:%s\tVN:%s\tCL:%s\n", "gmapper", SHRIMP_VERSION_STRING, command_line);
}
}
} else {
output = output_format_line(Rflag);
puts(output);
free(output);
}
before = gettimeinusecs();
bool launched = launch_scan_threads(fasta, left_fasta, right_fasta);
if (!launched) {
fprintf(stderr,"error: a fatal error occured while launching scan thread(s)!\n");
exit(1);
}
mapping_wallclock_usecs += (gettimeinusecs() - before);
if (single_reads_file) {
fasta_close(fasta);
} else {
fasta_close(left_fasta);
fasta_close(right_fasta);
}
print_statistics();
#pragma omp parallel shared(longest_read_len,max_window_len,a_gap_open_score, a_gap_extend_score, b_gap_open_score, b_gap_extend_score, \
match_score, mismatch_score,shrimp_mode,crossover_score,anchor_width) num_threads(num_threads)
{
sw_vector_cleanup();
if (shrimp_mode==MODE_COLOUR_SPACE) {
sw_full_cs_cleanup();
post_sw_cleanup();
}
sw_full_ls_cleanup();
f1_free();
if (use_regions) {
for (int number_in_pair = 0; number_in_pair < 2; number_in_pair++)
for (int st = 0; st < 2; st++)
//free(region_map[number_in_pair][st]);
my_free(region_map[number_in_pair][st], n_regions * sizeof(region_map[0][0][0]),
&mem_mapping, "region_map");
}
}
gen_st_delete(&contig_offsets_gen_st);
if (load_mmap != NULL) {
// munmap?
} else {
free_genome();
//free(seed);
if (Hflag) {
int sn;
for (sn = 0; sn < n_seeds; sn++) {
my_free(seed_hash_mask[sn], BPTO32BW(max_seed_span) * sizeof(seed_hash_mask[sn][0]),
&mem_small, "seed_hash_mask[%d]", sn);
}
my_free(seed_hash_mask, n_seeds * sizeof(seed_hash_mask[0]),
&mem_small, "seed_hash_mask");
}
my_free(seed, n_seeds * sizeof(seed[0]),
&mem_small, "seed");
}
//free(paired_mapping_options);
my_free(paired_mapping_options, n_paired_mapping_options * sizeof(paired_mapping_options[0]),
&mem_small, "paired_mapping_options");
//free(unpaired_mapping_options[0]);
my_free(unpaired_mapping_options[0], n_unpaired_mapping_options[0] * sizeof(unpaired_mapping_options[0][0]),
&mem_small, "unpaired_mapping_options[0]");
//free(unpaired_mapping_options[1]);
my_free(unpaired_mapping_options[1], n_unpaired_mapping_options[1] * sizeof(unpaired_mapping_options[0][0]),
&mem_small, "unpaired_mapping_options[1]");
if (sam_read_group_name != NULL)
free(sam_read_group_name);
// close some files
if (aligned_reads_file != NULL)
fclose(aligned_reads_file);
if (unaligned_reads_file != NULL)
fclose(unaligned_reads_file);
if (sam_header_hd != NULL)
fclose(sam_header_hd);
if (sam_header_sq != NULL)
fclose(sam_header_sq);
if (sam_header_rg != NULL)
fclose(sam_header_rg);
if (sam_header_pg != NULL)
fclose(sam_header_pg);
#ifdef MYALLOC_ENABLE_CRT
fprintf(stderr, "crt_mem: %lld\n", (long long)crt_mem);
#endif
#ifndef NDEBUG
fprintf(stderr, "mem_genomemap: max=%lld crt=%lld\n", (long long)count_get_max(&mem_genomemap), (long long)count_get_count(&mem_genomemap));
fprintf(stderr, "mem_mapping: max=%lld crt=%lld\n", (long long)count_get_max(&mem_mapping), (long long)count_get_count(&mem_mapping));
fprintf(stderr, "mem_thread_buffer: max=%lld crt=%lld\n", (long long)count_get_max(&mem_thread_buffer), (long long)count_get_count(&mem_thread_buffer));
fprintf(stderr, "mem_small: max=%lld crt=%lld\n", (long long)count_get_max(&mem_small), (long long)count_get_count(&mem_small));
fprintf(stderr, "mem_sw: max=%lld crt=%lld\n", (long long)count_get_max(&mem_sw), (long long)count_get_count(&mem_sw));
#endif
return 0;
}
|
dataset.h | #ifndef LIGHTGBM_DATASET_H_
#define LIGHTGBM_DATASET_H_
#include <LightGBM/utils/random.h>
#include <LightGBM/utils/text_reader.h>
#include <LightGBM/utils/openmp_wrapper.h>
#include <LightGBM/meta.h>
#include <LightGBM/config.h>
#include <LightGBM/feature_group.h>
#include <vector>
#include <utility>
#include <functional>
#include <string>
#include <unordered_set>
#include <mutex>
namespace LightGBM {
/*! \brief forward declaration */
class DatasetLoader;
/*!
* \brief This class is used to store some meta(non-feature) data for training data,
* e.g. labels, weights, initial scores, qurey level informations.
*
* Some details:
* 1. Label, used for traning.
* 2. Weights, weighs of records, optional
* 3. Query Boundaries, necessary for lambdarank.
* The documents of i-th query is in [ query_boundarise[i], query_boundarise[i+1] )
* 4. Query Weights, auto calculate by weights and query_boundarise(if both of them are existed)
* the weight for i-th query is sum(query_boundarise[i] , .., query_boundarise[i+1]) / (query_boundarise[i + 1] - query_boundarise[i+1])
* 5. Initial score. optional. if exsitng, the model will boost from this score, otherwise will start from 0.
*/
class Metadata {
public:
/*!
* \brief Null costructor
*/
Metadata();
/*!
* \brief Initialization will load qurey level informations, since it is need for sampling data
* \param data_filename Filename of data
* \param init_score_filename Filename of initial score
*/
void Init(const char* data_filename, const char* initscore_file);
/*!
* \brief init as subset
* \param metadata Filename of data
* \param used_indices
* \param num_used_indices
*/
void Init(const Metadata& metadata, const data_size_t* used_indices, data_size_t num_used_indices);
/*!
* \brief Initial with binary memory
* \param memory Pointer to memory
*/
void LoadFromMemory(const void* memory);
/*! \brief Destructor */
~Metadata();
/*!
* \brief Initial work, will allocate space for label, weight(if exists) and query(if exists)
* \param num_data Number of training data
* \param weight_idx Index of weight column, < 0 means doesn't exists
* \param query_idx Index of query id column, < 0 means doesn't exists
*/
void Init(data_size_t num_data, int weight_idx, int query_idx);
/*!
* \brief Partition label by used indices
* \param used_indices Indice of local used
*/
void PartitionLabel(const std::vector<data_size_t>& used_indices);
/*!
* \brief Partition meta data according to local used indices if need
* \param num_all_data Number of total training data, including other machines' data on parallel learning
* \param used_data_indices Indices of local used training data
*/
void CheckOrPartition(data_size_t num_all_data,
const std::vector<data_size_t>& used_data_indices);
void SetLabel(const label_t* label, data_size_t len);
void SetWeights(const label_t* weights, data_size_t len);
void SetQuery(const data_size_t* query, data_size_t len);
/*!
* \brief Set initial scores
* \param init_score Initial scores, this class will manage memory for init_score.
*/
void SetInitScore(const double* init_score, data_size_t len);
/*!
* \brief Save binary data to file
* \param file File want to write
*/
void SaveBinaryToFile(const VirtualFileWriter* writer) const;
/*!
* \brief Get sizes in byte of this object
*/
size_t SizesInByte() const;
/*!
* \brief Get pointer of label
* \return Pointer of label
*/
inline const label_t* label() const { return label_.data(); }
/*!
* \brief Set label for one record
* \param idx Index of this record
* \param value Label value of this record
*/
inline void SetLabelAt(data_size_t idx, label_t value)
{
label_[idx] = value;
}
/*!
* \brief Set Weight for one record
* \param idx Index of this record
* \param value Weight value of this record
*/
inline void SetWeightAt(data_size_t idx, label_t value)
{
weights_[idx] = value;
}
/*!
* \brief Set Query Id for one record
* \param idx Index of this record
* \param value Query Id value of this record
*/
inline void SetQueryAt(data_size_t idx, data_size_t value)
{
queries_[idx] = static_cast<data_size_t>(value);
}
/*!
* \brief Get weights, if not exists, will return nullptr
* \return Pointer of weights
*/
inline const label_t* weights() const {
if (!weights_.empty()) {
return weights_.data();
} else {
return nullptr;
}
}
/*!
* \brief Get data boundaries on queries, if not exists, will return nullptr
* we assume data will order by query,
* the interval of [query_boundaris[i], query_boundaris[i+1])
* is the data indices for query i.
* \return Pointer of data boundaries on queries
*/
inline const data_size_t* query_boundaries() const {
if (!query_boundaries_.empty()) {
return query_boundaries_.data();
} else {
return nullptr;
}
}
/*!
* \brief Get Number of queries
* \return Number of queries
*/
inline data_size_t num_queries() const { return num_queries_; }
/*!
* \brief Get weights for queries, if not exists, will return nullptr
* \return Pointer of weights for queries
*/
inline const label_t* query_weights() const {
if (!query_weights_.empty()) {
return query_weights_.data();
} else {
return nullptr;
}
}
/*!
* \brief Get initial scores, if not exists, will return nullptr
* \return Pointer of initial scores
*/
inline const double* init_score() const {
if (!init_score_.empty()) {
return init_score_.data();
} else {
return nullptr;
}
}
/*!
* \brief Get size of initial scores
*/
inline int64_t num_init_score() const { return num_init_score_; }
/*! \brief Disable copy */
Metadata& operator=(const Metadata&) = delete;
/*! \brief Disable copy */
Metadata(const Metadata&) = delete;
private:
/*! \brief Load initial scores from file */
void LoadInitialScore(const char* initscore_file);
/*! \brief Load wights from file */
void LoadWeights();
/*! \brief Load query boundaries from file */
void LoadQueryBoundaries();
/*! \brief Load query wights */
void LoadQueryWeights();
/*! \brief Filename of current data */
std::string data_filename_;
/*! \brief Number of data */
data_size_t num_data_;
/*! \brief Number of weights, used to check correct weight file */
data_size_t num_weights_;
/*! \brief Label data */
std::vector<label_t> label_;
/*! \brief Weights data */
std::vector<label_t> weights_;
/*! \brief Query boundaries */
std::vector<data_size_t> query_boundaries_;
/*! \brief Query weights */
std::vector<label_t> query_weights_;
/*! \brief Number of querys */
data_size_t num_queries_;
/*! \brief Number of Initial score, used to check correct weight file */
int64_t num_init_score_;
/*! \brief Initial score */
std::vector<double> init_score_;
/*! \brief Queries data */
std::vector<data_size_t> queries_;
/*! \brief mutex for threading safe call */
std::mutex mutex_;
bool weight_load_from_file_;
bool query_load_from_file_;
bool init_score_load_from_file_;
};
/*! \brief Interface for Parser */
class Parser {
public:
/*! \brief virtual destructor */
virtual ~Parser() {}
/*!
* \brief Parse one line with label
* \param str One line record, string format, should end with '\0'
* \param out_features Output columns, store in (column_idx, values)
* \param out_label Label will store to this if exists
*/
virtual void ParseOneLine(const char* str,
std::vector<std::pair<int, double>>* out_features, double* out_label) const = 0;
virtual int TotalColumns() const = 0;
/*!
* \brief Create a object of parser, will auto choose the format depend on file
* \param filename One Filename of data
* \param num_features Pass num_features of this data file if you know, <=0 means don't know
* \param label_idx index of label column
* \return Object of parser
*/
static Parser* CreateParser(const char* filename, bool header, int num_features, int label_idx);
};
/*! \brief The main class of data set,
* which are used to traning or validation
*/
class Dataset {
public:
friend DatasetLoader;
LIGHTGBM_EXPORT Dataset();
LIGHTGBM_EXPORT Dataset(data_size_t num_data);
void Construct(
std::vector<std::unique_ptr<BinMapper>>& bin_mappers,
int** sample_non_zero_indices,
const int* num_per_col,
size_t total_sample_cnt,
const Config& io_config);
/*! \brief Destructor */
LIGHTGBM_EXPORT ~Dataset();
LIGHTGBM_EXPORT bool CheckAlign(const Dataset& other) const {
if (num_features_ != other.num_features_) {
return false;
}
if (num_total_features_ != other.num_total_features_) {
return false;
}
if (label_idx_ != other.label_idx_) {
return false;
}
for (int i = 0; i < num_features_; ++i) {
if (!FeatureBinMapper(i)->CheckAlign(*(other.FeatureBinMapper(i)))) {
return false;
}
}
return true;
}
inline void PushOneRow(int tid, data_size_t row_idx, const std::vector<double>& feature_values) {
if (is_finish_load_) { return; }
for (size_t i = 0; i < feature_values.size() && i < static_cast<size_t>(num_total_features_); ++i) {
int feature_idx = used_feature_map_[i];
if (feature_idx >= 0) {
const int group = feature2group_[feature_idx];
const int sub_feature = feature2subfeature_[feature_idx];
feature_groups_[group]->PushData(tid, sub_feature, row_idx, feature_values[i]);
}
}
}
inline void PushOneRow(int tid, data_size_t row_idx, const std::vector<std::pair<int, double>>& feature_values) {
if (is_finish_load_) { return; }
for (auto& inner_data : feature_values) {
if (inner_data.first >= num_total_features_) { continue; }
int feature_idx = used_feature_map_[inner_data.first];
if (feature_idx >= 0) {
const int group = feature2group_[feature_idx];
const int sub_feature = feature2subfeature_[feature_idx];
feature_groups_[group]->PushData(tid, sub_feature, row_idx, inner_data.second);
}
}
}
inline void PushOneData(int tid, data_size_t row_idx, int group, int sub_feature, double value) {
feature_groups_[group]->PushData(tid, sub_feature, row_idx, value);
}
inline int RealFeatureIndex(int fidx) const {
return real_feature_idx_[fidx];
}
inline int InnerFeatureIndex(int col_idx) const {
return used_feature_map_[col_idx];
}
inline int Feature2Group(int feature_idx) const {
return feature2group_[feature_idx];
}
inline int Feture2SubFeature(int feature_idx) const {
return feature2subfeature_[feature_idx];
}
inline uint64_t GroupBinBoundary(int group_idx) const {
return group_bin_boundaries_[group_idx];
}
inline uint64_t NumTotalBin() const {
return group_bin_boundaries_.back();
}
inline std::vector<int> ValidFeatureIndices() const {
std::vector<int> ret;
for (int i = 0; i < num_total_features_; ++i) {
if (used_feature_map_[i] >= 0) {
ret.push_back(i);
}
}
return ret;
}
void ReSize(data_size_t num_data);
void CopySubset(const Dataset* fullset, const data_size_t* used_indices, data_size_t num_used_indices, bool need_meta_data);
LIGHTGBM_EXPORT void FinishLoad();
LIGHTGBM_EXPORT bool SetFloatField(const char* field_name, const float* field_data, data_size_t num_element);
LIGHTGBM_EXPORT bool SetDoubleField(const char* field_name, const double* field_data, data_size_t num_element);
LIGHTGBM_EXPORT bool SetIntField(const char* field_name, const int* field_data, data_size_t num_element);
LIGHTGBM_EXPORT bool GetFloatField(const char* field_name, data_size_t* out_len, const float** out_ptr);
LIGHTGBM_EXPORT bool GetDoubleField(const char* field_name, data_size_t* out_len, const double** out_ptr);
LIGHTGBM_EXPORT bool GetIntField(const char* field_name, data_size_t* out_len, const int** out_ptr);
/*!
* \brief Save current dataset into binary file, will save to "filename.bin"
*/
LIGHTGBM_EXPORT void SaveBinaryFile(const char* bin_filename);
LIGHTGBM_EXPORT void CopyFeatureMapperFrom(const Dataset* dataset);
LIGHTGBM_EXPORT void CreateValid(const Dataset* dataset);
void ConstructHistograms(const std::vector<int8_t>& is_feature_used,
const data_size_t* data_indices, data_size_t num_data,
int leaf_idx,
std::vector<std::unique_ptr<OrderedBin>>& ordered_bins,
const score_t* gradients, const score_t* hessians,
score_t* ordered_gradients, score_t* ordered_hessians,
bool is_constant_hessian,
HistogramBinEntry* histogram_data) const;
void FixHistogram(int feature_idx, double sum_gradient, double sum_hessian, data_size_t num_data,
HistogramBinEntry* data) const;
inline data_size_t Split(int feature,
const uint32_t* threshold, int num_threshold, bool default_left,
data_size_t* data_indices, data_size_t num_data,
data_size_t* lte_indices, data_size_t* gt_indices) const {
const int group = feature2group_[feature];
const int sub_feature = feature2subfeature_[feature];
return feature_groups_[group]->Split(sub_feature, threshold, num_threshold, default_left, data_indices, num_data, lte_indices, gt_indices);
}
inline int SubFeatureBinOffset(int i) const {
const int sub_feature = feature2subfeature_[i];
if (sub_feature == 0) {
return 1;
} else {
return 0;
}
}
inline int FeatureNumBin(int i) const {
const int group = feature2group_[i];
const int sub_feature = feature2subfeature_[i];
return feature_groups_[group]->bin_mappers_[sub_feature]->num_bin();
}
inline int8_t FeatureMonotone(int i) const {
if (monotone_types_.empty()) {
return 0;
} else {
return monotone_types_[i];
}
}
bool HasMonotone() const {
if (monotone_types_.empty()) {
return false;
} else {
for (size_t i = 0; i < monotone_types_.size(); ++i) {
if (monotone_types_[i] != 0) {
return true;
}
}
return false;
}
}
inline int FeatureGroupNumBin(int group) const {
return feature_groups_[group]->num_total_bin_;
}
inline const BinMapper* FeatureBinMapper(int i) const {
const int group = feature2group_[i];
const int sub_feature = feature2subfeature_[i];
return feature_groups_[group]->bin_mappers_[sub_feature].get();
}
inline const Bin* FeatureBin(int i) const {
const int group = feature2group_[i];
return feature_groups_[group]->bin_data_.get();
}
inline const Bin* FeatureGroupBin(int group) const {
return feature_groups_[group]->bin_data_.get();
}
inline bool FeatureGroupIsSparse(int group) const {
return feature_groups_[group]->is_sparse_;
}
inline BinIterator* FeatureIterator(int i) const {
const int group = feature2group_[i];
const int sub_feature = feature2subfeature_[i];
return feature_groups_[group]->SubFeatureIterator(sub_feature);
}
inline BinIterator* FeatureGroupIterator(int group) const {
return feature_groups_[group]->FeatureGroupIterator();
}
inline double RealThreshold(int i, uint32_t threshold) const {
const int group = feature2group_[i];
const int sub_feature = feature2subfeature_[i];
return feature_groups_[group]->bin_mappers_[sub_feature]->BinToValue(threshold);
}
// given a real threshold, find the closest threshold bin
inline uint32_t BinThreshold(int i, double threshold_double) const {
const int group = feature2group_[i];
const int sub_feature = feature2subfeature_[i];
return feature_groups_[group]->bin_mappers_[sub_feature]->ValueToBin(threshold_double);
}
inline void CreateOrderedBins(std::vector<std::unique_ptr<OrderedBin>>* ordered_bins) const {
ordered_bins->resize(num_groups_);
OMP_INIT_EX();
#pragma omp parallel for schedule(guided)
for (int i = 0; i < num_groups_; ++i) {
OMP_LOOP_EX_BEGIN();
ordered_bins->at(i).reset(feature_groups_[i]->bin_data_->CreateOrderedBin());
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
}
/*!
* \brief Get meta data pointer
* \return Pointer of meta data
*/
inline const Metadata& metadata() const { return metadata_; }
/*! \brief Get Number of used features */
inline int num_features() const { return num_features_; }
/*! \brief Get Number of feature groups */
inline int num_feature_groups() const { return num_groups_;}
/*! \brief Get Number of total features */
inline int num_total_features() const { return num_total_features_; }
/*! \brief Get the index of label column */
inline int label_idx() const { return label_idx_; }
/*! \brief Get names of current data set */
inline const std::vector<std::string>& feature_names() const { return feature_names_; }
inline void set_feature_names(const std::vector<std::string>& feature_names) {
if (feature_names.size() != static_cast<size_t>(num_total_features_)) {
Log::Fatal("Size of feature_names error, should equal with total number of features");
}
feature_names_ = std::vector<std::string>(feature_names);
// replace ' ' in feature_names with '_'
bool spaceInFeatureName = false;
for (auto& feature_name: feature_names_){
if (feature_name.find(' ') != std::string::npos){
spaceInFeatureName = true;
std::replace(feature_name.begin(), feature_name.end(), ' ', '_');
}
}
if (spaceInFeatureName){
Log::Warning("Find whitespaces in feature_names, replace with underlines");
}
}
inline std::vector<std::string> feature_infos() const {
std::vector<std::string> bufs;
for (int i = 0; i < num_total_features_; i++) {
int fidx = used_feature_map_[i];
if (fidx == -1) {
bufs.push_back("none");
} else {
const auto bin_mapper = FeatureBinMapper(fidx);
bufs.push_back(bin_mapper->bin_info());
}
}
return bufs;
}
/*! \brief Get Number of data */
inline data_size_t num_data() const { return num_data_; }
/*! \brief Disable copy */
Dataset& operator=(const Dataset&) = delete;
/*! \brief Disable copy */
Dataset(const Dataset&) = delete;
private:
std::string data_filename_;
/*! \brief Store used features */
std::vector<std::unique_ptr<FeatureGroup>> feature_groups_;
/*! \brief Mapper from real feature index to used index*/
std::vector<int> used_feature_map_;
/*! \brief Number of used features*/
int num_features_;
/*! \brief Number of total features*/
int num_total_features_;
/*! \brief Number of total data*/
data_size_t num_data_;
/*! \brief Store some label level data*/
Metadata metadata_;
/*! \brief index of label column */
int label_idx_ = 0;
/*! \brief Threshold for treating a feature as a sparse feature */
double sparse_threshold_;
/*! \brief store feature names */
std::vector<std::string> feature_names_;
/*! \brief store feature names */
static const char* binary_file_token;
int num_groups_;
std::vector<int> real_feature_idx_;
std::vector<int> feature2group_;
std::vector<int> feature2subfeature_;
std::vector<uint64_t> group_bin_boundaries_;
std::vector<int> group_feature_start_;
std::vector<int> group_feature_cnt_;
std::vector<int8_t> monotone_types_;
bool is_finish_load_;
};
} // namespace LightGBM
#endif // LightGBM_DATA_H_
|
composite.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE %
% C O O MM MM P P O O SS I T E %
% C O O M M M PPPP O O SSS I T EEE %
% C O O M M P O O SS I T E %
% CCCC OOO M M P OOO SSSSS IIIII T EEEEE %
% %
% %
% MagickCore Image Composite 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 "magick/studio.h"
#include "magick/accelerate-private.h"
#include "magick/artifact.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/client.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/fx.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/memory_.h"
#include "magick/option.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/resample.h"
#include "magick/resource_.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/threshold.h"
#include "magick/token.h"
#include "magick/utility.h"
#include "magick/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p o s i t e I m a g e C h a n n e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompositeImageChannel() returns the second image composited onto the first
% at the specified offset, using the specified composite method.
%
% The format of the CompositeImageChannel method is:
%
% MagickBooleanType CompositeImage(Image *image,
% const CompositeOperator compose,Image *source_image,
% const ssize_t x_offset,const ssize_t y_offset)
% MagickBooleanType CompositeImageChannel(Image *image,
% const ChannelType channel,const CompositeOperator compose,
% Image *source_image,const ssize_t x_offset,const ssize_t y_offset)
%
% A description of each parameter follows:
%
% o image: the canvas image, modified by he composition
%
% o channel: the channel.
%
% o compose: This operator affects how the composite is applied to
% the image. The operators and how they are utilized are listed here
% http://www.w3.org/TR/SVG12/#compositing.
%
% o source_image: the composite (source) image.
%
% o x_offset: the column offset of the composited image.
%
% o y_offset: the row offset of the composited image.
%
% Extra Controls from Image meta-data in 'source_image' (artifacts)
%
% o "compose:args"
% A string containing extra numerical arguments for specific compose
% methods, generally expressed as a 'geometry' or a comma separated list
% of numbers.
%
% Compose methods needing such arguments include "BlendCompositeOp" and
% "DisplaceCompositeOp".
%
% o "compose:outside-overlay"
% Modify how the composition is to effect areas not directly covered
% by the 'source_image' at the offset given. Normally this is
% dependant on the 'compose' method, especially Duff-Porter methods.
%
% If set to "false" then disable all normal handling of pixels not
% covered by the source_image. Typically used for repeated tiling
% of the source_image by the calling API.
%
% Previous to IM v6.5.3-3 this was called "modify-outside-overlay"
%
*/
/*
** Programmers notes on SVG specification.
**
** A Composition is defined by...
** Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors
** Blending areas : X = 1 for area of overlap ie: f(Sc,Dc)
** Y = 1 for source preserved
** Z = 1 for canvas preserved
**
** Conversion to transparency (then optimized)
** Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa)
** Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa)
**
** Where...
** Sca = Sc*Sa normalized Source color divided by Source alpha
** Dca = Dc*Da normalized Dest color divided by Dest alpha
** Dc' = Dca'/Da' the desired color value for this channel.
**
** Da' in in the follow formula as 'gamma' The resulting alpla value.
**
**
** Most functions use a blending mode of over (X=1,Y=1,Z=1)
** this results in the following optimizations...
** gamma = Sa+Da-Sa*Da;
** gamma = 1 - QuantumScale*alpha * QuantumScale*beta;
** opacity = QuantumScale*alpha*beta; // over blend, optimized 1-Gamma
**
** The above SVG definitions also define that Mathematical Composition
** methods should use a 'Over' blending mode for Alpha Channel.
** It however was not applied for composition modes of 'Plus', 'Minus',
** the modulus versions of 'Add' and 'Subtract'.
**
**
** Mathematical operator changes to be applied from IM v6.7...
**
** 1/ Modulus modes 'Add' and 'Subtract' are obsoleted and renamed
** 'ModulusAdd' and 'ModulusSubtract' for clarity.
**
** 2/ All mathematical compositions work as per the SVG specification
** with regard to blending. This now includes 'ModulusAdd' and
** 'ModulusSubtract'.
**
** 3/ When the special channel flag 'sync' (syncronize channel updates)
** is turned off (enabled by default) then mathematical compositions are
** only performed on the channels specified, and are applied
** independantally of each other. In other words the mathematics is
** performed as 'pure' mathematical operations, rather than as image
** operations.
*/
static inline MagickRealType Atop(const MagickRealType p,
const MagickRealType Sa,const MagickRealType q,
const MagickRealType magick_unused(Da))
{
magick_unreferenced(Da);
return(p*Sa+q*(1.0-Sa)); /* Da optimized out, Da/gamma => 1.0 */
}
static inline void CompositeAtop(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
composite->opacity=q->opacity; /* optimized Da = 1.0-Gamma */
composite->red=Atop(p->red,Sa,q->red,1.0);
composite->green=Atop(p->green,Sa,q->green,1.0);
composite->blue=Atop(p->blue,Sa,q->blue,1.0);
if (q->colorspace == CMYKColorspace)
composite->index=Atop(p->index,Sa,q->index,1.0);
}
/*
What is this Composition method for? Can't find any specification!
WARNING this is not doing correct 'over' blend handling (Anthony Thyssen).
*/
static inline void CompositeBumpmap(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
intensity;
intensity=MagickPixelIntensity(p);
composite->red=QuantumScale*intensity*q->red;
composite->green=QuantumScale*intensity*q->green;
composite->blue=QuantumScale*intensity*q->blue;
composite->opacity=(MagickRealType) QuantumScale*intensity*p->opacity;
if (q->colorspace == CMYKColorspace)
composite->index=QuantumScale*intensity*q->index;
}
static inline void CompositeClear(const MagickPixelPacket *q,
MagickPixelPacket *composite)
{
composite->opacity=(MagickRealType) TransparentOpacity;
composite->red=0.0;
composite->green=0.0;
composite->blue=0.0;
if (q->colorspace == CMYKColorspace)
composite->index=0.0;
}
static MagickRealType ColorBurn(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
double
SaSca;
if ((fabs(Sca) < MagickEpsilon) && (fabs(Dca-Da) < MagickEpsilon))
return(Sa*Da+Dca*(1.0-Sa));
if (Sca < MagickEpsilon)
return(Dca*(1.0-Sa));
SaSca=Sa*PerceptibleReciprocal(Sca);
return(Sa*Da-Sa*MagickMin(Da,(Da-Dca)*SaSca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeColorBurn(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*ColorBurn(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*ColorBurn(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*ColorBurn(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*ColorBurn(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static MagickRealType ColorDodge(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
Oct 2004 SVG specification.
*/
if ((Sca*Da+Dca*Sa) >= Sa*Da)
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Dca*Sa*Sa*PerceptibleReciprocal(Sa-Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
#if 0
/*
New specification, March 2009 SVG specification. This specification was
also wrong of non-overlap cases.
*/
if ((fabs(Sca-Sa) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon))
return(Sca*(1.0-Da));
if (fabs(Sca-Sa) < MagickEpsilon)
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Sa*MagickMin(Da,Dca*Sa/(Sa-Sca)));
#endif
#if 0
/*
Working from first principles using the original formula:
f(Sc,Dc) = Dc/(1-Sc)
This works correctly! Looks like the 2004 model was right but just
required a extra condition for correct handling.
*/
if ((fabs(Sca-Sa) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon))
return(Sca*(1.0-Da)+Dca*(1.0-Sa));
if (fabs(Sca-Sa) < MagickEpsilon)
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Dca*Sa*Sa/(Sa-Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
#endif
}
static inline void CompositeColorDodge(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*ColorDodge(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*ColorDodge(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*ColorDodge(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*ColorDodge(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType Darken(const MagickRealType p,
const MagickRealType alpha,const MagickRealType q,const MagickRealType beta)
{
if (p < q)
return(MagickOver_(p,alpha,q,beta)); /* src-over */
return(MagickOver_(q,beta,p,alpha)); /* dst-over */
}
static inline void CompositeDarken(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Darken is equivalent to a 'Minimum' method
OR a greyscale version of a binary 'Or'
OR the 'Intersection' of pixel sets.
*/
double
gamma;
if ( (channel & SyncChannels) != 0 ) {
composite->opacity=QuantumScale*p->opacity*q->opacity; /* Over Blend */
gamma=1.0-QuantumScale*composite->opacity;
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Darken(p->red,p->opacity,q->red,q->opacity);
composite->green=gamma*Darken(p->green,p->opacity,q->green,q->opacity);
composite->blue=gamma*Darken(p->blue,p->opacity,q->blue,q->opacity);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Darken(p->index,p->opacity,q->index,q->opacity);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=MagickMax(p->opacity,q->opacity);
if ( (channel & RedChannel) != 0 )
composite->red=MagickMin(p->red,q->red);
if ( (channel & GreenChannel) != 0 )
composite->green=MagickMin(p->green,q->green);
if ( (channel & BlueChannel) != 0 )
composite->blue=MagickMin(p->blue,q->blue);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=MagickMin(p->index,q->index);
}
}
static inline void CompositeDarkenIntensity(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Select the pixel based on the intensity level.
If 'Sync' flag select whole pixel based on alpha weighted intensity.
Otherwise use intensity only, but restrict copy according to channel.
*/
if ( (channel & SyncChannels) != 0 ) {
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity;
Da=1.0-QuantumScale*q->opacity;
*composite = (Sa*MagickPixelIntensity(p) < Da*MagickPixelIntensity(q))
? *p : *q;
}
else {
int from_p = (MagickPixelIntensity(p) < MagickPixelIntensity(q));
if ( (channel & AlphaChannel) != 0 )
composite->opacity = from_p ? p->opacity : q->opacity;
if ( (channel & RedChannel) != 0 )
composite->red = from_p ? p->red : q->red;
if ( (channel & GreenChannel) != 0 )
composite->green = from_p ? p->green : q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue = from_p ? p->blue : q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index = from_p ? p->index : q->index;
}
}
static inline MagickRealType Difference(const MagickRealType p,
const MagickRealType Sa,const MagickRealType q,const MagickRealType Da)
{
/* Optimized by Multipling by QuantumRange (taken from gamma). */
return(Sa*p+Da*q-Sa*Da*2.0*MagickMin(p,q));
}
static inline void CompositeDifference(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
/* Values are not normalized as an optimization. */
composite->red=gamma*Difference(p->red,Sa,q->red,Da);
composite->green=gamma*Difference(p->green,Sa,q->green,Da);
composite->blue=gamma*Difference(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Difference(p->index,Sa,q->index,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange-fabs((double) (p->opacity-q->opacity));
if ( (channel & RedChannel) != 0 )
composite->red=fabs((double) (p->red-q->red));
if ( (channel & GreenChannel) != 0 )
composite->green=fabs((double) (p->green-q->green));
if ( (channel & BlueChannel) != 0 )
composite->blue=fabs((double) (p->blue-q->blue));
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=fabs((double) (p->index-q->index));
}
}
static MagickRealType Divide(const MagickRealType Sca,const MagickRealType Sa,
const MagickRealType Dca,const MagickRealType Da)
{
/*
Divide Source by Destination
f(Sc,Dc) = Sc / Dc
But with appropriate handling for special case of Dc == 0 specifically
so that f(Black,Black)=Black and f(non-Black,Black)=White.
It is however also important to correctly do 'over' alpha blending which
is why the formula becomes so complex.
*/
if ((fabs(Sca) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon))
return(Sca*(1.0-Da)+Dca*(1.0-Sa));
if (fabs(Dca) < MagickEpsilon)
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Sca*Da*Da*PerceptibleReciprocal(Dca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeDivide(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Divide(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*Divide(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*Divide(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Divide(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Divide(Sa,1.0,Da,1.0));
if ( (channel & RedChannel) != 0 )
composite->red=QuantumRange*
Divide(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0);
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumRange*
Divide(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0);
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumRange*
Divide(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumRange*
Divide(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0);
}
}
static MagickRealType Exclusion(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
return(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeExclusion(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
MagickRealType
gamma,
Sa,
Da;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Exclusion(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*Exclusion(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*Exclusion(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Exclusion(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ((channel & AlphaChannel) != 0)
composite->opacity=QuantumRange*(1.0-Exclusion(Sa,1.0,Da,1.0));
if ((channel & RedChannel) != 0)
composite->red=QuantumRange*Exclusion(QuantumScale*p->red,1.0,
QuantumScale*q->red,1.0);
if ((channel & GreenChannel) != 0)
composite->green=QuantumRange*Exclusion(QuantumScale*p->green,1.0,
QuantumScale*q->green,1.0);
if ((channel & BlueChannel) != 0)
composite->blue=QuantumRange*Exclusion(QuantumScale*p->blue,1.0,
QuantumScale*q->blue,1.0);
if (((channel & IndexChannel) != 0) && (q->colorspace == CMYKColorspace))
composite->index=QuantumRange*Exclusion(QuantumScale*p->index,1.0,
QuantumScale*q->index,1.0);
}
}
static MagickRealType HardLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
if ((2.0*Sca) < Sa)
return(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
return(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeHardLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*HardLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*HardLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*HardLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*HardLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static MagickRealType HardMix(const MagickRealType Sca,
const MagickRealType Dca)
{
if ((Sca+Dca) < QuantumRange)
return(0.0);
else
return(1.0);
}
static inline void CompositeHardMix(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*HardMix(p->red*Sa,q->red*Da);
composite->green=gamma*HardMix(p->green*Sa,q->green*Da);
composite->blue=gamma*HardMix(p->blue*Sa,q->blue*Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*HardMix(p->index*Sa,q->index*Da);
}
static void HCLComposite(const double hue,const double chroma,const double luma,
MagickRealType *red,MagickRealType *green,MagickRealType *blue)
{
double
b,
c,
g,
h,
m,
r,
x;
/*
Convert HCL to RGB colorspace.
*/
assert(red != (MagickRealType *) NULL);
assert(green != (MagickRealType *) NULL);
assert(blue != (MagickRealType *) NULL);
h=6.0*hue;
c=chroma;
x=c*(1.0-fabs(fmod(h,2.0)-1.0));
r=0.0;
g=0.0;
b=0.0;
if ((0.0 <= h) && (h < 1.0))
{
r=c;
g=x;
}
else
if ((1.0 <= h) && (h < 2.0))
{
r=x;
g=c;
}
else
if ((2.0 <= h) && (h < 3.0))
{
g=c;
b=x;
}
else
if ((3.0 <= h) && (h < 4.0))
{
g=x;
b=c;
}
else
if ((4.0 <= h) && (h < 5.0))
{
r=x;
b=c;
}
else
if ((5.0 <= h) && (h < 6.0))
{
r=c;
b=x;
}
m=luma-(0.298839*r+0.586811*g+0.114350*b);
*red=QuantumRange*(r+m);
*green=QuantumRange*(g+m);
*blue=QuantumRange*(b+m);
}
static void CompositeHCL(const MagickRealType red,const MagickRealType green,
const MagickRealType blue,double *hue,double *chroma,double *luma)
{
double
b,
c,
g,
h,
max,
r;
/*
Convert RGB to HCL colorspace.
*/
assert(hue != (double *) NULL);
assert(chroma != (double *) NULL);
assert(luma != (double *) NULL);
r=(double) red;
g=(double) green;
b=(double) blue;
max=MagickMax(r,MagickMax(g,b));
c=max-(double) MagickMin(r,MagickMin(g,b));
h=0.0;
if (c == 0)
h=0.0;
else
if (red == (MagickRealType) max)
h=fmod((g-b)/c+6.0,6.0);
else
if (green == (MagickRealType) max)
h=((b-r)/c)+2.0;
else
if (blue == (MagickRealType) max)
h=((r-g)/c)+4.0;
*hue=(h/6.0);
*chroma=QuantumScale*c;
*luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b);
}
static inline MagickRealType In(const MagickRealType p,const MagickRealType Sa,
const MagickRealType magick_unused(q),const MagickRealType Da)
{
magick_unreferenced(q);
return(Sa*p*Da);
}
static inline void CompositeIn(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Sa,
Da;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=Sa*Da;
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*In(p->red,Sa,q->red,Da);
composite->green=gamma*In(p->green,Sa,q->green,Da);
composite->blue=gamma*In(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*In(p->index,Sa,q->index,Da);
}
static inline MagickRealType Lighten(const MagickRealType p,
const MagickRealType alpha,const MagickRealType q,const MagickRealType beta)
{
if (p > q)
return(MagickOver_(p,alpha,q,beta)); /* src-over */
return(MagickOver_(q,beta,p,alpha)); /* dst-over */
}
static inline void CompositeLighten(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Lighten is also equvalent to a 'Maximum' method
OR a greyscale version of a binary 'And'
OR the 'Union' of pixel sets.
*/
double
gamma;
if ( (channel & SyncChannels) != 0 ) {
composite->opacity=QuantumScale*p->opacity*q->opacity; /* Over Blend */
gamma=1.0-QuantumScale*composite->opacity;
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Lighten(p->red,p->opacity,q->red,q->opacity);
composite->green=gamma*Lighten(p->green,p->opacity,q->green,q->opacity);
composite->blue=gamma*Lighten(p->blue,p->opacity,q->blue,q->opacity);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Lighten(p->index,p->opacity,q->index,q->opacity);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=MagickMin(p->opacity,q->opacity);
if ( (channel & RedChannel) != 0 )
composite->red=MagickMax(p->red,q->red);
if ( (channel & GreenChannel) != 0 )
composite->green=MagickMax(p->green,q->green);
if ( (channel & BlueChannel) != 0 )
composite->blue=MagickMax(p->blue,q->blue);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=MagickMax(p->index,q->index);
}
}
static inline void CompositeLightenIntensity(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
/*
Select the pixel based on the intensity level.
If 'Sync' flag select whole pixel based on alpha weighted intensity.
Otherwise use Intenisty only, but restrict copy according to channel.
*/
if ( (channel & SyncChannels) != 0 ) {
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity;
Da=1.0-QuantumScale*q->opacity;
*composite = (Sa*MagickPixelIntensity(p) > Da*MagickPixelIntensity(q))
? *p : *q;
}
else {
int from_p = (MagickPixelIntensity(p) > MagickPixelIntensity(q));
if ( (channel & AlphaChannel) != 0 )
composite->opacity = from_p ? p->opacity : q->opacity;
if ( (channel & RedChannel) != 0 )
composite->red = from_p ? p->red : q->red;
if ( (channel & GreenChannel) != 0 )
composite->green = from_p ? p->green : q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue = from_p ? p->blue : q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index = from_p ? p->index : q->index;
}
}
#if 0
static inline MagickRealType LinearDodge(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
LinearDodge: simplifies to a trivial formula
f(Sc,Dc) = Sc + Dc
Dca' = Sca + Dca
*/
return(Sca+Dca);
}
#endif
static inline void CompositeLinearDodge(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*(p->red*Sa+q->red*Da);
composite->green=gamma*(p->green*Sa+q->green*Da);
composite->blue=gamma*(p->blue*Sa+q->blue*Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*(p->index*Sa+q->index*Da);
}
static inline MagickRealType LinearBurn(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
LinearBurn: as defined by Abode Photoshop, according to
http://www.simplefilter.de/en/basics/mixmods.html is:
f(Sc,Dc) = Sc + Dc - 1
*/
return(Sca+Dca-Sa*Da);
}
static inline void CompositeLinearBurn(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*LinearBurn(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*LinearBurn(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*LinearBurn(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*LinearBurn(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType LinearLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
#if 0
/*
Previous formula, was only valid for fully-opaque images.
*/
return(Dca+2*Sca-1.0);
#else
/*
LinearLight: as defined by Abode Photoshop, according to
http://www.simplefilter.de/en/basics/mixmods.html is:
f(Sc,Dc) = Dc + 2*Sc - 1
*/
return((Sca-Sa)*Da+Sca+Dca);
#endif
}
static inline void CompositeLinearLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*LinearLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*LinearLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*LinearLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*LinearLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType Mathematics(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da,
const GeometryInfo *geometry_info)
{
/*
'Mathematics' a free form user control mathematical composition is defined
as...
f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D
Where the arguments A,B,C,D are (currently) passed to composite as
a command separated 'geometry' string in "compose:args" image artifact.
A = a->rho, B = a->sigma, C = a->xi, D = a->psi
Applying the SVG transparency formula (see above), we get...
Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa)
Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) +
Dca*(1.0-Sa)
*/
return(geometry_info->rho*Sca*Dca+geometry_info->sigma*Sca*Da+
geometry_info->xi*Dca*Sa+geometry_info->psi*Sa*Da+Sca*(1.0-Da)+
Dca*(1.0-Sa));
}
static inline void CompositeMathematics(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel, const GeometryInfo
*args, MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* ??? - AT */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Mathematics(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da,args);
composite->green=gamma*Mathematics(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da,args);
composite->blue=gamma*Mathematics(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da,args);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Mathematics(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da,args);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Mathematics(Sa,1.0,Da,1.0,args));
if ( (channel & RedChannel) != 0 )
composite->red=QuantumRange*
Mathematics(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0,args);
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumRange*
Mathematics(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0,args);
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumRange*
Mathematics(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0,args);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumRange*
Mathematics(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0,args);
}
}
static inline void CompositePlus(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
if ( (channel & SyncChannels) != 0 ) {
/*
NOTE: "Plus" does not use 'over' alpha-blending but uses a
special 'plus' form of alph-blending. It is the ONLY mathematical
operator to do this. this is what makes it different to the
otherwise equivalent "LinearDodge" composition method.
Note however that color channels are still effected by the alpha channel
as a result of the blending, making it just as useless for independant
channel maths, just like all other mathematical composition methods.
As such the removal of the 'sync' flag, is still a usful convention.
The MagickPixelCompositePlus() function is defined in
"composite-private.h" so it can also be used for Image Blending.
*/
MagickPixelCompositePlus(p,p->opacity,q,q->opacity,composite);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=p->opacity+q->opacity-QuantumRange;
if ( (channel & RedChannel) != 0 )
composite->red=p->red+q->red;
if ( (channel & GreenChannel) != 0 )
composite->green=p->green+q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue=p->blue+q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=p->index+q->index;
}
}
static inline MagickRealType Minus(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,
const MagickRealType magick_unused(Da))
{
/*
Minus Source from Destination
f(Sc,Dc) = Sc - Dc
*/
magick_unreferenced(Da);
return(Sca+Dca-2*Dca*Sa);
}
static inline void CompositeMinus(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Minus(p->red*Sa,Sa,q->red*Da,Da);
composite->green=gamma*Minus(p->green*Sa,Sa,q->green*Da,Da);
composite->blue=gamma*Minus(p->blue*Sa,Sa,q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Minus(p->index*Sa,Sa,q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-(Sa-Da));
if ( (channel & RedChannel) != 0 )
composite->red=p->red-q->red;
if ( (channel & GreenChannel) != 0 )
composite->green=p->green-q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue=p->blue-q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=p->index-q->index;
}
}
static inline MagickRealType ModulusAdd(const MagickRealType Sc,
const MagickRealType Sa,const MagickRealType Dc,const MagickRealType Da)
{
if (((Sc*Sa)+(Dc*Da)) <= QuantumRange)
return((Sc*Sa)+Dc*Da);
return(((Sc*Sa)+Dc*Da)-QuantumRange);
}
static inline void CompositeModulusAdd(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
if ( (channel & SyncChannels) != 0 ) {
double
gamma;
MagickRealType
Sa,
Da;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=ModulusAdd(p->red,Sa,q->red,Da);
composite->green=ModulusAdd(p->green,Sa,q->green,Da);
composite->blue=ModulusAdd(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=ModulusAdd(p->index,Sa,q->index,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange-ModulusAdd(QuantumRange-p->opacity,
1.0,QuantumRange-q->opacity,1.0);
if ( (channel & RedChannel) != 0 )
composite->red=ModulusAdd(p->red,1.0,q->red,1.0);
if ( (channel & GreenChannel) != 0 )
composite->green=ModulusAdd(p->green,1.0,q->green,1.0);
if ( (channel & BlueChannel) != 0 )
composite->blue=ModulusAdd(p->blue,1.0,q->blue,1.0);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=ModulusAdd(p->index,1.0,q->index,1.0);
}
}
static inline MagickRealType ModulusSubtract(const MagickRealType Sc,
const MagickRealType Sa,const MagickRealType Dc,const MagickRealType Da)
{
if (((Sc*Sa)-(Dc*Da)) <= 0.0)
return((Sc*Sa)-Dc*Da);
return(((Sc*Sa)-Dc*Da)+QuantumRange);
}
static inline void CompositeModulusSubtract(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
if ( (channel & SyncChannels) != 0 ) {
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma = RoundToUnity(Sa+Da-Sa*Da);
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=ModulusSubtract(p->red,Sa,q->red,Da);
composite->green=ModulusSubtract(p->green,Sa,q->green,Da);
composite->blue=ModulusSubtract(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=ModulusSubtract(p->index,Sa,q->index,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange-ModulusSubtract(QuantumRange-p->opacity,
1.0,QuantumRange-q->opacity,1.0);
if ( (channel & RedChannel) != 0 )
composite->red=ModulusSubtract(p->red,1.0,q->red,1.0);
if ( (channel & GreenChannel) != 0 )
composite->green=ModulusSubtract(p->green,1.0,q->green,1.0);
if ( (channel & BlueChannel) != 0 )
composite->blue=ModulusSubtract(p->blue,1.0,q->blue,1.0);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=ModulusSubtract(p->index,1.0,q->index,1.0);
}
}
static inline MagickRealType Multiply(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
return(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeMultiply(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Multiply(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*Multiply(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*Multiply(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Multiply(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Sa*Da);
if ( (channel & RedChannel) != 0 )
composite->red=QuantumScale*p->red*q->red;
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumScale*p->green*q->green;
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumScale*p->blue*q->blue;
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumScale*p->index*q->index;
}
}
static inline MagickRealType Out(const MagickRealType p,
const MagickRealType Sa,const MagickRealType magick_unused(q),
const MagickRealType Da)
{
magick_unreferenced(q);
return(Sa*p*(1.0-Da));
}
static inline void CompositeOut(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=Sa*(1.0-Da);
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Out(p->red,Sa,q->red,Da);
composite->green=gamma*Out(p->green,Sa,q->green,Da);
composite->blue=gamma*Out(p->blue,Sa,q->blue,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Out(p->index,Sa,q->index,Da);
}
static MagickRealType PegtopLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
PegTop: A Soft-Light alternative: A continuous version of the Softlight
function, producing very similar results.
f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc
See http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm.
*/
if (fabs(Da) < MagickEpsilon)
return(Sca);
return(Dca*Dca*(Sa-2.0*Sca)*PerceptibleReciprocal(Da)+Sca*(2.0*Dca+1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositePegtopLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*PegtopLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*PegtopLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*PegtopLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*PegtopLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static MagickRealType PinLight(const MagickRealType Sca,
const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da)
{
/*
PinLight: A Photoshop 7 composition method
http://www.simplefilter.de/en/basics/mixmods.html
f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc
*/
if (Dca*Sa < Da*(2*Sca-Sa))
return(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa));
if ((Dca*Sa) > (2*Sca*Da))
return(Sca*Da+Sca+Dca*(1.0-Sa));
return(Sca*(1.0-Da)+Dca);
}
static inline void CompositePinLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*PinLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*PinLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*PinLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*PinLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static inline MagickRealType Screen(const MagickRealType Sca,
const MagickRealType Dca)
{
/* Screen: A negated multiply
f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc)
*/
return(Sca+Dca-Sca*Dca);
}
static inline void CompositeScreen(const MagickPixelPacket *p,
const MagickPixelPacket *q,const ChannelType channel,
MagickPixelPacket *composite)
{
double
gamma;
MagickRealType
Da,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
if ( (channel & SyncChannels) != 0 ) {
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
Sa*=(MagickRealType) QuantumScale;
Da*=(MagickRealType) QuantumScale; /* optimization */
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*Screen(p->red*Sa,q->red*Da);
composite->green=gamma*Screen(p->green*Sa,q->green*Da);
composite->blue=gamma*Screen(p->blue*Sa,q->blue*Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Screen(p->index*Sa,q->index*Da);
}
else { /* handle channels as separate grayscale channels */
if ( (channel & AlphaChannel) != 0 )
composite->opacity=QuantumRange*(1.0-Screen(Sa,Da));
if ( (channel & RedChannel) != 0 )
composite->red=QuantumRange*Screen(QuantumScale*p->red,
QuantumScale*q->red);
if ( (channel & GreenChannel) != 0 )
composite->green=QuantumRange*Screen(QuantumScale*p->green,
QuantumScale*q->green);
if ( (channel & BlueChannel) != 0 )
composite->blue=QuantumRange*Screen(QuantumScale*p->blue,
QuantumScale*q->blue);
if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace)
composite->index=QuantumRange*Screen(QuantumScale*p->index,
QuantumScale*q->index);
}
}
static MagickRealType SoftLight(const MagickRealType Sca,
const MagickRealType Sa, const MagickRealType Dca, const MagickRealType Da)
{
MagickRealType
alpha,
beta;
alpha=Dca*PerceptibleReciprocal(Da);
if ((2.0*Sca) < Sa)
return(Dca*(Sa+(2.0*Sca-Sa)*(1.0-alpha))+Sca*(1.0-Da)+Dca*(1.0-Sa));
if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da))
{
beta=Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*alpha*(4.0*alpha+1.0)*(alpha-1.0)+7.0*
alpha)+Sca*(1.0-Da)+Dca*(1.0-Sa);
return(beta);
}
beta=Dca*Sa+Da*(2.0*Sca-Sa)*(pow(alpha,0.5)-alpha)+Sca*(1.0-Da)+Dca*(1.0-Sa);
return(beta);
}
static inline void CompositeSoftLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*SoftLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*SoftLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*SoftLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*SoftLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
/*
Deprecated
Multiply difference by amount, if differance larger than threshold???
What use this is is completely unknown
The Opacity calculation appears to be inverted -- Anthony Thyssen
*/
static inline MagickRealType Threshold(const MagickRealType p,
const MagickRealType q,const MagickRealType threshold,
const MagickRealType amount)
{
MagickRealType
delta;
delta=p-q;
if ((MagickRealType) fabs((double) (2.0*delta)) < threshold)
return(q);
return(q+delta*amount);
}
static inline void CompositeThreshold(const MagickPixelPacket *p,
const MagickPixelPacket *q,const MagickRealType threshold,
const MagickRealType amount,MagickPixelPacket *composite)
{
composite->red=Threshold(p->red,q->red,threshold,amount);
composite->green=Threshold(p->green,q->green,threshold,amount);
composite->blue=Threshold(p->blue,q->blue,threshold,amount);
composite->opacity=QuantumRange-Threshold(p->opacity,q->opacity,
threshold,amount);
if (q->colorspace == CMYKColorspace)
composite->index=Threshold(p->index,q->index,threshold,amount);
}
static MagickRealType VividLight(const MagickRealType Sca,
const MagickRealType Sa, const MagickRealType Dca, const MagickRealType Da)
{
/*
VividLight: A Photoshop 7 composition method. See
http://www.simplefilter.de/en/basics/mixmods.html.
f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc))
*/
if ((fabs(Sa) < MagickEpsilon) || (fabs(Sca-Sa) < MagickEpsilon))
return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa));
if ((2*Sca) <= Sa)
return(Sa*(Da+Sa*(Dca-Da)*PerceptibleReciprocal(2.0*Sca))+Sca*(1.0-Da)+
Dca*(1.0-Sa));
return(Dca*Sa*Sa*PerceptibleReciprocal(2.0*(Sa-Sca))+Sca*(1.0-Da)+Dca*
(1.0-Sa));
}
static inline void CompositeVividLight(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma);
composite->red=gamma*VividLight(QuantumScale*p->red*Sa,Sa,QuantumScale*
q->red*Da,Da);
composite->green=gamma*VividLight(QuantumScale*p->green*Sa,Sa,QuantumScale*
q->green*Da,Da);
composite->blue=gamma*VividLight(QuantumScale*p->blue*Sa,Sa,QuantumScale*
q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*VividLight(QuantumScale*p->index*Sa,Sa,QuantumScale*
q->index*Da,Da);
}
static MagickRealType Xor(const MagickRealType Sca,const MagickRealType Sa,
const MagickRealType Dca,const MagickRealType Da)
{
return(Sca*(1.0-Da)+Dca*(1.0-Sa));
}
static inline void CompositeXor(const MagickPixelPacket *p,
const MagickPixelPacket *q,MagickPixelPacket *composite)
{
MagickRealType
Da,
gamma,
Sa;
Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */
Da=1.0-QuantumScale*q->opacity;
gamma=Sa+Da-2*Sa*Da; /* Xor blend mode X=0,Y=1,Z=1 */
composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma);
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*Xor(p->red*Sa,Sa,q->red*Da,Da);
composite->green=gamma*Xor(p->green*Sa,Sa,q->green*Da,Da);
composite->blue=gamma*Xor(p->blue*Sa,Sa,q->blue*Da,Da);
if (q->colorspace == CMYKColorspace)
composite->index=gamma*Xor(p->index*Sa,Sa,q->index*Da,Da);
}
MagickExport MagickBooleanType CompositeImage(Image *image,
const CompositeOperator compose,const Image *source_image,
const ssize_t x_offset,const ssize_t y_offset)
{
MagickBooleanType
status;
status=CompositeImageChannel(image,DefaultChannels,compose,source_image,
x_offset,y_offset);
return(status);
}
MagickExport MagickBooleanType CompositeImageChannel(Image *image,
const ChannelType channel,const CompositeOperator compose,
const Image *composite,const ssize_t x_offset,const ssize_t y_offset)
{
#define CompositeImageTag "Composite/Image"
CacheView
*source_view,
*image_view;
const char
*value;
ExceptionInfo
*exception;
GeometryInfo
geometry_info;
Image
*canvas_image,
*source_image;
MagickBooleanType
clamp,
clip_to_self,
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
amount,
canvas_dissolve,
midpoint,
percent_luma,
percent_chroma,
source_dissolve,
threshold;
MagickStatusType
flags;
ssize_t
y;
/*
Prepare composite image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(composite != (Image *) NULL);
assert(composite->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
exception=(&image->exception);
source_image=CloneImage(composite,0,0,MagickTrue,exception);
if (source_image == (const Image *) NULL)
return(MagickFalse);
(void) SetImageColorspace(source_image,image->colorspace);
GetMagickPixelPacket(image,&zero);
canvas_image=(Image *) NULL;
amount=0.5;
canvas_dissolve=1.0;
clip_to_self=MagickTrue;
percent_luma=100.0;
percent_chroma=100.0;
source_dissolve=1.0;
threshold=0.05f;
switch (compose)
{
case ClearCompositeOp:
case SrcCompositeOp:
case InCompositeOp:
case SrcInCompositeOp:
case OutCompositeOp:
case SrcOutCompositeOp:
case DstInCompositeOp:
case DstAtopCompositeOp:
{
/*
Modify canvas outside the overlaid region.
*/
clip_to_self=MagickFalse;
break;
}
case OverCompositeOp:
{
if (image->matte != MagickFalse)
break;
if (source_image->matte != MagickFalse)
break;
}
case CopyCompositeOp:
{
if ((x_offset < 0) || (y_offset < 0))
break;
if ((x_offset+(ssize_t) source_image->columns) >= (ssize_t) image->columns)
break;
if ((y_offset+(ssize_t) source_image->rows) >= (ssize_t) image->rows)
break;
status=MagickTrue;
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(source_image,image,source_image->rows,1)
#endif
for (y=0; y < (ssize_t) source_image->rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*source_indexes;
register const PixelPacket
*p;
register IndexPacket
*indexes;
register PixelPacket
*q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,
1,exception);
q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset,
source_image->columns,1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
source_indexes=GetCacheViewVirtualIndexQueue(source_view);
indexes=GetCacheViewAuthenticIndexQueue(image_view);
(void) memcpy(q,p,source_image->columns*sizeof(*p));
if ((indexes != (IndexPacket *) NULL) &&
(source_indexes != (const IndexPacket *) NULL))
(void) memcpy(indexes,source_indexes,
source_image->columns*sizeof(*indexes));
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType)
y,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
source_image=DestroyImage(source_image);
return(status);
}
case CopyOpacityCompositeOp:
case ChangeMaskCompositeOp:
{
/*
Modify canvas outside the overlaid region and require an alpha
channel to exist, to add transparency.
*/
if (image->matte == MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
clip_to_self=MagickFalse;
break;
}
case BlurCompositeOp:
{
CacheView
*canvas_view,
*source_view;
MagickPixelPacket
pixel;
MagickRealType
angle_range,
angle_start,
height,
width;
ResampleFilter
*resample_filter;
SegmentInfo
blur;
/*
Blur Image by resampling.
Blur Image dictated by an overlay gradient map: X = red_channel;
Y = green_channel; compose:args = x_scale[,y_scale[,angle]].
*/
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
{
source_image=DestroyImage(source_image);
return(MagickFalse);
}
/*
Gather the maximum blur sigma values from user.
*/
SetGeometryInfo(&geometry_info);
flags=NoValue;
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
flags=ParseGeometry(value,&geometry_info);
if ((flags & WidthValue) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"InvalidGeometry","'%s' '%s'","compose:args",value);
source_image=DestroyImage(source_image);
canvas_image=DestroyImage(canvas_image);
return(MagickFalse);
}
/*
Users input sigma now needs to be converted to the EWA ellipse size.
The filter defaults to a sigma of 0.5 so to make this match the
users input the ellipse size needs to be doubled.
*/
width=height=geometry_info.rho*2.0;
if ((flags & HeightValue) != 0 )
height=geometry_info.sigma*2.0;
/* default the unrotated ellipse width and height axis vectors */
blur.x1=width;
blur.x2=0.0;
blur.y1=0.0;
blur.y2=height;
/* rotate vectors if a rotation angle is given */
if ((flags & XValue) != 0 )
{
MagickRealType
angle;
angle=DegreesToRadians(geometry_info.xi);
blur.x1=width*cos(angle);
blur.x2=width*sin(angle);
blur.y1=(-height*sin(angle));
blur.y2=height*cos(angle);
}
/* Otherwise lets set a angle range and calculate in the loop */
angle_start=0.0;
angle_range=0.0;
if ((flags & YValue) != 0 )
{
angle_start=DegreesToRadians(geometry_info.xi);
angle_range=DegreesToRadians(geometry_info.psi)-angle_start;
}
/*
Set up a gaussian cylindrical filter for EWA Bluring.
As the minimum ellipse radius of support*1.0 the EWA algorithm
can only produce a minimum blur of 0.5 for Gaussian (support=2.0)
This means that even 'No Blur' will be still a little blurry!
The solution (as well as the problem of preventing any user
expert filter settings, is to set our own user settings, then
restore them afterwards.
*/
resample_filter=AcquireResampleFilter(image,exception);
SetResampleFilter(resample_filter,GaussianFilter,1.0);
/* do the variable blurring of each pixel in image */
pixel=zero;
source_view=AcquireVirtualCacheView(source_image,exception);
canvas_view=AcquireAuthenticCacheView(canvas_image,exception);
for (y=0; y < (ssize_t) source_image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict r;
register IndexPacket
*magick_restrict canvas_indexes;
register ssize_t
x;
if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows))
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,
1,exception);
r=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,
1,exception);
if ((p == (const PixelPacket *) NULL) || (r == (PixelPacket *) NULL))
break;
canvas_indexes=GetCacheViewAuthenticIndexQueue(canvas_view);
for (x=0; x < (ssize_t) source_image->columns; x++)
{
if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns))
{
p++;
continue;
}
if (fabs(angle_range) > MagickEpsilon)
{
MagickRealType
angle;
angle=angle_start+angle_range*QuantumScale*GetPixelBlue(p);
blur.x1=width*cos(angle);
blur.x2=width*sin(angle);
blur.y1=(-height*sin(angle));
blur.y2=height*cos(angle);
}
#if 0
if ( x == 10 && y == 60 ) {
fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n",
blur.x1, blur.x2, blur.y1, blur.y2);
fprintf(stderr, "scaled by=%lf,%lf\n",
QuantumScale*GetPixelRed(p), QuantumScale*GetPixelGreen(p));
}
#endif
ScaleResampleFilter(resample_filter,
blur.x1*QuantumScale*GetPixelRed(p),
blur.y1*QuantumScale*GetPixelGreen(p),
blur.x2*QuantumScale*GetPixelRed(p),
blur.y2*QuantumScale*GetPixelGreen(p));
(void) ResamplePixelColor(resample_filter,(double) x_offset+x,(double)
y_offset+y,&pixel);
SetPixelPacket(canvas_image,&pixel,r,canvas_indexes+x);
p++;
r++;
}
sync=SyncCacheViewAuthenticPixels(canvas_view,exception);
if (sync == MagickFalse)
break;
}
resample_filter=DestroyResampleFilter(resample_filter);
source_view=DestroyCacheView(source_view);
canvas_view=DestroyCacheView(canvas_view);
source_image=DestroyImage(source_image);
source_image=canvas_image;
break;
}
case DisplaceCompositeOp:
case DistortCompositeOp:
{
CacheView
*canvas_view,
*source_view,
*image_view;
MagickPixelPacket
pixel;
MagickRealType
horizontal_scale,
vertical_scale;
PointInfo
center,
offset;
register IndexPacket
*magick_restrict canvas_indexes;
register PixelPacket
*magick_restrict r;
/*
Displace/Distort based on overlay gradient map:
X = red_channel; Y = green_channel;
compose:args = x_scale[,y_scale[,center.x,center.y]]
*/
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
{
source_image=DestroyImage(source_image);
return(MagickFalse);
}
SetGeometryInfo(&geometry_info);
flags=NoValue;
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
flags=ParseGeometry(value,&geometry_info);
if ((flags & (WidthValue | HeightValue)) == 0 )
{
if ((flags & AspectValue) == 0)
{
horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0;
vertical_scale=(MagickRealType) (source_image->rows-1)/2.0;
}
else
{
horizontal_scale=(MagickRealType) (image->columns-1)/2.0;
vertical_scale=(MagickRealType) (image->rows-1)/2.0;
}
}
else
{
horizontal_scale=geometry_info.rho;
vertical_scale=geometry_info.sigma;
if ((flags & PercentValue) != 0)
{
if ((flags & AspectValue) == 0)
{
horizontal_scale*=(source_image->columns-1)/200.0;
vertical_scale*=(source_image->rows-1)/200.0;
}
else
{
horizontal_scale*=(image->columns-1)/200.0;
vertical_scale*=(image->rows-1)/200.0;
}
}
if ((flags & HeightValue) == 0)
vertical_scale=horizontal_scale;
}
/*
Determine fixed center point for absolute distortion map
Absolute distort ==
Displace offset relative to a fixed absolute point
Select that point according to +X+Y user inputs.
default = center of overlay image
arg flag '!' = locations/percentage relative to background image
*/
center.x=(MagickRealType) x_offset;
center.y=(MagickRealType) y_offset;
if (compose == DistortCompositeOp)
{
if ((flags & XValue) == 0)
if ((flags & AspectValue) != 0)
center.x=((MagickRealType) image->columns-1)/2.0;
else
center.x=(MagickRealType) (x_offset+(source_image->columns-1)/
2.0);
else
if ((flags & AspectValue) == 0)
center.x=(MagickRealType) (x_offset+geometry_info.xi);
else
center.x=geometry_info.xi;
if ((flags & YValue) == 0)
if ((flags & AspectValue) != 0)
center.y=((MagickRealType) image->rows-1)/2.0;
else
center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0);
else
if ((flags & AspectValue) != 0)
center.y=geometry_info.psi;
else
center.y=(MagickRealType) (y_offset+geometry_info.psi);
}
/*
Shift the pixel offset point as defined by the provided,
displacement/distortion map. -- Like a lens...
*/
pixel=zero;
image_view=AcquireVirtualCacheView(image,exception);
source_view=AcquireVirtualCacheView(source_image,exception);
canvas_view=AcquireAuthenticCacheView(canvas_image,exception);
for (y=0; y < (ssize_t) source_image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows))
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,
1,exception);
r=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,
1,exception);
if ((p == (const PixelPacket *) NULL) || (r == (PixelPacket *) NULL))
break;
canvas_indexes=GetCacheViewAuthenticIndexQueue(canvas_view);
for (x=0; x < (ssize_t) source_image->columns; x++)
{
if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns))
{
p++;
continue;
}
/*
Displace the offset.
*/
offset.x=(double) ((horizontal_scale*(GetPixelRed(p)-
(((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType)
QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ?
x : 0));
offset.y=(double) ((vertical_scale*(GetPixelGreen(p)-
(((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType)
QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ?
y : 0));
status=InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) offset.x,(double) offset.y,
&pixel,exception);
if (status == MagickFalse)
break;
/*
Mask with the 'invalid pixel mask' in alpha channel.
*/
pixel.opacity=(MagickRealType) QuantumRange*(1.0-(1.0-QuantumScale*
pixel.opacity)*(1.0-QuantumScale*GetPixelOpacity(p)));
SetPixelPacket(canvas_image,&pixel,r,canvas_indexes+x);
p++;
r++;
}
if (x < (ssize_t) source_image->columns)
break;
sync=SyncCacheViewAuthenticPixels(canvas_view,exception);
if (sync == MagickFalse)
break;
}
canvas_view=DestroyCacheView(canvas_view);
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
source_image=DestroyImage(source_image);
source_image=canvas_image;
break;
}
case DissolveCompositeOp:
{
/*
Geometry arguments to dissolve factors.
*/
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
source_dissolve=geometry_info.rho/100.0;
canvas_dissolve=1.0;
if ((source_dissolve-MagickEpsilon) < 0.0)
source_dissolve=0.0;
if ((source_dissolve+MagickEpsilon) > 1.0)
{
canvas_dissolve=2.0-source_dissolve;
source_dissolve=1.0;
}
if ((flags & SigmaValue) != 0)
canvas_dissolve=geometry_info.sigma/100.0;
if ((canvas_dissolve-MagickEpsilon) < 0.0)
canvas_dissolve=0.0;
clip_to_self=MagickFalse;
if ((canvas_dissolve+MagickEpsilon) > 1.0 )
{
canvas_dissolve=1.0;
clip_to_self=MagickTrue;
}
}
break;
}
case BlendCompositeOp:
{
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
source_dissolve=geometry_info.rho/100.0;
canvas_dissolve=1.0-source_dissolve;
if ((flags & SigmaValue) != 0)
canvas_dissolve=geometry_info.sigma/100.0;
clip_to_self=MagickFalse;
if ((canvas_dissolve+MagickEpsilon) > 1.0)
clip_to_self=MagickTrue;
}
break;
}
case MathematicsCompositeOp:
{
/*
Just collect the values from "compose:args", setting.
Unused values are set to zero automagically.
Arguments are normally a comma separated list, so this probably should
be changed to some 'general comma list' parser, (with a minimum
number of values)
*/
SetGeometryInfo(&geometry_info);
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
(void) ParseGeometry(value,&geometry_info);
break;
}
case ModulateCompositeOp:
{
/*
Determine the luma and chroma scale.
*/
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
percent_luma=geometry_info.rho;
if ((flags & SigmaValue) != 0)
percent_chroma=geometry_info.sigma;
}
break;
}
case ThresholdCompositeOp:
{
/*
Determine the amount and threshold.
This Composition method is deprecated
*/
value=GetImageArtifact(image,"compose:args");
if (value != (char *) NULL)
{
flags=ParseGeometry(value,&geometry_info);
amount=geometry_info.rho;
threshold=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
threshold=0.05f;
}
threshold*=QuantumRange;
break;
}
default:
break;
}
value=GetImageArtifact(image,"compose:outside-overlay");
if (value != (const char *) NULL)
clip_to_self=IsMagickTrue(value) == MagickFalse ? MagickTrue : MagickFalse;
value=GetImageArtifact(image,"compose:clip-to-self");
if (value != (const char *) NULL)
clip_to_self=IsMagickTrue(value) != MagickFalse ? MagickTrue : MagickFalse;
clamp=MagickTrue;
value=GetImageArtifact(image,"compose:clamp");
if (value != (const char *) NULL)
clamp=IsMagickTrue(value);
/*
Composite image.
*/
#if defined(MAGICKCORE_OPENCL_SUPPORT)
status=AccelerateCompositeImage(image,channel,compose,source_image,
x_offset,y_offset,canvas_dissolve,source_dissolve,exception);
if (status != MagickFalse)
return(status);
#endif
status=MagickTrue;
progress=0;
midpoint=((MagickRealType) QuantumRange+1.0)/2;
GetMagickPixelPacket(source_image,&zero);
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(source_image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const PixelPacket
*pixels;
double
luma,
hue,
chroma,
sans;
MagickPixelPacket
composite,
canvas,
source;
register const IndexPacket
*magick_restrict source_indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
if (clip_to_self != MagickFalse)
{
if (y < y_offset)
continue;
if ((y-y_offset) >= (ssize_t) source_image->rows)
continue;
}
/*
If pixels is NULL, y is outside overlay region.
*/
pixels=(PixelPacket *) NULL;
p=(PixelPacket *) NULL;
if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows))
{
p=GetCacheViewVirtualPixels(source_view,0,y-y_offset,
source_image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
pixels=p;
if (x_offset < 0)
p-=x_offset;
}
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
source_indexes=GetCacheViewVirtualIndexQueue(source_view);
GetMagickPixelPacket(source_image,&source);
GetMagickPixelPacket(image,&canvas);
hue=0.0;
chroma=0.0;
luma=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (clip_to_self != MagickFalse)
{
if (x < x_offset)
{
q++;
continue;
}
if ((x-x_offset) >= (ssize_t) source_image->columns)
break;
}
canvas.red=(MagickRealType) GetPixelRed(q);
canvas.green=(MagickRealType) GetPixelGreen(q);
canvas.blue=(MagickRealType) GetPixelBlue(q);
if (image->matte != MagickFalse)
canvas.opacity=(MagickRealType) GetPixelOpacity(q);
if (image->colorspace == CMYKColorspace)
canvas.index=(MagickRealType) GetPixelIndex(indexes+x);
if (image->colorspace == CMYKColorspace)
{
canvas.red=(MagickRealType) QuantumRange-canvas.red;
canvas.green=(MagickRealType) QuantumRange-canvas.green;
canvas.blue=(MagickRealType) QuantumRange-canvas.blue;
canvas.index=(MagickRealType) QuantumRange-canvas.index;
}
/*
Handle canvas modifications outside overlaid region.
*/
composite=canvas;
if ((pixels == (PixelPacket *) NULL) || (x < x_offset) ||
((x-x_offset) >= (ssize_t) source_image->columns))
{
switch (compose)
{
case DissolveCompositeOp:
case BlendCompositeOp:
{
composite.opacity=(MagickRealType) (QuantumRange-canvas_dissolve*
(QuantumRange-composite.opacity));
break;
}
case ClearCompositeOp:
case SrcCompositeOp:
{
CompositeClear(&canvas,&composite);
break;
}
case InCompositeOp:
case SrcInCompositeOp:
case OutCompositeOp:
case SrcOutCompositeOp:
case DstInCompositeOp:
case DstAtopCompositeOp:
case CopyOpacityCompositeOp:
case ChangeMaskCompositeOp:
{
composite.opacity=(MagickRealType) TransparentOpacity;
break;
}
default:
{
(void) GetOneVirtualMagickPixel(source_image,x-x_offset,
y-y_offset,&composite,exception);
break;
}
}
if (image->colorspace == CMYKColorspace)
{
composite.red=(MagickRealType) QuantumRange-composite.red;
composite.green=(MagickRealType) QuantumRange-composite.green;
composite.blue=(MagickRealType) QuantumRange-composite.blue;
composite.index=(MagickRealType) QuantumRange-composite.index;
}
SetPixelRed(q,clamp != MagickFalse ?
ClampPixel(composite.red) : ClampToQuantum(composite.red));
SetPixelGreen(q,clamp != MagickFalse ?
ClampPixel(composite.green) : ClampToQuantum(composite.green));
SetPixelBlue(q,clamp != MagickFalse ?
ClampPixel(composite.blue) : ClampToQuantum(composite.blue));
if (image->matte != MagickFalse)
SetPixelOpacity(q,clamp != MagickFalse ?
ClampPixel(composite.opacity) :
ClampToQuantum(composite.opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(indexes+x,clamp != MagickFalse ?
ClampPixel(composite.index) : ClampToQuantum(composite.index));
q++;
continue;
}
/*
Handle normal overlay of source onto canvas.
*/
source.red=(MagickRealType) GetPixelRed(p);
source.green=(MagickRealType) GetPixelGreen(p);
source.blue=(MagickRealType) GetPixelBlue(p);
if (source_image->matte != MagickFalse)
source.opacity=(MagickRealType) GetPixelOpacity(p);
if (source_image->colorspace == CMYKColorspace)
source.index=(MagickRealType) GetPixelIndex(source_indexes+
x-x_offset);
if (source_image->colorspace == CMYKColorspace)
{
source.red=(MagickRealType) QuantumRange-source.red;
source.green=(MagickRealType) QuantumRange-source.green;
source.blue=(MagickRealType) QuantumRange-source.blue;
source.index=(MagickRealType) QuantumRange-source.index;
}
switch (compose)
{
/* Duff-Porter Compositions */
case ClearCompositeOp:
{
CompositeClear(&canvas,&composite);
break;
}
case SrcCompositeOp:
case CopyCompositeOp:
case ReplaceCompositeOp:
{
composite=source;
break;
}
case NoCompositeOp:
case DstCompositeOp:
break;
case OverCompositeOp:
case SrcOverCompositeOp:
{
MagickPixelCompositeOver(&source,source.opacity,&canvas,
canvas.opacity,&composite);
break;
}
case DstOverCompositeOp:
{
MagickPixelCompositeOver(&canvas,canvas.opacity,&source,
source.opacity,&composite);
break;
}
case SrcInCompositeOp:
case InCompositeOp:
{
CompositeIn(&source,&canvas,&composite);
break;
}
case DstInCompositeOp:
{
CompositeIn(&canvas,&source,&composite);
break;
}
case OutCompositeOp:
case SrcOutCompositeOp:
{
CompositeOut(&source,&canvas,&composite);
break;
}
case DstOutCompositeOp:
{
CompositeOut(&canvas,&source,&composite);
break;
}
case AtopCompositeOp:
case SrcAtopCompositeOp:
{
CompositeAtop(&source,&canvas,&composite);
break;
}
case DstAtopCompositeOp:
{
CompositeAtop(&canvas,&source,&composite);
break;
}
case XorCompositeOp:
{
CompositeXor(&source,&canvas,&composite);
break;
}
/* Mathematical Compositions */
case PlusCompositeOp:
{
CompositePlus(&source,&canvas,channel,&composite);
break;
}
case MinusDstCompositeOp:
{
CompositeMinus(&source,&canvas,channel,&composite);
break;
}
case MinusSrcCompositeOp:
{
CompositeMinus(&canvas,&source,channel,&composite);
break;
}
case ModulusAddCompositeOp:
{
CompositeModulusAdd(&source,&canvas,channel,&composite);
break;
}
case ModulusSubtractCompositeOp:
{
CompositeModulusSubtract(&source,&canvas,channel,&composite);
break;
}
case DifferenceCompositeOp:
{
CompositeDifference(&source,&canvas,channel,&composite);
break;
}
case ExclusionCompositeOp:
{
CompositeExclusion(&source,&canvas,channel,&composite);
break;
}
case MultiplyCompositeOp:
{
CompositeMultiply(&source,&canvas,channel,&composite);
break;
}
case ScreenCompositeOp:
{
CompositeScreen(&source,&canvas,channel,&composite);
break;
}
case DivideDstCompositeOp:
{
CompositeDivide(&source,&canvas,channel,&composite);
break;
}
case DivideSrcCompositeOp:
{
CompositeDivide(&canvas,&source,channel,&composite);
break;
}
case DarkenCompositeOp:
{
CompositeDarken(&source,&canvas,channel,&composite);
break;
}
case LightenCompositeOp:
{
CompositeLighten(&source,&canvas,channel,&composite);
break;
}
case DarkenIntensityCompositeOp:
{
CompositeDarkenIntensity(&source,&canvas,channel,&composite);
break;
}
case LightenIntensityCompositeOp:
{
CompositeLightenIntensity(&source,&canvas,channel,&composite);
break;
}
case MathematicsCompositeOp:
{
CompositeMathematics(&source,&canvas,channel,&geometry_info,
&composite);
break;
}
/* Lighting Compositions */
case ColorDodgeCompositeOp:
{
CompositeColorDodge(&source,&canvas,&composite);
break;
}
case ColorBurnCompositeOp:
{
CompositeColorBurn(&source,&canvas,&composite);
break;
}
case LinearDodgeCompositeOp:
{
CompositeLinearDodge(&source,&canvas,&composite);
break;
}
case LinearBurnCompositeOp:
{
CompositeLinearBurn(&source,&canvas,&composite);
break;
}
case HardLightCompositeOp:
{
CompositeHardLight(&source,&canvas,&composite);
break;
}
case HardMixCompositeOp:
{
CompositeHardMix(&source,&canvas,&composite);
break;
}
case OverlayCompositeOp:
{
/* Overlay = Reversed HardLight. */
CompositeHardLight(&canvas,&source,&composite);
break;
}
case SoftLightCompositeOp:
{
CompositeSoftLight(&source,&canvas,&composite);
break;
}
case LinearLightCompositeOp:
{
CompositeLinearLight(&source,&canvas,&composite);
break;
}
case PegtopLightCompositeOp:
{
CompositePegtopLight(&source,&canvas,&composite);
break;
}
case VividLightCompositeOp:
{
CompositeVividLight(&source,&canvas,&composite);
break;
}
case PinLightCompositeOp:
{
CompositePinLight(&source,&canvas,&composite);
break;
}
/* Other Composition */
case ChangeMaskCompositeOp:
{
if ((composite.opacity > ((MagickRealType) QuantumRange/2.0)) ||
(IsMagickColorSimilar(&source,&canvas) != MagickFalse))
composite.opacity=(MagickRealType) TransparentOpacity;
else
composite.opacity=(MagickRealType) OpaqueOpacity;
break;
}
case BumpmapCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
CompositeBumpmap(&source,&canvas,&composite);
break;
}
case DissolveCompositeOp:
{
MagickPixelCompositeOver(&source,(MagickRealType) (QuantumRange-
source_dissolve*(QuantumRange-source.opacity)),&canvas,
(MagickRealType) (QuantumRange-canvas_dissolve*(QuantumRange-
canvas.opacity)),&composite);
break;
}
case BlendCompositeOp:
{
MagickPixelCompositeBlend(&source,source_dissolve,&canvas,
canvas_dissolve,&composite);
break;
}
case StereoCompositeOp:
{
composite.red=(MagickRealType) GetPixelRed(p);
composite.opacity=(composite.opacity+canvas.opacity/2);
break;
}
case ThresholdCompositeOp:
{
CompositeThreshold(&source,&canvas,threshold,amount,&composite);
break;
}
case ModulateCompositeOp:
{
ssize_t
offset;
if (source.opacity == TransparentOpacity)
break;
offset=(ssize_t) (MagickPixelIntensityToQuantum(&source)-midpoint);
if (offset == 0)
break;
CompositeHCL(canvas.red,canvas.green,canvas.blue,&hue,
&chroma,&luma);
luma+=(0.01*percent_luma*offset)/midpoint;
chroma*=0.01*percent_chroma;
HCLComposite(hue,chroma,luma,&composite.red,&composite.green,
&composite.blue);
break;
}
case HueCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (canvas.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(canvas.red,canvas.green,canvas.blue,&hue,
&chroma,&luma);
CompositeHCL(source.red,source.green,source.blue,&hue,&sans,&sans);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < canvas.opacity)
composite.opacity=source.opacity;
break;
}
case SaturateCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (canvas.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(canvas.red,canvas.green,canvas.blue,&hue,
&chroma,&luma);
CompositeHCL(source.red,source.green,source.blue,&sans,&chroma,
&sans);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < canvas.opacity)
composite.opacity=source.opacity;
break;
}
case LuminizeCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (canvas.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(canvas.red,canvas.green,canvas.blue,&hue,
&chroma,&luma);
CompositeHCL(source.red,source.green,source.blue,&sans,&sans,
&luma);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < canvas.opacity)
composite.opacity=source.opacity;
break;
}
case ColorizeCompositeOp:
{
if (source.opacity == TransparentOpacity)
break;
if (canvas.opacity == TransparentOpacity)
{
composite=source;
break;
}
CompositeHCL(canvas.red,canvas.green,canvas.blue,&sans,
&sans,&luma);
CompositeHCL(source.red,source.green,source.blue,&hue,&chroma,&sans);
HCLComposite(hue,chroma,luma,&composite.red,
&composite.green,&composite.blue);
if (source.opacity < canvas.opacity)
composite.opacity=source.opacity;
break;
}
case CopyRedCompositeOp:
case CopyCyanCompositeOp:
{
composite.red=source.red;
break;
}
case CopyGreenCompositeOp:
case CopyMagentaCompositeOp:
{
composite.green=source.green;
break;
}
case CopyBlueCompositeOp:
case CopyYellowCompositeOp:
{
composite.blue=source.blue;
break;
}
case CopyOpacityCompositeOp:
{
if (source.matte == MagickFalse)
composite.opacity=(MagickRealType) (QuantumRange-
MagickPixelIntensityToQuantum(&source));
else
composite.opacity=source.opacity;
break;
}
case CopyBlackCompositeOp:
{
if (source.colorspace != CMYKColorspace)
ConvertRGBToCMYK(&source);
composite.index=source.index;
break;
}
/* compose methods that are already handled */
case BlurCompositeOp:
case DisplaceCompositeOp:
case DistortCompositeOp:
{
composite=source;
break;
}
default:
break;
}
if (image->colorspace == CMYKColorspace)
{
composite.red=(MagickRealType) QuantumRange-composite.red;
composite.green=(MagickRealType) QuantumRange-composite.green;
composite.blue=(MagickRealType) QuantumRange-composite.blue;
composite.index=(MagickRealType) QuantumRange-composite.index;
}
SetPixelRed(q,clamp != MagickFalse ?
ClampPixel(composite.red) : ClampToQuantum(composite.red));
SetPixelGreen(q,clamp != MagickFalse ?
ClampPixel(composite.green) : ClampToQuantum(composite.green));
SetPixelBlue(q,clamp != MagickFalse ?
ClampPixel(composite.blue) : ClampToQuantum(composite.blue));
SetPixelOpacity(q,clamp != MagickFalse ?
ClampPixel(composite.opacity) : ClampToQuantum(composite.opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(indexes+x,clamp != MagickFalse ?
ClampPixel(composite.index) : ClampToQuantum(composite.index));
p++;
if (p >= (pixels+source_image->columns))
p=pixels;
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,CompositeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
if (canvas_image != (Image * ) NULL)
canvas_image=DestroyImage(canvas_image);
else
source_image=DestroyImage(source_image);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T e x t u r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TextureImage() repeatedly tiles the texture image across and down the image
% canvas.
%
% The format of the TextureImage method is:
%
% MagickBooleanType TextureImage(Image *image,const Image *texture)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o texture: This image is the texture to layer on the background.
%
*/
MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture)
{
#define TextureImageTag "Texture/Image"
CacheView
*image_view,
*texture_view;
ExceptionInfo
*exception;
Image
*texture_image;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (texture == (const Image *) NULL)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
exception=(&image->exception);
texture_image=CloneImage(texture,0,0,MagickTrue,exception);
if (texture_image == (const Image *) NULL)
return(MagickFalse);
(void) TransformImageColorspace(texture_image,image->colorspace);
(void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod);
status=MagickTrue;
if ((image->compose != CopyCompositeOp) &&
((image->compose != OverCompositeOp) || (image->matte != MagickFalse) ||
(texture_image->matte != MagickFalse)))
{
/*
Tile texture onto the image background.
*/
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows)
{
register ssize_t
x;
if (status == MagickFalse)
continue;
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns)
{
MagickBooleanType
thread_status;
thread_status=CompositeImage(image,image->compose,texture_image,x+
texture_image->tile_offset.x,y+texture_image->tile_offset.y);
if (thread_status == MagickFalse)
{
status=thread_status;
break;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType)
y,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
(void) SetImageProgress(image,TextureImageTag,(MagickOffsetType)
image->rows,image->rows);
texture_image=DestroyImage(texture_image);
return(status);
}
/*
Tile texture onto the image background (optimized).
*/
status=MagickTrue;
texture_view=AcquireVirtualCacheView(texture_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,texture_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*texture_indexes;
register const PixelPacket
*p;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
size_t
width;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x,(y+
texture_image->tile_offset.y) % texture_image->rows,
texture_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
texture_indexes=GetCacheViewVirtualIndexQueue(texture_view);
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns)
{
width=texture_image->columns;
if ((x+(ssize_t) width) > (ssize_t) image->columns)
width=image->columns-x;
(void) memcpy(q,p,width*sizeof(*p));
if ((image->colorspace == CMYKColorspace) &&
(texture_image->colorspace == CMYKColorspace))
{
(void) memcpy(indexes,texture_indexes,width*
sizeof(*indexes));
indexes+=width;
}
q+=width;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
texture_view=DestroyCacheView(texture_view);
image_view=DestroyCacheView(image_view);
texture_image=DestroyImage(texture_image);
return(status);
}
|
GB_AxB_colscale_meta.c | //------------------------------------------------------------------------------
// GB_AxB_colscale_meta: C=A*D where D is a square diagonal matrix
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// All entries in C=A*D are computed fully in parallel, using the same kind of
// parallelism as Template/GB_reduce_each_vector.c.
{
// Dx, j, and Ah are unused if the operator is FIRST or PAIR
#include "GB_unused.h"
//--------------------------------------------------------------------------
// get C, A, and D
//--------------------------------------------------------------------------
const int64_t *GB_RESTRICT Ap = A->p ;
const int64_t *GB_RESTRICT Ah = A->h ;
const GB_ATYPE *GB_RESTRICT Ax = A_is_pattern ? NULL : A->x ;
const GB_BTYPE *GB_RESTRICT Dx = D_is_pattern ? NULL : D->x ;
//--------------------------------------------------------------------------
// C=A*D
//--------------------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
// if kfirst > klast then task tid does no work at all
int64_t kfirst = kfirst_slice [tid] ;
int64_t klast = klast_slice [tid] ;
//----------------------------------------------------------------------
// C(:,kfirst:klast) = A(:,kfirst:klast)*D(kfirst:klast,kfirst:klast)
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// find the part of A(:,k) and C(:,k) to be operated on by this task
//------------------------------------------------------------------
int64_t j = (Ah == NULL) ? k : Ah [k] ;
int64_t pA_start, pA_end ;
GB_get_pA_and_pC (&pA_start, &pA_end, NULL,
tid, k, kfirst, klast, pstart_slice, NULL, NULL, Ap) ;
//------------------------------------------------------------------
// C(:,j) = A(:,j)*D(j,j)
//------------------------------------------------------------------
GB_GETB (djj, Dx, j) ; // djj = D (j,j)
GB_PRAGMA_VECTORIZE
for (int64_t p = pA_start ; p < pA_end ; p++)
{
GB_GETA (aij, Ax, p) ; // aij = A(i,j)
GB_BINOP (GB_CX (p), aij, djj) ; // C(i,j) = aij * djj
}
}
}
}
|
MultiHashFunction.h | /*
* MultiHashFunction.h
*
* Created on: 10/feb/2017
* Author: samuele
*/
#ifndef HASH_MULTIHASHFUNCTION_H_
#define HASH_MULTIHASHFUNCTION_H_
#include "HashFunction.h"
inline static void GetHashes_speedup_multi_unit(const string& s_Str, const SpacedQmer_Multi& spaced_qmers,
Hash_Err_V_V& vHashes, hash_type (*fConvertion)(char)) {
//Inizializzo vettore per gli hash e errori
// if(vHashes.size() != v_spaced.size())
// {
// vHashes.resize(v_spaced.size());
// vHashes.shrink_to_fit();
// }
//Get hash v for all unit present
const MapUnit& map_unit = spaced_qmers.getMapUnit();
Hash_Err_V_V hash_v(map_unit.n_one.size());
#pragma omp parallel for
for(size_t i = 0; i < map_unit.n_one.size(); ++i)//parallel computation
GetHashes_speedup_previous(s_Str, map_unit.n_one[i], hash_v[i], fConvertion);
#pragma omp parallel for
for(size_t s = 0; s < spaced_qmers.size(); ++s)
{
const SpacedQmer& spaced = spaced_qmers[s];
long n_hashes = s_Str.size()-spaced.GetQ()+1;
Hash_Err_V& hashes = vHashes[s];
hashes.clear();
if(n_hashes>0)
{
hashes.resize(n_hashes); //Crea vettore
//Combine different hash
const V_Pos_Ones& v_pos = map_unit.v_v_pos[s];
#pragma omp parallel for
for(size_t i = 0; i < hashes.size(); ++i)
{
Hash_Err& curr_hash = hashes[i];
for(const Pos_Ones& unit_pos : v_pos)
{
Hash_Err_V& hash_unit_v = hash_v[unit_pos.index_one];
Hash_Err& hash_unit = hash_unit_v[i+unit_pos.pos_start];
curr_hash.hash |= (hash_unit.hash << unit_pos.n_one_before*2);
if(!hash_unit.isCorrect())
curr_hash.add_pos_err(unit_pos.n_one_before, hash_unit);//aggiungi errore posizione corretta
}
}
}
}
}
#endif /* HASH_MULTIHASHFUNCTION_H_ */
|
GB_unaryop__lnot_int16_fp64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int16_fp64
// op(A') function: GB_tran__lnot_int16_fp64
// C type: int16_t
// A type: double
// cast: int16_t cij ; GB_CAST_SIGNED(cij,aij,16)
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
double
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
int16_t z ; GB_CAST_SIGNED(z,x,16) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_INT16 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int16_fp64
(
int16_t *restrict Cx,
const double *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int16_fp64
(
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_unaryop__lnot_int8_int64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int8_int64
// op(A') function: GB_tran__lnot_int8_int64
// C type: int8_t
// A type: int64_t
// cast: int8_t cij = (int8_t) aij
// unaryop: cij = !(aij != 0)
#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 != 0) ;
// casting
#define GB_CASTING(z, aij) \
int8_t z = (int8_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_LNOT || GxB_NO_INT8 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int8_int64
(
int8_t *Cx, // Cx and Ax may be aliased
int64_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int8_int64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
sort.h | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#pragma once
#include <algorithm>
#include <functional>
#include <iterator>
#include "atlas/library/config.h"
#include "atlas/parallel/omp/omp.h"
#if ATLAS_HAVE_OMP
#include <omp.h>
#define ATLAS_HAVE_OMP_SORTING 1
#else
#define ATLAS_HAVE_OMP_SORTING 0
#endif
// Bug in Cray 8.5 or below results in segmentation fault in atlas_test_omp_sort
#if ATLAS_HAVE_OMP_SORTING && defined( _CRAYC )
#if _RELEASE <= 8 && _RELEASE_MINOR < 6
#undef ATLAS_HAVE_OMP_SORTING
#define ATLAS_HAVE_OMP_SORTING 0
#endif
#endif
namespace atlas {
namespace omp {
/**
* sort
* ====
*
* 1) template <typename RandomAccessIterator>
* void sort ( RandomAccessIterator first, RandomAccessIterator last );
*
* 2) template <typename RandomAccessIterator, typename Compare>
* void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
*
* Sort elements in range
* Sorts the elements in the range [first,last) into ascending order.
*
* The elements are compared using operator< for the first version, and comp for the second.
*
* Equivalent elements are not guaranteed to keep their original relative order (see stable_sort).
*
* Parameters
* ----------
* first, last
* Random-access iterators to the initial and final positions of the sequence to be sorted. The range used is [first,last),
* which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
* RandomAccessIterator shall point to a type for which swap is properly defined and which is both move-constructible and move-assignable.
* comp
* Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.
* The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
* The function shall not modify any of its arguments.
* This can either be a function pointer or a function object.
*
*
*
* merge_blocks
* ============
*
* 1) template<typename RandomAccessIterator, typename RandomAccessIterator2>
* void merge_blocks( RandomAccessIterator first, RandomAccessIterator last,
* RandomAccessIterator2 blocks_size_first, RandomAccessIterator2 blocks_size_last );
*
*
* 1) template<typename RandomAccessIterator, typename RandomAccessIterator2, typename Compare >
* void merge_blocks( RandomAccessIterator first, RandomAccessIterator last,
* RandomAccessIterator2 blocks_size_first, RandomAccessIterator2 blocks_size_last,
* Compare compare );
*
* Sort elements in range [first + *blocks_first, first + *blocks_last) using a merge sort
* where each block in range [blocks_first,blocks_last) is already sorted.
*
* Parameters
* ----------
* first, last
* Random-access iterators for bounding the sequence to be sorted
* blocks_begin, blocks_end
* Random-access iterators that define offsets from paramter "first" of blocks that are already sorted
*/
namespace detail {
#if ATLAS_HAVE_OMP_SORTING
template <typename RandomAccessIterator, typename Compare>
void merge_sort_recursive( const RandomAccessIterator& iterator, size_t begin, size_t end, Compare compare ) {
auto size = end - begin;
if ( size >= 256 ) {
auto mid = begin + size / 2;
//#pragma omp taskgroup
// --> it would be preferred to use taskgroup and taskyield instead of taskwait,
// but this leads to segfaults on Cray (cce/8.5.8)
{
#if ATLAS_OMP_TASK_UNTIED_SUPPORTED
#pragma omp task shared( iterator ) untied if ( size >= ( 1 << 15 ) )
#else
#pragma omp task shared( iterator )
#endif
merge_sort_recursive( iterator, begin, mid, compare );
#if ATLAS_OMP_TASK_UNTIED_SUPPORTED
#pragma omp task shared( iterator ) untied if ( size >= ( 1 << 15 ) )
#else
#pragma omp task shared( iterator )
#endif
merge_sort_recursive( iterator, mid, end, compare );
//#pragma omp taskyield
#pragma omp taskwait
}
std::inplace_merge( iterator + begin, iterator + mid, iterator + end, compare );
}
else {
std::sort( iterator + begin, iterator + end, compare );
}
}
#endif
#if ATLAS_HAVE_OMP_SORTING
template <typename RandomAccessIterator, typename Indexable, typename Compare>
void merge_blocks_recursive( const RandomAccessIterator& iterator, const Indexable& blocks, size_t blocks_begin,
size_t blocks_end, Compare compare ) {
if ( blocks_end <= blocks_begin + 1 ) {
// recursion done, go back out
return;
}
size_t blocks_mid = ( blocks_begin + blocks_end ) / 2;
//#pragma omp taskgroup
// --> it would be preferred to use taskgroup and taskyield instead of taskwait,
// but this leads to segfaults on Cray (cce/8.5.8)
{
#pragma omp task shared( iterator, blocks )
merge_blocks_recursive( iterator, blocks, blocks_begin, blocks_mid, compare );
#pragma omp task shared( iterator, blocks )
merge_blocks_recursive( iterator, blocks, blocks_mid, blocks_end, compare );
//#pragma omp taskyield
#pragma omp taskwait
}
auto begin = iterator + blocks[blocks_begin];
auto mid = iterator + blocks[blocks_mid];
auto end = iterator + blocks[blocks_end];
std::inplace_merge( begin, mid, end, compare );
}
#endif
template <typename RandomAccessIterator, typename Indexable, typename Compare>
void merge_blocks_recursive_seq( RandomAccessIterator& iterator, const Indexable& blocks, size_t blocks_begin,
size_t blocks_end, Compare compare ) {
if ( blocks_end <= blocks_begin + 1 ) {
// recursion done, go back out
return;
}
size_t blocks_mid = ( blocks_begin + blocks_end ) / 2;
{
merge_blocks_recursive_seq( iterator, blocks, blocks_begin, blocks_mid, compare );
merge_blocks_recursive_seq( iterator, blocks, blocks_mid, blocks_end, compare );
}
auto begin = iterator + blocks[blocks_begin];
auto mid = iterator + blocks[blocks_mid];
auto end = iterator + blocks[blocks_end];
std::inplace_merge( begin, mid, end, compare );
}
} // namespace detail
template <typename RandomAccessIterator, typename Compare>
void sort( RandomAccessIterator first, RandomAccessIterator last, Compare compare ) {
#if ATLAS_HAVE_OMP_SORTING
if ( atlas_omp_get_max_threads() > 1 ) {
#pragma omp parallel
#pragma omp single
detail::merge_sort_recursive( first, 0, std::distance( first, last ), compare );
}
else {
std::sort( first, last, compare );
}
#else
std::sort( first, last, compare );
#endif
}
template <typename RandomAccessIterator>
void sort( RandomAccessIterator first, RandomAccessIterator last ) {
using value_type = typename std::iterator_traits<RandomAccessIterator>::value_type;
::atlas::omp::sort( first, last, std::less<value_type>() );
}
template <typename RandomAccessIterator, typename RandomAccessIterator2, typename Compare>
void merge_blocks( RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator2 blocks_size_first,
RandomAccessIterator2 blocks_size_last, Compare compare ) {
using size_type = typename std::iterator_traits<RandomAccessIterator2>::value_type;
size_type nb_blocks = std::distance( blocks_size_first, blocks_size_last );
std::vector<size_type> blocks_displs( nb_blocks + 1 );
blocks_displs[0] = 0;
for ( size_t i = 1; i < blocks_displs.size(); ++i ) {
blocks_displs[i] = blocks_displs[i - 1] + blocks_size_first[i - 1];
}
#if ATLAS_HAVE_OMP_SORTING
if ( atlas_omp_get_max_threads() > 1 ) {
#pragma omp parallel
#pragma omp single
detail::merge_blocks_recursive( first, blocks_displs, 0, nb_blocks, compare );
}
else {
detail::merge_blocks_recursive_seq( first, blocks_displs, 0, nb_blocks, compare );
}
#else
detail::merge_blocks_recursive_seq( first, blocks_displs, 0, nb_blocks, compare );
#endif
}
template <typename RandomAccessIterator, typename RandomAccessIterator2>
void merge_blocks( RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator2 blocks_size_first,
RandomAccessIterator2 blocks_size_last ) {
using value_type = typename std::iterator_traits<RandomAccessIterator>::value_type;
::atlas::omp::merge_blocks( first, last, blocks_size_first, blocks_size_last, std::less<value_type>() );
}
} // namespace omp
} // namespace atlas
#undef ATLAS_OMP_TASK_UNTIED_SUPPORTED
#undef ATLAS_HAVE_OMP_SORTING
|
sieve.c | /*
* Adapted from: http://w...content-available-to-author-only...s.org/sieve-of-eratosthenes
*
* Programa testado no PARCODE
*
* Tempo sequencial:
* real 0m4.412s
* user 0m4.318s
* sys 0m0.080s
*
* Tempo paralelo:
* real 0m3.659s
* user 0m6.781s
* sys 0m0.080s
*
* Tempo paralelo com escalonamento:
* real 0m2.487s
* user 0m9.562s
* sys 0m0.084s
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
int sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
int primes = 0;
bool *prime = (bool *)malloc((n + 1) * sizeof(bool));
int sqrt_n = sqrt(n);
memset(prime, true, (n + 1) * sizeof(bool));
//#pragma omp parallel for
#pragma omp parallel for schedule(dynamic)
for (int p = 2; p <= sqrt_n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
// count prime numbers
#pragma omp parallel for reduction(+:primes)
for (int p = 2; p <= n; p++)
if (prime[p])
primes++;
return (primes);
}
int main()
{
int n = 100000000;
printf("%d\n", sieveOfEratosthenes(n));
return 0;
}
|
GB_unop__erfc_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__erfc_fp64_fp64
// op(A') function: GB_unop_tran__erfc_fp64_fp64
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = erfc (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 = erfc (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] = erfc (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ERFC || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__erfc_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] = erfc (z) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__erfc_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
|
omp_trap1.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
double y(double x); /* Интегрируемая функция */
void Trap(double a, double b, int n, double* global_result_p);
int main(int argc, char* argv[]) {
double global_result = 0.0; /* Хранить результат в global_result */
double a, b; /* Левый и правый концы отрезка */
int n; /* Количество трапеций */
int thread_count;
// Количество потоков:
thread_count = 10;
a = 0;
b = 5;
n = (b - a) / 0.00000005;
if (n % thread_count != 0) {
fprintf(stderr, "Количество трапеций должно ровно делиться на количество потоков\n");
exit(0);
}
// Директива parallel создает параллельный регион для следующего за ней
// структурированного блока, например:
// #pragma omp parallel [раздел[ [,] раздел]...]
// структурированный блок
// Эта директива сообщает компилятору, что структурированный блок кода должен
// быть выполнен параллельно, в нескольких потоках. Каждый поток будет
// выполнять один и тот же поток команд, но не один и тот же набор команд -
// все зависит от операторов, управляющих логикой программы,
// таких как if-else.
#pragma omp parallel num_threads(thread_count)
Trap(a, b, n, &global_result);
printf("С n = %d трапеций, приближенное значение\n", n);
printf("определенного интеграла от %f до %f = %.14e\n",
a, b, global_result);
return 0;
} /* main */
/*------------------------------------------------------------------
* Функция: y
* Назначение: Посчитать значение интегрируемой функции
* Входной аргумент: x
* Возвращаемое значение: y(x)
*/
double y(double x) {
double return_val;
return_val = exp(x) * x - cos(x);
return return_val;
} /* y */
/*------------------------------------------------------------------
* Функция: Trap
* Назначение: Метод трапеций
* Входные аргументы:
* a: левый конец отрезка
* b: правый конец отрезка
* n: количество трапеций
* Выходные аргументы:
* integral: приближенное значение определенного интеграла от a до b для y(x)
*/
void Trap(double a, double b, int n, double* global_result_p) {
double h, x, my_result;
double local_a, local_b;
int i, local_n;
// Номер потока в группе потоков:
// Число в диапазоне от 0 до omp_get_num_threads - 1.
int my_rank = omp_get_thread_num();
// Число потоков, входящих в текущую группу потоков:
// Если вызывающий поток выполняется не в параллельном регионе,
// эта функция возвращает 1.
int thread_count = omp_get_num_threads();
h = (b-a)/n;
local_n = n/thread_count;
local_a = a + my_rank*local_n*h;
local_b = local_a + local_n*h;
my_result = (y(local_a) + y(local_b))/2.0;
for (i = 1; i <= local_n-1; i++) {
x = local_a + i*h;
my_result += y(x);
}
my_result = my_result*h;
// Использование критической секции в качестве барьера:
// В OpenMP для входа в критическую секцию применяется директива
// #pragma omp critical [имя].
// Доступ к блоку кода является взаимоисключающим только для других
// критических секций с тем же именем (это справедливо для всего процесса).
// Если имя не указано, директива ставится в соответствие некоему имени,
// выбираемому системой. Доступ ко всем неименованным критическим секциям
// является взаимоисключающим.
#pragma omp critical
*global_result_p += my_result;
} /* Trap */
|
ellipticPreconCoarsenHex3D.c | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
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.
*/
extern "C" void ellipticPreconCoarsenHex3D(const dlong& Nelements,
const dfloat* __restrict__ R,
const dfloat* __restrict__ qf,
dfloat* __restrict__ qc)
{
dfloat s_q[p_NqFine][p_NqFine];
dfloat s_Pq[p_NqCoarse][p_NqFine];
dfloat s_R[p_NqCoarse][p_NqFine];
dfloat s_RT[p_NqFine][p_NqCoarse];
dfloat r_q[p_NqFine][p_NqFine][p_NqCoarse];
for(int j = 0; j < p_NqCoarse; ++j){
for(int i = 0; i < p_NqFine; ++i) {
const int t = i + j * p_NqFine;
const dfloat r = R[t];
s_R[j][i] = r;
s_RT[i][j] = r;
}
}
#pragma omp parallel for private(s_Pq, r_q, s_q)
for(dlong e = 0; e < Nelements; ++e) {
for(int j = 0; j < p_NqFine; ++j)
for(int i = 0; i < p_NqFine; ++i) {
for(int k = 0; k < p_NqCoarse; ++k)
r_q[j][i][k] = 0;
for(int k = 0; k < p_NqFine; ++k) {
const int id = i + j * p_NqFine + k * p_NqFine * p_NqFine + e * p_NpFine;
const dfloat tmp = qf[id];
#pragma unroll
for(int m = 0; m < p_NqCoarse; ++m)
r_q[j][i][m] += s_RT[k][m] * tmp;
}
}
for(int k = 0; k < p_NqCoarse; ++k) {
#pragma unroll
for(int j = 0; j < p_NqFine; ++j)
#pragma unroll
for(int i = 0; i < p_NqFine; ++i)
s_q[i][j] = r_q[j][i][k];
for(int j = 0; j < p_NqCoarse; ++j){
for(int i = 0; i < p_NqFine; ++i){
dfloat res = 0;
#pragma unroll
for(int m = 0; m < p_NqFine; ++m)
res += s_R[j][m] * s_q[i][m];
s_Pq[j][i] = res;
}
}
for(int j = 0; j < p_NqCoarse; ++j)
for(int i = 0; i < p_NqCoarse; ++i) {
dfloat res = 0;
#pragma unroll
for(int m = 0; m < p_NqFine; ++m)
res += s_R[i][m] * s_Pq[j][m];
const int id = i + j * p_NqCoarse + k * p_NqCoarse * p_NqCoarse + e * p_NpCoarse;
qc[id] = res;
}
}
}
}
|
ctl_list.c | /********************************************************************[libaroma]*
* Copyright (C) 2011-2015 Ahmad Amarullah (http://amarullz.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*______________________________________________________________________________
*
* Filename : ctl_list.c
* Description : list control
*
* + This is part of libaroma, an embedded ui toolkit.
* + 04/03/15 - Author(s): Ahmad Amarullah
*
*/
#ifndef __libaroma_ctl_list_c__
#define __libaroma_ctl_list_c__
#include <aroma_internal.h>
#include "../ui/ui_internal.h"
/* SCROLL CONTROL HANDLER */
dword _libaroma_ctl_list_message(
LIBAROMA_CONTROLP, LIBAROMA_CTL_SCROLL_CLIENTP,LIBAROMA_MSGP,int,int);
void _libaroma_ctl_list_destroy(
LIBAROMA_CONTROLP, LIBAROMA_CTL_SCROLL_CLIENTP);
byte _libaroma_ctl_list_thread(
LIBAROMA_CONTROLP, LIBAROMA_CTL_SCROLL_CLIENTP);
void _libaroma_ctl_list_draw(
LIBAROMA_CONTROLP, LIBAROMA_CTL_SCROLL_CLIENTP, LIBAROMA_CANVASP,
int, int, int, int);
static LIBAROMA_CTL_SCROLL_CLIENT_HANDLER _libaroma_ctl_list_handler={
draw:_libaroma_ctl_list_draw,
destroy:_libaroma_ctl_list_destroy,
thread:_libaroma_ctl_list_thread,
message:_libaroma_ctl_list_message
};
/* list structure */
typedef struct {
int h;
int hpad;
int vpad;
int itemn;
byte flags;
LIBAROMA_CTL_LIST_ITEMP first;
LIBAROMA_CTL_LIST_ITEMP last;
LIBAROMA_CTL_LIST_ITEMP touched;
LIBAROMA_CTL_LIST_ITEMP focused;
int threadn;
LIBAROMA_CTL_LIST_ITEMP * threads;
LIBAROMA_MUTEX mutex;
LIBAROMA_MUTEX imutex;
LIBAROMA_CTL_LIST_TOUCHPOS pos;
} LIBAROMA_CTL_LIST, * LIBAROMA_CTL_LISTP;
/*
* Function : __libaroma_ctl_list_item_reg_thread
* Return Value: byte
* Descriptions: register item thread
*/
byte __libaroma_ctl_list_item_reg_thread(
LIBAROMA_CONTROLP ctl, LIBAROMA_CTL_LIST_ITEMP item){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
/*
if (!item->handler->message){
ALOGW("item_reg_thread item doesn't have message handler");
return 0;
}
*/
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (mi->threadn==0){
mi->threads = (LIBAROMA_CTL_LIST_ITEMP *)
malloc(sizeof(LIBAROMA_CTL_LIST_ITEMP));
mi->threads[0] = item;
mi->threadn=1;
}
else{
int i;
for (i=0;i<mi->threadn;i++){
if (mi->threads[i]==item){
/* already registered */
return 2;
}
}
LIBAROMA_CTL_LIST_ITEMP * new_threads = (LIBAROMA_CTL_LIST_ITEMP *)
realloc(mi->threads, sizeof(LIBAROMA_CTL_LIST_ITEMP)*(mi->threadn+1));
if (!new_threads){
if (mi->threads){
free(mi->threads);
}
mi->threads=NULL;
mi->threadn=0;
ALOGW("item_reg_thread cannot realloc threads");
return 0;
}
mi->threads=new_threads;
mi->threads[mi->threadn]=item;
mi->threadn++;
}
return 1;
} /* End of __libaroma_ctl_list_item_reg_thread */
/*
* Function : __libaroma_ctl_list_item_unreg_thread
* Return Value: byte
* Descriptions: unregister item thread
*/
byte __libaroma_ctl_list_item_unreg_thread(
LIBAROMA_CONTROLP ctl, LIBAROMA_CTL_LIST_ITEMP item){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (mi->threadn<1){
return 0;
}
if (mi->threadn==1){
if (mi->threads[0]==item){
free(mi->threads);
mi->threads=NULL;
mi->threadn=0;
return 1;
}
return 0;
}
LIBAROMA_CTL_LIST_ITEMP * new_threads = (LIBAROMA_CTL_LIST_ITEMP *)
malloc(sizeof(LIBAROMA_CTL_LIST_ITEMP)*(mi->threadn-1));
if (!new_threads){
ALOGW("item_unreg_thread cannot allocate new threads");
if (mi->threads){
free(mi->threads);
}
mi->threads=NULL;
mi->threadn=0;
return 0;
}
int i;
int z=0;
int n=-1;
for (i=0;i<mi->threadn;i++){
if (mi->threads[i]==item){
n=i;
}
else{
new_threads[z++]=mi->threads[i];
}
}
if (n>-1){
free(mi->threads);
mi->threads=new_threads;
mi->threadn--;
return 1;
}
free(new_threads);
ALOGV("item_unreg_thread item is unregistered");
return 0;
} /* End of __libaroma_ctl_list_item_unreg_thread */
/*
* Function : _libaroma_ctl_list_draw_item_fresh
* Return Value: void
* Descriptions: fresh item drawing
*/
void _libaroma_ctl_list_draw_item_fresh(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_LIST_ITEMP item,
LIBAROMA_CANVASP canvas,
word bgcolor,
int hpad,
byte flag
){
if ((!canvas)||(!item)||(!ctl)) {
return;
}
/* cleanup */
if (!(flag&LIBAROMA_CTL_LIST_ITEM_DRAW_ADDONS)){
libaroma_canvas_setcolor(canvas,bgcolor,0xff);
}
LIBAROMA_CANVASP tcanvas=NULL;
LIBAROMA_CANVASP ccv = canvas;
/* have horizontal padding */
if (hpad>0){
tcanvas = libaroma_canvas_area(
canvas, hpad, 0, canvas->w-hpad*2, canvas->h
);
if (tcanvas){
ccv = tcanvas;
}
}
/* draw directly */
if (item->handler->draw!=NULL){
item->handler->draw(ctl,item,ccv,bgcolor,
flag);
}
if (tcanvas){
libaroma_canvas_free(tcanvas);
}
} /* End of _libaroma_ctl_list_draw_item_fresh */
/*
* Function : _libaroma_ctl_list_free_state
* Return Value: void
* Descriptions: free state
*/
void _libaroma_ctl_list_free_state(LIBAROMA_CTL_LIST_ITEMP item){
if (item->state!=NULL){
if (item->state->cache_rest){
libaroma_canvas_free(item->state->cache_rest);
}
if (item->state->cache_push){
libaroma_canvas_free(item->state->cache_push);
}
if (item->state->cache_client){
libaroma_canvas_free(item->state->cache_client);
}
free(item->state);
ALOGT("[X] State Freed %x",item->id);
}
item->state=NULL;
} /* End of _libaroma_ctl_list_free_state */
/*
* Function : _libaroma_ctl_list_new_state
* Return Value: byte
* Descriptions: create new state
*/
byte _libaroma_ctl_list_init_state(
LIBAROMA_CTL_LIST_ITEMP item
){
if (item->state==NULL){
item->state =
(LIBAROMA_CTL_LIST_ITEM_STATEP) calloc(sizeof(
LIBAROMA_CTL_LIST_ITEM_STATE
),1);
if (!item->state){
ALOGW("list_new_state alloc memory failed");
return 0;
}
ALOGT("[0] State Created %x",item->id);
return 1;
}
return 2;
} /* End of _libaroma_ctl_list_new_state */
/*
* Function : _libaroma_ctl_list_init_state_cache
* Return Value: byte
* Descriptions: init cache canvases
*/
byte _libaroma_ctl_list_init_state_cache(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_LIST_ITEMP item
){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (item->state){
if (!item->state->cache_rest){
item->state->cache_rest=libaroma_canvas(ctl->w,item->h);
}
if (!item->state->cache_push){
item->state->cache_push=libaroma_canvas(ctl->w,item->h);
}
word bgcolor = libaroma_ctl_scroll_get_bg_color(ctl);
if (item->state->cache_rest){
_libaroma_ctl_list_draw_item_fresh(
ctl,item,item->state->cache_rest,bgcolor,mi->hpad,
LIBAROMA_CTL_LIST_ITEM_DRAW_NORMAL|LIBAROMA_CTL_LIST_ITEM_DRAW_CACHE
);
}
if (item->state->cache_push){
_libaroma_ctl_list_draw_item_fresh(
ctl,item,item->state->cache_push,bgcolor,mi->hpad,
LIBAROMA_CTL_LIST_ITEM_DRAW_PUSHED|LIBAROMA_CTL_LIST_ITEM_DRAW_CACHE
);
}
return 1;
}
return 0;
} /* End of _libaroma_ctl_list_init_state_cache */
/*
* Function : _libaroma_ctl_list_draw_item
* Return Value: void
* Descriptions: draw item
*/
void _libaroma_ctl_list_draw_item(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_LIST_ITEMP item,
LIBAROMA_CANVASP canvas,
word bgcolor
){
if ((!item)||(!canvas)){
return;
}
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
/* normal animation handler */
if (item->state){
if (item->state->normal_handler){
libaroma_draw(canvas, item->state->cache_rest, 0, 0, 0);
int ripple_i = 0;
int ripple_p = 0;
while(libaroma_ripple_loop(&item->state->ripple,&ripple_i,&ripple_p)){
int x=0;
int y=(item->y+libaroma_dp(1));
int size=0;
byte push_opacity=0;
byte ripple_opacity=0;
if (libaroma_ripple_calculation(
&item->state->ripple, canvas->w, canvas->h,
&push_opacity, &ripple_opacity,
&x, &y, &size, ripple_p
)){
libaroma_draw_opacity(canvas,
item->state->cache_push, 0, 0, 2,
(byte) push_opacity
);
libaroma_draw_mask_circle(
canvas,
item->state->cache_push,
x, y,
x, y,
size,
ripple_opacity
);
}
}
if (item->state->normal_handler==2){
_libaroma_ctl_list_draw_item_fresh(
ctl, item,canvas,bgcolor,mi->hpad,
LIBAROMA_CTL_LIST_ITEM_DRAW_ADDONS
);
}
return;
}
}
/* draw fresh */
_libaroma_ctl_list_draw_item_fresh(
ctl, item,canvas,bgcolor,mi->hpad, LIBAROMA_CTL_LIST_ITEM_DRAW_NORMAL
);
} /* End of _libaroma_ctl_list_draw_item */
/*
* Function : _libaroma_ctl_list_dodraw_item
* Return Value: byte
* Descriptions: do draw item directly
*/
byte _libaroma_ctl_list_dodraw_item(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_LIST_ITEMP item
){
if (!item){
return 0;
}
byte res=0;
if (libaroma_ctl_scroll_is_visible(ctl,item->y,item->h)){
word bgcolor = libaroma_ctl_scroll_get_bg_color(ctl);
LIBAROMA_CANVASP canvas=libaroma_canvas(ctl->w,item->h);
if (canvas!=NULL){
_libaroma_ctl_list_draw_item(
ctl,item,canvas,bgcolor
);
res=libaroma_ctl_scroll_blit(
ctl,
canvas,
0, item->y, canvas->w, canvas->h,
0
);
libaroma_canvas_free(canvas);
}
}
return res;
} /* End of _libaroma_ctl_list_dodraw_item */
/*
* Function : _libaroma_ctl_list_thread
* Return Value: byte
* Descriptions: scroll list thread
*/
byte _libaroma_ctl_list_thread(
LIBAROMA_CONTROLP ctl, LIBAROMA_CTL_SCROLL_CLIENTP client){
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
byte need_redraw=0;
int i;
libaroma_mutex_lock(mi->imutex);
libaroma_mutex_lock(mi->mutex);
int num_thread = mi->threadn;
if (num_thread>0){
LIBAROMA_CTL_LIST_ITEMP * threads = (LIBAROMA_CTL_LIST_ITEMP *) malloc(
sizeof(LIBAROMA_CTL_LIST_ITEM)*num_thread);
for (i=0;i<num_thread;i++){
threads[i]=mi->threads[i];
}
#ifdef LIBAROMA_CONFIG_OPENMP
#pragma omp parallel for
#endif
for (i=0;i<num_thread;i++){
LIBAROMA_CTL_LIST_ITEMP item = threads[i];
if (item){
byte unreg_me=0;
byte is_draw=0;
if (item->state){
/* normal behaviour */
if (item->state->normal_handler){
byte res = libaroma_ripple_thread(&item->state->ripple, 0);
if (res&LIBAROMA_RIPPLE_REDRAW){
is_draw = 1;
}
if (res&LIBAROMA_RIPPLE_HOLDED){
if (item->handler->message){
int cx = 0; int cy=0;
LIBAROMA_CTL_LIST_TOUCHPOSP pos = libaroma_ctl_list_getpos(ctl);
if (pos){
cy = pos->last_y - item->y;
cx = pos->last_x;
}
byte msgret=item->handler->message(
ctl,
item,
LIBAROMA_CTL_LIST_ITEM_MSG_TOUCH_HOLDED,
LIBAROMA_CTL_LIST_ITEM_MSGPARAM_HOLDED,
cx, cy
);
if (msgret&LIBAROMA_CTL_LIST_ITEM_MSGRET_NEED_DRAW){
is_draw=1;
}
if (msgret&LIBAROMA_CTL_LIST_ITEM_MSGRET_UNREG_THREAD){
unreg_me=1;
}
}
}
if (res&LIBAROMA_RIPPLE_RELEASED){
_libaroma_ctl_list_free_state(item);
unreg_me=1;
}
}
}
if (item->handler->message){
byte msgret=item->handler->message(
ctl,
item,
LIBAROMA_CTL_LIST_ITEM_MSG_THREAD,
libaroma_ctl_scroll_is_visible(ctl,item->y,item->h),
0,
0
);
if (msgret&LIBAROMA_CTL_LIST_ITEM_MSGRET_NEED_DRAW){
is_draw=1;
}
if (msgret&LIBAROMA_CTL_LIST_ITEM_MSGRET_UNREG_THREAD){
unreg_me=1;
}
}
if (is_draw){
if (_libaroma_ctl_list_dodraw_item(ctl,item)){
need_redraw=1;
}
}
/* unreg thread */
if (!unreg_me){
threads[i] = NULL;
}
}
}
/* unreg threads */
for (i=0;i<num_thread;i++){
LIBAROMA_CTL_LIST_ITEMP item = threads[i];
if (item!=NULL){
if (!(item->flags&LIBAROMA_CTL_LIST_ITEM_REGISTER_THREAD)){
__libaroma_ctl_list_item_unreg_thread(ctl, item);
}
}
}
free(threads);
}
libaroma_mutex_unlock(mi->mutex);
libaroma_mutex_unlock(mi->imutex);
return need_redraw;
} /* End of _libaroma_ctl_list_thread */
/*
* Function : _libaroma_ctl_list_item_by_y
* Return Value: void
* Descriptions: get item by y position
*/
LIBAROMA_CTL_LIST_ITEMP _libaroma_ctl_list_item_by_y(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_SCROLL_CLIENTP client,
int y){
if (client->handler!=&_libaroma_ctl_list_handler){
return NULL;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
/* find first item */
LIBAROMA_CTL_LIST_ITEMP f = mi->first;
while(f){
if ((f->y<=y)&&(f->y+f->h>y)){
return f;
}
f = f->next;
}
return NULL;
} /* End of _libaroma_ctl_list_item_by_y */
/*
* Function : _libaroma_ctl_list_draw
* Return Value: void
* Descriptions: draw routine
*/
void _libaroma_ctl_list_draw(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_SCROLL_CLIENTP client,
LIBAROMA_CANVASP cv,
int x, int y, int w, int h){
if (client->handler!=&_libaroma_ctl_list_handler){
return;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (y<mi->vpad){
libaroma_draw_rect(
cv, 0, 0, w, mi->vpad-y,
libaroma_ctl_scroll_get_bg_color(ctl),
0xff
);
}
if (y+h>mi->h-mi->vpad){
int dh=(y+h)-(mi->h-mi->vpad);
libaroma_draw_rect(
cv, 0, h-dh, w, dh,
libaroma_ctl_scroll_get_bg_color(ctl),
0xff
);
}
libaroma_mutex_lock(mi->imutex);
/* find first item */
int current_index = 0;
LIBAROMA_CTL_LIST_ITEMP f = mi->first;
while(f){
if (f->y+f->h>y){
break;
}
f = f->next;
current_index++;
}
word bgcolor = libaroma_ctl_scroll_get_bg_color(ctl);
/* draw routine */
LIBAROMA_CTL_LIST_ITEMP item = f;
while(item){
if (item->y>=y+h){
break;
}
LIBAROMA_CANVASP canvas=NULL;
byte is_area=0;
if ((item->y>=y)&&(item->y+item->h<y+cv->h)){
canvas = libaroma_canvas_area(cv,0,item->y-y,w,item->h);
is_area=1;
}
else{
canvas = libaroma_canvas(w,item->h);
}
if (canvas!=NULL){
_libaroma_ctl_list_draw_item(
ctl, item, canvas, bgcolor
);
/* blit into working canvas */
if (!is_area){
libaroma_draw(cv,canvas,0,item->y-y,0);
}
libaroma_canvas_free(canvas);
}
item=item->next;
current_index++;
}
libaroma_mutex_unlock(mi->imutex);
} /* End of _libaroma_ctl_list_draw */
/*
* Function : _libaroma_ctl_list_scroll_message
* Return Value: dword
* Descriptions: handle scroll message
*/
dword _libaroma_ctl_list_scroll_message(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_SCROLL_CLIENTP client,
LIBAROMA_CTL_LISTP mi,
int msg,
int param,
int x,
int y){
switch(msg){
case LIBAROMA_CTL_SCROLL_MSG_ISNEED_TOUCH:{
if ((y<mi->vpad)||(y>mi->h-mi->vpad)){
ALOGT("list_scroll_message ISNEED(%i,%i) not needed",x,y);
/* no need touch handle */
return 0;
}
LIBAROMA_CTL_LIST_ITEMP item=
_libaroma_ctl_list_item_by_y(ctl, client, y);
if (item){
if (item->flags&LIBAROMA_CTL_LIST_ITEM_RECEIVE_TOUCH){
mi->touched = item;
ALOGT("list_scroll_message ISNEED(%i,%i) needed",x,y);
return LIBAROMA_CTL_SCROLL_MSG_HANDLED;
}
}
ALOGT("list_scroll_message ISNEED(%i,%i) item don't use touch",x,y);
return 0;
}
break;
case LIBAROMA_CTL_SCROLL_MSG_TOUCH_DOWN:{
ALOGT("list_scroll_message TOUCH_DOWN(%i,%i)",x,y);
mi->pos.start_x=x;
mi->pos.start_y=y;
mi->pos.last_x=x;
mi->pos.last_y=y;
byte retval = 0;
if (mi->touched!=NULL){
byte mres = 0;
if (mi->touched->handler->message){
int cy = y - mi->touched->y;
mres=mi->touched->handler->message(
ctl,
mi->touched,
LIBAROMA_CTL_LIST_ITEM_MSG_TOUCH_DOWN,
0,
x, cy
);
}
if (!(mres&LIBAROMA_CTL_LIST_ITEM_MSGRET_HANDLED)){
/* init state item */
if (_libaroma_ctl_list_init_state(mi->touched)){
_libaroma_ctl_list_init_state_cache(ctl,mi->touched);
if (mres&LIBAROMA_CTL_LIST_ITEM_MSGRET_HAVE_ADDONS_DRAW){
mi->touched->state->normal_handler = 2;
}
else{
mi->touched->state->normal_handler = 1;
}
libaroma_mutex_lock(mi->mutex);
libaroma_ripple_down(&mi->touched->state->ripple, x, y);
__libaroma_ctl_list_item_reg_thread(ctl, mi->touched);
libaroma_mutex_unlock(mi->mutex);
}
}
else if(mi->touched->state){
mi->touched->state->normal_handler = 0;
}
if (mres&LIBAROMA_CTL_LIST_ITEM_MSGRET_NEED_DRAW){
if (_libaroma_ctl_list_dodraw_item(ctl,mi->touched)){
retval=LIBAROMA_CTL_SCROLL_MSG_NEED_DRAW;
}
}
}
return retval;
}
break;
case LIBAROMA_CTL_SCROLL_MSG_TOUCH_MOVE:{
ALOGT("list_scroll_message TOUCH_MOVE(%i,%i)",x,y);
mi->pos.last_x=x;
mi->pos.last_y=y;
byte retval = 0;
if (mi->touched!=NULL){
byte mres = 0;
if (mi->touched->handler->message){
int cy = y - mi->touched->y;
mres=mi->touched->handler->message(
ctl,
mi->touched,
LIBAROMA_CTL_LIST_ITEM_MSG_TOUCH_MOVE,
0,
x, cy
);
}
if (mi->touched->state){
libaroma_ripple_move(&mi->touched->state->ripple,x,y);
}
if (mres&LIBAROMA_CTL_LIST_ITEM_MSGRET_NEED_DRAW){
if (_libaroma_ctl_list_dodraw_item(ctl,mi->touched)){
retval=LIBAROMA_CTL_SCROLL_MSG_NEED_DRAW;
}
}
}
return retval;
}
break;
case LIBAROMA_CTL_SCROLL_MSG_TOUCH_UP:
case LIBAROMA_CTL_SCROLL_MSG_TOUCH_CANCEL:{
ALOGT_IF(msg==LIBAROMA_CTL_SCROLL_MSG_TOUCH_UP,
"list_scroll_message TOUCH_UP(%i,%i)",x,y);
ALOGT_IF(msg==LIBAROMA_CTL_SCROLL_MSG_TOUCH_CANCEL,
"list_scroll_message TOUCH_CANCEL(%i,%i)",x,y);
mi->pos.last_x=x;
mi->pos.last_y=y;
byte retval = 0;
if (mi->touched!=NULL){
dword param_msg = 0;
if (mi->touched->state){
if (msg==LIBAROMA_CTL_SCROLL_MSG_TOUCH_CANCEL){
libaroma_ripple_cancel(&mi->touched->state->ripple);
}
else{
byte res = libaroma_ripple_up(&mi->touched->state->ripple,0);
if (res&LIBAROMA_RIPPLE_HOLDED){
param_msg = LIBAROMA_CTL_LIST_ITEM_MSGPARAM_HOLDED;
}
}
}
byte mres = 0;
if (mi->touched->handler->message){
int cy = y - mi->touched->y;
mres=mi->touched->handler->message(
ctl,
mi->touched,
(msg==LIBAROMA_CTL_SCROLL_MSG_TOUCH_UP)?
LIBAROMA_CTL_LIST_ITEM_MSG_TOUCH_UP:
LIBAROMA_CTL_LIST_ITEM_MSG_TOUCH_CANCEL,
param_msg,
x, cy
);
}
if (mres&LIBAROMA_CTL_LIST_ITEM_MSGRET_NEED_DRAW){
if (_libaroma_ctl_list_dodraw_item(ctl,mi->touched)){
retval=LIBAROMA_CTL_SCROLL_MSG_NEED_DRAW;
}
}
}
return retval;
}
break;
}
return 0;
} /* End of _libaroma_ctl_list_scroll_message */
/*
* Function : _libaroma_ctl_list_message
* Return Value: dword
* Descriptions: message handler
*/
dword _libaroma_ctl_list_message(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_SCROLL_CLIENTP client,
LIBAROMA_MSGP msg,
int x, int y){
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
dword res=0;
/* handle the message */
libaroma_mutex_lock(mi->imutex);
switch(msg->msg){
case LIBAROMA_CTL_SCROLL_MSG:{
res=_libaroma_ctl_list_scroll_message(
ctl, client, mi, msg->x, msg->y, x, y
);
}
break;
}
libaroma_mutex_unlock(mi->imutex);
return res;
} /* End of _libaroma_ctl_list_message */
/*
* Function : _libaroma_ctl_list_destroy
* Return Value: void
* Descriptions: destroy scroll list client
*/
void _libaroma_ctl_list_destroy(
LIBAROMA_CONTROLP ctl, LIBAROMA_CTL_SCROLL_CLIENTP client){
if (client->handler!=&_libaroma_ctl_list_handler){
return;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
/* cleanup items */
LIBAROMA_CTL_LIST_ITEMP f = mi->first;
while(f){
LIBAROMA_CTL_LIST_ITEMP p = f;
f = p->next;
/* destroy */
if (p->handler->destroy!=NULL){
p->handler->destroy(ctl,p);
}
_libaroma_ctl_list_free_state(p);
free(p);
}
if (mi->threadn>0){
free(mi->threads);
}
/* free internal data */
libaroma_mutex_free(mi->imutex);
libaroma_mutex_free(mi->mutex);
free(mi);
client->internal=NULL;
client->handler=NULL;
} /* End of _libaroma_ctl_list_destroy */
/*
* Function : libaroma_ctl_list
* Return Value: LIBAROMA_CONTROLP
* Descriptions: create list scroll control
*/
LIBAROMA_CONTROLP libaroma_ctl_list(
LIBAROMA_WINDOWP win, word id,
int x, int y, int w, int h,
int horizontal_padding,
int vertical_padding,
word bg_color, byte flags
){
/* allocating internal data */
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP)
calloc(sizeof(LIBAROMA_CTL_LIST),1);
if (!mi){
ALOGW("libaroma_ctl_list cannot allocating memory for list control");
return NULL;
}
mi->vpad = libaroma_window_measure_point(vertical_padding);
mi->hpad = libaroma_window_measure_point(horizontal_padding);
mi->h = mi->vpad*2;
mi->flags = flags;
libaroma_mutex_init(mi->mutex);
libaroma_mutex_init(mi->imutex);
/* create scroll control */
LIBAROMA_CONTROLP ctl = libaroma_ctl_scroll(
win, id, x, y, w, h, bg_color, flags
);
/* set scroll client */
libaroma_ctl_scroll_set_client(
ctl,
(voidp) mi,
&_libaroma_ctl_list_handler
);
/* set initial height */
libaroma_ctl_scroll_set_height(ctl, mi->h);
return ctl;
} /* End of libaroma_ctl_list */
/*
* Function : __libaroma_ctl_list_repos_next_items
* Return Value: byte
* Descriptions: reposition next items
*/
byte __libaroma_ctl_list_repos_next_items(LIBAROMA_CTL_LIST_ITEMP first,
int y){
LIBAROMA_CTL_LIST_ITEMP f=first;
while(f){
f->y=y;
y+=f->h;
f = f->next;
}
return 1;
} /* End of __libaroma_ctl_list_repos_next_items */
/*
* Function : libaroma_ctl_list_getpos
* Return Value: LIBAROMA_CTL_LIST_TOUCHPOSP
* Descriptions: get touch positions
*/
LIBAROMA_CTL_LIST_TOUCHPOSP libaroma_ctl_list_getpos(LIBAROMA_CONTROLP ctl){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return NULL;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return NULL;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
return &mi->pos;
} /* End of libaroma_ctl_list_getpos */
/*
* Function : libaroma_ctl_list_get_item_count
* Return Value : int
* Descriptions : get listitem's item count
*/
int libaroma_ctl_list_get_item_count(
LIBAROMA_CONTROLP ctl){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (!(mi->itemn)){
return 0;
}
return mi->itemn;
}
/*
* Function : libaroma_ctl_list_get_touched_item
* Return Value : LIBAROMA_CTL_LIST_ITEMP
* Descriptions : get touched item
*/
LIBAROMA_CTL_LIST_ITEMP libaroma_ctl_list_get_touched_item(
LIBAROMA_CONTROLP ctl){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return NULL;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return NULL;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (!(mi->touched)){
return NULL;
}
return mi->touched;
}
/*
* Function : libaroma_ctl_list_get_focused_item
* Return Value : LIBAROMA_CTL_LIST_ITEMP
* Descriptions : get focused item
*/
LIBAROMA_CTL_LIST_ITEMP libaroma_ctl_list_get_focused_item(
LIBAROMA_CONTROLP ctl){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return NULL;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return NULL;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (!(mi->focused)){
return NULL;
}
return mi->focused;
}
/*
* Function : libaroma_ctl_list_get_item_internal
* Return Value: LIBAROMA_CTL_LIST_ITEMP
* Descriptions: get item at index or id
*/
LIBAROMA_CTL_LIST_ITEMP libaroma_ctl_list_get_item_internal(
LIBAROMA_CONTROLP ctl, int index, byte find_id
){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return NULL;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return NULL;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (!find_id){
if (index==-1){
return mi->last;
}
else if (index==0){
return mi->first;
}
}
int curr_index = 0;
libaroma_mutex_lock(mi->imutex);
LIBAROMA_CTL_LIST_ITEMP f = mi->first;
if (f){
while(f){
if (((!find_id)&&(curr_index==index))||((find_id)&&(f->id==index))) {
libaroma_mutex_unlock(mi->imutex);
return f;
}
f = f->next;
curr_index++;
}
}
libaroma_mutex_unlock(mi->imutex);
/* not found */
return NULL;
} /* End of libaroma_ctl_list_get_item_internal */
/*
* Function : libaroma_ctl_list_del_itemp_internal
* Return Value: byte
* Descriptions: del item from list
*/
byte libaroma_ctl_list_del_itemp_internal(
LIBAROMA_CONTROLP ctl, LIBAROMA_CTL_LIST_ITEMP f
){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
libaroma_mutex_lock(mi->imutex);
libaroma_mutex_lock(mi->mutex);
if (f){
if ((f==mi->first)&&(f==mi->last)){
mi->first=mi->last=NULL;
}
else if (f==mi->first){
mi->first = f->next;
mi->first->prev=NULL;
__libaroma_ctl_list_repos_next_items(
mi->first,
f->y
);
}
else if (f==mi->last){
mi->last=f->prev;
mi->last->next=NULL;
}
else{
f->prev->next = f->next;
f->next->prev = f->prev;
__libaroma_ctl_list_repos_next_items(
f->next,
f->next->prev->y+f->next->prev->h
);
}
mi->itemn--;
mi->h-=f->h;
if (f->handler->destroy!=NULL){
f->handler->destroy(ctl,f);
}
_libaroma_ctl_list_free_state(f);
__libaroma_ctl_list_item_unreg_thread(ctl, f);
if (mi->touched==f){
mi->touched=NULL;
}
free(f);
libaroma_mutex_unlock(mi->mutex);
libaroma_mutex_unlock(mi->imutex);
libaroma_ctl_scroll_request_height(ctl, mi->h);
return 1;
}
libaroma_mutex_unlock(mi->mutex);
libaroma_mutex_unlock(mi->imutex);
return 0;
} /* End of libaroma_ctl_list_del_itemp_internal */
/*
* Function : libaroma_ctl_list_del_item_internal
* Return Value: byte
* Descriptions: del list item by id/index
*/
byte libaroma_ctl_list_del_item_internal(
LIBAROMA_CONTROLP ctl, int index, byte find_id
){
return
libaroma_ctl_list_del_itemp_internal(
ctl,
libaroma_ctl_list_get_item_internal(
ctl, index, find_id
)
);
} /* End of libaroma_ctl_list_del_item_internal */
/*
* Function : libaroma_ctl_list_is_valid
* Return Value: byte
* Descriptions: check control, if it was valid list control
*/
byte libaroma_ctl_list_is_valid(LIBAROMA_CONTROLP ctl){
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
return 1;
} /* End of libaroma_ctl_list_is_valid */
/*
* Function : libaroma_ctl_list_item_setheight
* Return Value: byte
* Descriptions: update item height
*/
byte libaroma_ctl_list_item_setheight(
LIBAROMA_CONTROLP ctl,LIBAROMA_CTL_LIST_ITEMP item, int h){
if (!item){
return 0;
}
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
if (item->h!=h){
mi->h-=item->h;
item->h=h;
mi->h+=item->h;
__libaroma_ctl_list_repos_next_items(item,item->y);
libaroma_ctl_scroll_request_height(ctl, mi->h);
return 1;
}
return 2;
} /* End of libaroma_ctl_list_item_setheight */
/*
* Function : libaroma_ctl_list_item_position
* Return Value: byte
* Descriptions: get item position
*/
byte libaroma_ctl_list_item_position(
LIBAROMA_CONTROLP ctl,LIBAROMA_CTL_LIST_ITEMP item,
LIBAROMA_RECTP rect, byte absolute){
if (!rect){
return 0;
}
if (!item){
return 0;
}
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
int x=0;
int y=0;
if (absolute){
libaroma_window_calculate_pos_abs(NULL,ctl,&x,&y);
}
else{
libaroma_window_calculate_pos(NULL,ctl,&x,&y);
}
int ctl_y = libaroma_ctl_scroll_get_scroll(ctl,NULL);
rect->x=x;
rect->y=item->y-(y+ctl_y+mi->vpad);
rect->w=ctl->w-(mi->hpad*2);
rect->h=item->h;
return 1;
} /* End of libaroma_ctl_list_item_position */
/*
* Function : libaroma_ctl_list_scroll_to_item
* Return Value: byte
* Descriptions: focus item to scroll
*/
byte libaroma_ctl_list_scroll_to_item(
LIBAROMA_CONTROLP ctl,
LIBAROMA_CTL_LIST_ITEMP item,
byte smooth
){
if (!item){
return 0;
}
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return 0;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return 0;
}
/*LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;*/
int sel_cy = item->y + (item->h>>1);
int draw_y = (ctl->h>>1) - sel_cy;
draw_y = (draw_y<0)?(0-draw_y):0;
if (smooth){
libaroma_ctl_scroll_request_pos(ctl,draw_y);
}
else{
libaroma_ctl_scroll_set_pos(ctl,draw_y);
}
return 1;
} /* End of libaroma_ctl_list_scroll_to_item */
/*
* Function : libaroma_ctl_list_add_item_internal
* Return Value: LIBAROMA_CTL_LIST_ITEMP
* Descriptions: add item internally
*/
LIBAROMA_CTL_LIST_ITEMP libaroma_ctl_list_add_item_internal(
LIBAROMA_CONTROLP ctl,
int id,
int height,
word flags,
voidp internal,
LIBAROMA_CTL_LIST_ITEM_HANDLERP handler,
int at_index){
if (!handler){
return NULL;
}
LIBAROMA_CTL_SCROLL_CLIENTP client = libaroma_ctl_scroll_get_client(ctl);
if (!client){
return NULL;
}
if (client->handler!=&_libaroma_ctl_list_handler){
return NULL;
}
LIBAROMA_CTL_LISTP mi = (LIBAROMA_CTL_LISTP) client->internal;
LIBAROMA_CTL_LIST_ITEMP item = (LIBAROMA_CTL_LIST_ITEMP)
calloc(sizeof(LIBAROMA_CTL_LIST_ITEM),1);
if (item==NULL){
ALOGW("list_add_item_internal cannot allocating memory for item");
return NULL;
}
libaroma_mutex_lock(mi->imutex);
libaroma_mutex_lock(mi->mutex);
item->y=0;
item->h=height;
item->id=id;
item->flags=flags;
item->handler=handler;
item->internal=internal;
if (mi->last==NULL){
mi->first=mi->last=item;
item->y=mi->vpad;
mi->h+=item->h;
}
else if (at_index<0){
/* at last */
item->prev=mi->last;
mi->last->next = item;
item->y = mi->last->y + mi->last->h;
mi->last = item;
mi->h+=item->h;
}
else if (at_index==0){
/* at first */
item->next = mi->first;
item->y=mi->vpad;
mi->first = item;
mi->h+=item->h;
__libaroma_ctl_list_repos_next_items(item,mi->vpad);
}
else{
int curr_index = 0;
LIBAROMA_CTL_LIST_ITEMP f = mi->first;
if (f){
while(f){
if (curr_index==at_index){
item->prev = f;
item->next = f->next;
__libaroma_ctl_list_repos_next_items(item,f->y+f->h);
f->next = item;
if (item->next==NULL){
mi->last = item;
}
mi->h+=item->h;
break;
}
f = f->next;
if (!f){
curr_index=-1;
break;
}
curr_index++;
}
}
else{
curr_index=-1;
}
if (curr_index<0){
/* add in last */
item->prev=mi->last;
mi->last->next = item;
item->y = mi->last->y + mi->last->h;
mi->last = item;
mi->h+=item->h;
}
}
mi->itemn++;
if (flags&LIBAROMA_CTL_LIST_ITEM_REGISTER_THREAD){
__libaroma_ctl_list_item_reg_thread(ctl,item);
}
libaroma_mutex_unlock(mi->mutex);
libaroma_mutex_unlock(mi->imutex);
/* set current height */
libaroma_ctl_scroll_request_height(ctl, mi->h);
return item;
} /* End of libaroma_ctl_list_add_item_internal */
/*
* Function : libaroma_listitem_nonitem
* Return Value: byte
* Descriptions: is non item
*/
byte libaroma_listitem_nonitem(LIBAROMA_CTL_LIST_ITEMP item){
if (!item){
return 1;
}
if (libaroma_listitem_isdivider(item)){
return 1;
}
return libaroma_listitem_iscaption(item);
} /* End of libaroma_listitem_nonitem */
#endif /* __libaroma_ctl_list_c__ */
|
opencl_strip_fmt_plug.c | /* STRIP Password Manager cracker patch for JtR. Hacked together during
* September of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> */
#ifdef HAVE_OPENCL
#if FMT_EXTERNS_H
extern struct fmt_main fmt_opencl_strip;
#elif FMT_REGISTERS_H
john_register_one(&fmt_opencl_strip);
#else
#include <string.h>
#include "aes.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include "arch.h"
#include "formats.h"
#include "options.h"
#include "common.h"
#include "stdint.h"
#include "misc.h"
#include "common-opencl.h"
#define FORMAT_LABEL "strip-opencl"
#define FORMAT_NAME "STRIP Password Manager"
#define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL"
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define BINARY_SIZE 0
#define PLAINTEXT_LENGTH 64
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 1
#define SALT_ALIGN 4
#define ITERATIONS 4000
#define FILE_HEADER_SZ 16
#define SQLITE_FILE_HEADER "SQLite format 3"
#define HMAC_SALT_MASK 0x3a
#define FAST_PBKDF2_ITER 2
#define SQLITE_MAX_PAGE_SIZE 65536
static struct fmt_tests strip_tests[] = {
/* test vector created by STRIP for Windows */
{"$strip$*66cd7a4ff7716f7b86cf587ce18eb39518e096eb152615ada8d007d9f035c20c711e62cbde96d8c3aad2a4658497a6119addc97ed3c970580cd666f301c63ce041a1748ee5c3861ada3cd6ee75b5d68891f731b3c2e3294b08e10ce3c23c2bfac158f8c45d0332791f64d1e3ad55e936d17a42fef5228e713b8188050c9a61c7f026af6203172cf2fc54c8b439e2260d7a00a4156713f92f8466de5c05cd8701e0d3d9cb3f392ae918e6900d5363886d4e1ed7e90da76b180ef9555c1cd358f6d1ee3755a208fee4d5aa1c776a0888200b21a3da6614d5fe2303e78c09563d862d19deecdc9f0ec7fbc015689a74f4eb477d9f22298b1b3f866ca4cb772d74821a1f8d03fd5fd0d020ffd41dd449b431ddf3bbfba3399311d9827be428202ee56e2c2a4e91f3415b4282c691f16cd447cf877b576ab963ea4ea3dc7d8c433febdc36607fd2372c4165abb59e3e75c28142f1f2575ecca6d97a9f782c3410151f8bbcbc65a42fdc59fdc4ecd8214a2bbd3a4562fac21c48f7fc69a4ecbcf664b4e435d7734fde5494e4d80019a0302e22565ed6a49b29cecf81077fd92f0105d18a421e04ee0deaca6389214abc7182db7003da7e267816531010b236eadfea20509718ff743ed5ad2828b6501dd84a371feed26f0514bbda69118a69048ebb71e3e2c54fb918422f1320724a353fe8d81a562197454d2c67443be8a4008a756aec0998386a5fd48e379befe966b42dfa6684ff049a61b51de5f874a12ab7d9ab33dc84738e036e294c22a07bebcc95be9999ab988a1fa1c944ab95be970045accb661249be8cc34fcc0680cb1aff8dfee21f586c571b1d09bf370c6fc131418201e0414acb2e4005b0b6fda1f3d73b7865823a008d1d3f45492a960dbdd6331d78d9e2e6a368f08ee3456b6d78df1d5630f825c536fff60bad23fb164d151d80a03b0c78edbfdee5c7183d7527e289428cf554ad05c9d75011f6b233744f12cd85fbb62f5d1ae22f43946f24a483a64377bf3fa16bf32cea1ab4363ef36206a5989e97ff847e5d645791571b9ecd1db194119b7663897b9175dd9cc123bcc7192eaf56d4a2779c502700e88c5c20b962943084bcdf024dc4f19ca649a860bdbd8f8f9b4a9d03027ae80f4a3168fc030859acb08a871950b024d27306cdc1a408b2b3799bb8c1f4b6ac3593aab42c962c979cd9e6f59d029f8d392315830cfcf4066bf03e0fc5c0f3630e9c796ddb38f51a2992b0a61d6ef115cb34d36c7d94b6c9d49dfe8d064d92b483f12c14fa10bf1170a575e4571836cef0a1fbf9f8b6968abda5e964bb16fd62fde1d1df0f5ee9c68ce568014f46f1717b6cd948b0da9a6f4128da338960dbbcbc9c9c3b486859c06e5e2338db3458646054ccd59bb940c7fc60cda34f633c26dde83bb717b75fefcbd09163f147d59a6524752a47cd94", "openwall"},
/* test vector created by STRIP Password Manager (for Android) */
{"$strip$*78adb0052203efa1bd1b02cac098cc9af1bf7e84ee2eaebaaba156bdcfe729ab12ee7ba8a84e79d11dbd67eee82bcb24be99dbd5db7f4c3a62f188ce4b48edf4ebf6cbf5a5869a61f83fbdb3cb4bf79b3c2c898f422d71eab31afdf3a8d4e97204dedbe7bd8b5e4c891f4880ca917c8b2f67ca06035e7f8db1fae91c45db6a08adf96ec5ddcb9e60b648acf883a7550ea5b67e2d27623e8de315f29cba48b8b1d1bde62283615ab88293b29ad73ae404a42b13e35a95770a504d81e335c00328a6290e411fa2708a697fab7c2d17ff5d0a3fe508118bb43c3d5e72ef563e0ffd337f559085a1373651ca2b8444f4437d8ac0c19aa0a24b248d1d283062afbc3b4ccc9b1861f59518eba771f1d9707affe0222ff946da7c014265ab4ba1f6417dd22d92e4adf5b7e462588f0a42e061a3dad041cbb312d8862aed3cf490df50b710a695517b0c8771a01f82db09231d392d825f5667012e349d2ed787edf8448bbb1ff548bee3a33392cd209e8b6c1de8202f6527d354c3858b5e93790c4807a8967b4c0321ed3a1d09280921650ac33308bd04f35fb72d12ff64a05300053358c5d018a62841290f600f7df0a7371b6fac9b41133e2509cb90f774d02e7202185b9641d063ed38535afb81590bfd5ad9a90107e4ff6d097ac8f35435f307a727f5021f190fc157956414bfce4818a1e5c6af187485683498dcc1d56c074c534a99125c6cfbf5242087c6b0ae10971b0ff6114a93616e1a346a22fcac4c8f6e5c4a19f049bbc7a02d2a31d39548f12440c36dbb253299a11b630e8fd88e7bfe58545d60dce5e8566a0a190d816cb775bd859b8623a7b076bce82c52e9cff6a2d221f9d3fd888ac30c7e3000ba8ed326881ffe911e27bb8982b56caa9a12065721269976517d2862e4a486b7ed143ee42c6566bba04c41c3371220f4843f26e328c33a5fb8450dadc466202ffc5c49cc95827916771e49e0602c3f8468537a81cf2fa1db34c090fccab6254436c05657cf29c3c415bb22a42adeac7870858bf96039b81c42c3d772509fdbe9a94eaf99ee9c59bac3ea97da31e9feac14ed53a0af5c5ebd2e81e40a5140da4f8a44048d5f414b0ba9bfb8024c7abaf5346fde6368162a045d1196f81d55ed746cc6cbd7a7c9cdbfa392279169626437da15a62730c2990772e106a5b84a60edaa6c5b8030e1840aa6361f39a12121a1e33b9e63fb2867d6241de1fb6e2cd1bd9a78c7122258d052ea53a4bff4e097ed49fc17b9ec196780f4c6506e74a5abb10c2545e6f7608d2eefad179d54ad31034576be517affeb3964c65562538dd6ea7566a52c75e4df593895539609a44097cb6d31f438e8f7717ce2bf777c76c22d60b15affeb89f08084e8f316be3f4aefa4fba8ec2cc1dc845c7affbc0ce5ebccdbfde5ebab080a285f02bdfb76c6dbd243e5ee1e5d", "p@$$w0rD"},
{NULL}
};
typedef struct {
uint32_t length;
uint8_t v[PLAINTEXT_LENGTH];
} strip_password;
typedef struct {
uint32_t v[32/4];
} strip_hash;
typedef struct {
int iterations;
int outlen;
uint8_t length;
uint8_t salt[20];
} strip_salt;
static int *cracked;
static int any_cracked;
static struct custom_salt {
unsigned char salt[16];
unsigned char data[1024];
} *cur_salt;
static cl_int cl_error;
static strip_password *inbuffer;
static strip_hash *outbuffer;
static strip_salt currentsalt;
static cl_mem mem_in, mem_out, mem_setting;
static struct fmt_main *self;
static size_t insize, outsize, settingsize, cracked_size;
#define STEP 0
#define SEED 256
// This file contains auto-tuning routine(s). Has to be included after formats definitions.
#include "opencl-autotune.h"
#include "memdbg.h"
static const char * warn[] = {
"xfer: ", ", crypt: ", ", xfer: "
};
/* ------- Helper functions ------- */
static size_t get_task_max_work_group_size()
{
return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel);
}
static void create_clobj(size_t gws, struct fmt_main *self)
{
insize = sizeof(strip_password) * gws;
outsize = sizeof(strip_hash) * gws;
settingsize = sizeof(strip_salt);
cracked_size = sizeof(*cracked) * gws;
inbuffer = mem_calloc(1, insize);
outbuffer = mem_alloc(outsize);
cracked = mem_calloc(1, cracked_size);
/// Allocate memory
mem_in =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL,
&cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem in");
mem_setting =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize,
NULL, &cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem setting");
mem_out =
clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL,
&cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem out");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in),
&mem_in), "Error while setting mem_in kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out),
&mem_out), "Error while setting mem_out kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting),
&mem_setting), "Error while setting mem_salt kernel argument");
}
static void release_clobj(void)
{
if (inbuffer) {
HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in");
HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting");
HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out");
MEM_FREE(inbuffer);
MEM_FREE(outbuffer);
MEM_FREE(cracked);
}
}
static void done(void)
{
if (autotuned) {
release_clobj();
HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel");
HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program");
autotuned--;
}
}
static void init(struct fmt_main *_self)
{
self = _self;
opencl_prepare_dev(gpu_id);
}
static void reset(struct db_main *db)
{
if (!autotuned) {
char build_opts[64];
snprintf(build_opts, sizeof(build_opts),
"-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d",
PLAINTEXT_LENGTH,
(int)sizeof(currentsalt.salt),
(int)sizeof(outbuffer->v));
opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl",
gpu_id, build_opts);
crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error);
HANDLE_CLERROR(cl_error, "Error creating kernel");
// Initialize openCL tuning (library) for this format.
opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self,
create_clobj, release_clobj,
sizeof(strip_password), 0, db);
// Auto tune execution from shared/included code.
autotune_run(self, 1, 0, 1000);
}
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy;
char *keeptr;
char *p;
if (strncmp(ciphertext, "$strip$*", 8))
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += 7+1; /* skip over "$strip$" and first '*' */
if ((p = strtokm(ctcopy, "*")) == NULL) /* salt + data */
goto err;
if (hexlenl(p) != 2048)
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *p;
int i;
static struct custom_salt *cs;
if (!cs)
cs = mem_alloc_tiny(sizeof(struct custom_salt), 4);
memset(cs, 0, sizeof(struct custom_salt));
ctcopy += 7+1; /* skip over "$strip$" and first '*' */
p = strtokm(ctcopy, "*");
for (i = 0; i < 16; i++)
cs->salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
for (; i < 1024; i++)
cs->data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
return (void *)cs;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
memcpy((char*)currentsalt.salt, cur_salt->salt, 16);
currentsalt.length = 16;
currentsalt.iterations = ITERATIONS;
currentsalt.outlen = 32;
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting,
CL_FALSE, 0, settingsize, ¤tsalt, 0, NULL, NULL),
"Copy salt to gpu");
}
#undef set_key
static void set_key(char *key, int index)
{
uint8_t length = strlen(key);
if (length > PLAINTEXT_LENGTH)
length = PLAINTEXT_LENGTH;
inbuffer[index].length = length;
memcpy(inbuffer[index].v, key, length);
}
static char *get_key(int index)
{
static char ret[PLAINTEXT_LENGTH + 1];
uint8_t length = inbuffer[index].length;
memcpy(ret, inbuffer[index].v, length);
ret[length] = '\0';
return ret;
}
/* verify validity of page */
static int verify_page(unsigned char *page1)
{
uint32_t pageSize;
uint32_t usableSize;
if (memcmp(page1, SQLITE_FILE_HEADER, 16) != 0) {
return -1;
}
if (page1[19] > 2) {
return -1;
}
if (memcmp(&page1[21], "\100\040\040", 3) != 0) {
return -1;
}
pageSize = (page1[16] << 8) | (page1[17] << 16);
if (((pageSize - 1) & pageSize) != 0 || pageSize > SQLITE_MAX_PAGE_SIZE || pageSize <= 256) {
return -1;
}
if ((pageSize & 7) != 0) {
return -1;
}
usableSize = pageSize - page1[20];
if (usableSize < 480) {
return -1;
}
return 0;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index;
size_t *lws = local_work_size ? &local_work_size : NULL;
global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size);
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
/// Copy data to gpu
BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0,
insize, inbuffer, 0, NULL, multi_profilingEvent[0]),
"Copy data to gpu");
/// Run kernel
BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1,
NULL, &global_work_size, lws, 0, NULL,
multi_profilingEvent[1]), "Run kernel");
/// Read the result back
BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0,
outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back");
if (ocl_autotune_running)
return count;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
{
unsigned char master[32];
unsigned char output[1024];
unsigned char *iv_in;
unsigned char iv_out[16];
int size;
int page_sz = 1008; /* 1024 - strlen(SQLITE_FILE_HEADER) */
int reserve_sz = 16; /* for HMAC off case */
AES_KEY akey;
memcpy(master, outbuffer[index].v, 32);
memcpy(output, SQLITE_FILE_HEADER, FILE_HEADER_SZ);
size = page_sz - reserve_sz;
iv_in = cur_salt->data + size + 16;
memcpy(iv_out, iv_in, 16);
if (AES_set_decrypt_key(master, 256, &akey) < 0) {
fprintf(stderr, "AES_set_decrypt_key failed!\n");
}
/* decrypting 24 bytes is enough */
AES_cbc_encrypt(cur_salt->data + 16, output + 16, 24, &akey, iv_out, AES_DECRYPT);
if (verify_page(output) == 0)
{
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
struct fmt_main fmt_opencl_strip = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT,
{ NULL },
strip_tests
}, {
init,
done,
reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
#endif /* HAVE_OPENCL */
|
boundary_mask_l1_mex.c | #include <inttypes.h>
#include <omp.h>
#include "mex.h"
#include "boundary_mask_l1_mex.h"
void boundary_mask_l1(uint8_t *B,
const uint8_t *G, const size_t *sz, const uint8_t l1);
#ifdef BOUNDARY_MASK_L1_MEX
void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if ((nrhs != 3) || (nlhs > 1)) {
mexErrMsgTxt("Usage: boundary_mask_mex(B, G, l1);");
}
uint8_t *B = (uint8_t *)mxGetData(prhs[0]);
const uint8_t *G = (const uint8_t *)mxGetData(prhs[1]);
const uint8_t l1 = (const uint8_t)mxGetScalar(prhs[2]);
const size_t *sz = (const size_t *)mxGetDimensions(prhs[0]);
boundary_mask_l1(B, G, sz, l1);
if (nlhs == 1) {
plhs[0] = mxCreateDoubleScalar(1.0);
}
return;
}
#endif
void
mx_boundary_mask_l1(mxArray *mxB, const mxArray *mxG, uint8_t l1)
{
uint8_t *B = (uint8_t *)mxGetData(mxB);
const uint8_t *G = (const uint8_t *)mxGetData(mxG);
const size_t *sz = (const size_t *)mxGetDimensions(mxG);
boundary_mask_l1(B, G, sz, l1);
return;
}
void
boundary_mask_l1(uint8_t *B,
const uint8_t *G, const size_t *sz, const uint8_t l1)
{
size_t i, j, k;
size_t l;
const size_t nx = sz[0];
const size_t ny = sz[1];
const size_t nz = sz[2];
const size_t nxny = nx*ny;
const size_t nxnynz = nx*ny*nz;
size_t NX = nx-1;
size_t NY = nx*(ny-1);
size_t NZ = nxny*(nz-1);
uint8_t *GL = (uint8_t *)calloc(nx*ny*nz, sizeof(*G));
#pragma omp parallel for private(i,j,k,l) schedule(static) \
if(nxny*nz > 32*32*32)
for(k = 0; k < nxnynz; k += nxny) {
for(j = 0; j < nxny; j += nx) {
l = j + k;
for(i = 0; i < nx; ++i, ++l) {
if ((i == 0) || (j == 0) || (k == 0)
|| (i == NX) || (j == NY) || (k == NZ)) {
B[l] = GL[l] = G[l];
} else {
B[l] = GL[l] = G[l] &&
!(G[l-1] && G[l+1]
&& G[l-nx] && G[l+nx]
&& G[l-nxny] && G[l+nxny]);
}
}
}
}
for(size_t L1 = 1; L1 < l1; ++L1) {
#pragma omp parallel for private(i,j,k,l) schedule(static) \
if(nxny*nz > 32*32*32)
for(k = L1*nxny; k < nxnynz-L1*nxny; k += nxny) {
for(j = L1*nx; j < nxny-L1*nx; j += nx) {
l = L1 + j + k;
for(i = L1; i < nx-L1; ++i, ++l) {
if (G[l] && !GL[l] &&
((GL[l-1] == L1) || (GL[l+1] == L1) ||
(GL[l-nx] == L1) || (GL[l+nx] == L1) ||
(GL[l-nxny] == L1) || (GL[l+nxny] == L1))) {
B[l] = 1;
GL[l] = L1+1;
}
}
}
}
}
if (NULL != GL) {
free(GL);
GL = NULL;
}
return;
}
|
H2Pack_aux_structs.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "H2Pack_config.h"
#include "H2Pack_aux_structs.h"
#include "linalg_lib_wrapper.h"
#include "utils.h"
// ========================== H2P_tree_node ========================== //
// Initialize an H2P_tree_node structure
void H2P_tree_node_init(H2P_tree_node_p *node_, const int dim)
{
const int max_child = 1 << dim;
H2P_tree_node_p node = (H2P_tree_node_p) malloc(sizeof(struct H2P_tree_node));
ASSERT_PRINTF(node != NULL, "Failed to allocate H2P_tree_node structure\n");
node->children = (void**) malloc(sizeof(H2P_tree_node_p) * max_child);
node->enbox = (DTYPE*) malloc(sizeof(DTYPE) * dim * 2);
ASSERT_PRINTF(
node->children != NULL && node->enbox != NULL,
"Failed to allocate arrays in an H2P_tree_node structure\n"
);
for (int i = 0; i < max_child; i++)
node->children[i] = NULL;
*node_ = node;
}
// Recursively destroy an H2P_tree_node node and its children nodes
void H2P_tree_node_destroy(H2P_tree_node_p *node_)
{
H2P_tree_node_p node = *node_;
if (node == NULL) return;
for (int i = 0; i < node->n_child; i++)
{
H2P_tree_node_p child_i = (H2P_tree_node_p) node->children[i];
if (child_i != NULL) H2P_tree_node_destroy(&child_i);
free(child_i);
}
free(node->children);
free(node->enbox);
free(node);
*node_ = NULL;
}
// ------------------------------------------------------------------- //
// =========================== H2P_int_vec =========================== //
// Initialize an H2P_int_vec structure
void H2P_int_vec_init(H2P_int_vec_p *int_vec_, int capacity)
{
if (capacity < 0) capacity = 128;
H2P_int_vec_p int_vec = (H2P_int_vec_p) malloc(sizeof(struct H2P_int_vec));
ASSERT_PRINTF(int_vec != NULL, "Failed to allocate H2P_int_vec structure\n");
int_vec->data = (int*) malloc(sizeof(int) * capacity);
ASSERT_PRINTF(int_vec->data != NULL, "Failed to allocate integer vector of size %d\n", capacity);
int_vec->capacity = capacity;
int_vec->length = 0;
*int_vec_ = int_vec;
}
// Destroy an H2P_int_vec structure
void H2P_int_vec_destroy(H2P_int_vec_p *int_vec_)
{
H2P_int_vec_p int_vec = *int_vec_;
if (int_vec == NULL) return;
free(int_vec->data);
free(int_vec);
*int_vec_ = NULL;
}
// Free the memory used by an H2P_int_vec structure and reset its capacity to 128
void H2P_int_vec_reset(H2P_int_vec_p int_vec)
{
if (int_vec == NULL) return;
free(int_vec->data);
int_vec->capacity = 128;
int_vec->length = 0;
int_vec->data = (int*) malloc(sizeof(int) * int_vec->capacity);
ASSERT_PRINTF(int_vec->data != NULL, "Failed to allocate integer vector of size %d\n", int_vec->capacity);
}
// Concatenate values in an H2P_int_vec to another H2P_int_vec
void H2P_int_vec_concatenate(H2P_int_vec_p dst_vec, H2P_int_vec_p src_vec)
{
int s_len = src_vec->length;
int d_len = dst_vec->length;
int new_length = s_len + d_len;
if (new_length > dst_vec->capacity)
H2P_int_vec_set_capacity(dst_vec, new_length);
memcpy(dst_vec->data + d_len, src_vec->data, sizeof(int) * s_len);
dst_vec->length = new_length;
}
// Gather elements in an H2P_int_vec to another H2P_int_vec
void H2P_int_vec_gather(H2P_int_vec_p src_vec, H2P_int_vec_p idx, H2P_int_vec_p dst_vec)
{
H2P_int_vec_set_capacity(dst_vec, idx->length);
for (int i = 0; i < idx->length; i++)
dst_vec->data[i] = src_vec->data[idx->data[i]];
dst_vec->length = idx->length;
}
// ------------------------------------------------------------------- //
// ======================= H2P_partition_vars ======================== //
// Initialize an H2P_partition_vars structure
void H2P_partition_vars_init(H2P_partition_vars_p *part_vars_)
{
H2P_partition_vars_p part_vars = (H2P_partition_vars_p) malloc(sizeof(struct H2P_partition_vars));
H2P_int_vec_init(&part_vars->r_adm_pairs, 10240);
H2P_int_vec_init(&part_vars->r_inadm_pairs, 10240);
part_vars->curr_po_idx = 0;
part_vars->max_level = 0;
part_vars->n_leaf_node = 0;
*part_vars_ = part_vars;
}
// Destroy an H2P_partition_vars structure
void H2P_partition_vars_destroy(H2P_partition_vars_p *part_vars_)
{
H2P_partition_vars_p part_vars = *part_vars_;
if (part_vars == NULL) return;
H2P_int_vec_destroy(&part_vars->r_adm_pairs);
H2P_int_vec_destroy(&part_vars->r_inadm_pairs);
free(part_vars->r_adm_pairs);
free(part_vars->r_inadm_pairs);
free(part_vars);
*part_vars_ = NULL;
}
// ------------------------------------------------------------------- //
// ========================== H2P_dense_mat ========================== //
// Initialize an H2P_dense_mat structure
void H2P_dense_mat_init(H2P_dense_mat_p *mat_, const int nrow, const int ncol)
{
H2P_dense_mat_p mat = (H2P_dense_mat_p) malloc(sizeof(struct H2P_dense_mat));
ASSERT_PRINTF(mat != NULL, "Failed to allocate H2P_dense_mat structure\n");
mat->nrow = MAX(0, nrow);
mat->ncol = MAX(0, ncol);
mat->ld = mat->ncol;
mat->size = mat->nrow * mat->ncol;
if (mat->size > 0)
{
mat->data = malloc_aligned(sizeof(DTYPE) * mat->size, 64);
ASSERT_PRINTF(mat->data != NULL, "Failed to allocate %d * %d dense matrix\n", nrow, ncol);
} else {
mat->data = NULL;
}
*mat_ = mat;
}
// Destroy an H2P_dense_mat structure
void H2P_dense_mat_destroy(H2P_dense_mat_p *mat_)
{
H2P_dense_mat_p mat = *mat_;
if (mat == NULL) return;
free_aligned(mat->data);
free(mat);
*mat_ = NULL;
}
// Reset an H2P_dense_mat structure to its default size (0-by-0) and release the memory
void H2P_dense_mat_reset(H2P_dense_mat_p mat)
{
if (mat == NULL) return;
free_aligned(mat->data);
mat->data = NULL;
mat->size = 0;
mat->nrow = 0;
mat->ncol = 0;
mat->ld = 0;
}
// Copy the data in an H2P_dense_mat structure to another H2P_dense_mat structure
void H2P_dense_mat_copy(H2P_dense_mat_p src_mat, H2P_dense_mat_p dst_mat)
{
H2P_dense_mat_resize(dst_mat, src_mat->nrow, src_mat->ncol);
copy_matrix_block(sizeof(DTYPE), src_mat->nrow, src_mat->ncol, src_mat->data, src_mat->ld, dst_mat->data, dst_mat->ld);
}
// Permute rows in an H2P_dense_mat structure
void H2P_dense_mat_permute_rows(H2P_dense_mat_p mat, const int *p)
{
DTYPE *mat_dst = (DTYPE*) malloc_aligned(sizeof(DTYPE) * mat->nrow * mat->ncol, 64);
ASSERT_PRINTF(mat_dst != NULL, "Failed to allocate buffer of size %d * %d\n", mat->nrow, mat->ncol);
for (int irow = 0; irow < mat->nrow; irow++)
{
DTYPE *src_row = mat->data + p[irow] * mat->ld;
DTYPE *dst_row = mat_dst + irow * mat->ncol;
memcpy(dst_row, src_row, sizeof(DTYPE) * mat->ncol);
}
free_aligned(mat->data);
mat->ld = mat->ncol;
mat->size = mat->nrow * mat->ncol;
mat->data = mat_dst;
}
// Select rows in an H2P_dense_mat structure
void H2P_dense_mat_select_rows(H2P_dense_mat_p mat, H2P_int_vec_p row_idx)
{
for (int irow = 0; irow < row_idx->length; irow++)
{
DTYPE *src = mat->data + row_idx->data[irow] * mat->ld;
DTYPE *dst = mat->data + irow * mat->ld;
if (src != dst) memcpy(dst, src, sizeof(DTYPE) * mat->ncol);
}
mat->nrow = row_idx->length;
}
// Select columns in an H2P_dense_mat structure
void H2P_dense_mat_select_columns(H2P_dense_mat_p mat, H2P_int_vec_p col_idx)
{
for (int irow = 0; irow < mat->nrow; irow++)
{
DTYPE *mat_row = mat->data + irow * mat->ld;
for (int icol = 0; icol < col_idx->length; icol++)
mat_row[icol] = mat_row[col_idx->data[icol]];
}
mat->ncol = col_idx->length;
for (int irow = 1; irow < mat->nrow; irow++)
{
DTYPE *src = mat->data + irow * mat->ld;
DTYPE *dst = mat->data + irow * mat->ncol;
memmove(dst, src, sizeof(DTYPE) * mat->ncol);
}
mat->ld = mat->ncol;
}
// Normalize columns in an H2P_dense_mat structure
void H2P_dense_mat_normalize_columns(H2P_dense_mat_p mat, H2P_dense_mat_p workbuf)
{
int nrow = mat->nrow, ncol = mat->ncol;
H2P_dense_mat_resize(workbuf, 1, ncol);
DTYPE *inv_2norm = workbuf->data;
#if 0
#pragma omp simd
for (int icol = 0; icol < ncol; icol++)
inv_2norm[icol] = mat->data[icol] * mat->data[icol];
for (int irow = 1; irow < nrow; irow++)
{
DTYPE *mat_row = mat->data + irow * mat->ld;
#pragma omp simd
for (int icol = 0; icol < ncol; icol++)
inv_2norm[icol] += mat_row[icol] * mat_row[icol];
}
#pragma omp simd
for (int icol = 0; icol < ncol; icol++)
inv_2norm[icol] = 1.0 / DSQRT(inv_2norm[icol]);
#endif
// Slower, but more accurate
for (int icol = 0; icol < ncol; icol++)
inv_2norm[icol] = 1.0 / CBLAS_NRM2(nrow, mat->data + icol, ncol);
for (int irow = 0; irow < nrow; irow++)
{
DTYPE *mat_row = mat->data + irow * mat->ld;
#pragma omp simd
for (int icol = 0; icol < ncol; icol++)
mat_row[icol] *= inv_2norm[icol];
}
}
// Perform GEMM C := alpha * op(A) * op(B) + beta * C
void H2P_dense_mat_gemm(
const DTYPE alpha, const DTYPE beta, const int transA, const int transB,
H2P_dense_mat_p A, H2P_dense_mat_p B, H2P_dense_mat_p C
)
{
int M, N, KA, KB;
CBLAS_TRANSPOSE transA_, transB_;
if (transA == 0)
{
transA_ = CblasNoTrans;
M = A->nrow;
KA = A->ncol;
} else {
transA_ = CblasTrans;
M = A->ncol;
KA = A->nrow;
}
if (transB == 0)
{
transB_ = CblasNoTrans;
N = B->ncol;
KB = B->nrow;
} else {
transB_ = CblasTrans;
N = B->nrow;
KB = B->ncol;
}
if (KA != KB)
{
ERROR_PRINTF("GEMM size mismatched: A[%d * %d], B[%d * %d]\n", M, KA, KB, N);
return;
}
if (beta == 0.0 && (C->nrow < M || C->ncol < N)) H2P_dense_mat_resize(C, M, N);
CBLAS_GEMM(
CblasRowMajor, transA_, transB_, M, N, KA,
alpha, A->data, A->ld, B->data, B->ld,
beta, C->data, C->ld
);
}
// Create a block diagonal matrix created by aligning the input matrices along the diagonal
void H2P_dense_mat_blkdiag(H2P_dense_mat_p *mats, H2P_int_vec_p idx, H2P_dense_mat_p new_mat)
{
int nrow = 0, ncol = 0;
for (int i = 0; i < idx->length; i++)
{
H2P_dense_mat_p mat_i = mats[idx->data[i]];
nrow += mat_i->nrow;
ncol += mat_i->ncol;
}
H2P_dense_mat_resize(new_mat, nrow, ncol);
memset(new_mat->data, 0, sizeof(DTYPE) * nrow * ncol);
nrow = 0; ncol = 0;
for (int i = 0; i < idx->length; i++)
{
H2P_dense_mat_p mat_i = mats[idx->data[i]];
int nrow_i = mat_i->nrow;
int ncol_i = mat_i->ncol;
DTYPE *dst = new_mat->data + nrow * new_mat->ld + ncol;
copy_matrix_block(sizeof(DTYPE), nrow_i, ncol_i, mat_i->data, mat_i->ld, dst, new_mat->ld);
nrow += nrow_i;
ncol += ncol_i;
}
}
// Vertically concatenates the input matrices
void H2P_dense_mat_vertcat(H2P_dense_mat_p *mats, H2P_int_vec_p idx, H2P_dense_mat_p new_mat)
{
int nrow = 0, ncol = mats[idx->data[0]]->ncol;
for (int i = 0; i < idx->length; i++)
{
H2P_dense_mat_p mat_i = mats[idx->data[i]];
if (mat_i->ncol != ncol)
{
ERROR_PRINTF("%d-th matrix has %d columns, 1st matrix has %d columns\n", i+1, mat_i->ncol, ncol);
return;
}
nrow += mat_i->nrow;
}
H2P_dense_mat_resize(new_mat, nrow, ncol);
nrow = 0; ncol = 0;
for (int i = 0; i < idx->length; i++)
{
H2P_dense_mat_p mat_i = mats[idx->data[i]];
int nrow_i = mat_i->nrow;
int ncol_i = mat_i->ncol;
DTYPE *dst = new_mat->data + nrow * new_mat->ld;
copy_matrix_block(sizeof(DTYPE), nrow_i, ncol_i, mat_i->data, mat_i->ld, dst, new_mat->ld);
nrow += nrow_i;
}
}
// Horizontally concatenates the input matrices
void H2P_dense_mat_horzcat(H2P_dense_mat_p *mats, H2P_int_vec_p idx, H2P_dense_mat_p new_mat)
{
int nrow = mats[idx->data[0]]->nrow, ncol = 0;
for (int i = 0; i < idx->length; i++)
{
H2P_dense_mat_p mat_i = mats[idx->data[i]];
if (mat_i->nrow != nrow)
{
ERROR_PRINTF("%d-th matrix has %d rows, 1st matrix has %d rows\n", i+1, mat_i->nrow, nrow);
return;
}
ncol += mat_i->ncol;
}
H2P_dense_mat_resize(new_mat, nrow, ncol);
memset(new_mat->data, 0, sizeof(DTYPE) * nrow * ncol);
nrow = 0; ncol = 0;
for (int i = 0; i < idx->length; i++)
{
H2P_dense_mat_p mat_i = mats[idx->data[i]];
int nrow_i = mat_i->nrow;
int ncol_i = mat_i->ncol;
DTYPE *dst = new_mat->data + ncol;
copy_matrix_block(sizeof(DTYPE), nrow_i, ncol_i, mat_i->data, mat_i->ld, dst, new_mat->ld);
ncol += mat_i->ncol;
}
}
// Print an H2P_dense_mat structure, for debugging
void H2P_dense_mat_print(H2P_dense_mat_p mat)
{
for (int irow = 0; irow < mat->nrow; irow++)
{
DTYPE *mat_row = mat->data + irow * mat->ld;
for (int icol = 0; icol < mat->ncol; icol++) printf("% .4lf ", mat_row[icol]);
printf("\n");
}
}
// ------------------------------------------------------------------- //
// ========================== H2P_thread_buf ========================= //
void H2P_thread_buf_init(H2P_thread_buf_p *thread_buf_, const int krnl_mat_size)
{
H2P_thread_buf_p thread_buf = (H2P_thread_buf_p) malloc(sizeof(struct H2P_thread_buf));
ASSERT_PRINTF(thread_buf != NULL, "Failed to allocate H2P_thread_buf structure\n");
H2P_int_vec_init(&thread_buf->idx0, 1024);
H2P_int_vec_init(&thread_buf->idx1, 1024);
H2P_dense_mat_init(&thread_buf->mat0, 1024, 1);
H2P_dense_mat_init(&thread_buf->mat1, 1024, 1);
H2P_dense_mat_init(&thread_buf->mat2, 1024, 1);
thread_buf->y = (DTYPE*) malloc_aligned(sizeof(DTYPE) * krnl_mat_size, 64);
ASSERT_PRINTF(thread_buf->y != NULL, "Failed to allocate y of size %d in H2P_thread_buf\n", krnl_mat_size);
*thread_buf_ = thread_buf;
}
void H2P_thread_buf_destroy(H2P_thread_buf_p *thread_buf_)
{
H2P_thread_buf_p thread_buf = *thread_buf_;
if (thread_buf == NULL) return;
H2P_int_vec_destroy(&thread_buf->idx0);
H2P_int_vec_destroy(&thread_buf->idx1);
H2P_dense_mat_destroy(&thread_buf->mat0);
H2P_dense_mat_destroy(&thread_buf->mat1);
H2P_dense_mat_destroy(&thread_buf->mat2);
free_aligned(thread_buf->y);
free(thread_buf);
*thread_buf_ = NULL;
}
void H2P_thread_buf_reset(H2P_thread_buf_p thread_buf)
{
if (thread_buf == NULL) return;
H2P_int_vec_reset(thread_buf->idx0);
H2P_int_vec_reset(thread_buf->idx1);
H2P_dense_mat_reset(thread_buf->mat0);
H2P_dense_mat_reset(thread_buf->mat1);
H2P_dense_mat_reset(thread_buf->mat2);
}
// ------------------------------------------------------------------- // |
gemm.c | #include "gemm.h"
#include "utils.h"
#include "im2col.h"
#include "dark_cuda.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <stdint.h>
#ifdef _WIN32
#include <intrin.h>
#endif
#if defined(_OPENMP)
#include <omp.h>
#endif
#define TILE_M 4 // 4 ops
#define TILE_N 16 // AVX2 = 2 ops * 8 floats
#define TILE_K 16 // loop
#ifdef __cplusplus
#define PUT_IN_REGISTER
#else
#define PUT_IN_REGISTER register
#endif
void gemm_bin(int M, int N, int K, float ALPHA,
char *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i,j,k;
for(i = 0; i < M; ++i){
for(k = 0; k < K; ++k){
char A_PART = A[i*lda+k];
if(A_PART){
for(j = 0; j < N; ++j){
C[i*ldc+j] += B[k*ldb+j];
}
} else {
for(j = 0; j < N; ++j){
C[i*ldc+j] -= B[k*ldb+j];
}
}
}
}
}
float *random_matrix(int rows, int cols)
{
int i;
float* m = (float*)xcalloc(rows * cols, sizeof(float));
for(i = 0; i < rows*cols; ++i){
m[i] = (float)rand()/RAND_MAX;
}
return m;
}
void time_random_matrix(int TA, int TB, int m, int k, int n)
{
float *a;
if(!TA) a = random_matrix(m,k);
else a = random_matrix(k,m);
int lda = (!TA)?k:m;
float *b;
if(!TB) b = random_matrix(k,n);
else b = random_matrix(n,k);
int ldb = (!TB)?n:k;
float *c = random_matrix(m,n);
int i;
clock_t start = clock(), end;
for(i = 0; i<10; ++i){
gemm_cpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n);
}
end = clock();
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf ms\n",m,k,k,n, TA, TB, (float)(end-start)/CLOCKS_PER_SEC);
free(a);
free(b);
free(c);
}
void gemm(int TA, int TB, int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float BETA,
float *C, int ldc)
{
gemm_cpu( TA, TB, M, N, K, ALPHA,A,lda, B, ldb,BETA,C,ldc);
}
//--------------------------------------------
// XNOR bitwise GEMM for binary neural network
//--------------------------------------------
static inline unsigned char xnor(unsigned char a, unsigned char b) {
//return a == b;
return !(a^b);
}
// INT-32
static inline uint32_t get_bit_int32(uint32_t const*const src, size_t index) {
size_t src_i = index / 32;
int src_shift = index % 32;
unsigned char val = (src[src_i] & (1 << src_shift)) > 0;
return val;
}
static inline uint32_t xnor_int32(uint32_t a, uint32_t b) {
return ~(a^b);
}
static inline uint64_t xnor_int64(uint64_t a, uint64_t b) {
return ~(a^b);
}
static inline uint32_t fill_bit_int32(char src) {
if (src == 0) return 0x00000000;
else return 0xFFFFFFFF;
}
static inline uint64_t fill_bit_int64(char src) {
if (src == 0) return 0x0000000000000000;
else return 0xFFFFFFFFFFFFFFFF;
}
void binary_int32_printf(uint32_t src) {
int i;
for (i = 0; i < 32; ++i) {
if (src & 1) printf("1");
else printf("0");
src = src >> 1;
}
printf("\n");
}
void binary_int64_printf(uint64_t src) {
int i;
for (i = 0; i < 64; ++i) {
if (src & 1) printf("1");
else printf("0");
src = src >> 1;
}
printf("\n");
}
/*
void gemm_nn_custom_bin_mean(int M, int N, int K, float ALPHA_UNUSED,
unsigned char *A, int lda,
unsigned char *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int *count_arr = xcalloc(M*N, sizeof(int));
int i, j, k;
for (i = 0; i < M; ++i) { // l.n - filters [16 - 55 - 1024]
for (k = 0; k < K; ++k) { // l.size*l.size*l.c - one filter size [27 - 9216]
char a_bit = get_bit(A, i*lda + k);
for (j = 0; j < N; ++j) { // out_h*out_w - one channel output size [169 - 173056]
char b_bit = get_bit(B, k*ldb + j);
count_arr[i*ldc + j] += xnor(a_bit, b_bit);
}
}
}
for (i = 0; i < M; ++i) {
float mean_val = mean_arr[i];
for (j = 0; j < N; ++j) {
C[i*ldc + j] = (2 * count_arr[i*ldc + j] - K) * mean_val;
}
}
free(count_arr);
}
*/
/*
void gemm_nn_custom_bin_mean_transposed(int M, int N, int K, float ALPHA_UNUSED,
unsigned char *A, int lda,
unsigned char *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int *count_arr = xcalloc(M*N, sizeof(int));
int i, j, k;
for (i = 0; i < M; ++i) { // l.n - filters [16 - 55 - 1024]
for (j = 0; j < N; ++j) { // out_h*out_w - one channel output size [169 - 173056]
for (k = 0; k < K; ++k) { // l.size*l.size*l.c - one filter size [27 - 9216]
char a_bit = get_bit(A, i*lda + k);
char b_bit = get_bit(B, j*ldb + k);
count_arr[i*ldc + j] += xnor(a_bit, b_bit);
}
}
}
for (i = 0; i < M; ++i) {
float mean_val = mean_arr[i];
for (j = 0; j < N; ++j) {
C[i*ldc + j] = (2 * count_arr[i*ldc + j] - K) * mean_val;
}
}
free(count_arr);
}
*/
/*
void gemm_nn_custom_bin_mean(int M, int N, int K, float ALPHA_UNUSED,
unsigned char *A, int lda,
unsigned char *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int *count_arr = xcalloc(M*N, sizeof(int));
int i;
#pragma omp parallel for
for (i = 0; i < M; ++i) { // l.n - filters [16 - 55 - 1024]
int j, k, h;
for (k = 0; k < K; ++k) { // l.size*l.size*l.c - one filter size [27 - 9216]
const char a_bit = get_bit(A, i*lda + k);
uint64_t a_bit64 = fill_bit_int64(a_bit);
int k_ldb = k*ldb;
for (j = 0; j < N; j += 64) { // out_h*out_w - one channel output size [169 - 173056]
if ((N - j > 64) && (k_ldb % 8 == 0)) {
uint64_t b_bit64 = *((uint64_t *)(B + (k_ldb + j) / 8));
uint64_t c_bit64 = xnor_int64(a_bit64, b_bit64);
//printf("\n %d \n",__builtin_popcountll(c_bit64)); // gcc
printf("\n %d \n", __popcnt64(c_bit64)); // msvs
int h;
for (h = 0; h < 64; ++h)
if ((c_bit64 >> h) & 1) count_arr[i*ldc + j + h] += 1;
//binary_int64_printf(a_bit64);
//binary_int64_printf(b_bit64);
//binary_int64_printf(c_bit64);
}
else {
for (; j < N; ++j) { // out_h*out_w - one channel output size [169 - 173056]
char b_bit = get_bit(B, k_ldb + j);
if (xnor(a_bit, b_bit)) count_arr[i*ldc + j] += 1;
}
}
}
}
}
if (mean_arr) {
//int K_2 = K / 2;
for (i = 0; i < M; ++i) {
float mean_val = mean_arr[i];
//float mean_val2 = 2 * mean_val;
for (j = 0; j < N; ++j) {
C[i*ldc + j] = (2 * count_arr[i*ldc + j] - K) * mean_val;
//C[i*ldc + j] = (count_arr[i*ldc + j] - K_2) *mean_val2;
}
}
}
else {
for (i = 0; i < M; ++i) {
for (j = 0; j < N; ++j) {
C[i*ldc + j] = count_arr[i*ldc + j] - K / 2;
}
}
}
free(count_arr);
//getchar();
}
*/
/*
void gemm_nn_custom_bin_mean_transposed(int M, int N, int K, float ALPHA_UNUSED,
unsigned char *A, int lda,
unsigned char *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int i;
#pragma omp parallel for
for (i = 0; i < M; ++i) { // l.n - filters [16 - 55 - 1024]
int j, k, h;
float mean_val = mean_arr[i];
for (j = 0; j < N; ++j) { // out_h*out_w - one channel output size [169 - 173056]
int count = 0;
for (k = 0; k < K; k += 64) { // l.size*l.size*l.c - one filter size [27 - 9216]
uint64_t a_bit64 = *((uint64_t *)(A + (i*lda + k) / 8));
uint64_t b_bit64 = *((uint64_t *)(B + (j*ldb + k) / 8));
uint64_t c_bit64 = xnor_int64(a_bit64, b_bit64);
#ifdef WIN32
int tmp_count = __popcnt64(c_bit64);
#else
int tmp_count = __builtin_popcountll(c_bit64);
#endif
if (K - k < 64) tmp_count = tmp_count - (64 - (K - k)); // remove extra bits
count += tmp_count;
//binary_int64_printf(c_bit64);
//printf(", count = %d \n\n", tmp_count);
}
C[i*ldc + j] = (2 * count - K) * mean_val;
}
}
}
*/
//----------------------------
// is not used
/*
void transpose_32x32_bits_my(uint32_t *A, uint32_t *B, int lda, int ldb)
{
unsigned int x, y;
for (y = 0; y < 32; ++y) {
for (x = 0; x < 32; ++x) {
if (A[y * lda] & ((uint32_t)1 << x)) B[x * ldb] |= (uint32_t)1 << y;
}
}
}
*/
#ifndef GPU
uint8_t reverse_8_bit(uint8_t a) {
return ((a * 0x0802LU & 0x22110LU) | (a * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
}
uint32_t reverse_32_bit(uint32_t a)
{
// unsigned int __rbit(unsigned int val) // for ARM //__asm__("rbit %0, %1\n" : "=r"(output) : "r"(input));
return (reverse_8_bit(a >> 24) << 0) |
(reverse_8_bit(a >> 16) << 8) |
(reverse_8_bit(a >> 8) << 16) |
(reverse_8_bit(a >> 0) << 24);
}
#define swap(a0, a1, j, m) t = (a0 ^ (a1 >>j)) & m; a0 = a0 ^ t; a1 = a1 ^ (t << j);
void transpose32_optimized(uint32_t A[32]) {
int j, k;
unsigned m, t;
//m = 0x0000FFFF;
//for (j = 16; j != 0; j = j >> 1, m = m ^ (m << j)) {
// for (k = 0; k < 32; k = (k + j + 1) & ~j) {
// t = (A[k] ^ (A[k + j] >> j)) & m;
// A[k] = A[k] ^ t;
// A[k + j] = A[k + j] ^ (t << j);
// }
//}
j = 16;
m = 0x0000FFFF;
for (k = 0; k < 32; k = (k + j + 1) & ~j) { swap(A[k], A[k + j], j, m); }
j = 8;
m = 0x00ff00ff;
for (k = 0; k < 32; k = (k + j + 1) & ~j) { swap(A[k], A[k + j], j, m); }
j = 4;
m = 0x0f0f0f0f;
for (k = 0; k < 32; k = (k + j + 1) & ~j) { swap(A[k], A[k + j], j, m); }
j = 2;
m = 0x33333333;
for (k = 0; k < 32; k = (k + j + 1) & ~j) { swap(A[k], A[k + j], j, m); }
j = 1;
m = 0x55555555;
for (k = 0; k < 32; k = (k + j + 1) & ~j) { swap(A[k], A[k + j], j, m); }
// reverse Y
for (j = 0; j < 16; ++j) {
uint32_t tmp = A[j];
A[j] = reverse_32_bit(A[31 - j]);
A[31 - j] = reverse_32_bit(tmp);
}
}
void transpose_32x32_bits_reversed_diagonale(uint32_t *A, uint32_t *B, int m, int n)
{
unsigned A_tmp[32];
int i;
#pragma unroll
for (i = 0; i < 32; ++i) A_tmp[i] = A[i * m];
transpose32_optimized(A_tmp);
#pragma unroll
for (i = 0; i < 32; ++i) B[i*n] = A_tmp[i];
}
void transpose_8x8_bits_my(unsigned char *A, unsigned char *B, int lda, int ldb)
{
unsigned x, y;
for (y = 0; y < 8; ++y) {
for (x = 0; x < 8; ++x) {
if (A[y * lda] & (1 << x)) B[x * ldb] |= 1 << y;
}
}
}
unsigned char reverse_byte_1(char a)
{
return ((a & 0x1) << 7) | ((a & 0x2) << 5) |
((a & 0x4) << 3) | ((a & 0x8) << 1) |
((a & 0x10) >> 1) | ((a & 0x20) >> 3) |
((a & 0x40) >> 5) | ((a & 0x80) >> 7);
}
unsigned char reverse_byte(unsigned char a)
{
return ((a * 0x0802LU & 0x22110LU) | (a * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
}
static unsigned char lookup[16] = {
0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe,
0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf, };
unsigned char reverse_byte_3(unsigned char n) {
// Reverse the top and bottom nibble then swap them.
return (lookup[n & 0b1111] << 4) | lookup[n >> 4];
}
void transpose8rS32_reversed_diagonale(unsigned char* A, unsigned char* B, int m, int n)
{
unsigned x, y, t;
x = y = 0;
// Load the array and pack it into x and y.
//x = (A[0] << 24) | (A[m] << 16) | (A[2 * m] << 8) | A[3 * m];
//y = (A[4 * m] << 24) | (A[5 * m] << 16) | (A[6 * m] << 8) | A[7 * m];
t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7);
t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7);
t = (x ^ (x >> 14)) & 0x0000CCCC; x = x ^ t ^ (t << 14);
t = (y ^ (y >> 14)) & 0x0000CCCC; y = y ^ t ^ (t << 14);
t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
x = t;
B[7 * n] = reverse_byte(x >> 24); B[6 * n] = reverse_byte(x >> 16); B[5 * n] = reverse_byte(x >> 8); B[4 * n] = reverse_byte(x);
B[3 * n] = reverse_byte(y >> 24); B[2 * n] = reverse_byte(y >> 16); B[1 * n] = reverse_byte(y >> 8); B[0 * n] = reverse_byte(y);
}
/*
// transpose by 8-bit
void transpose_bin(char *A, char *B, const int n, const int m,
const int lda, const int ldb, const int block_size)
{
//printf("\n n = %d, ldb = %d \t\t m = %d, lda = %d \n", n, ldb, m, lda);
int i;
#pragma omp parallel for
for (i = 0; i < n; i += 8) {
int j;
for (j = 0; j < m; j += 8) {
int a_index = i*lda + j;
int b_index = j*ldb + i;
//transpose_8x8_bits_my(&A[a_index/8], &B[b_index/8], lda/8, ldb/8);
transpose8rS32_reversed_diagonale(&A[a_index / 8], &B[b_index / 8], lda / 8, ldb / 8);
}
for (; j < m; ++j) {
if (get_bit(A, i*lda + j)) set_bit(B, j*ldb + i);
}
}
}
*/
#endif
// transpose by 32-bit
void transpose_bin(uint32_t *A, uint32_t *B, const int n, const int m,
const int lda, const int ldb, const int block_size)
{
//printf("\n n = %d (n mod 32 = %d), m = %d (m mod 32 = %d) \n", n, n % 32, m, m % 32);
//printf("\n lda = %d (lda mod 32 = %d), ldb = %d (ldb mod 32 = %d) \n", lda, lda % 32, ldb, ldb % 32);
int i;
#pragma omp parallel for
for (i = 0; i < n; i += 32) {
int j;
for (j = 0; j < m; j += 32) {
int a_index = i*lda + j;
int b_index = j*ldb + i;
transpose_32x32_bits_reversed_diagonale(&A[a_index / 32], &B[b_index / 32], lda / 32, ldb / 32);
//transpose_32x32_bits_my(&A[a_index/32], &B[b_index/32], lda/32, ldb/32);
}
for (; j < m; ++j) {
if (get_bit((const unsigned char* const)A, i * lda + j)) set_bit((unsigned char* const)B, j * ldb + i);
}
}
}
static inline int popcnt_32(uint32_t val32) {
#ifdef WIN32 // Windows MSVS
int tmp_count = __popcnt(val32);
#else // Linux GCC
int tmp_count = __builtin_popcount(val32);
#endif
return tmp_count;
}
//----------------------------
#if (defined(__AVX__) && defined(__x86_64__)) || (defined(_WIN64) && !defined(__MINGW32__))
#if (defined(_WIN64) && !defined(__MINGW64__))
#include <intrin.h>
#include <ammintrin.h>
#include <immintrin.h>
#include <smmintrin.h>
#if defined(_MSC_VER) && _MSC_VER <= 1900
static inline __int32 _mm256_extract_epi64(__m256i a, const int index) {
return a.m256i_i64[index];
}
static inline __int32 _mm256_extract_epi32(__m256i a, const int index) {
return a.m256i_i32[index];
}
#endif
static inline float _dn_castu32_f32(uint32_t a) {
return *((float *)&a);
}
static inline float _mm256_extract_float32(__m256 a, const int index) {
return a.m256_f32[index];
}
#else // Linux GCC/Clang
#include <x86intrin.h>
#include <ammintrin.h>
#include <immintrin.h>
#include <smmintrin.h>
#include <cpuid.h>
static inline float _dn_castu32_f32(uint32_t a) {
return *((float *)&a);
}
static inline float _mm256_extract_float32(__m256 a, const int index) {
switch(index) {
case 0:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 0));
case 1:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 1));
case 2:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 2));
case 3:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 3));
case 4:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 4));
case 5:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 5));
case 6:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 6));
case 7:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 7));
default:
return _dn_castu32_f32(_mm256_extract_epi32(_mm256_castps_si256(a), 0));
}
}
void asm_cpuid(uint32_t* abcd, uint32_t eax)
{
uint32_t ebx = 0, edx = 0, ecx = 0;
// EBX is saved to EDI and later restored
__asm__("movl %%ebx, %%edi;"
"cpuid;"
"xchgl %%ebx, %%edi;"
: "=D"(ebx),
"+a"(eax), "+c"(ecx), "=d"(edx));
abcd[0] = eax;
abcd[1] = ebx;
abcd[2] = ecx;
abcd[3] = edx;
}
#endif
#ifdef _WIN32
// Windows
#define cpuid(info, x) __cpuidex(info, x, 0)
#else
// GCC Intrinsics
void cpuid(int info[4], int InfoType) {
__cpuid_count(InfoType, 0, info[0], info[1], info[2], info[3]);
}
#endif
// Misc.
static int HW_MMX, HW_x64, HW_RDRAND, HW_BMI1, HW_BMI2, HW_ADX, HW_PREFETCHWT1;
static int HW_ABM; // Advanced Bit Manipulation
// SIMD: 128-bit
static int HW_SSE, HW_SSE2, HW_SSE3, HW_SSSE3, HW_SSE41, HW_SSE42, HW_SSE4a, HW_AES, HW_SHA;
// SIMD: 256-bit
static int HW_AVX, HW_XOP, HW_FMA3, HW_FMA4, HW_AVX2;
// SIMD: 512-bit
static int HW_AVX512F; // AVX512 Foundation
static int HW_AVX512CD; // AVX512 Conflict Detection
static int HW_AVX512PF; // AVX512 Prefetch
static int HW_AVX512ER; // AVX512 Exponential + Reciprocal
static int HW_AVX512VL; // AVX512 Vector Length Extensions
static int HW_AVX512BW; // AVX512 Byte + Word
static int HW_AVX512DQ; // AVX512 Doubleword + Quadword
static int HW_AVX512IFMA; // AVX512 Integer 52-bit Fused Multiply-Add
static int HW_AVX512VBMI; // AVX512 Vector Byte Manipulation Instructions
// https://stackoverflow.com/questions/6121792/how-to-check-if-a-cpu-supports-the-sse3-instruction-set
void check_cpu_features(void) {
int info[4];
cpuid(info, 0);
int nIds = info[0];
cpuid(info, 0x80000000);
unsigned nExIds = info[0];
// Detect Features
if (nIds >= 0x00000001) {
cpuid(info, 0x00000001);
HW_MMX = (info[3] & ((uint32_t)1 << 23)) != 0;
HW_SSE = (info[3] & ((uint32_t)1 << 25)) != 0;
HW_SSE2 = (info[3] & ((uint32_t)1 << 26)) != 0;
HW_SSE3 = (info[2] & ((uint32_t)1 << 0)) != 0;
HW_SSSE3 = (info[2] & ((uint32_t)1 << 9)) != 0;
HW_SSE41 = (info[2] & ((uint32_t)1 << 19)) != 0;
HW_SSE42 = (info[2] & ((uint32_t)1 << 20)) != 0;
HW_AES = (info[2] & ((uint32_t)1 << 25)) != 0;
HW_AVX = (info[2] & ((uint32_t)1 << 28)) != 0;
HW_FMA3 = (info[2] & ((uint32_t)1 << 12)) != 0;
HW_RDRAND = (info[2] & ((uint32_t)1 << 30)) != 0;
}
if (nIds >= 0x00000007) {
cpuid(info, 0x00000007);
HW_AVX2 = (info[1] & ((uint32_t)1 << 5)) != 0;
HW_BMI1 = (info[1] & ((uint32_t)1 << 3)) != 0;
HW_BMI2 = (info[1] & ((uint32_t)1 << 8)) != 0;
HW_ADX = (info[1] & ((uint32_t)1 << 19)) != 0;
HW_SHA = (info[1] & ((uint32_t)1 << 29)) != 0;
HW_PREFETCHWT1 = (info[2] & ((uint32_t)1 << 0)) != 0;
HW_AVX512F = (info[1] & ((uint32_t)1 << 16)) != 0;
HW_AVX512CD = (info[1] & ((uint32_t)1 << 28)) != 0;
HW_AVX512PF = (info[1] & ((uint32_t)1 << 26)) != 0;
HW_AVX512ER = (info[1] & ((uint32_t)1 << 27)) != 0;
HW_AVX512VL = (info[1] & ((uint32_t)1 << 31)) != 0;
HW_AVX512BW = (info[1] & ((uint32_t)1 << 30)) != 0;
HW_AVX512DQ = (info[1] & ((uint32_t)1 << 17)) != 0;
HW_AVX512IFMA = (info[1] & ((uint32_t)1 << 21)) != 0;
HW_AVX512VBMI = (info[2] & ((uint32_t)1 << 1)) != 0;
}
if (nExIds >= 0x80000001) {
cpuid(info, 0x80000001);
HW_x64 = (info[3] & ((uint32_t)1 << 29)) != 0;
HW_ABM = (info[2] & ((uint32_t)1 << 5)) != 0;
HW_SSE4a = (info[2] & ((uint32_t)1 << 6)) != 0;
HW_FMA4 = (info[2] & ((uint32_t)1 << 16)) != 0;
HW_XOP = (info[2] & ((uint32_t)1 << 11)) != 0;
}
}
int is_avx() {
static int result = -1;
if (result == -1) {
check_cpu_features();
result = HW_AVX;
if (result == 1) printf(" Used AVX \n");
else printf(" Not used AVX \n");
}
return result;
}
int is_fma_avx2() {
static int result = -1;
if (result == -1) {
check_cpu_features();
result = HW_FMA3 && HW_AVX2;
if (result == 1) printf(" Used FMA & AVX2 \n");
else printf(" Not used FMA & AVX2 \n");
}
return result;
}
// https://software.intel.com/sites/landingpage/IntrinsicsGuide
void gemm_nn(int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i, j, k;
if (is_avx() == 1) { // AVX
for (i = 0; i < M; ++i) {
for (k = 0; k < K; ++k) {
float A_PART = ALPHA*A[i*lda + k];
__m256 a256, b256, c256, result256; // AVX
a256 = _mm256_set1_ps(A_PART);
for (j = 0; j < N - 8; j += 8) {
b256 = _mm256_loadu_ps(&B[k*ldb + j]);
c256 = _mm256_loadu_ps(&C[i*ldc + j]);
// FMA - Intel Haswell (2013), AMD Piledriver (2012)
//result256 = _mm256_fmadd_ps(a256, b256, c256);
result256 = _mm256_mul_ps(a256, b256);
result256 = _mm256_add_ps(result256, c256);
_mm256_storeu_ps(&C[i*ldc + j], result256);
}
int prev_end = (N % 8 == 0) ? (N - 8) : (N / 8) * 8;
for (j = prev_end; j < N; ++j)
C[i*ldc + j] += A_PART*B[k*ldb + j];
}
}
}
else {
for (i = 0; i < M; ++i) {
for (k = 0; k < K; ++k) {
PUT_IN_REGISTER float A_PART = ALPHA * A[i * lda + k];
for (j = 0; j < N; ++j) {
C[i*ldc + j] += A_PART*B[k*ldb + j];
}
/* // SSE
__m128 a128, b128, c128, result128; // SSE
a128 = _mm_set1_ps(A_PART);
for (j = 0; j < N - 4; j += 4) {
b128 = _mm_loadu_ps(&B[k*ldb + j]);
c128 = _mm_loadu_ps(&C[i*ldc + j]);
//result128 = _mm_fmadd_ps(a128, b128, c128);
result128 = _mm_mul_ps(a128, b128);
result128 = _mm_add_ps(result128, c128);
_mm_storeu_ps(&C[i*ldc + j], result128);
}
int prev_end = (N % 4 == 0) ? (N - 4) : (N / 4) * 4;
for (j = prev_end; j < N; ++j){
C[i*ldc + j] += A_PART*B[k*ldb + j];
}
*/
}
}
}
}
void gemm_nn_fast(int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i;
#pragma omp parallel for
for (i = 0; i < (M / TILE_M)*TILE_M; i += TILE_M)
{
int j, k;
int i_d, k_d;
for (k = 0; k < (K / TILE_K)*TILE_K; k += TILE_K)
{
for (j = 0; j < (N / TILE_N)*TILE_N; j += TILE_N)
{
// L1 - 6 bits tag [11:6] - cache size 32 KB, conflict for each 4 KB
// L2 - 9 bits tag [14:6] - cache size 256 KB, conflict for each 32 KB
// L3 - 13 bits tag [18:6] - cache size 8 MB, conflict for each 512 KB
__m256 result256;
__m256 a256_0, b256_0; // AVX
__m256 a256_1, b256_1; // AVX
__m256 a256_2;// , b256_2; // AVX
__m256 a256_3;// , b256_3; // AVX
__m256 c256_0, c256_1, c256_2, c256_3;
__m256 c256_4, c256_5, c256_6, c256_7;
c256_0 = _mm256_loadu_ps(&C[(0 + i)*ldc + (0 + j)]);
c256_1 = _mm256_loadu_ps(&C[(1 + i)*ldc + (0 + j)]);
c256_2 = _mm256_loadu_ps(&C[(0 + i)*ldc + (8 + j)]);
c256_3 = _mm256_loadu_ps(&C[(1 + i)*ldc + (8 + j)]);
c256_4 = _mm256_loadu_ps(&C[(2 + i)*ldc + (0 + j)]);
c256_5 = _mm256_loadu_ps(&C[(3 + i)*ldc + (0 + j)]);
c256_6 = _mm256_loadu_ps(&C[(2 + i)*ldc + (8 + j)]);
c256_7 = _mm256_loadu_ps(&C[(3 + i)*ldc + (8 + j)]);
for (k_d = 0; k_d < (TILE_K); ++k_d)
{
a256_0 = _mm256_set1_ps(ALPHA*A[(0 + i)*lda + (k_d + k)]);
a256_1 = _mm256_set1_ps(ALPHA*A[(1 + i)*lda + (k_d + k)]);
a256_2 = _mm256_set1_ps(ALPHA*A[(2 + i)*lda + (k_d + k)]);
a256_3 = _mm256_set1_ps(ALPHA*A[(3 + i)*lda + (k_d + k)]);
b256_0 = _mm256_loadu_ps(&B[(k_d + k)*ldb + (0 + j)]);
b256_1 = _mm256_loadu_ps(&B[(k_d + k)*ldb + (8 + j)]);
// FMA - Intel Haswell (2013), AMD Piledriver (2012)
//c256_0 = _mm256_fmadd_ps(a256_0, b256_0, c256_0);
//c256_1 = _mm256_fmadd_ps(a256_1, b256_0, c256_1);
//c256_2 = _mm256_fmadd_ps(a256_0, b256_1, c256_2);
//c256_3 = _mm256_fmadd_ps(a256_1, b256_1, c256_3);
//c256_4 = _mm256_fmadd_ps(a256_2, b256_0, c256_4);
//c256_5 = _mm256_fmadd_ps(a256_3, b256_0, c256_5);
//c256_6 = _mm256_fmadd_ps(a256_2, b256_1, c256_6);
//c256_7 = _mm256_fmadd_ps(a256_3, b256_1, c256_7);
result256 = _mm256_mul_ps(a256_0, b256_0);
c256_0 = _mm256_add_ps(result256, c256_0);
result256 = _mm256_mul_ps(a256_1, b256_0);
c256_1 = _mm256_add_ps(result256, c256_1);
result256 = _mm256_mul_ps(a256_0, b256_1);
c256_2 = _mm256_add_ps(result256, c256_2);
result256 = _mm256_mul_ps(a256_1, b256_1);
c256_3 = _mm256_add_ps(result256, c256_3);
result256 = _mm256_mul_ps(a256_2, b256_0);
c256_4 = _mm256_add_ps(result256, c256_4);
result256 = _mm256_mul_ps(a256_3, b256_0);
c256_5 = _mm256_add_ps(result256, c256_5);
result256 = _mm256_mul_ps(a256_2, b256_1);
c256_6 = _mm256_add_ps(result256, c256_6);
result256 = _mm256_mul_ps(a256_3, b256_1);
c256_7 = _mm256_add_ps(result256, c256_7);
}
_mm256_storeu_ps(&C[(0 + i)*ldc + (0 + j)], c256_0);
_mm256_storeu_ps(&C[(1 + i)*ldc + (0 + j)], c256_1);
_mm256_storeu_ps(&C[(0 + i)*ldc + (8 + j)], c256_2);
_mm256_storeu_ps(&C[(1 + i)*ldc + (8 + j)], c256_3);
_mm256_storeu_ps(&C[(2 + i)*ldc + (0 + j)], c256_4);
_mm256_storeu_ps(&C[(3 + i)*ldc + (0 + j)], c256_5);
_mm256_storeu_ps(&C[(2 + i)*ldc + (8 + j)], c256_6);
_mm256_storeu_ps(&C[(3 + i)*ldc + (8 + j)], c256_7);
}
for (j = (N / TILE_N)*TILE_N; j < N; ++j) {
for (i_d = i; i_d < (i + TILE_M); ++i_d)
{
for (k_d = k; k_d < (k + TILE_K); ++k_d)
{
PUT_IN_REGISTER float A_PART = ALPHA*A[i_d*lda + k_d];
C[i_d*ldc + j] += A_PART*B[k_d*ldb + j];
}
}
}
}
for (k = (K / TILE_K)*TILE_K; k < K; ++k)
{
for (i_d = i; i_d < (i + TILE_M); ++i_d)
{
PUT_IN_REGISTER float A_PART = ALPHA*A[i_d*lda + k];
for (j = 0; j < N; ++j) {
C[i_d*ldc + j] += A_PART*B[k*ldb + j];
}
}
}
}
for (i = (M / TILE_M)*TILE_M; i < M; ++i) {
int j, k;
for (k = 0; k < K; ++k) {
PUT_IN_REGISTER float A_PART = ALPHA*A[i*lda + k];
for (j = 0; j < N; ++j) {
C[i*ldc + j] += A_PART*B[k*ldb + j];
}
}
}
}
void gemm_nn_bin_32bit_packed(int M, int N, int K, float ALPHA,
uint32_t *A, int lda,
uint32_t *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int i;
#pragma omp parallel for
for (i = 0; i < M; ++i) { // l.n
int j, s;
float mean_val = mean_arr[i];
//printf(" l.mean_arr[i] = %d \n ", l.mean_arr[i]);
for (s = 0; s < K; ++s) // l.size*l.size*l.c/32 or (l.size*l.size*l.c)
{
PUT_IN_REGISTER uint32_t A_PART = A[i*lda + s];
__m256i a256 = _mm256_set1_epi32(A_PART);
for (j = 0; j < N - 8; j += 8)
{
__m256i b256 = *((__m256i*)&B[s*ldb + j]);
__m256i xor256 = _mm256_xor_si256(a256, b256); // xnor = xor(a,b)
__m256i all_1 = _mm256_set1_epi8((char)255);
__m256i xnor256 = _mm256_andnot_si256(xor256, all_1); // xnor = not(xor(a,b))
// waiting for - CPUID Flags: AVX512VPOPCNTDQ: __m512i _mm512_popcnt_epi32(__m512i a)
__m256 count = _mm256_setr_ps(
popcnt_32(_mm256_extract_epi32(xnor256, 0)),
popcnt_32(_mm256_extract_epi32(xnor256, 1)),
popcnt_32(_mm256_extract_epi32(xnor256, 2)),
popcnt_32(_mm256_extract_epi32(xnor256, 3)),
popcnt_32(_mm256_extract_epi32(xnor256, 4)),
popcnt_32(_mm256_extract_epi32(xnor256, 5)),
popcnt_32(_mm256_extract_epi32(xnor256, 6)),
popcnt_32(_mm256_extract_epi32(xnor256, 7)));
__m256 val2 = _mm256_set1_ps(2);
count = _mm256_mul_ps(count, val2); // count * 2
__m256 val32 = _mm256_set1_ps(32);
count = _mm256_sub_ps(count, val32); // count - 32
__m256 mean256 = _mm256_set1_ps(mean_val);
count = _mm256_mul_ps(count, mean256); // count * mean_val
__m256 c256 = *((__m256*)&C[i*ldc + j]);
count = _mm256_add_ps(count, c256); // c = c + count
*((__m256*)&C[i*ldc + j]) = count;
}
for (; j < N; ++j) // out_h*out_w;
{
PUT_IN_REGISTER uint32_t B_PART = B[s*ldb + j];
uint32_t xnor_result = ~(A_PART ^ B_PART);
int32_t count = popcnt_32(xnor_result); // must be Signed int
C[i*ldc + j] += (2 * count - 32) * mean_val;
}
}
}
}
void convolution_2d_old(int w, int h, int ksize, int n, int c, int pad, int stride,
float *weights, float *input, float *output)
{
//const int out_h = (h + 2 * pad - ksize) / stride + 1; // output_height=input_height for stride=1 and pad=1
//const int out_w = (w + 2 * pad - ksize) / stride + 1; // output_width=input_width for stride=1 and pad=1
int fil;
// filter index
#pragma omp parallel for // "omp parallel for" - automatic parallelization of loop by using OpenMP
for (fil = 0; fil < n; ++fil) {
//int i, f, j;
int chan, y, x, f_y, f_x;
// channel index
for (chan = 0; chan < c; ++chan)
// input - y
for (y = 0; y < h; ++y)
// input - x
for (x = 0; x < w; ++x)
{
int const output_index = fil*w*h + y*w + x;
int const weights_pre_index = fil*c*ksize*ksize + chan*ksize*ksize;
int const input_pre_index = chan*w*h;
float sum = 0;
// filter - y
for (f_y = 0; f_y < ksize; ++f_y)
{
int input_y = y + f_y - pad;
// filter - x
for (f_x = 0; f_x < ksize; ++f_x)
{
int input_x = x + f_x - pad;
if (input_y < 0 || input_x < 0 || input_y >= h || input_x >= w) continue;
int input_index = input_pre_index + input_y*w + input_x;
int weights_index = weights_pre_index + f_y*ksize + f_x;
sum += input[input_index] * weights[weights_index];
}
}
// l.output[filters][width][height] +=
// state.input[channels][width][height] *
// l.weights[filters][channels][filter_width][filter_height];
output[output_index] += sum;
}
}
}
void convolution_2d(int w, int h, int ksize, int n, int c, int pad, int stride,
float *weights, float *input, float *output, float *mean)
{
//const int out_h = (h + 2 * pad - ksize) / stride + 1; // output_height=input_height for stride=1 and pad=1
//const int out_w = (w + 2 * pad - ksize) / stride + 1; // output_width=input_width for stride=1 and pad=1
int i;
#if defined(_OPENMP)
static int max_num_threads = 0;
if (max_num_threads == 0) {
max_num_threads = omp_get_max_threads();
//omp_set_num_threads( max_num_threads / 2);
}
#endif
//convolution_2d_old(w, h, ksize, n, c, pad, stride, weights, input, output);
__m256i all256_sing1 = _mm256_set_epi32(0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000);
for (i = 0; i < ksize*ksize*n*c; i+=8) {
*((__m256*)&weights[i]) = _mm256_and_ps(*((__m256*)&weights[i]), _mm256_castsi256_ps(all256_sing1));
}
//for (i = 0; i < w*h*c; i += 8) {
//(*(__m256*)&input[i]) = _mm256_and_ps(*((__m256*)&input[i]), _mm256_castsi256_ps(all256_sing1));
//}
//__m256i all256_last_zero = _mm256_set1_epi32(0xFFFFFFFF);
//all256_last_zero.m256i_i32[7] = 0;
__m256i all256_last_zero =
_mm256_set_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0);
__m256i idx256 = _mm256_set_epi32(0, 7, 6, 5, 4, 3, 2, 1);
//__m256 all256_sing1 = _mm256_set1_ps(0x80000000);
__m256 all256_one = _mm256_set1_ps(1);
__m256i all256i_one = _mm256_set1_epi32(1);
///__m256i src256 = _mm256_loadu_si256((__m256i *)(&src[i]));
///__m256i result256 = _mm256_and_si256(src256, all256_sing1); // check sign in 8 x 32-bit floats
int fil;
// filter index
#pragma omp parallel for // "omp parallel for" - automatic parallelization of loop by using OpenMP
for (fil = 0; fil < n; ++fil) {
int chan, y, x, f_y, f_x;
float cur_mean = fabs(mean[fil]);
__m256 mean256 = _mm256_set1_ps(cur_mean);
// channel index
//for (chan = 0; chan < c; ++chan)
// input - y
for (y = 0; y < h; ++y)
// input - x
for (x = 0; x < w-8; x+=8)
{
int const output_index = fil*w*h + y*w + x;
float sum = 0;
__m256 sum256 = _mm256_set1_ps(0);
for (chan = 0; chan < c; ++chan) {
int const weights_pre_index = fil*c*ksize*ksize + chan*ksize*ksize;
int const input_pre_index = chan*w*h;
// filter - y
for (f_y = 0; f_y < ksize; ++f_y)
{
int input_y = y + f_y - pad;
//__m256 in = *((__m256*)&input[input_pre_index + input_y*w]);
if (input_y < 0 || input_y >= h) continue;
//__m256 in = _mm256_loadu_ps(&input[input_pre_index + input_y*w + x - pad]);
// filter - x
for (f_x = 0; f_x < ksize; ++f_x)
{
int input_x = x + f_x - pad;
//if (input_y < 0 || input_x < 0 || input_y >= h || input_x >= w) continue;
int input_index = input_pre_index + input_y*w + input_x;
int weights_index = weights_pre_index + f_y*ksize + f_x;
//if (input_y < 0 || input_y >= h) continue;
//sum += input[input_index] * weights[weights_index];
__m256 in = *((__m256*)&input[input_index]);
__m256 w = _mm256_set1_ps(weights[weights_index]);
//__m256 w_sign = _mm256_and_ps(w, _mm256_castsi256_ps(all256_sing1)); // check sign in 8 x 32-bit floats
__m256 xor256 = _mm256_xor_ps(w, in);
//printf("\n xor256_1 = %f, xor256_2 = %f \n", xor256.m256_f32[0], xor256.m256_f32[1]);
//printf("\n in = %f, w = %f, xor256 = %f \n", in.m256_f32[0], w_sign.m256_f32[0], xor256.m256_f32[0]);
//__m256 pn1 = _mm256_and_ps(_mm256_castsi256_ps(all256i_one), xor256);
//sum256 = xor256;
sum256 = _mm256_add_ps(xor256, sum256);
//printf("\n --- \n");
//printf("\n 0 = %f, 1 = %f, 2 = %f, 3 = %f, 4 = %f, 5 = %f, 6 = %f, 7 = %f \n", in.m256_f32[0], in.m256_f32[1], in.m256_f32[2], in.m256_f32[3], in.m256_f32[4], in.m256_f32[5], in.m256_f32[6], in.m256_f32[7]);
if (f_x < ksize-1) {
//in = _mm256_permutevar8x32_ps(in, idx256);
//in = _mm256_and_ps(in, _mm256_castsi256_ps(all256_last_zero));
}
}
}
}
// l.output[filters][width][height] +=
// state.input[channels][width][height] *
// l.weights[filters][channels][filter_width][filter_height];
//output[output_index] += sum;
sum256 = _mm256_mul_ps(sum256, mean256);
//printf("\n cur_mean = %f, sum256 = %f, sum256 = %f, in = %f \n",
// cur_mean, sum256.m256_f32[0], sum256.m256_f32[1], input[input_pre_index]);
//__m256 out = *((__m256*)&output[output_index]);
//out = _mm256_add_ps(out, sum256);
//(*(__m256*)&output[output_index]) = out;
*((__m256*)&output[output_index]) = sum256;
//_mm256_storeu_ps(&C[i*ldc + j], result256);
}
}
}
// http://graphics.stanford.edu/~seander/bithacks.html
// https://stackoverflow.com/questions/17354971/fast-counting-the-number-of-set-bits-in-m128i-register
// https://arxiv.org/pdf/1611.07612.pdf
static inline int popcnt128(__m128i n) {
const __m128i n_hi = _mm_unpackhi_epi64(n, n);
#if defined(_MSC_VER)
return __popcnt64(_mm_cvtsi128_si64(n)) + __popcnt64(_mm_cvtsi128_si64(n_hi));
#elif defined(__APPLE__) && defined(__clang__)
return _mm_popcnt_u64(_mm_cvtsi128_si64(n)) + _mm_popcnt_u64(_mm_cvtsi128_si64(n_hi));
#else
return __popcntq(_mm_cvtsi128_si64(n)) + __popcntq(_mm_cvtsi128_si64(n_hi));
#endif
}
static inline int popcnt256(__m256i n) {
return popcnt128(_mm256_extractf128_si256(n, 0)) + popcnt128(_mm256_extractf128_si256(n, 1));
}
static inline __m256i count256(__m256i v) {
__m256i lookup =
_mm256_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2,
2, 3, 2, 3, 3, 4, 0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4);
__m256i low_mask = _mm256_set1_epi8(0x0f);
__m256i lo = _mm256_and_si256(v, low_mask);
__m256i hi = _mm256_and_si256(_mm256_srli_epi32(v, 4), low_mask);
__m256i popcnt1 = _mm256_shuffle_epi8(lookup, lo);
__m256i popcnt2 = _mm256_shuffle_epi8(lookup, hi);
__m256i total = _mm256_add_epi8(popcnt1, popcnt2);
return _mm256_sad_epu8(total, _mm256_setzero_si256());
}
static inline int popcnt256_custom(__m256i n) {
__m256i val = count256(n);
//return val.m256i_i64[0] +
//val.m256i_i64[1] +
//val.m256i_i64[2] +
//val.m256i_i64[3];
return _mm256_extract_epi64(val, 0)
+ _mm256_extract_epi64(val, 1)
+ _mm256_extract_epi64(val, 2)
+ _mm256_extract_epi64(val, 3);
}
static inline void xnor_avx2_popcnt(__m256i a_bit256, __m256i b_bit256, __m256i *count_sum) {
__m256i c_bit256 = _mm256_set1_epi8((char)255);
__m256i xor256 = _mm256_xor_si256(a_bit256, b_bit256); // xnor = not(xor(a,b))
c_bit256 = _mm256_andnot_si256(xor256, c_bit256); // can be optimized - we can do other NOT for wegihts once and do not do this NOT
*count_sum = _mm256_add_epi64(count256(c_bit256), *count_sum); // 1st part - popcnt Mula's algorithm
}
// 2nd part - popcnt Mula's algorithm
static inline int get_count_mula(__m256i count_sum) {
return _mm256_extract_epi64(count_sum, 0)
+ _mm256_extract_epi64(count_sum, 1)
+ _mm256_extract_epi64(count_sum, 2)
+ _mm256_extract_epi64(count_sum, 3);
}
// 5x times faster than gemm()-float32
// further optimizations: do mean-mult only for the last layer
void gemm_nn_custom_bin_mean_transposed(int M, int N, int K, float ALPHA_UNUSED,
unsigned char *A, int lda,
unsigned char *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int i;
#if defined(_OPENMP)
static int max_num_threads = 0;
if (max_num_threads == 0) {
max_num_threads = omp_get_max_threads();
//omp_set_num_threads(max_num_threads / 2);
}
#endif
//#pragma omp parallel for
//for (i = 0; i < M; ++i)
#pragma omp parallel for
for (i = 0; i < (M/2)*2; i += 2)
{ // l.n - filters [16 - 55 - 1024]
float mean_val_0 = mean_arr[i + 0];
float mean_val_1 = mean_arr[i + 1];
int j, k;
//__m256i all_1 = _mm256_set1_epi8(255);
//for (j = 0; j < N; ++j)
for (j = 0; j < (N/2)*2; j += 2)
{ // out_h*out_w - one channel output size [169 - 173056]
//int count = 0;
const int bit_step = 256;
__m256i count_sum_0 = _mm256_set1_epi8(0);
__m256i count_sum_1 = _mm256_set1_epi8(0);
__m256i count_sum_2 = _mm256_set1_epi8(0);
__m256i count_sum_3 = _mm256_set1_epi8(0);
for (k = 0; k < K; k += bit_step) { // l.size*l.size*l.c - one filter size [27 - 9216]
__m256i a_bit256_0 = _mm256_loadu_si256((__m256i *)(A + ((i + 0)*lda + k) / 8));
__m256i b_bit256_0 = _mm256_loadu_si256((__m256i *)(B + ((j + 0)*ldb + k) / 8));
__m256i a_bit256_1 = _mm256_loadu_si256((__m256i *)(A + ((i + 1)*lda + k) / 8));
__m256i b_bit256_1 = _mm256_loadu_si256((__m256i *)(B + ((j + 1)*ldb + k) / 8));
xnor_avx2_popcnt(a_bit256_0, b_bit256_0, &count_sum_0);
xnor_avx2_popcnt(a_bit256_0, b_bit256_1, &count_sum_1);
xnor_avx2_popcnt(a_bit256_1, b_bit256_0, &count_sum_2);
xnor_avx2_popcnt(a_bit256_1, b_bit256_1, &count_sum_3);
//count += popcnt256(c_bit256);
//binary_int64_printf(c_bit64);
//printf(", count = %d \n\n", tmp_count);
}
int count_0 = get_count_mula(count_sum_0);
int count_1 = get_count_mula(count_sum_1);
int count_2 = get_count_mula(count_sum_2);
int count_3 = get_count_mula(count_sum_3);
const int f1 = (K % bit_step == 0) ? 0 : (bit_step - (K % bit_step));
count_0 = count_0 - f1; // remove extra bits (from empty space for align only)
count_1 = count_1 - f1;
count_2 = count_2 - f1;
count_3 = count_3 - f1;
C[i*ldc + (j + 0)] = (2 * count_0 - K) * mean_val_0;
C[i*ldc + (j + 1)] = (2 * count_1 - K) * mean_val_0;
C[(i + 1)*ldc + (j + 0)] = (2 * count_2 - K) * mean_val_1;
C[(i + 1)*ldc + (j + 1)] = (2 * count_3 - K) * mean_val_1;
}
int i_d;
for (i_d = 0; i_d < 2; ++i_d)
{
float mean_val = mean_arr[i + i_d];
for (j = (N / 2) * 2; j < N; j += 1)
{ // out_h*out_w - one channel output size [169 - 173056]
const int bit_step = 256;
__m256i count_sum = _mm256_set1_epi8(0);
for (k = 0; k < K; k += bit_step) { // l.size*l.size*l.c - one filter size [27 - 9216]
__m256i a_bit256_0 = _mm256_loadu_si256((__m256i *)(A + ((i + i_d + 0)*lda + k) / 8));
__m256i b_bit256_0 = _mm256_loadu_si256((__m256i *)(B + ((j + 0)*ldb + k) / 8));
xnor_avx2_popcnt(a_bit256_0, b_bit256_0, &count_sum);
}
int count = get_count_mula(count_sum);
const int f1 = (K % bit_step == 0) ? 0 : (bit_step - (K % bit_step));
count = count - f1; // remove extra bits (from empty space for align only)
C[(i + i_d)*ldc + j] = (2 * count - K) * mean_val;
}
}
}
for (i = (M / 2) * 2; i < M; i += 1)
{
float mean_val = mean_arr[i];
int j, k;
for (j = 0; j < N; j += 1)
{ // out_h*out_w - one channel output size [169 - 173056]
const int bit_step = 256;
__m256i count_sum = _mm256_set1_epi8(0);
for (k = 0; k < K; k += bit_step) { // l.size*l.size*l.c - one filter size [27 - 9216]
__m256i a_bit256_0 = _mm256_loadu_si256((__m256i *)(A + ((i + 0)*lda + k) / 8));
__m256i b_bit256_0 = _mm256_loadu_si256((__m256i *)(B + ((j + 0)*ldb + k) / 8));
xnor_avx2_popcnt(a_bit256_0, b_bit256_0, &count_sum);
}
int count = get_count_mula(count_sum);
const int f1 = (K % bit_step == 0) ? 0 : (bit_step - (K % bit_step));
count = count - f1; // remove extra bits (from empty space for align only)
C[i*ldc + j] = (2 * count - K) * mean_val;
}
}
}
//From Berkeley Vision's Caffe!
//https://github.com/BVLC/caffe/blob/master/LICENSE
void im2col_cpu_custom_transpose(float* data_im,
int channels, int height, int width,
int ksize, int stride, int pad, float* data_col, int ldb_align)
{
const int height_col = (height + 2 * pad - ksize) / stride + 1;
const int width_col = (width + 2 * pad - ksize) / stride + 1;
const int channels_col = channels * ksize * ksize;
int c;
// optimized version
if (height_col == height && width_col == width && stride == 1 && pad == 1)
{
#pragma omp parallel for
for (c = 0; c < channels_col; ++c) {
int h, w;
int w_offset = c % ksize;
int h_offset = (c / ksize) % ksize;
int c_im = c / ksize / ksize;
for (h = pad; h < height_col - pad; ++h) {
for (w = pad; w < width_col - pad - 4; w+=8) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = (h * width_col + w)*ldb_align + c; // transposed & aligned
//data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
__m256 src256 = _mm256_loadu_ps((float *)(&data_im[im_col + width*(im_row + height*c_im)]));
data_col[col_index + ldb_align * 0] = _mm256_extract_float32(src256, 0);// src256.m256_f32[0];
data_col[col_index + ldb_align * 1] = _mm256_extract_float32(src256, 1);// src256.m256_f32[1];
data_col[col_index + ldb_align * 2] = _mm256_extract_float32(src256, 2);// src256.m256_f32[2];
data_col[col_index + ldb_align * 3] = _mm256_extract_float32(src256, 3);// src256.m256_f32[3];
data_col[col_index + ldb_align * 4] = _mm256_extract_float32(src256, 4);// src256.m256_f32[4];
data_col[col_index + ldb_align * 5] = _mm256_extract_float32(src256, 5);// src256.m256_f32[5];
data_col[col_index + ldb_align * 6] = _mm256_extract_float32(src256, 6);// src256.m256_f32[6];
data_col[col_index + ldb_align * 7] = _mm256_extract_float32(src256, 7);// src256.m256_f32[7];
//_mm256_storeu_ps(&data_col[col_index], src256);
}
for (; w < width_col - pad; ++w) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
int col_index = (h * width_col + w)*ldb_align + c; // transposed & aligned
data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
}
}
{
w = 0;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (h * width_col + w)*ldb_align + c; // transposed & aligned
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
w = width_col - 1;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (h * width_col + w)*ldb_align + c; // transposed & aligned
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
h = 0;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (h * width_col + w)*ldb_align + c; // transposed & aligned
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
h = height_col - 1;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (h * width_col + w)*ldb_align + c; // transposed & aligned
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
}
}
else {
#pragma omp parallel for
for (c = 0; c < channels_col; ++c) {
int h, w;
int w_offset = c % ksize;
int h_offset = (c / ksize) % ksize;
int c_im = c / ksize / ksize;
for (h = 0; h < height_col; ++h) {
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h * stride;
int im_col = w_offset + w * stride;
int col_index = (h * width_col + w)*ldb_align + c; // transposed & aligned
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
}
}
}
//From Berkeley Vision's Caffe!
//https://github.com/BVLC/caffe/blob/master/LICENSE
void im2col_cpu_custom(float* data_im,
int channels, int height, int width,
int ksize, int stride, int pad, float* data_col)
{
int c;
const int height_col = (height + 2 * pad - ksize) / stride + 1;
const int width_col = (width + 2 * pad - ksize) / stride + 1;
const int channels_col = channels * ksize * ksize;
// optimized version
if (height_col == height && width_col == width && stride == 1 && pad == 1 && is_fma_avx2())
{
#pragma omp parallel for
for (c = 0; c < channels_col; ++c) {
int h, w;
int w_offset = c % ksize;
int h_offset = (c / ksize) % ksize;
int c_im = c / ksize / ksize;
for (h = pad; h < height_col-pad; ++h) {
for (w = pad; w < width_col-pad-8; w += 8) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
int col_index = (c * height_col + h) * width_col + w;
//data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
__m256 src256 = _mm256_loadu_ps((float *)(&data_im[im_col + width*(im_row + height*c_im)]));
_mm256_storeu_ps(&data_col[col_index], src256);
}
for (; w < width_col - pad; ++w) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
}
}
{
w = 0;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
w = width_col-1;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
h = 0;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
h = height_col-1;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
}
}
else {
//printf("\n Error: is no non-optimized version \n");
im2col_cpu(data_im, channels, height, width, ksize, stride, pad, data_col);
}
}
//From Berkeley Vision's Caffe!
//https://github.com/BVLC/caffe/blob/master/LICENSE
void im2col_cpu_custom_align(float* data_im,
int channels, int height, int width,
int ksize, int stride, int pad, float* data_col, int bit_align)
{
int c;
const int height_col = (height + 2 * pad - ksize) / stride + 1;
const int width_col = (width + 2 * pad - ksize) / stride + 1;
const int channels_col = channels * ksize * ksize;
// optimized version
if (height_col == height && width_col == width && stride == 1 && pad == 1 && is_fma_avx2())
{
int new_ldb = bit_align;
#pragma omp parallel for
for (c = 0; c < channels_col; ++c) {
int h, w;
int w_offset = c % ksize;
int h_offset = (c / ksize) % ksize;
int c_im = c / ksize / ksize;
for (h = pad; h < height_col - pad; ++h) {
for (w = pad; w < width_col - pad - 8; w += 8) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
__m256 src256 = _mm256_loadu_ps((float *)(&data_im[im_col + width*(im_row + height*c_im)]));
_mm256_storeu_ps(&data_col[col_index], src256);
}
for (; w < width_col - pad; ++w) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
}
}
{
w = 0;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
}
}
{
w = width_col - 1;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
}
}
{
h = 0;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
}
}
{
h = height_col - 1;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
}
}
}
}
else {
printf("\n Error: is no non-optimized version \n");
//im2col_cpu(data_im, channels, height, width, ksize, stride, pad, data_col); // must be aligned for transpose after float_to_bin
// float_to_bit(b, t_input, src_size);
// transpose_bin(t_input, *t_bit_input, k, n, bit_align, new_ldb, 8);
}
}
//From Berkeley Vision's Caffe!
//https://github.com/BVLC/caffe/blob/master/LICENSE
void im2col_cpu_custom_bin(float* data_im,
int channels, int height, int width,
int ksize, int stride, int pad, float* data_col, int bit_align)
{
int c;
const int height_col = (height + 2 * pad - ksize) / stride + 1;
const int width_col = (width + 2 * pad - ksize) / stride + 1;
const int channels_col = channels * ksize * ksize;
// optimized version
if (height_col == height && width_col == width && stride == 1 && pad == 1 && is_fma_avx2())
{
__m256i all256_sing1 = _mm256_set_epi32(0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000);
__m256 float_zero256 = _mm256_set1_ps(0.00);
int new_ldb = bit_align;
#pragma omp parallel for
for (c = 0; c < channels_col; ++c) {
int h, w;
int w_offset = c % ksize;
int h_offset = (c / ksize) % ksize;
int c_im = c / ksize / ksize;
for (h = pad; h < height_col - pad; ++h) {
for (w = pad; w < width_col - pad - 8; w += 8) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//__m256i src256 = _mm256_loadu_si256((__m256i *)(&data_im[im_col + width*(im_row + height*c_im)]));
//__m256i result256 = _mm256_and_si256(src256, all256_sing1); // check sign in 8 x 32-bit floats
//uint16_t mask = _mm256_movemask_ps(_mm256_castsi256_ps(result256)); // (val >= 0) ? 0 : 1
//mask = ~mask; // inverse mask, (val >= 0) ? 1 : 0
__m256 src256 = _mm256_loadu_ps((float *)(&data_im[im_col + width*(im_row + height*c_im)]));
__m256 result256 = _mm256_cmp_ps(src256, float_zero256, _CMP_GT_OS);
uint16_t mask = _mm256_movemask_ps(result256); // (val > 0) ? 0 : 1
uint16_t* dst_ptr = (uint16_t*)&((uint8_t*)data_col)[col_index / 8];
*dst_ptr |= (mask << (col_index % 8));
}
for (; w < width_col - pad; ++w) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
float val = data_im[im_col + width*(im_row + height*c_im)];
if (val > 0) set_bit((unsigned char* const)data_col, col_index);
}
}
{
w = 0;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char* const)data_col, col_index);
}
}
{
w = width_col - 1;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char* const)data_col, col_index);
}
}
{
h = 0;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char* const)data_col, col_index);
}
}
{
h = height_col - 1;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char* const)data_col, col_index);
}
}
}
}
else {
printf("\n Error: is no non-optimized version \n");
//im2col_cpu(data_im, channels, height, width, ksize, stride, pad, data_col); // must be aligned for transpose after float_to_bin
// float_to_bit(b, t_input, src_size);
// transpose_bin(t_input, *t_bit_input, k, n, bit_align, new_ldb, 8);
}
}
void activate_array_cpu_custom(float *x, const int n, const ACTIVATION a)
{
int i = 0;
if (a == LINEAR)
{}
else if (a == LEAKY)
{
if (is_fma_avx2()) {
__m256i all256_sing1 = _mm256_set_epi32(0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000);
__m256 all256_01 = _mm256_set1_ps(0.1F);
for (i = 0; i < n - 8; i += 8) {
//x[i] = (x[i]>0) ? x[i] : .1*x[i];
__m256 src256 = _mm256_loadu_ps(&x[i]);
__m256 mult256 = _mm256_mul_ps((src256), all256_01); // mult * 0.1
__m256i sign256 = _mm256_and_si256(_mm256_castps_si256(src256), all256_sing1); // check sign in 8 x 32-bit floats
__m256 result256 = _mm256_blendv_ps(src256, mult256, _mm256_castsi256_ps(sign256)); // (sign>0) ? src : mult;
_mm256_storeu_ps(&x[i], result256);
}
}
for (; i < n; ++i) {
x[i] = (x[i]>0) ? x[i] : .1*x[i];
}
}
else {
for (i = 0; i < n; ++i) {
x[i] = activate(x[i], a);
}
}
}
void float_to_bit(float *src, unsigned char *dst, size_t size)
{
size_t dst_size = size / 8 + 1;
memset(dst, 0, dst_size);
size_t i;
//__m256i all256_sing1 = _mm256_set_epi32(0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000);
__m256 float_zero256 = _mm256_set1_ps(0.0);
for (i = 0; i < size; i+=8)
{
//__m256i src256 = _mm256_loadu_si256((__m256i *)(&src[i]));
//__m256i result256 = _mm256_and_si256(src256, all256_sing1); // check sign in 8 x 32-bit floats
//uint32_t mask = _mm256_movemask_ps(_mm256_castsi256_ps(result256)); // (val >= 0) ? 0 : 1
////mask = ~mask; // inverse mask, (val >= 0) ? 1 : 0
__m256 src256 = _mm256_loadu_ps((float *)(&src[i]));
__m256 result256 = _mm256_cmp_ps(src256, float_zero256, _CMP_GT_OS);
uint32_t mask = _mm256_movemask_ps(result256); // (val > 0) ? 0 : 1
dst[i / 8] = mask;
}
}
static inline void transpose4x4_SSE(float *A, float *B, const int lda, const int ldb)
{
__m128 row1 = _mm_loadu_ps(&A[0 * lda]);
__m128 row2 = _mm_loadu_ps(&A[1 * lda]);
__m128 row3 = _mm_loadu_ps(&A[2 * lda]);
__m128 row4 = _mm_loadu_ps(&A[3 * lda]);
_MM_TRANSPOSE4_PS(row1, row2, row3, row4);
_mm_storeu_ps(&B[0 * ldb], row1);
_mm_storeu_ps(&B[1 * ldb], row2);
_mm_storeu_ps(&B[2 * ldb], row3);
_mm_storeu_ps(&B[3 * ldb], row4);
}
void transpose_block_SSE4x4(float *A, float *B, const int n, const int m,
const int lda, const int ldb, const int block_size)
{
int i;
#pragma omp parallel for
for (i = 0; i < n; i += block_size) {
int j, i2, j2;
//int max_i2 = (i + block_size < n) ? (i + block_size) : n;
if (i + block_size < n) {
int max_i2 = i + block_size;
for (j = 0; j < m; j += block_size) {
//int max_j2 = (j + block_size < m) ? (j + block_size) : m;
if (j + block_size < m) {
int max_j2 = j + block_size;
for (i2 = i; i2 < max_i2; i2 += 4) {
for (j2 = j; j2 < max_j2; j2 += 4) {
transpose4x4_SSE(&A[i2*lda + j2], &B[j2*ldb + i2], lda, ldb);
}
}
}
else {
for (i2 = i; i2 < max_i2; ++i2) {
for (j2 = j; j2 < m; ++j2) {
B[j2*ldb + i2] = A[i2*lda + j2];
}
}
}
}
}
else {
for (i2 = i; i2 < n; ++i2) {
for (j2 = 0; j2 < m; ++j2) {
B[j2*ldb + i2] = A[i2*lda + j2];
}
}
}
}
}
void forward_maxpool_layer_avx(float *src, float *dst, int *indexes, int size, int w, int h, int out_w, int out_h, int c,
int pad, int stride, int batch)
{
const int w_offset = -pad / 2;
const int h_offset = -pad / 2;
int b, k;
for (b = 0; b < batch; ++b) {
#pragma omp parallel for
for (k = 0; k < c; ++k) {
int i, j, m, n;
for (i = 0; i < out_h; ++i) {
//for (j = 0; j < out_w; ++j) {
j = 0;
if(stride == 1 && is_avx() == 1) {
for (j = 0; j < out_w - 8 - (size - 1); j += 8) {
int out_index = j + out_w*(i + out_h*(k + c*b));
__m256 max256 = _mm256_set1_ps(-FLT_MAX);
for (n = 0; n < size; ++n) {
for (m = 0; m < size; ++m) {
int cur_h = h_offset + i*stride + n;
int cur_w = w_offset + j*stride + m;
int index = cur_w + w*(cur_h + h*(k + b*c));
int valid = (cur_h >= 0 && cur_h < h &&
cur_w >= 0 && cur_w < w);
if (!valid) continue;
__m256 src256 = _mm256_loadu_ps(&src[index]);
max256 = _mm256_max_ps(src256, max256);
}
}
_mm256_storeu_ps(&dst[out_index], max256);
}
}
else if (size == 2 && stride == 2 && is_avx() == 1) {
for (j = 0; j < out_w - 4; j += 4) {
int out_index = j + out_w*(i + out_h*(k + c*b));
//float max = -FLT_MAX;
//int max_i = -1;
__m128 max128 = _mm_set1_ps(-FLT_MAX);
for (n = 0; n < size; ++n) {
//for (m = 0; m < size; ++m)
m = 0;
{
int cur_h = h_offset + i*stride + n;
int cur_w = w_offset + j*stride + m;
int index = cur_w + w*(cur_h + h*(k + b*c));
int valid = (cur_h >= 0 && cur_h < h &&
cur_w >= 0 && cur_w < w);
if (!valid) continue;
__m256 src256 = _mm256_loadu_ps(&src[index]);
__m256 src256_2 = _mm256_permute_ps(src256, (1 << 0) | (3 << 4));
__m256 max256 = _mm256_max_ps(src256, src256_2);
__m128 src128_0 = _mm256_extractf128_ps(max256, 0);
__m128 src128_1 = _mm256_extractf128_ps(max256, 1);
__m128 src128 = _mm_shuffle_ps(src128_0, src128_1, (2 << 2) | (2 << 6));
max128 = _mm_max_ps(src128, max128);
}
}
_mm_storeu_ps(&dst[out_index], max128);
}
}
for (; j < out_w; ++j) {
int out_index = j + out_w*(i + out_h*(k + c*b));
float max = -FLT_MAX;
int max_i = -1;
for (n = 0; n < size; ++n) {
for (m = 0; m < size; ++m) {
int cur_h = h_offset + i*stride + n;
int cur_w = w_offset + j*stride + m;
int index = cur_w + w*(cur_h + h*(k + b*c));
int valid = (cur_h >= 0 && cur_h < h &&
cur_w >= 0 && cur_w < w);
float val = (valid != 0) ? src[index] : -FLT_MAX;
max_i = (val > max) ? index : max_i;
max = (val > max) ? val : max;
}
}
dst[out_index] = max;
if (indexes) indexes[out_index] = max_i;
}
}
}
}
}
#else // AVX
int is_avx() {
return 0;
}
int is_fma_avx2() {
return 0;
}
void gemm_nn(int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i, j, k;
for (i = 0; i < M; ++i) {
for (k = 0; k < K; ++k) {
PUT_IN_REGISTER float A_PART = ALPHA * A[i * lda + k];
for (j = 0; j < N; ++j) {
C[i*ldc + j] += A_PART*B[k*ldb + j];
}
}
}
}
void gemm_nn_fast(int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i, j, k;
#pragma omp parallel for
for (i = 0; i < M; ++i) {
for (k = 0; k < K; ++k) {
PUT_IN_REGISTER float A_PART = ALPHA*A[i*lda + k];
for (j = 0; j < N; ++j) {
C[i*ldc + j] += A_PART*B[k*ldb + j];
}
}
}
}
void gemm_nn_bin_32bit_packed(int M, int N, int K, float ALPHA,
uint32_t *A, int lda,
uint32_t *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int i;
#pragma omp parallel for
for (i = 0; i < M; ++i) { // l.n
int j, s;
float mean_val = mean_arr[i];
//printf(" l.mean_arr[i] = %d \n ", l.mean_arr[i]);
for (s = 0; s < K; ++s) // l.size*l.size*l.c/32 or (l.size*l.size*l.c)
{
//PUT_IN_REGISTER float A_PART = 1*a[i*k + s];
PUT_IN_REGISTER uint32_t A_PART = A[i * lda + s];
for (j = 0; j < N; ++j) // out_h*out_w;
{
//c[i*n + j] += A_PART*b[s*n + j];
PUT_IN_REGISTER uint32_t B_PART = B[s * ldb + j];
uint32_t xnor_result = ~(A_PART ^ B_PART);
//printf(" xnor_result = %d, ", xnor_result);
int32_t count = popcnt_32(xnor_result); // must be Signed int
C[i*ldc + j] += (2 * count - 32) * mean_val;
//c[i*n + j] += count*mean;
}
}
}
}
void convolution_2d(int w, int h, int ksize, int n, int c, int pad, int stride,
float *weights, float *input, float *output, float *mean)
{
const int out_h = (h + 2 * pad - ksize) / stride + 1; // output_height=input_height for stride=1 and pad=1
const int out_w = (w + 2 * pad - ksize) / stride + 1; // output_width=input_width for stride=1 and pad=1
//int i, f, j;
int fil;
// filter index
#pragma omp parallel for // "omp parallel for" - automatic parallelization of loop by using OpenMP
for (fil = 0; fil < n; ++fil) {
int chan, y, x, f_y, f_x;
// channel index
for (chan = 0; chan < c; ++chan)
// input - y
for (y = 0; y < h; ++y)
// input - x
for (x = 0; x < w; ++x)
{
int const output_index = fil*w*h + y*w + x;
int const weights_pre_index = fil*c*ksize*ksize + chan*ksize*ksize;
int const input_pre_index = chan*w*h;
float sum = 0;
// filter - y
for (f_y = 0; f_y < ksize; ++f_y)
{
int input_y = y + f_y - pad;
// filter - x
for (f_x = 0; f_x < ksize; ++f_x)
{
int input_x = x + f_x - pad;
if (input_y < 0 || input_x < 0 || input_y >= h || input_x >= w) continue;
int input_index = input_pre_index + input_y*w + input_x;
int weights_index = weights_pre_index + f_y*ksize + f_x;
sum += input[input_index] * weights[weights_index];
}
}
// l.output[filters][width][height] +=
// state.input[channels][width][height] *
// l.weights[filters][channels][filter_width][filter_height];
output[output_index] += sum;
}
}
}
static inline int popcnt_64(uint64_t val64) {
#ifdef WIN32 // Windows
#ifdef _WIN64 // Windows 64-bit
int tmp_count = __popcnt64(val64);
#else // Windows 32-bit
int tmp_count = __popcnt(val64);
tmp_count += __popcnt(val64 >> 32);
#endif
#else // Linux
#if defined(__x86_64__) || defined(__aarch64__) // Linux 64-bit
int tmp_count = __builtin_popcountll(val64);
#else // Linux 32-bit
int tmp_count = __builtin_popcount(val64);
tmp_count += __builtin_popcount(val64 >> 32);
#endif
#endif
return tmp_count;
}
void gemm_nn_custom_bin_mean_transposed(int M, int N, int K, float ALPHA_UNUSED,
unsigned char *A, int lda,
unsigned char *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int i;
#pragma omp parallel for
for (i = 0; i < M; ++i) { // l.n - filters [16 - 55 - 1024]
int j, k;
float mean_val = mean_arr[i];
for (j = 0; j < N; ++j) { // out_h*out_w - one channel output size [169 - 173056]
int count = 0;
for (k = 0; k < K; k += 64) { // l.size*l.size*l.c - one filter size [27 - 9216]
uint64_t a_bit64 = *((uint64_t *)(A + (i*lda + k) / 8));
uint64_t b_bit64 = *((uint64_t *)(B + (j*ldb + k) / 8));
uint64_t c_bit64 = xnor_int64(a_bit64, b_bit64);
int tmp_count = popcnt_64(c_bit64);
if (K - k < 64) tmp_count = tmp_count - (64 - (K - k)); // remove extra bits
count += tmp_count;
//binary_int64_printf(c_bit64);
//printf(", count = %d \n\n", tmp_count);
}
C[i*ldc + j] = (2 * count - K) * mean_val;
}
}
}
void im2col_cpu_custom_transpose(float* data_im,
int channels, int height, int width,
int ksize, int stride, int pad, float* data_col, int ldb_align)
{
printf("\n im2col_cpu_custom_transpose() isn't implemented without AVX \n");
}
//From Berkeley Vision's Caffe!
//https://github.com/BVLC/caffe/blob/master/LICENSE
void im2col_cpu_custom(float* data_im,
int channels, int height, int width,
int ksize, int stride, int pad, float* data_col)
{
im2col_cpu(data_im, channels, height, width, ksize, stride, pad, data_col);
return;
int c;
const int height_col = (height + 2 * pad - ksize) / stride + 1;
const int width_col = (width + 2 * pad - ksize) / stride + 1;
const int channels_col = channels * ksize * ksize;
// optimized version
if (height_col == height && width_col == width && stride == 1 && pad == 1)
{
#pragma omp parallel for
for (c = 0; c < channels_col; ++c) {
int h, w;
int w_offset = c % ksize;
int h_offset = (c / ksize) % ksize;
int c_im = c / ksize / ksize;
for (h = pad; h < height_col - pad; ++h) {
for (w = pad; w < width_col - pad; ++w) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
}
for (; w < width_col - pad; ++w) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
}
}
{
w = 0;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
w = width_col - 1;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
h = 0;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
{
h = height_col - 1;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
int col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
}
}
}
}
else {
//printf("\n Error: is no non-optimized version \n");
im2col_cpu(data_im, channels, height, width, ksize, stride, pad, data_col);
}
}
//From Berkeley Vision's Caffe!
//https://github.com/BVLC/caffe/blob/master/LICENSE
void im2col_cpu_custom_bin(float* data_im,
int channels, int height, int width,
int ksize, int stride, int pad, float* data_col, int bit_align)
{
int c;
const int height_col = (height + 2 * pad - ksize) / stride + 1;
const int width_col = (width + 2 * pad - ksize) / stride + 1;
const int channels_col = channels * ksize * ksize;
// optimized version
if (height_col == height && width_col == width && stride == 1 && pad == 1)
{
int new_ldb = bit_align;
#pragma omp parallel for
for (c = 0; c < channels_col; ++c) {
int h, w;
int w_offset = c % ksize;
int h_offset = (c / ksize) % ksize;
int c_im = c / ksize / ksize;
for (h = pad; h < height_col - pad; ++h) {
for (w = pad; w < width_col - pad - 8; w += 1) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
float val = data_im[im_col + width*(im_row + height*c_im)];
if (val > 0) set_bit((unsigned char*)data_col, col_index);
}
for (; w < width_col - pad; ++w) {
int im_row = h_offset + h - pad;
int im_col = w_offset + w - pad;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = data_im[im_col + width*(im_row + height*c_im)];
float val = data_im[im_col + width*(im_row + height*c_im)];
if (val > 0) set_bit((unsigned char*)data_col, col_index);
}
}
{
w = 0;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char*)data_col, col_index);
}
}
{
w = width_col - 1;
for (h = 0; h < height_col; ++h) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char*)data_col, col_index);
}
}
{
h = 0;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char*)data_col, col_index);
}
}
{
h = height_col - 1;
for (w = 0; w < width_col; ++w) {
int im_row = h_offset + h;
int im_col = w_offset + w;
//int col_index = (c * height_col + h) * width_col + w;
int col_index = c * new_ldb + h * width_col + w;
//data_col[col_index] = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
float val = im2col_get_pixel(data_im, height, width, channels, im_row, im_col, c_im, pad);
if (val > 0) set_bit((unsigned char*)data_col, col_index);
}
}
}
}
else {
printf("\n Error: is no non-optimized version \n");
//im2col_cpu(data_im, channels, height, width, ksize, stride, pad, data_col); // must be aligned for transpose after float_to_bin
// float_to_bit(b, t_input, src_size);
// transpose_bin(t_input, *t_bit_input, k, n, bit_align, new_ldb, 8);
}
}
void activate_array_cpu_custom(float *x, const int n, const ACTIVATION a)
{
int i;
if (a == LINEAR)
{
}
else if (a == LEAKY)
{
for (i = 0; i < n; ++i) {
x[i] = (x[i]>0) ? x[i] : .1*x[i];
}
}
else {
for (i = 0; i < n; ++i) {
x[i] = activate(x[i], a);
}
}
}
void float_to_bit(float *src, unsigned char *dst, size_t size)
{
size_t dst_size = size / 8 + 1;
memset(dst, 0, dst_size);
size_t i;
char* byte_arr = (char*)xcalloc(size, sizeof(char));
for (i = 0; i < size; ++i) {
if (src[i] > 0) byte_arr[i] = 1;
}
//for (i = 0; i < size; ++i) {
// dst[i / 8] |= byte_arr[i] << (i % 8);
//}
for (i = 0; i < size; i += 8) {
char dst_tmp = 0;
dst_tmp |= byte_arr[i + 0] << 0;
dst_tmp |= byte_arr[i + 1] << 1;
dst_tmp |= byte_arr[i + 2] << 2;
dst_tmp |= byte_arr[i + 3] << 3;
dst_tmp |= byte_arr[i + 4] << 4;
dst_tmp |= byte_arr[i + 5] << 5;
dst_tmp |= byte_arr[i + 6] << 6;
dst_tmp |= byte_arr[i + 7] << 7;
dst[i / 8] = dst_tmp;
}
free(byte_arr);
}
static inline void transpose_scalar_block(float *A, float *B, const int lda, const int ldb, const int block_size)
{
int i;
//#pragma omp parallel for
for (i = 0; i<block_size; i++) {
int j;
for (j = 0; j<block_size; j++) {
B[j*ldb + i] = A[i*lda + j];
}
}
}
void transpose_block_SSE4x4(float *A, float *B, const int n, const int m,
const int lda, const int ldb, const int block_size)
{
int i;
#pragma omp parallel for
for (i = 0; i < n; i += block_size) {
int j, i2, j2;
for (j = 0; j < m; j += block_size) {
int max_i2 = i + block_size < n ? i + block_size : n;
int max_j2 = j + block_size < m ? j + block_size : m;
for (i2 = i; i2 < max_i2; ++i2) {
for (j2 = j; j2 < max_j2; ++j2) {
B[j2*ldb + i2] = A[i2*lda + j2];
}
}
}
}
}
void forward_maxpool_layer_avx(float *src, float *dst, int *indexes, int size, int w, int h, int out_w, int out_h, int c,
int pad, int stride, int batch)
{
int b, k;
const int w_offset = -pad / 2;
const int h_offset = -pad / 2;
for (b = 0; b < batch; ++b) {
#pragma omp parallel for
for (k = 0; k < c; ++k) {
int i, j, m, n;
for (i = 0; i < out_h; ++i) {
for (j = 0; j < out_w; ++j) {
int out_index = j + out_w*(i + out_h*(k + c*b));
float max = -FLT_MAX;
int max_i = -1;
for (n = 0; n < size; ++n) {
for (m = 0; m < size; ++m) {
int cur_h = h_offset + i*stride + n;
int cur_w = w_offset + j*stride + m;
int index = cur_w + w*(cur_h + h*(k + b*c));
int valid = (cur_h >= 0 && cur_h < h &&
cur_w >= 0 && cur_w < w);
float val = (valid != 0) ? src[index] : -FLT_MAX;
max_i = (val > max) ? index : max_i;
max = (val > max) ? val : max;
}
}
dst[out_index] = max;
if (indexes) indexes[out_index] = max_i;
}
}
}
}
}
#endif // AVX
// 32 channels -> 1 channel (with 32 floats)
// 256 channels -> 8 channels (with 32 floats)
void repack_input(float *input, float *re_packed_input, int w, int h, int c)
{
const int items_per_channel = w * h;
int chan, i;
for (chan = 0; chan < c; chan += 32)
{
for (i = 0; i < items_per_channel; ++i)
{
int c_pack;
for (c_pack = 0; c_pack < 32; ++c_pack) {
float src = input[(chan + c_pack)*items_per_channel + i];
re_packed_input[chan*items_per_channel + i * 32 + c_pack] = src;
}
}
}
}
void transpose_uint32(uint32_t *src, uint32_t *dst, int src_h, int src_w, int src_align, int dst_align)
{
//l.bit_align - algined (n) by 32
//new_ldb - aligned (k) by 256
int i;
//#pragma omp parallel for
for (i = 0; i < src_h; i += 1) // l.size*l.size*l.c;
{
int j;
for (j = 0; j < src_w; j += 1) // out_h*out_w;
{
((uint32_t *)dst)[j*dst_align / 32 + i] = ((uint32_t *)src)[i*src_align + j];
}
}
}
void gemm_nn_bin_transposed_32bit_packed(int M, int N, int K, float ALPHA,
uint32_t *A, int lda,
uint32_t *B, int ldb,
float *C, int ldc, float *mean_arr)
{
int i;
#pragma omp parallel for
for (i = 0; i < M; ++i) { // l.n
int j, s;
float mean_val = mean_arr[i];
for (j = 0; j < N; ++j) // out_h*out_w;
{
float val = 0;
for (s = 0; s < K; ++s) // l.size*l.size*l.c/32 or (l.size*l.size*l.c)
{
PUT_IN_REGISTER uint32_t A_PART = ((uint32_t*)A)[i*lda + s];
PUT_IN_REGISTER uint32_t B_PART = ((uint32_t*)B)[j * ldb + s];
uint32_t xnor_result = ~(A_PART ^ B_PART);
int32_t count = popcnt_32(xnor_result); // must be Signed int
val += (2 * count - 32) * mean_val;
}
C[i*ldc + j] += val;
}
}
}
void convolution_repacked(uint32_t *packed_input, uint32_t *packed_weights, float *output,
int w, int h, int c, int n, int size, int pad, int new_lda, float *mean_arr)
{
int fil;
// filter index
#pragma omp parallel for
for (fil = 0; fil < n; ++fil) {
float mean_val = mean_arr[fil];
int chan, y, x, f_y, f_x; // c_pack
// channel index
for (chan = 0; chan < c / 32; ++chan)
//for (chan = 0; chan < l.c; chan += 32)
//for (c_pack = 0; c_pack < 32; ++c_pack)
// input - y
for (y = 0; y < h; ++y)
// input - x
for (x = 0; x < w; ++x)
{
int const output_index = fil*w*h + y*w + x;
float sum = 0;
// filter - y
for (f_y = 0; f_y < size; ++f_y)
{
int input_y = y + f_y - pad;
// filter - x
for (f_x = 0; f_x < size; ++f_x)
{
int input_x = x + f_x - pad;
if (input_y < 0 || input_x < 0 || input_y >= h || input_x >= w) continue;
// normal
//float input = state.input[(chan + c_pack)*l.w*l.h + input_y*l.w + input_x];
//float weight = l.weights[fil*l.c*l.size*l.size + (chan + c_pack)*l.size*l.size + f_y*l.size + f_x];
// packed
//float input = re_packed_input[chan*l.w*l.h + (input_y*l.w + input_x) * 32 + c_pack];
//float weight = l.weights[fil*l.c*l.size*l.size + chan*l.size*l.size + (f_y*l.size + f_x) * 32 + c_pack];
//sum += input * weight;
//float input = re_packed_input[chan*l.w*l.h + (input_y*l.w + input_x) * 32 + c_pack];
//float weight = l.weights[fil*l.c*l.size*l.size + chan*l.size*l.size + (f_y*l.size + f_x) * 32 + c_pack];
//uint32_t bit1 = input > 0;
//uint32_t bit2 = weight > 0;
//uint32_t count = (~(bit1 ^ bit2)) & 1;
//float result = (2 * (float)count - 1) * mean_val;
//printf("\n mul = %f, bit1 = %d, bit2 = %d, count = %d, mean = %f, result = %f ", input*weight, bit1, bit2, count, mean_val, result);
//sum += result;
uint32_t input = ((uint32_t *)packed_input)[chan*w*h + input_y*w + input_x];
//uint32_t weight = ((uint32_t *)l.align_bit_weights)[fil*l.c*l.size*l.size/32 + chan*l.size*l.size + f_y*l.size + f_x];
uint32_t weight = ((uint32_t *)packed_weights)[fil*new_lda / 32 + chan*size*size + f_y*size + f_x];
uint32_t xnor_result = ~(input ^ weight);
int32_t count = popcnt_32(xnor_result); // mandatory Signed int
sum += (2 * count - 32) * mean_val;
}
}
// l.output[filters][width][height] +=
// state.input[channels][width][height] *
// l.weights[filters][channels][filter_width][filter_height];
output[output_index] += sum;
}
}
}
void gemm_nt(int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i,j,k;
for(i = 0; i < M; ++i){
for(j = 0; j < N; ++j){
PUT_IN_REGISTER float sum = 0;
for(k = 0; k < K; ++k){
sum += ALPHA*A[i*lda+k]*B[j*ldb + k];
}
C[i*ldc+j] += sum;
}
}
}
void gemm_tn(int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i,j,k;
for(i = 0; i < M; ++i){
for(k = 0; k < K; ++k){
PUT_IN_REGISTER float A_PART = ALPHA * A[k * lda + i];
for(j = 0; j < N; ++j){
C[i*ldc+j] += A_PART*B[k*ldb+j];
}
}
}
}
void gemm_tt(int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float *C, int ldc)
{
int i,j,k;
for(i = 0; i < M; ++i){
for(j = 0; j < N; ++j){
PUT_IN_REGISTER float sum = 0;
for(k = 0; k < K; ++k){
sum += ALPHA*A[i+k*lda]*B[k+j*ldb];
}
C[i*ldc+j] += sum;
}
}
}
void gemm_cpu(int TA, int TB, int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float BETA,
float *C, int ldc)
{
//printf("cpu: %d %d %d %d %d %f %d %d %f %d\n",TA, TB, M, N, K, ALPHA, lda, ldb, BETA, ldc);
if (BETA != 1){
int i, j;
for(i = 0; i < M; ++i){
for(j = 0; j < N; ++j){
C[i*ldc + j] *= BETA;
}
}
}
is_avx(); // initialize static variable
if (is_fma_avx2() && !TA && !TB) {
gemm_nn_fast(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);
}
else {
int t;
#pragma omp parallel for
for (t = 0; t < M; ++t) {
if (!TA && !TB)
gemm_nn(1, N, K, ALPHA, A + t*lda, lda, B, ldb, C + t*ldc, ldc);
else if (TA && !TB)
gemm_tn(1, N, K, ALPHA, A + t, lda, B, ldb, C + t*ldc, ldc);
else if (!TA && TB)
gemm_nt(1, N, K, ALPHA, A + t*lda, lda, B, ldb, C + t*ldc, ldc);
else
gemm_tt(1, N, K, ALPHA, A + t, lda, B, ldb, C + t*ldc, ldc);
}
}
}
#ifdef GPU
#include <math.h>
void gemm_ongpu(int TA, int TB, int M, int N, int K, float ALPHA,
float *A_gpu, int lda,
float *B_gpu, int ldb,
float BETA,
float *C_gpu, int ldc)
{
cublasHandle_t handle = blas_handle();
cudaError_t stream_status = (cudaError_t)cublasSetStream(handle, get_cuda_stream());
CHECK_CUDA(stream_status);
cudaError_t status = (cudaError_t)cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),
(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb, A_gpu, lda, &BETA, C_gpu, ldc);
CHECK_CUDA(status);
}
void gemm_gpu(int TA, int TB, int M, int N, int K, float ALPHA,
float *A, int lda,
float *B, int ldb,
float BETA,
float *C, int ldc)
{
float *A_gpu = cuda_make_array(A, (TA ? lda*K:lda*M));
float *B_gpu = cuda_make_array(B, (TB ? ldb*N : ldb*K));
float *C_gpu = cuda_make_array(C, ldc*M);
gemm_ongpu(TA, TB, M, N, K, ALPHA, A_gpu, lda, B_gpu, ldb, BETA, C_gpu, ldc);
cuda_pull_array(C_gpu, C, ldc*M);
cuda_free(A_gpu);
cuda_free(B_gpu);
cuda_free(C_gpu);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void time_gpu_random_matrix(int TA, int TB, int m, int k, int n)
{
float *a;
if(!TA) a = random_matrix(m,k);
else a = random_matrix(k,m);
int lda = (!TA)?k:m;
float *b;
if(!TB) b = random_matrix(k,n);
else b = random_matrix(n,k);
int ldb = (!TB)?n:k;
float *c = random_matrix(m,n);
int i;
clock_t start = clock(), end;
for(i = 0; i<32; ++i){
gemm_gpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n);
}
end = clock();
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s\n",m,k,k,n, TA, TB, (float)(end-start)/CLOCKS_PER_SEC);
free(a);
free(b);
free(c);
}
void time_ongpu(int TA, int TB, int m, int k, int n)
{
int iter = 10;
float *a = random_matrix(m,k);
float *b = random_matrix(k,n);
int lda = (!TA)?k:m;
int ldb = (!TB)?n:k;
float *c = random_matrix(m,n);
float *a_cl = cuda_make_array(a, m*k);
float *b_cl = cuda_make_array(b, k*n);
float *c_cl = cuda_make_array(c, m*n);
int i;
clock_t start = clock(), end;
for(i = 0; i<iter; ++i){
gemm_ongpu(TA,TB,m,n,k,1,a_cl,lda,b_cl,ldb,1,c_cl,n);
cudaDeviceSynchronize();
}
double flop = ((double)m)*n*(2.*k + 2.)*iter;
double gflop = flop/pow(10., 9);
end = clock();
double seconds = sec(end-start);
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s, %lf GFLOPS\n",m,k,k,n, TA, TB, seconds, gflop/seconds);
cuda_free(a_cl);
cuda_free(b_cl);
cuda_free(c_cl);
free(a);
free(b);
free(c);
}
void test_gpu_accuracy(int TA, int TB, int m, int k, int n)
{
srand(0);
float *a;
if(!TA) a = random_matrix(m,k);
else a = random_matrix(k,m);
int lda = (!TA)?k:m;
float *b;
if(!TB) b = random_matrix(k,n);
else b = random_matrix(n,k);
int ldb = (!TB)?n:k;
float *c = random_matrix(m,n);
float *c_gpu = random_matrix(m,n);
memset(c, 0, m*n*sizeof(float));
memset(c_gpu, 0, m*n*sizeof(float));
int i;
//pm(m,k,b);
gemm_gpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c_gpu,n);
//printf("GPU\n");
//pm(m, n, c_gpu);
gemm_cpu(TA,TB,m,n,k,1,a,lda,b,ldb,1,c,n);
//printf("\n\nCPU\n");
//pm(m, n, c);
double sse = 0;
for(i = 0; i < m*n; ++i) {
//printf("%f %f\n", c[i], c_gpu[i]);
sse += pow(c[i]-c_gpu[i], 2);
}
printf("Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %g SSE\n",m,k,k,n, TA, TB, sse/(m*n));
free(a);
free(b);
free(c);
free(c_gpu);
}
int test_gpu_blas()
{
/*
test_gpu_accuracy(0,0,10,576,75);
test_gpu_accuracy(0,0,17,10,10);
test_gpu_accuracy(1,0,17,10,10);
test_gpu_accuracy(0,1,17,10,10);
test_gpu_accuracy(1,1,17,10,10);
test_gpu_accuracy(0,0,1000,10,100);
test_gpu_accuracy(1,0,1000,10,100);
test_gpu_accuracy(0,1,1000,10,100);
test_gpu_accuracy(1,1,1000,10,100);
test_gpu_accuracy(0,0,10,10,10);
time_ongpu(0,0,64,2916,363);
time_ongpu(0,0,64,2916,363);
time_ongpu(0,0,64,2916,363);
time_ongpu(0,0,192,729,1600);
time_ongpu(0,0,384,196,1728);
time_ongpu(0,0,256,196,3456);
time_ongpu(0,0,256,196,2304);
time_ongpu(0,0,128,4096,12544);
time_ongpu(0,0,128,4096,4096);
*/
time_ongpu(0,0,64,75,12544);
time_ongpu(0,0,64,75,12544);
time_ongpu(0,0,64,75,12544);
time_ongpu(0,0,64,576,12544);
time_ongpu(0,0,256,2304,784);
time_ongpu(1,1,2304,256,784);
time_ongpu(0,0,512,4608,196);
time_ongpu(1,1,4608,512,196);
return 0;
}
#endif
void init_cpu() {
is_avx();
is_fma_avx2();
}
|
module_bl_mynn_mym_turbulence_impl.h |
#ifndef __MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_H__
#define __MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_H__
// File version granularity.
#ifndef MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_VERSION_MAJOR
#define MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_VERSION_MAJOR 1
#endif
#ifndef MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_VERSION_MINOR
#define MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_VERSION_MINOR 0
#endif
#ifndef MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_PATCH_VERSION
#define MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_PATCH_VERSION 0
#endif
#ifndef MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_CREATE_DATE
#define MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_CREATE_DATE "Date: 10-11-2016 , Time: 11:57 AM GMT+2"
#endif
// Set this value to successful build date/time.
#ifndef MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_BUILD_DATE
#define MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_BUILD_DATE ""
#endif
#ifndef MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_AUTHOR
#define MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_AUTHOR "Name: Bernard Gingold , e-mail: beniekg@gmail.com"
#endif
#include "module_bl_mynn_F90_iface.h"
#include "PhysLib_Config.h"
#include "std_headers.h"
namespace wrf_phys_wrappers {
namespace module_bl_mynn {
template<typename R32 = float,
typename I32 = int > struct Wrap_Mym_Turbulence {
/*************************************
Constructors and Destructor.
**************************************/
/*
@Purpose:
Deafult Constructor - explicitly default.
*/
Wrap_Mym_Turbulence() = default;
/*
@Purpose:
1st 'main' Constructor which purpose
is to allocate and initialize scalar
and array members. Array members are
zero-filled. Caller must later initialize
input arrays to correct physical state.
*/
Wrap_Mym_Turbulence(_In_ const I32 kts,
_In_ const I32 kte,
_In_ const I32 levflag,
_In_ const I32 bl_mynn_mixlength,
_In_ const I32 bl_mynn_edmf,
_In_ const I32 bl_mynn_tkebudget,
_In_ const R32 rmo,
_In_ const R32 flt,
_In_ const R32 flq,
_In_ const R32 Psig_bl,
_In_ const R32 Psig_shcu,
_In_ const R32 zi)
:
m_kts{ kts },
m_kte{ kte },
m_levflag{ levflag },
m_bl_mynn_mixlength{ bl_mynn_mixlength },
m_bl_mynn_edmf{ bl_mynn_edmf },
m_bl_mynn_tkebudget{ bl_mynn_tkebudget },
m_rmo{ rmo },
m_flt{ flt },
m_flq{ flq },
m_Psig_bl{ Psig_bl },
m_Psig_shcu{ Psig_shcu },
m_zi{ zi },
m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_zw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) },
m_u{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_v{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_thl{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qw{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_ql{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_tsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_cov{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_vt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_vq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_cldfra_bl1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_edmf_a1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_edmf_qc1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_theta{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_sh{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_el{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfm{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfh{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdk{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdc{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_tcd{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qcd{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qWT1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qSHEAR1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qBUOY1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qDISS1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) } {
for (int i{ 0 }; i != this->m_totArrays; ++i) {
if ((&this->m_dz)[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 1st Ctor: 'Wrap_Mym_Turbulence'!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_dz)[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if(m_kte >= (1 << 16))
for (int i = m_kts; i != m_kte; ++i) {
m_dz[i] = 0.f;
m_zw[i] = 0.f;
m_u[i] = 0.f;
m_v[i] = 0.f;
m_thl[i] = 0.f;
m_ql[i] = 0.f;
m_qw[i] = 0.f;
m_qke[i] = 0.f;
m_tsq[i] = 0.f;
m_qsq[i] = 0.f;
m_cov[i] = 0.f;
m_vt[i] = 0.f;
m_vq[i] = 0.f;
m_cldfra_bl1D[i] = 0.f;
m_edmf_a1[i] = 0.f;
m_edmf_qc1[i] = 0.f;
m_el[i] = 0.f;
m_dfm[i] = 0.f;
m_dfh[i] = 0.f;
m_dfq[i] = 0.f;
m_pdk[i] = 0.f;
m_pdt[i] = 0.f;
m_pdq[i] = 0.f;
m_pdc[i] = 0.f;
m_tcd[i] = 0.f;
m_qcd[i] = 0.f;
m_qWT1D[i] = 0.f;
m_qSHEAR1D[i] = 0.f;
m_qBUOY1D[i] = 0.f;
m_qDISS1D[i] = 0.f;
}
const int top = m_kte + 1;
m_zw[top] = 0.f;
#else
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for (int i = m_kts; i != m_kte; ++i) {
m_dz[i] = 0.f;
m_zw[i] = 0.f;
m_u[i] = 0.f;
m_v[i] = 0.f;
m_thl[i] = 0.f;
m_ql[i] = 0.f;
m_qw[i] = 0.f;
m_qke[i] = 0.f;
m_tsq[i] = 0.f;
m_qsq[i] = 0.f;
m_cov[i] = 0.f;
m_vt[i] = 0.f;
m_vq[i] = 0.f;
m_cldfra_bl1D[i] = 0.f;
m_edmf_a1[i] = 0.f;
m_edmf_qc1[i] = 0.f;
m_el[i] = 0.f;
m_dfm[i] = 0.f;
m_dfh[i] = 0.f;
m_dfq[i] = 0.f;
m_pdk[i] = 0.f;
m_pdt[i] = 0.f;
m_pdq[i] = 0.f;
m_pdc[i] = 0.f;
m_tcd[i] = 0.f;
m_qcd[i] = 0.f;
m_qWT1D[i] = 0.f;
m_qSHEAR1D[i] = 0.f;
m_qBUOY1D[i] = 0.f;
m_qDISS1D[i] = 0.f;
}
const int top = m_kte + 1;
m_zw[top] = 0.f;
#endif
}
/*
@Purpose:
2nd 'main' Constructor which purpose
is to allocate and initialize scalar
and array members. Array output members are
zero-filled. Caller must pass initialized
input arrays to correct physical state.
*/
Wrap_Mym_Turbulence(_In_ const I32 kts,
_In_ const I32 kte,
_In_ const I32 levflag,
_In_ const I32 bl_mynn_mixlength,
_In_ const I32 bl_mynn_edmf,
_In_ const I32 bl_mynn_tkebudget,
_In_ const R32 rmo,
_In_ const R32 flt,
_In_ const R32 flq,
_In_ const R32 Psig_bl,
_In_ const R32 Psig_shcu,
_In_ const R32 zi,
_In_ R32* __restrict dz,
_In_ R32* __restrict zw,
_In_ R32* __restrict u,
_In_ R32* __restrict v,
_In_ R32* __restrict thl,
_In_ R32* __restrict qw,
_In_ R32* __restrict ql,
_In_ R32* __restrict qke,
_In_ R32* __restrict tsq,
_In_ R32* __restrict qsq,
_In_ R32* __restrict cov,
_In_ R32* __restrict vt,
_In_ R32* __restrict vq,
_In_ R32* __restrict cldfra_bl1D,
_In_ R32* __restrict edmf_a1,
_In_ R32* __restrict edmf_qc1,
_In_ R32* __restrict theta,
_In_ R32* __restrict qWT1D,
_In_ R32* __restrict qSHEAR1D,
_In_ R32* __restrict qBUOY1D,
_In_ R32* __restrict qDISS1)
:
m_kts{ kts },
m_kte{ kte },
m_levflag{ levflag },
m_bl_mynn_mixlength{ bl_mynn_mixlength },
m_bl_mynn_edmf{ bl_mynn_edmf },
m_bl_mynn_tkebudget{ bl_mynn_tkebudget },
m_rmo{ rmo },
m_flt{ flt },
m_flq{ flq },
m_Psig_bl{ Psig_bl },
m_Psig_shcu{ Psig_shcu },
m_zi{ zi },
m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_zw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) },
m_u{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_v{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_thl{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qw{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_ql{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_tsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_cov{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_vt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_vq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_cldfra_bl1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_edmf_a1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_edmf_qc1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_theta{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_sh{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_el{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfm{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfh{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdk{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdc{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_tcd{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qcd{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qWT1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qSHEAR1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qBUOY1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qDISS1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) } {
for (int i{ 0 }; i != this->m_totArrays; ++i) {
if ((&this->m_dz)[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor: 'Wrap_Mym_Turbulence'!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_dz)[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
if (dz == NULL ||
zw == NULL ||
u == NULL ||
v == NULL ||
thl == NULL ||
qw == NULL ||
ql == NULL ||
qke == NULL ||
tsq == NULL ||
qsq == NULL ||
cov == NULL ||
vt == NULL ||
vq == NULL ||
cldfra_bl1D == NULL ||
edmf_a1 == NULL ||
edmf_qc1 == NULL ||
qWT1D == NULL ||
qSHEAR1D == NULL ||
qBUOY1D == NULL ||
qDISS1 == NULL ) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor: 'Wrap_Mym_Turbulence'!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "One or more caller's arrays contains invalid pointer!!\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if(m_kte >= (1 << 16))
for (int i = m_kts; i != m_kte; ++i) {
m_dz[i] = dz[i];
m_zw[i] = zw[i];
m_u[i] = u[i];
m_v[i] = v[i];
m_thl[i] = thl[i];
m_ql[i] = ql[i];
m_qw[i] = qw[i];
m_qke[i] = qke[i];
m_tsq[i] = tsq[i];
m_qsq[i] = qsq[i];
m_cov[i] = cov[i];
m_vt[i] = vt[i];
m_vq[i] = vq[i];
m_cldfra_bl1D[i] = cldfra_bl1D[i];
m_edmf_a1[i] = edmf_a1[i];
m_edmf_qc1[i] = edmf_qc1[i];
m_el[i] = 0.f;
m_dfm[i] = 0.f;
m_dfh[i] = 0.f;
m_dfq[i] = 0.f;
m_pdk[i] = 0.f;
m_pdt[i] = 0.f;
m_pdq[i] = 0.f;
m_pdc[i] = 0.f;
m_tcd[i] = 0.f;
m_qcd[i] = 0.f;
m_qWT1D[i] = qWT1D[i];
m_qSHEAR1D[i] = qSHEAR1D[i];
m_qBUOY1D[i] = qBUOY1D[i];
m_qDISS1D[i] = qDISS1[i];
}
const int top = m_kte + 1;
m_zw[top] = zw[top];
#else
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for (int i = m_kts; i != m_kte; ++i) {
m_dz[i] = dz[i];
m_zw[i] = zw[i];
m_u[i] = u[i];
m_v[i] = v[i];
m_thl[i] = thl[i];
m_ql[i] = ql[i];
m_qw[i] = qw[i];
m_qke[i] = qke[i];
m_tsq[i] = tsq[i];
m_qsq[i] = qsq[i];
m_cov[i] = cov[i];
m_vt[i] = vt[i];
m_vq[i] = vq[i];
m_cldfra_bl1D[i] = cldfra_bl1D[i];
m_edmf_a1[i] = edmf_a1[i];
m_edmf_qc1[i] = edmf_qc1[i];
m_el[i] = 0.f;
m_dfm[i] = 0.f;
m_dfh[i] = 0.f;
m_dfq[i] = 0.f;
m_pdk[i] = 0.f;
m_pdt[i] = 0.f;
m_pdq[i] = 0.f;
m_pdc[i] = 0.f;
m_tcd[i] = 0.f;
m_qcd[i] = 0.f;
m_qWT1D[i] = qWT1D[i];
m_qSHEAR1D[i] = qSHEAR1D[i];
m_qBUOY1D[i] = qBUOY1D[i];
m_qDISS1D[i] = qDISS1[i];
}
const int top = m_kte + 1;
m_zw[top] = zw[top];
#endif
}
/*
@Purpose:
Copy Constructor implements deep copy semantics.
*/
Wrap_Mym_Turbulence(_In_ const Wrap_Mym_Turbulence &x)
:
m_kts{ x.m_kts },
m_kte{ x.m_kte },
m_levflag{ x.m_levflag },
m_bl_mynn_mixlength{ x.m_bl_mynn_mixlength },
m_bl_mynn_edmf{ x.m_bl_mynn_edmf },
m_bl_mynn_tkebudget{ x.m_bl_mynn_tkebudget },
m_rmo{ x.m_rmo },
m_flt{ x.m_flt },
m_flq{ x.m_flq },
m_Psig_bl{ x.m_Psig_bl },
m_Psig_shcu{ x.m_Psig_shcu },
m_zi{ x.m_zi },
m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_zw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) },
m_u{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_v{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_thl{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qw{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_ql{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_tsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qsq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_cov{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_vt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_vq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_cldfra_bl1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_edmf_a1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_edmf_qc1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_theta{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_sh{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_el{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfm{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfh{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_dfq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdk{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdt{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdq{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_pdc{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_tcd{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qcd{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qWT1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qSHEAR1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qBUOY1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) },
m_qDISS1D{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) } {
for (int i{ 0 }; i != this->m_totArrays; ++i) {
if ((&this->m_dz)[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy Ctor: 'Wrap_Mym_Turbulence'!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_dz)[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if(m_kte >= (1 << 16))
for (int i = m_kts; i != m_kte; ++i) {
m_dz[i] = x.m_dz[i];
m_zw[i] = x.m_zw[i];
m_u[i] = x.m_u[i];
m_v[i] = x.m_v[i];
m_thl[i] = x.m_thl[i];
m_ql[i] = x.m_ql[i];
m_qw[i] = x.m_qw[i];
m_qke[i] = x.m_qke[i];
m_tsq[i] = x.m_tsq[i];
m_qsq[i] = x.m_qsq[i];
m_cov[i] = x.m_cov[i];
m_vt[i] = x.m_vt[i];
m_vq[i] = x.m_vq[i];
m_cldfra_bl1D[i] = x.m_cldfra_bl1D[i];
m_edmf_a1[i] = x.m_edmf_a1[i];
m_edmf_qc1[i] = x.m_edmf_qc1[i];
m_el[i] = x.m_el[i];
m_dfm[i] = x.m_dfm[i];
m_dfh[i] = x.m_dfh[i];
m_dfq[i] = x.m_dfq[i];
m_pdk[i] = x.m_pdk[i];
m_pdt[i] = x.m_pdt[i];
m_pdq[i] = x.m_pdq[i];
m_pdc[i] = x.m_pdc[i];
m_tcd[i] = x.m_tcd[i];
m_qcd[i] = x.m_qcd[i];
m_qWT1D[i] = x.m_qWT1D[i];
m_qSHEAR1D[i] = x.m_qSHEAR1D[i];
m_qBUOY1D[i] = x.m_qBUOY1D[i];
m_qDISS1D[i] = x.m_qDISS1[i];
}
const int top = m_kte + 1;
m_zw[top] = x.m_zw[top];
#else
#if defined (USE_AUTO_VECTRORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for (int i = m_kts; i != m_kte; ++i) {
m_dz[i] = x.m_dz[i];
m_zw[i] = x.m_zw[i];
m_u[i] = x.m_u[i];
m_v[i] = x.m_v[i];
m_thl[i] = x.m_thl[i];
m_ql[i] = x.m_ql[i];
m_qw[i] = x.m_qw[i];
m_qke[i] = x.m_qke[i];
m_tsq[i] = x.m_tsq[i];
m_qsq[i] = x.m_qsq[i];
m_cov[i] = x.m_cov[i];
m_vt[i] = x.m_vt[i];
m_vq[i] = x.m_vq[i];
m_cldfra_bl1D[i] = x.m_cldfra_bl1D[i];
m_edmf_a1[i] = x.m_edmf_a1[i];
m_edmf_qc1[i] = x.m_edmf_qc1[i];
m_el[i] = x.m_el[i];
m_dfm[i] = x.m_dfm[i];
m_dfh[i] = x.m_dfh[i];
m_dfq[i] = x.m_dfq[i];
m_pdk[i] = x.m_pdk[i];
m_pdt[i] = x.m_pdt[i];
m_pdq[i] = x.m_pdq[i];
m_pdc[i] = x.m_pdc[i];
m_tcd[i] = x.m_tcd[i];
m_qcd[i] = x.m_qcd[i];
m_qWT1D[i] = x.m_qWT1D[i];
m_qSHEAR1D[i] = x.m_qSHEAR1D[i];
m_qBUOY1D[i] = x.m_qBUOY1D[i];
m_qDISS1D[i] = x.m_qDISS1[i];
}
const int top = m_kte + 1;
m_zw[top] = x.m_zw[top];
#endif
}
/*
@Purpose:
Move Constructor implements shallow copy semantics.
*/
Wrap_Mym_Turbulence(_In_ Wrap_Mym_Turbulence &&x)
:
m_kts{ x.m_kts },
m_kte{ x.m_kte },
m_levflag{ x.m_levflag },
m_bl_mynn_mixlength{ x.m_bl_mynn_mixlength },
m_bl_mynn_edmf{ x.m_bl_mynn_edmf },
m_bl_mynn_tkebudget{ x.m_bl_mynn_tkebudget },
m_rmo{ x.m_rmo },
m_flt{ x.m_flt },
m_flq{ x.m_flq },
m_Psig_bl{ x.m_Psig_bl },
m_Psig_shcu{ x.m_Psig_shcu },
m_zi{ x.m_zi } {
for (int i{ 0 }; i != this->m_totArrays; ++i) {
(&this->m_dz)[i] = (&x.m_dz)[i];
}
for (int i{ 0 }; i != this->m_totArrays; ++i) {
(&x.m_dz)[i] = NULL;
}
this->m_kts = 0;
this->m_kte = 0;
}
/*
@Purpose:
Class Destructor.
*/
~Wrap_Mym_Turbulence() {
for (int i{ 0 }; i != this->m_totArrays; ++i) {
if ((&this->m_dz)[i]) {
_mm_free((&this->m_dz)[i]);
}
}
for (int i{ 0 }; i != this->m_totArrays; ++i) {
(&this->m_dz)[i] = NULL;
}
this->m_kts = 0;
this->m_kte = 0;
}
/*
@Purpose:
Copy-assign Operator implements deep copy semantics.
*/
Wrap_Mym_Turbulence & operator=(_In_ const Wrap_Mym_Turbulence &x) {
if (this == &x) return (*this);
m_kts = x.m_kts;
m_kte = x.m_kte;
m_levflag = x.m_levflag;
m_bl_mynn_mixlength = x.m_bl_mynn_mixlength;
m_bl_mynn_edmf = x.m_bl_mynn_edmf;
m_bl_mynn_tkebudget = x.m_bl_mynn_tkebudget;
m_rmo = x.m_rmo;
m_flt = x.m_flt;
m_flq = x.m_flq;
m_Psig_bl = x.m_Psig_bl;
m_Psig_shcu = x.m_Psig_shcu;
m_zi = x.m_zi;
constexpr int ntPtrs1{32};
R32 *tPtrs1D[ntPtrs1] = {};
for (int i{ 0 }; i != this->m_totArrays; ++i) {
tPtrs1D[i] = reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)),align32B));
}
for (int i{ 0 }; i != this->m_totArrays; ++i) {
if (ntPtrs1[i] == NULL) {
std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy Operator: 'Wrap_Mym_Turbulence'!!\n";
std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n";
std::cerr << "***** ERROR-DETAILS ***** \n";
std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << tPtrs1D[i] << "\n";
std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n";
std::exit(-1);
}
}
#if defined (USE_ICL_OPENMP) && \
OPENMP_CURR_VER >= 40
#pragma omp parallel for if(m_kme >= (1 << 16))
for (int idx = 0; idx != this->m_totArrays; ++i) {
for (int i = m_kms; i != m_kme; ++i) {
tPtrs1D[idx][i] = (&x.m_dz)[idx][i];
}
}
const int top = m_kte + 1;
tPtrs1D[0][top] = x.m_dz[top];
for (int i {0}; i != this->m_totArrays; ++i) {
_mm_free((&this->m_dz)[i]);
}
for (int i {0}; i != this->m_totArrays; ++i) {
(&this->m_dz)[i] = tPtrs1D[i];
}
return (*this);
#else
for (int idx = 0; idx != this->m_totArrays; ++i) {
#if defined (USE_AUTO_VECTORIZATION)
#pragma ivdep
#pragma simd
#pragma unroll(UNROLL_4X)
#endif
for (int i = m_kms; i != m_kme; ++i) {
tPtrs1D[idx][i] = (&x.m_dz)[idx][i];
}
}
const int top = m_kte + 1;
tPtrs1D[0][top] = x.m_dz[top];
for (int i {0}; i != this->m_totArrays; ++i) {
_mm_free((&this->m_dz)[i]);
}
for (int i{ 0 }; i != this->m_totArrays; ++i) {
(&this->m_dz)[i] = tPtrs1D[i];
}
return (*this);
#endif
}
/*
@Purpose:
Move-assign Operator implements shallow copy semantics.
*/
Wrap_Mym_Turbulence & operator=(_In_ Wrap_Mym_Turbulence &&x) {
if (this == &x) return (*this);
m_kts = x.m_kts;
m_kte = x.m_kte;
m_levflag = x.m_levflag;
m_bl_mynn_mixlength = x.m_bl_mynn_mixlength;
m_bl_mynn_edmf = x.m_bl_mynn_edmf;
m_bl_mynn_tkebudget = x.m_bl_mynn_tkebudget;
m_rmo = x.m_rmo;
m_flt = x.m_flt;
m_flq = x.m_flq;
m_Psig_bl = x.m_Psig_bl;
m_Psig_shcu = x.m_Psig_shcu;
m_zi = x.m_zi;
for (int i{ 0 }; i != m_totArrays; ++i) {
_mm_free((&this->m_dz)[i]);
}
for (int i{ 0 }; i != m_totArrays; ++i) {
(&this->m_dz)[i] = (&x.m_dz)[i];
}
for (int i{ 0 }; i != this->m_totArrays; ++i) {
(&x.m_dz)[i] = NULL;
}
m_kts = 0;
m_kte = 0;
return (*this);
}
/*
@Purpose:
Call Fortran 90 'MYM_TURBULENCE' subroutine.
*/
void Call_Mym_Turbulence() {
MODULE_BL_MYNN_mp_MYM_TURBULENCE(&this->m_kts, &this->m_kte,
&this->m_levflag, &this->m_dz[0], &this->m_zw[0],
&this->m_u[0], &this->m_v[0], &this->m_thl[0], &this->m_ql[0],
&this->m_qw[0], &this->m_qke[0], &this->m_tsq[0], &this->m_qsq[0],
&this->m_cov[0], &this->m_vt[0], &this->m_vq[0],
&this->m_rmo, &this->m_flt, &this->m_flq, &this->m_zi,
&this->m_theta[0], &this->m_sh[0], &this->m_el[0],
&this->m_dfm[0], &this->m_dfh[0], &this->m_dfq[0], &this->m_tcd[0],
&this->m_qcd[0], &this->m_pdk[0], &this->m_pdt[0], &this->m_pdq[0],
&this->m_pdc[0], &this->m_qWT1D[0], &this->m_qSHEAR1D[0], &this->m_qBUOY1D[0],
&this->m_qDISS1D[0], &this->m_bl_mynn_tkebudget,
&this->m_Psig_bl, &this->m_Psig_shcu, &this->m_cldfra_bl1D[0],
&this->m_bl_mynn_mixlength, &this->m_edmf_a1[0], &this->m_edmf_qc1[0],
&this->m_bl_mynn_edmf);
}
/*
@Purpose:
Member variables.
*/
I32 m_kts;
I32 m_kte;
I32 m_levflag;
I32 m_bl_mynn_mixlength;
I32 m_bl_mynn_edmf;
I32 m_bl_mynn_tkebudget;
R32 m_rmo;
R32 m_flt;
R32 m_flq;
R32 m_Psig_bl;
R32 m_Psig_shcu;
R32 m_zi;
// Input arrays.
_Field_size_(m_kte) R32* __restrict m_dz;
_Field_size_(m_kte) R32* __restrict m_zw;
_Field_size_(m_kte) R32* __restrict m_u;
_Field_size_(m_kte) R32* __restrict m_v;
_Field_size_(m_kte) R32* __restrict m_thl;
_Field_size_(m_kte) R32* __restrict m_qw;
_Field_size_(m_kte) R32* __restrict m_ql;
_Field_size_(m_kte) R32* __restrict m_qke;
_Field_size_(m_kte) R32* __restrict m_tsq;
_Field_size_(m_kte) R32* __restrict m_qsq;
_Field_size_(m_kte) R32* __restrict m_cov;
_Field_size_(m_kte) R32* __restrict m_vt;
_Field_size_(m_kte) R32* __restrict m_vq;
_Field_size_(m_kte) R32* __restrict m_cldfra_bl1D;
_Field_size_(m_kte) R32* __restrict m_edmf_a1;
_Field_size_(m_kte) R32* __restrict m_edmf_qc1;
_Field_size_(m_kte) R32* __restrict m_theta;
_Field_size_(m_kte) R32* __restrict m_sh;
// Output arrays.
_Field_size_(m_kte) R32* __restrict m_el;
_Field_size_(m_kte) R32* __restrict m_dfm;
_Field_size_(m_kte) R32* __restrict m_dfh;
_Field_size_(m_kte) R32* __restrict m_dfq;
_Field_size_(m_kte) R32* __restrict m_pdk;
_Field_size_(m_kte) R32* __restrict m_pdt;
_Field_size_(m_kte) R32* __restrict m_pdq;
_Field_size_(m_kte) R32* __restrict m_pdc;
_Field_size_(m_kte) R32* __restrict m_tcd;
_Field_size_(m_kte) R32* __restrict m_qcd;
_Field_size_(m_kte) R32* __restrict m_qWT1D;
_Field_size_(m_kte) R32* __restrict m_qSHEAR1D;
_Field_size_(m_kte) R32* __restrict m_qBUOY1D;
_Field_size_(m_kte) R32* __restrict m_qDISS1D;
static const int m_totArrays = 32;
};
}
}
#endif /*__MODULE_BL_MYNN_MYM_TURBULENCE_IMPL_H__*/ |
par_strength.c | /*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* $Revision: 2.19 $
***********************************************************************EHEADER*/
/******************************************************************************
*
*****************************************************************************/
/* following should be in a header file */
#include "_hypre_parcsr_ls.h"
/*==========================================================================*/
/*==========================================================================*/
/**
Generates strength matrix
Notes:
\begin{itemize}
\item The underlying matrix storage scheme is a hypre_ParCSR matrix.
\item The routine returns the following:
\begin{itemize}
\item S - a ParCSR matrix representing the "strength matrix". This is
used in the coarsening and interpolation routines.
\end{itemize}
\item The graph of the "strength matrix" for A is a subgraph of the
graph of A, but requires nonsymmetric storage even if A is
symmetric. This is because of the directional nature of the
"strengh of dependence" notion (see below). Since we are using
nonsymmetric storage for A right now, this is not a problem. If we
ever add the ability to store A symmetrically, then we could store
the strength graph as floats instead of doubles to save space.
\item This routine currently "compresses" the strength matrix. We
should consider the possibility of defining this matrix to have the
same "nonzero structure" as A. To do this, we could use the same
A\_i and A\_j arrays, and would need only define the S\_data array.
There are several pros and cons to discuss.
\end{itemize}
Terminology:
\begin{itemize}
\item Ruge's terminology: A point is "strongly connected to" $j$, or
"strongly depends on" $j$, if $-a_ij >= \theta max_{l != j} \{-a_il\}$.
\item Here, we retain some of this terminology, but with a more
generalized notion of "strength". We also retain the "natural"
graph notation for representing the directed graph of a matrix.
That is, the nonzero entry $a_ij$ is represented as: i --> j. In
the strength matrix, S, the entry $s_ij$ is also graphically denoted
as above, and means both of the following:
\begin{itemize}
\item $i$ "depends on" $j$ with "strength" $s_ij$
\item $j$ "influences" $i$ with "strength" $s_ij$
\end{itemize}
\end{itemize}
{\bf Input files:}
_hypre_parcsr_ls.h
@return Error code.
@param A [IN]
coefficient matrix
@param strength_threshold [IN]
threshold parameter used to define strength
@param max_row_sum [IN]
parameter used to modify definition of strength for diagonal dominant matrices
@param S_ptr [OUT]
strength matrix
@see */
/*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGCreateS(hypre_ParCSRMatrix *A,
double strength_threshold,
double max_row_sum,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
hypre_ParCSRMatrix **S_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
double *A_diag_data = hypre_CSRMatrixData(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
double *A_offd_data = NULL;
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A);
HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_Int num_nonzeros_diag;
HYPRE_Int num_nonzeros_offd = 0;
HYPRE_Int num_cols_offd = 0;
hypre_ParCSRMatrix *S;
hypre_CSRMatrix *S_diag;
HYPRE_Int *S_diag_i;
HYPRE_Int *S_diag_j;
/* double *S_diag_data; */
hypre_CSRMatrix *S_offd;
HYPRE_Int *S_offd_i = NULL;
HYPRE_Int *S_offd_j = NULL;
/* double *S_offd_data; */
double diag, row_scale, row_sum;
HYPRE_Int i, jA, jS;
HYPRE_Int ierr = 0;
HYPRE_Int *dof_func_offd;
HYPRE_Int num_sends;
HYPRE_Int *int_buf_data;
HYPRE_Int index, start, j;
/*--------------------------------------------------------------
* Compute a ParCSR strength matrix, S.
*
* For now, the "strength" of dependence/influence is defined in
* the following way: i depends on j if
* aij > hypre_max (k != i) aik, aii < 0
* or
* aij < hypre_min (k != i) aik, aii >= 0
* Then S_ij = 1, else S_ij = 0.
*
* NOTE: the entries are negative initially, corresponding
* to "unaccounted-for" dependence.
*----------------------------------------------------------------*/
num_nonzeros_diag = A_diag_i[num_variables];
num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
A_offd_i = hypre_CSRMatrixI(A_offd);
num_nonzeros_offd = A_offd_i[num_variables];
S = hypre_ParCSRMatrixCreate(comm, global_num_vars, global_num_vars,
row_starts, row_starts,
num_cols_offd, num_nonzeros_diag, num_nonzeros_offd);
/* row_starts is owned by A, col_starts = row_starts */
hypre_ParCSRMatrixSetRowStartsOwner(S,0);
S_diag = hypre_ParCSRMatrixDiag(S);
hypre_CSRMatrixI(S_diag) = hypre_CTAlloc(HYPRE_Int, num_variables+1);
hypre_CSRMatrixJ(S_diag) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_diag);
S_offd = hypre_ParCSRMatrixOffd(S);
hypre_CSRMatrixI(S_offd) = hypre_CTAlloc(HYPRE_Int, num_variables+1);
S_diag_i = hypre_CSRMatrixI(S_diag);
S_diag_j = hypre_CSRMatrixJ(S_diag);
S_offd_i = hypre_CSRMatrixI(S_offd);
dof_func_offd = NULL;
if (num_cols_offd)
{
A_offd_data = hypre_CSRMatrixData(A_offd);
hypre_CSRMatrixJ(S_offd) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd);
S_offd_j = hypre_CSRMatrixJ(S_offd);
hypre_ParCSRMatrixColMapOffd(S) = hypre_CTAlloc(HYPRE_Int, num_cols_offd);
if (num_functions > 1)
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd);
}
/*-------------------------------------------------------------------
* Get the dof_func data for the off-processor columns
*-------------------------------------------------------------------*/
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (num_functions > 1)
{
int_buf_data = hypre_CTAlloc(HYPRE_Int,hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends));
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data);
}
/* give S same nonzero structure as A */
hypre_ParCSRMatrixCopy(A,S,0);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,diag,row_scale,row_sum,jA) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_variables; i++)
{
diag = A_diag_data[A_diag_i[i]];
/* compute scaling factor and row sum */
row_scale = 0.0;
row_sum = diag;
if (num_functions > 1)
{
if (diag < 0)
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (dof_func[i] == dof_func[A_diag_j[jA]])
{
row_scale = hypre_max(row_scale, A_diag_data[jA]);
row_sum += A_diag_data[jA];
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (dof_func[i] == dof_func_offd[A_offd_j[jA]])
{
row_scale = hypre_max(row_scale, A_offd_data[jA]);
row_sum += A_offd_data[jA];
}
}
}
else
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (dof_func[i] == dof_func[A_diag_j[jA]])
{
row_scale = hypre_min(row_scale, A_diag_data[jA]);
row_sum += A_diag_data[jA];
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (dof_func[i] == dof_func_offd[A_offd_j[jA]])
{
row_scale = hypre_min(row_scale, A_offd_data[jA]);
row_sum += A_offd_data[jA];
}
}
}
}
else
{
if (diag < 0)
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
row_scale = hypre_max(row_scale, A_diag_data[jA]);
row_sum += A_diag_data[jA];
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
row_scale = hypre_max(row_scale, A_offd_data[jA]);
row_sum += A_offd_data[jA];
}
}
else
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
row_scale = hypre_min(row_scale, A_diag_data[jA]);
row_sum += A_diag_data[jA];
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
row_scale = hypre_min(row_scale, A_offd_data[jA]);
row_sum += A_offd_data[jA];
}
}
}
row_sum = fabs( row_sum / diag );
/* compute row entries of S */
S_diag_j[A_diag_i[i]] = -1;
if ((row_sum > max_row_sum) && (max_row_sum < 1.0))
{
/* make all dependencies weak */
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
S_diag_j[jA] = -1;
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
S_offd_j[jA] = -1;
}
}
else
{
if (num_functions > 1)
{
if (diag < 0)
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (A_diag_data[jA] <= strength_threshold * row_scale
|| dof_func[i] != dof_func[A_diag_j[jA]])
{
S_diag_j[jA] = -1;
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (A_offd_data[jA] <= strength_threshold * row_scale
|| dof_func[i] != dof_func_offd[A_offd_j[jA]])
{
S_offd_j[jA] = -1;
}
}
}
else
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (A_diag_data[jA] >= strength_threshold * row_scale
|| dof_func[i] != dof_func[A_diag_j[jA]])
{
S_diag_j[jA] = -1;
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (A_offd_data[jA] >= strength_threshold * row_scale
|| dof_func[i] != dof_func_offd[A_offd_j[jA]])
{
S_offd_j[jA] = -1;
}
}
}
}
else
{
if (diag < 0)
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (A_diag_data[jA] <= strength_threshold * row_scale)
{
S_diag_j[jA] = -1;
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (A_offd_data[jA] <= strength_threshold * row_scale)
{
S_offd_j[jA] = -1;
}
}
}
else
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (A_diag_data[jA] >= strength_threshold * row_scale)
{
S_diag_j[jA] = -1;
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (A_offd_data[jA] >= strength_threshold * row_scale)
{
S_offd_j[jA] = -1;
}
}
}
}
}
}
/*--------------------------------------------------------------
* "Compress" the strength matrix.
*
* NOTE: S has *NO DIAGONAL ELEMENT* on any row. Caveat Emptor!
*
* NOTE: This "compression" section of code may be removed, and
* coarsening will still be done correctly. However, the routine
* that builds interpolation would have to be modified first.
*----------------------------------------------------------------*/
/* RDF: not sure if able to thread this loop */
jS = 0;
for (i = 0; i < num_variables; i++)
{
S_diag_i[i] = jS;
for (jA = A_diag_i[i]; jA < A_diag_i[i+1]; jA++)
{
if (S_diag_j[jA] > -1)
{
S_diag_j[jS] = S_diag_j[jA];
jS++;
}
}
}
S_diag_i[num_variables] = jS;
hypre_CSRMatrixNumNonzeros(S_diag) = jS;
/* RDF: not sure if able to thread this loop */
jS = 0;
for (i = 0; i < num_variables; i++)
{
S_offd_i[i] = jS;
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (S_offd_j[jA] > -1)
{
S_offd_j[jS] = S_offd_j[jA];
jS++;
}
}
}
S_offd_i[num_variables] = jS;
hypre_CSRMatrixNumNonzeros(S_offd) = jS;
hypre_ParCSRMatrixCommPkg(S) = NULL;
*S_ptr = S;
hypre_TFree(dof_func_offd);
return (ierr);
}
/*==========================================================================*/
/*==========================================================================*/
/**
Generates strength matrix
Notes:
\begin{itemize}
\item The underlying matrix storage scheme is a hypre_ParCSR matrix.
\item The routine returns the following:
\begin{itemize}
\item S - a ParCSR matrix representing the "strength matrix". This is
used in the coarsening and interpolation routines.
\end{itemize}
\item The graph of the "strength matrix" for A is a subgraph of the
graph of A, but requires nonsymmetric storage even if A is
symmetric. This is because of the directional nature of the
"strengh of dependence" notion (see below). Since we are using
nonsymmetric storage for A right now, this is not a problem. If we
ever add the ability to store A symmetrically, then we could store
the strength graph as floats instead of doubles to save space.
\item This routine currently "compresses" the strength matrix. We
should consider the possibility of defining this matrix to have the
same "nonzero structure" as A. To do this, we could use the same
A\_i and A\_j arrays, and would need only define the S\_data array.
There are several pros and cons to discuss.
\end{itemize}
Terminology:
\begin{itemize}
\item Ruge's terminology: A point is "strongly connected to" $j$, or
"strongly depends on" $j$, if $|a_ij| >= \theta max_{l != j} |a_il|}$.
\item Here, we retain some of this terminology, but with a more
generalized notion of "strength". We also retain the "natural"
graph notation for representing the directed graph of a matrix.
That is, the nonzero entry $a_ij$ is represented as: i --> j. In
the strength matrix, S, the entry $s_ij$ is also graphically denoted
as above, and means both of the following:
\begin{itemize}
\item $i$ "depends on" $j$ with "strength" $s_ij$
\item $j$ "influences" $i$ with "strength" $s_ij$
\end{itemize}
\end{itemize}
{\bf Input files:}
_hypre_parcsr_ls.h
@return Error code.
@param A [IN]
coefficient matrix
@param strength_threshold [IN]
threshold parameter used to define strength
@param max_row_sum [IN]
parameter used to modify definition of strength for diagonal dominant matrices
@param S_ptr [OUT]
strength matrix
@see */
/*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGCreateSabs(hypre_ParCSRMatrix *A,
double strength_threshold,
double max_row_sum,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
hypre_ParCSRMatrix **S_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
double *A_diag_data = hypre_CSRMatrixData(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
double *A_offd_data = NULL;
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A);
HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_Int num_nonzeros_diag;
HYPRE_Int num_nonzeros_offd = 0;
HYPRE_Int num_cols_offd = 0;
hypre_ParCSRMatrix *S;
hypre_CSRMatrix *S_diag;
HYPRE_Int *S_diag_i;
HYPRE_Int *S_diag_j;
/* double *S_diag_data; */
hypre_CSRMatrix *S_offd;
HYPRE_Int *S_offd_i = NULL;
HYPRE_Int *S_offd_j = NULL;
/* double *S_offd_data; */
double diag, row_scale, row_sum;
HYPRE_Int i, jA, jS;
HYPRE_Int ierr = 0;
HYPRE_Int *dof_func_offd;
HYPRE_Int num_sends;
HYPRE_Int *int_buf_data;
HYPRE_Int index, start, j;
/*--------------------------------------------------------------
* Compute a ParCSR strength matrix, S.
*
* For now, the "strength" of dependence/influence is defined in
* the following way: i depends on j if
* aij > hypre_max (k != i) aik, aii < 0
* or
* aij < hypre_min (k != i) aik, aii >= 0
* Then S_ij = 1, else S_ij = 0.
*
* NOTE: the entries are negative initially, corresponding
* to "unaccounted-for" dependence.
*----------------------------------------------------------------*/
num_nonzeros_diag = A_diag_i[num_variables];
num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
A_offd_i = hypre_CSRMatrixI(A_offd);
num_nonzeros_offd = A_offd_i[num_variables];
S = hypre_ParCSRMatrixCreate(comm, global_num_vars, global_num_vars,
row_starts, row_starts,
num_cols_offd, num_nonzeros_diag, num_nonzeros_offd);
/* row_starts is owned by A, col_starts = row_starts */
hypre_ParCSRMatrixSetRowStartsOwner(S,0);
S_diag = hypre_ParCSRMatrixDiag(S);
hypre_CSRMatrixI(S_diag) = hypre_CTAlloc(HYPRE_Int, num_variables+1);
hypre_CSRMatrixJ(S_diag) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_diag);
S_offd = hypre_ParCSRMatrixOffd(S);
hypre_CSRMatrixI(S_offd) = hypre_CTAlloc(HYPRE_Int, num_variables+1);
S_diag_i = hypre_CSRMatrixI(S_diag);
S_diag_j = hypre_CSRMatrixJ(S_diag);
S_offd_i = hypre_CSRMatrixI(S_offd);
dof_func_offd = NULL;
if (num_cols_offd)
{
A_offd_data = hypre_CSRMatrixData(A_offd);
hypre_CSRMatrixJ(S_offd) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd);
S_offd_j = hypre_CSRMatrixJ(S_offd);
hypre_ParCSRMatrixColMapOffd(S) = hypre_CTAlloc(HYPRE_Int, num_cols_offd);
if (num_functions > 1)
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd);
}
/*-------------------------------------------------------------------
* Get the dof_func data for the off-processor columns
*-------------------------------------------------------------------*/
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (num_functions > 1)
{
int_buf_data = hypre_CTAlloc(HYPRE_Int,hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends));
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data);
}
/* give S same nonzero structure as A */
hypre_ParCSRMatrixCopy(A,S,0);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,diag,row_scale,row_sum,jA) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_variables; i++)
{
diag = A_diag_data[A_diag_i[i]];
/* compute scaling factor and row sum */
row_scale = 0.0;
row_sum = diag;
if (num_functions > 1)
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (dof_func[i] == dof_func[A_diag_j[jA]])
{
row_scale = hypre_max(row_scale, fabs(A_diag_data[jA]));
row_sum += fabs(A_diag_data[jA]);
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (dof_func[i] == dof_func_offd[A_offd_j[jA]])
{
row_scale = hypre_max(row_scale, fabs(A_offd_data[jA]));
row_sum += fabs(A_offd_data[jA]);
}
}
}
else
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
row_scale = hypre_max(row_scale, fabs(A_diag_data[jA]));
row_sum += fabs(A_diag_data[jA]);
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
row_scale = hypre_max(row_scale, fabs(A_offd_data[jA]));
row_sum += fabs(A_offd_data[jA]);
}
}
row_sum = fabs( row_sum / diag );
/* compute row entries of S */
S_diag_j[A_diag_i[i]] = -1;
if ((row_sum > max_row_sum) && (max_row_sum < 1.0))
{
/* make all dependencies weak */
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
S_diag_j[jA] = -1;
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
S_offd_j[jA] = -1;
}
}
else
{
if (num_functions > 1)
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (fabs(A_diag_data[jA]) <= strength_threshold * row_scale
|| dof_func[i] != dof_func[A_diag_j[jA]])
{
S_diag_j[jA] = -1;
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (fabs(A_offd_data[jA]) <= strength_threshold * row_scale
|| dof_func[i] != dof_func_offd[A_offd_j[jA]])
{
S_offd_j[jA] = -1;
}
}
}
else
{
for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++)
{
if (fabs(A_diag_data[jA]) <= strength_threshold * row_scale)
{
S_diag_j[jA] = -1;
}
}
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (fabs(A_offd_data[jA]) <= strength_threshold * row_scale)
{
S_offd_j[jA] = -1;
}
}
}
}
}
/*--------------------------------------------------------------
* "Compress" the strength matrix.
*
* NOTE: S has *NO DIAGONAL ELEMENT* on any row. Caveat Emptor!
*
* NOTE: This "compression" section of code may be removed, and
* coarsening will still be done correctly. However, the routine
* that builds interpolation would have to be modified first.
*----------------------------------------------------------------*/
/* RDF: not sure if able to thread this loop */
jS = 0;
for (i = 0; i < num_variables; i++)
{
S_diag_i[i] = jS;
for (jA = A_diag_i[i]; jA < A_diag_i[i+1]; jA++)
{
if (S_diag_j[jA] > -1)
{
S_diag_j[jS] = S_diag_j[jA];
jS++;
}
}
}
S_diag_i[num_variables] = jS;
hypre_CSRMatrixNumNonzeros(S_diag) = jS;
/* RDF: not sure if able to thread this loop */
jS = 0;
for (i = 0; i < num_variables; i++)
{
S_offd_i[i] = jS;
for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++)
{
if (S_offd_j[jA] > -1)
{
S_offd_j[jS] = S_offd_j[jA];
jS++;
}
}
}
S_offd_i[num_variables] = jS;
hypre_CSRMatrixNumNonzeros(S_offd) = jS;
hypre_ParCSRMatrixCommPkg(S) = NULL;
*S_ptr = S;
hypre_TFree(dof_func_offd);
return (ierr);
}
/*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGCreateSCommPkg(hypre_ParCSRMatrix *A,
hypre_ParCSRMatrix *S,
HYPRE_Int **col_offd_S_to_A_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_MPI_Status *status;
hypre_MPI_Request *requests;
hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommPkg *comm_pkg_S;
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
HYPRE_Int *col_map_offd_S = hypre_ParCSRMatrixColMapOffd(S);
HYPRE_Int *recv_procs_A = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A);
HYPRE_Int *recv_vec_starts_A =
hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A);
HYPRE_Int *send_procs_A =
hypre_ParCSRCommPkgSendProcs(comm_pkg_A);
HYPRE_Int *send_map_starts_A =
hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A);
HYPRE_Int *recv_procs_S;
HYPRE_Int *recv_vec_starts_S;
HYPRE_Int *send_procs_S;
HYPRE_Int *send_map_starts_S;
HYPRE_Int *send_map_elmts_S;
HYPRE_Int *col_offd_S_to_A;
HYPRE_Int *S_marker;
HYPRE_Int *send_change;
HYPRE_Int *recv_change;
HYPRE_Int num_variables = hypre_CSRMatrixNumRows(S_diag);
HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd);
HYPRE_Int num_cols_offd_S;
HYPRE_Int i, j, jcol;
HYPRE_Int proc, cnt, proc_cnt, total_nz;
HYPRE_Int first_row;
HYPRE_Int ierr = 0;
HYPRE_Int num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A);
HYPRE_Int num_recvs_A = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A);
HYPRE_Int num_sends_S;
HYPRE_Int num_recvs_S;
HYPRE_Int num_nonzeros;
num_nonzeros = S_offd_i[num_variables];
S_marker = NULL;
if (num_cols_offd_A)
S_marker = hypre_CTAlloc(HYPRE_Int,num_cols_offd_A);
for (i=0; i < num_cols_offd_A; i++)
S_marker[i] = -1;
for (i=0; i < num_nonzeros; i++)
{
jcol = S_offd_j[i];
S_marker[jcol] = 0;
}
proc = 0;
proc_cnt = 0;
cnt = 0;
num_recvs_S = 0;
for (i=0; i < num_recvs_A; i++)
{
for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++)
{
if (!S_marker[j])
{
S_marker[j] = cnt;
cnt++;
proc = 1;
}
}
if (proc) {num_recvs_S++; proc = 0;}
}
num_cols_offd_S = cnt;
recv_change = NULL;
recv_procs_S = NULL;
send_change = NULL;
if (col_map_offd_S) hypre_TFree(col_map_offd_S);
col_map_offd_S = NULL;
col_offd_S_to_A = NULL;
if (num_recvs_A) recv_change = hypre_CTAlloc(HYPRE_Int, num_recvs_A);
if (num_sends_A) send_change = hypre_CTAlloc(HYPRE_Int, num_sends_A);
if (num_recvs_S) recv_procs_S = hypre_CTAlloc(HYPRE_Int, num_recvs_S);
recv_vec_starts_S = hypre_CTAlloc(HYPRE_Int, num_recvs_S+1);
if (num_cols_offd_S)
{
col_map_offd_S = hypre_CTAlloc(HYPRE_Int,num_cols_offd_S);
col_offd_S_to_A = hypre_CTAlloc(HYPRE_Int,num_cols_offd_S);
}
if (num_cols_offd_S < num_cols_offd_A)
{
for (i=0; i < num_nonzeros; i++)
{
jcol = S_offd_j[i];
S_offd_j[i] = S_marker[jcol];
}
proc = 0;
proc_cnt = 0;
cnt = 0;
recv_vec_starts_S[0] = 0;
for (i=0; i < num_recvs_A; i++)
{
for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++)
{
if (S_marker[j] != -1)
{
col_map_offd_S[cnt] = col_map_offd_A[j];
col_offd_S_to_A[cnt++] = j;
proc = 1;
}
}
recv_change[i] = j-cnt-recv_vec_starts_A[i]
+recv_vec_starts_S[proc_cnt];
if (proc)
{
recv_procs_S[proc_cnt++] = recv_procs_A[i];
recv_vec_starts_S[proc_cnt] = cnt;
proc = 0;
}
}
}
else
{
for (i=0; i < num_recvs_A; i++)
{
for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++)
{
col_map_offd_S[j] = col_map_offd_A[j];
col_offd_S_to_A[j] = j;
}
recv_procs_S[i] = recv_procs_A[i];
recv_vec_starts_S[i] = recv_vec_starts_A[i];
}
recv_vec_starts_S[num_recvs_A] = recv_vec_starts_A[num_recvs_A];
}
requests = hypre_CTAlloc(hypre_MPI_Request,num_sends_A+num_recvs_A);
j=0;
for (i=0; i < num_sends_A; i++)
hypre_MPI_Irecv(&send_change[i],1,HYPRE_MPI_INT,send_procs_A[i],
0,comm,&requests[j++]);
for (i=0; i < num_recvs_A; i++)
hypre_MPI_Isend(&recv_change[i],1,HYPRE_MPI_INT,recv_procs_A[i],
0,comm,&requests[j++]);
status = hypre_CTAlloc(hypre_MPI_Status,j);
hypre_MPI_Waitall(j,requests,status);
hypre_TFree(status);
hypre_TFree(requests);
num_sends_S = 0;
total_nz = send_map_starts_A[num_sends_A];
for (i=0; i < num_sends_A; i++)
{
if (send_change[i])
{
if ((send_map_starts_A[i+1]-send_map_starts_A[i]) > send_change[i])
num_sends_S++;
}
else
num_sends_S++;
total_nz -= send_change[i];
}
send_procs_S = NULL;
if (num_sends_S)
send_procs_S = hypre_CTAlloc(HYPRE_Int,num_sends_S);
send_map_starts_S = hypre_CTAlloc(HYPRE_Int,num_sends_S+1);
send_map_elmts_S = NULL;
if (total_nz)
send_map_elmts_S = hypre_CTAlloc(HYPRE_Int,total_nz);
proc = 0;
proc_cnt = 0;
for (i=0; i < num_sends_A; i++)
{
cnt = send_map_starts_A[i+1]-send_map_starts_A[i]-send_change[i];
if (cnt)
{
send_procs_S[proc_cnt++] = send_procs_A[i];
send_map_starts_S[proc_cnt] = send_map_starts_S[proc_cnt-1]+cnt;
}
}
comm_pkg_S = hypre_CTAlloc(hypre_ParCSRCommPkg,1);
hypre_ParCSRCommPkgComm(comm_pkg_S) = comm;
hypre_ParCSRCommPkgNumRecvs(comm_pkg_S) = num_recvs_S;
hypre_ParCSRCommPkgRecvProcs(comm_pkg_S) = recv_procs_S;
hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_S) = recv_vec_starts_S;
hypre_ParCSRCommPkgNumSends(comm_pkg_S) = num_sends_S;
hypre_ParCSRCommPkgSendProcs(comm_pkg_S) = send_procs_S;
hypre_ParCSRCommPkgSendMapStarts(comm_pkg_S) = send_map_starts_S;
comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_S, col_map_offd_S,
send_map_elmts_S);
hypre_ParCSRCommHandleDestroy(comm_handle);
first_row = hypre_ParCSRMatrixFirstRowIndex(A);
if (first_row)
for (i=0; i < send_map_starts_S[num_sends_S]; i++)
send_map_elmts_S[i] -= first_row;
hypre_ParCSRCommPkgSendMapElmts(comm_pkg_S) = send_map_elmts_S;
hypre_ParCSRMatrixCommPkg(S) = comm_pkg_S;
hypre_ParCSRMatrixColMapOffd(S) = col_map_offd_S;
hypre_CSRMatrixNumCols(S_offd) = num_cols_offd_S;
hypre_TFree(S_marker);
hypre_TFree(send_change);
hypre_TFree(recv_change);
*col_offd_S_to_A_ptr = col_offd_S_to_A;
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_BoomerAMGCreate2ndS : creates strength matrix on coarse points
* for second coarsening pass in aggressive coarsening (S*S+2S)
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_BoomerAMGCreate2ndS( hypre_ParCSRMatrix *S, HYPRE_Int *CF_marker,
HYPRE_Int num_paths, HYPRE_Int *coarse_row_starts, hypre_ParCSRMatrix **C_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S);
hypre_ParCSRCommPkg *tmp_comm_pkg;
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
HYPRE_Int num_cols_diag_S = hypre_CSRMatrixNumCols(S_diag);
HYPRE_Int num_cols_offd_S = hypre_CSRMatrixNumCols(S_offd);
hypre_ParCSRMatrix *S2;
HYPRE_Int *col_map_offd_C = NULL;
hypre_CSRMatrix *C_diag;
HYPRE_Int *C_diag_data = NULL;
HYPRE_Int *C_diag_i;
HYPRE_Int *C_diag_j = NULL;
hypre_CSRMatrix *C_offd;
HYPRE_Int *C_offd_data=NULL;
HYPRE_Int *C_offd_i;
HYPRE_Int *C_offd_j=NULL;
HYPRE_Int C_diag_size;
HYPRE_Int C_offd_size;
HYPRE_Int num_cols_offd_C = 0;
HYPRE_Int *S_ext_diag_i = NULL;
HYPRE_Int *S_ext_diag_j = NULL;
HYPRE_Int S_ext_diag_size = 0;
HYPRE_Int *S_ext_offd_i = NULL;
HYPRE_Int *S_ext_offd_j = NULL;
HYPRE_Int S_ext_offd_size = 0;
HYPRE_Int *CF_marker_offd = NULL;
HYPRE_Int *S_marker = NULL;
HYPRE_Int *S_marker_offd = NULL;
HYPRE_Int *temp = NULL;
HYPRE_Int *fine_to_coarse = NULL;
HYPRE_Int *fine_to_coarse_offd = NULL;
HYPRE_Int *map_S_to_C = NULL;
HYPRE_Int num_sends = 0;
HYPRE_Int num_recvs = 0;
HYPRE_Int *send_map_starts;
HYPRE_Int *tmp_send_map_starts = NULL;
HYPRE_Int *send_map_elmts;
HYPRE_Int *recv_vec_starts;
HYPRE_Int *tmp_recv_vec_starts = NULL;
HYPRE_Int *int_buf_data = NULL;
HYPRE_Int i, j, k;
HYPRE_Int i1, i2, i3;
HYPRE_Int jj1, jj2, jcol, jrow, j_cnt;
HYPRE_Int jj_count_diag, jj_count_offd;
HYPRE_Int jj_row_begin_diag, jj_row_begin_offd;
HYPRE_Int cnt, cnt_offd, cnt_diag;
HYPRE_Int num_procs, my_id;
HYPRE_Int value, index;
HYPRE_Int num_coarse;
HYPRE_Int num_coarse_offd;
HYPRE_Int num_nonzeros;
HYPRE_Int num_nonzeros_diag;
HYPRE_Int num_nonzeros_offd;
HYPRE_Int global_num_coarse;
HYPRE_Int my_first_cpt, my_last_cpt;
HYPRE_Int *S_int_i = NULL;
HYPRE_Int *S_int_j = NULL;
HYPRE_Int *S_ext_i = NULL;
HYPRE_Int *S_ext_j = NULL;
/*-----------------------------------------------------------------------
* Extract S_ext, i.e. portion of B that is stored on neighbor procs
* and needed locally for matrix matrix product
*-----------------------------------------------------------------------*/
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm, &my_id);
#ifdef HYPRE_NO_GLOBAL_PARTITION
my_first_cpt = coarse_row_starts[0];
my_last_cpt = coarse_row_starts[1]-1;
if (my_id == (num_procs -1)) global_num_coarse = coarse_row_starts[1];
hypre_MPI_Bcast(&global_num_coarse, 1, HYPRE_MPI_INT, num_procs-1, comm);
#else
my_first_cpt = coarse_row_starts[my_id];
my_last_cpt = coarse_row_starts[my_id+1]-1;
global_num_coarse = coarse_row_starts[num_procs];
#endif
if (num_cols_offd_S)
{
CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S);
fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S);
}
if (num_cols_diag_S) fine_to_coarse = hypre_CTAlloc(HYPRE_Int, num_cols_diag_S);
num_coarse = 0;
for (i=0; i < num_cols_diag_S; i++)
{
if (CF_marker[i] > 0)
{
fine_to_coarse[i] = num_coarse + my_first_cpt;
num_coarse++;
}
else
{
fine_to_coarse[i] = -1;
}
}
if (num_procs > 1)
{
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(S);
comm_pkg = hypre_ParCSRMatrixCommPkg(S);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg);
send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg);
num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg);
recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends]);
index = 0;
for (i = 0; i < num_sends; i++)
{
for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++)
int_buf_data[index++]
= fine_to_coarse[send_map_elmts[j]];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
fine_to_coarse_offd);
for (i=0; i < num_cols_diag_S; i++)
if (CF_marker[i] > 0)
fine_to_coarse[i] -= my_first_cpt;
hypre_ParCSRCommHandleDestroy(comm_handle);
index = 0;
for (i = 0; i < num_sends; i++)
{
for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++)
{
int_buf_data[index++] = CF_marker[send_map_elmts[j]];
}
}
comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data,
CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data);
S_int_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends]+1);
S_ext_i = hypre_CTAlloc(HYPRE_Int, recv_vec_starts[num_recvs]+1);
/*--------------------------------------------------------------------------
* generate S_int_i through adding number of coarse row-elements of offd and diag
* for corresponding rows. S_int_i[j+1] contains the number of coarse elements of
* a row j (which is determined through send_map_elmts)
*--------------------------------------------------------------------------*/
S_int_i[0] = 0;
j_cnt = 0;
num_nonzeros = 0;
for (i=0; i < num_sends; i++)
{
for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++)
{
jrow = send_map_elmts[j];
index = 0;
for (k = S_diag_i[jrow]; k < S_diag_i[jrow+1]; k++)
{
if (CF_marker[S_diag_j[k]] > 0) index++;
}
for (k = S_offd_i[jrow]; k < S_offd_i[jrow+1]; k++)
{
if (CF_marker_offd[S_offd_j[k]] > 0) index++;
}
S_int_i[++j_cnt] = index;
num_nonzeros += S_int_i[j_cnt];
}
}
/*--------------------------------------------------------------------------
* initialize communication
*--------------------------------------------------------------------------*/
if (num_procs > 1)
comm_handle =
hypre_ParCSRCommHandleCreate(11,comm_pkg,&S_int_i[1],&S_ext_i[1]);
if (num_nonzeros) S_int_j = hypre_CTAlloc(HYPRE_Int, num_nonzeros);
tmp_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1);
tmp_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1);
tmp_send_map_starts[0] = 0;
j_cnt = 0;
for (i=0; i < num_sends; i++)
{
for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++)
{
jrow = send_map_elmts[j];
for (k=S_diag_i[jrow]; k < S_diag_i[jrow+1]; k++)
{
if (CF_marker[S_diag_j[k]] > 0)
S_int_j[j_cnt++] = fine_to_coarse[S_diag_j[k]]+my_first_cpt;
}
for (k=S_offd_i[jrow]; k < S_offd_i[jrow+1]; k++)
{
if (CF_marker_offd[S_offd_j[k]] > 0)
S_int_j[j_cnt++] = fine_to_coarse_offd[S_offd_j[k]];
}
}
tmp_send_map_starts[i+1] = j_cnt;
}
tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1);
hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm;
hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends;
hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs;
hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) =
hypre_ParCSRCommPkgSendProcs(comm_pkg);
hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) =
hypre_ParCSRCommPkgRecvProcs(comm_pkg);
hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = tmp_send_map_starts;
hypre_ParCSRCommHandleDestroy(comm_handle);
comm_handle = NULL;
/*--------------------------------------------------------------------------
* after communication exchange S_ext_i[j+1] contains the number of coarse elements
* of a row j !
* evaluate S_ext_i and compute num_nonzeros for S_ext
*--------------------------------------------------------------------------*/
for (i=0; i < recv_vec_starts[num_recvs]; i++)
S_ext_i[i+1] += S_ext_i[i];
num_nonzeros = S_ext_i[recv_vec_starts[num_recvs]];
if (num_nonzeros) S_ext_j = hypre_CTAlloc(HYPRE_Int, num_nonzeros);
tmp_recv_vec_starts[0] = 0;
for (i=0; i < num_recvs; i++)
tmp_recv_vec_starts[i+1] = S_ext_i[recv_vec_starts[i+1]];
hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = tmp_recv_vec_starts;
comm_handle = hypre_ParCSRCommHandleCreate(11,tmp_comm_pkg,S_int_j,S_ext_j);
hypre_ParCSRCommHandleDestroy(comm_handle);
comm_handle = NULL;
hypre_TFree(tmp_send_map_starts);
hypre_TFree(tmp_recv_vec_starts);
hypre_TFree(tmp_comm_pkg);
hypre_TFree(S_int_i);
hypre_TFree(S_int_j);
S_ext_diag_size = 0;
S_ext_offd_size = 0;
for (i=0; i < num_cols_offd_S; i++)
{
for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++)
{
if (S_ext_j[j] < my_first_cpt || S_ext_j[j] > my_last_cpt)
S_ext_offd_size++;
else
S_ext_diag_size++;
}
}
S_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S+1);
S_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S+1);
if (S_ext_diag_size)
{
S_ext_diag_j = hypre_CTAlloc(HYPRE_Int, S_ext_diag_size);
}
if (S_ext_offd_size)
{
S_ext_offd_j = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size);
}
cnt_offd = 0;
cnt_diag = 0;
cnt = 0;
num_coarse_offd = 0;
for (i=0; i < num_cols_offd_S; i++)
{
if (CF_marker_offd[i] > 0) num_coarse_offd++;
for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++)
{
i1 = S_ext_j[j];
if (i1 < my_first_cpt || i1 > my_last_cpt)
S_ext_offd_j[cnt_offd++] = i1;
else
S_ext_diag_j[cnt_diag++] = i1 - my_first_cpt;
}
S_ext_diag_i[++cnt] = cnt_diag;
S_ext_offd_i[cnt] = cnt_offd;
}
hypre_TFree(S_ext_i);
hypre_TFree(S_ext_j);
cnt = 0;
if (S_ext_offd_size || num_coarse_offd)
{
temp = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size+num_coarse_offd);
for (i=0; i < S_ext_offd_size; i++)
temp[i] = S_ext_offd_j[i];
cnt = S_ext_offd_size;
for (i=0; i < num_cols_offd_S; i++)
if (CF_marker_offd[i] > 0) temp[cnt++] = fine_to_coarse_offd[i];
}
if (cnt)
{
qsort0(temp, 0, cnt-1);
num_cols_offd_C = 1;
value = temp[0];
for (i=1; i < cnt; i++)
{
if (temp[i] > value)
{
value = temp[i];
temp[num_cols_offd_C++] = value;
}
}
}
if (num_cols_offd_C)
col_map_offd_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_C);
for (i=0; i < num_cols_offd_C; i++)
col_map_offd_C[i] = temp[i];
if (S_ext_offd_size || num_coarse_offd)
hypre_TFree(temp);
for (i=0 ; i < S_ext_offd_size; i++)
S_ext_offd_j[i] = hypre_BinarySearch(col_map_offd_C,
S_ext_offd_j[i],
num_cols_offd_C);
if (num_cols_offd_S)
{
map_S_to_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_S);
cnt = 0;
for (i=0; i < num_cols_offd_S; i++)
{
if (CF_marker_offd[i] > 0)
{
while (fine_to_coarse_offd[i] > col_map_offd_C[cnt])
{
cnt++;
}
map_S_to_C[i] = cnt++;
}
else
{
map_S_to_C[i] = -1;
}
}
}
}
/*-----------------------------------------------------------------------
* Allocate and initialize some stuff.
*-----------------------------------------------------------------------*/
if (num_coarse) S_marker = hypre_CTAlloc(HYPRE_Int, num_coarse);
for (i1 = 0; i1 < num_coarse; i1++)
S_marker[i1] = -1;
S_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C);
for (i1 = 0; i1 < num_cols_offd_C; i1++)
S_marker_offd[i1] = -1;
C_diag_i = hypre_CTAlloc(HYPRE_Int, num_coarse+1);
C_offd_i = hypre_CTAlloc(HYPRE_Int, num_coarse+1);
/*-----------------------------------------------------------------------
* Loop over rows of S
*-----------------------------------------------------------------------*/
cnt = 0;
num_nonzeros_diag = 0;
num_nonzeros_offd = 0;
for (i1 = 0; i1 < num_cols_diag_S; i1++)
{
if (CF_marker[i1] > 0)
{
for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++)
{
jcol = S_diag_j[jj1];
if (CF_marker[jcol] > 0)
{
S_marker[fine_to_coarse[jcol]] = i1;
num_nonzeros_diag++;
}
}
for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++)
{
jcol = S_offd_j[jj1];
if (CF_marker_offd[jcol] > 0)
{
S_marker_offd[map_S_to_C[jcol]] = i1;
num_nonzeros_offd++;
}
}
for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++)
{
i2 = S_diag_j[jj1];
for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++)
{
i3 = S_diag_j[jj2];
if (CF_marker[i3] > 0 && S_marker[fine_to_coarse[i3]] != i1)
{
S_marker[fine_to_coarse[i3]] = i1;
num_nonzeros_diag++;
}
}
for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++)
{
i3 = S_offd_j[jj2];
if (CF_marker_offd[i3] > 0 &&
S_marker_offd[map_S_to_C[i3]] != i1)
{
S_marker_offd[map_S_to_C[i3]] = i1;
num_nonzeros_offd++;
}
}
}
for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++)
{
i2 = S_offd_j[jj1];
for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++)
{
i3 = S_ext_diag_j[jj2];
if (S_marker[i3] != i1)
{
S_marker[i3] = i1;
num_nonzeros_diag++;
}
}
for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++)
{
i3 = S_ext_offd_j[jj2];
if (S_marker_offd[i3] != i1)
{
S_marker_offd[i3] = i1;
num_nonzeros_offd++;
}
}
}
C_diag_i[++cnt] = num_nonzeros_diag;
C_offd_i[cnt] = num_nonzeros_offd;
}
}
if (num_nonzeros_diag)
{
C_diag_j = hypre_CTAlloc(HYPRE_Int,num_nonzeros_diag);
C_diag_data = hypre_CTAlloc(HYPRE_Int,num_nonzeros_diag);
}
if (num_nonzeros_offd)
{
C_offd_j = hypre_CTAlloc(HYPRE_Int,num_nonzeros_offd);
C_offd_data = hypre_CTAlloc(HYPRE_Int,num_nonzeros_offd);
}
for (i1 = 0; i1 < num_coarse; i1++)
S_marker[i1] = -1;
for (i1 = 0; i1 < num_cols_offd_C; i1++)
S_marker_offd[i1] = -1;
jj_count_diag = 0;
jj_count_offd = 0;
for (i1 = 0; i1 < num_cols_diag_S; i1++)
{
/*--------------------------------------------------------------------
* Set marker for diagonal entry, C_{i1,i1} (for square matrices).
*--------------------------------------------------------------------*/
jj_row_begin_diag = jj_count_diag;
jj_row_begin_offd = jj_count_offd;
if (CF_marker[i1] > 0)
{
for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++)
{
jcol = S_diag_j[jj1];
if (CF_marker[jcol] > 0)
{
S_marker[fine_to_coarse[jcol]] = jj_count_diag;
C_diag_j[jj_count_diag] = fine_to_coarse[jcol];
C_diag_data[jj_count_diag] = 2;
jj_count_diag++;
}
}
for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++)
{
jcol = S_offd_j[jj1];
if (CF_marker_offd[jcol] > 0)
{
index = map_S_to_C[jcol];
S_marker_offd[index] = jj_count_offd;
C_offd_j[jj_count_offd] = index;
C_offd_data[jj_count_offd] = 2;
jj_count_offd++;
}
}
for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++)
{
i2 = S_diag_j[jj1];
for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++)
{
i3 = S_diag_j[jj2];
if (CF_marker[i3] > 0)
{
if (S_marker[fine_to_coarse[i3]] < jj_row_begin_diag)
{
S_marker[fine_to_coarse[i3]] = jj_count_diag;
C_diag_j[jj_count_diag] = fine_to_coarse[i3];
C_diag_data[jj_count_diag]++;
jj_count_diag++;
}
else
{
C_diag_data[S_marker[fine_to_coarse[i3]]]++;
}
}
}
for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++)
{
i3 = S_offd_j[jj2];
if (CF_marker_offd[i3] > 0)
{
index = map_S_to_C[i3];
if (S_marker_offd[index] < jj_row_begin_offd)
{
S_marker_offd[index] = jj_count_offd;
C_offd_j[jj_count_offd] = index;
C_offd_data[jj_count_offd]++;
jj_count_offd++;
}
else
{
C_offd_data[S_marker_offd[index]]++;
}
}
}
}
for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++)
{
i2 = S_offd_j[jj1];
for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++)
{
i3 = S_ext_diag_j[jj2];
if (S_marker[i3] < jj_row_begin_diag)
{
S_marker[i3] = jj_count_diag;
C_diag_j[jj_count_diag] = i3;
C_diag_data[jj_count_diag]++;
jj_count_diag++;
}
else
{
C_diag_data[S_marker[i3]]++;
}
}
for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++)
{
i3 = S_ext_offd_j[jj2];
if (S_marker_offd[i3] < jj_row_begin_offd)
{
S_marker_offd[i3] = jj_count_offd;
C_offd_j[jj_count_offd] = i3;
C_offd_data[jj_count_offd]++;
jj_count_offd++;
}
else
{
C_offd_data[S_marker_offd[i3]]++;
}
}
}
}
}
cnt = 0;
for (i=0; i < num_coarse; i++)
{
for (j=C_diag_i[i]; j < C_diag_i[i+1]; j++)
{
jcol = C_diag_j[j];
if (C_diag_data[j] >= num_paths && jcol != i)
C_diag_j[cnt++] = jcol;
}
C_diag_i[i] = cnt;
}
if (num_nonzeros_diag) hypre_TFree(C_diag_data);
for (i=num_coarse; i > 0; i--)
C_diag_i[i] = C_diag_i[i-1];
C_diag_i[0] = 0;
cnt = 0;
for (i=0; i < num_coarse; i++)
{
for (j=C_offd_i[i]; j < C_offd_i[i+1]; j++)
{
jcol = C_offd_j[j];
if (C_offd_data[j] >= num_paths)
C_offd_j[cnt++] = jcol;
}
C_offd_i[i] = cnt;
}
if (num_nonzeros_offd) hypre_TFree(C_offd_data);
for (i=num_coarse; i > 0; i--)
C_offd_i[i] = C_offd_i[i-1];
C_offd_i[0] = 0;
cnt = 0;
for (i=0; i < num_cols_diag_S; i++)
{
if (CF_marker[i] > 0)
{
if (!(C_diag_i[cnt+1]-C_diag_i[cnt]) &&
!(C_offd_i[cnt+1]-C_offd_i[cnt]))
CF_marker[i] = 2;
cnt++;
}
}
C_diag_size = C_diag_i[num_coarse];
C_offd_size = C_offd_i[num_coarse];
S2 = hypre_ParCSRMatrixCreate(comm, global_num_coarse,
global_num_coarse, coarse_row_starts,
coarse_row_starts, num_cols_offd_C, C_diag_size, C_offd_size);
hypre_ParCSRMatrixOwnsRowStarts(S2) = 0;
C_diag = hypre_ParCSRMatrixDiag(S2);
hypre_CSRMatrixI(C_diag) = C_diag_i;
if (num_nonzeros_diag) hypre_CSRMatrixJ(C_diag) = C_diag_j;
C_offd = hypre_ParCSRMatrixOffd(S2);
hypre_CSRMatrixI(C_offd) = C_offd_i;
hypre_ParCSRMatrixOffd(S2) = C_offd;
if (num_cols_offd_C)
{
if (num_nonzeros_offd) hypre_CSRMatrixJ(C_offd) = C_offd_j;
hypre_ParCSRMatrixColMapOffd(S2) = col_map_offd_C;
}
/*-----------------------------------------------------------------------
* Free various arrays
*-----------------------------------------------------------------------*/
hypre_TFree(S_marker);
hypre_TFree(S_marker_offd);
hypre_TFree(S_ext_diag_i);
hypre_TFree(fine_to_coarse);
if (S_ext_diag_size)
{
hypre_TFree(S_ext_diag_j);
}
hypre_TFree(S_ext_offd_i);
if (S_ext_offd_size)
{
hypre_TFree(S_ext_offd_j);
}
if (num_cols_offd_S)
{
hypre_TFree(map_S_to_C);
hypre_TFree(CF_marker_offd);
hypre_TFree(fine_to_coarse_offd);
}
*C_ptr = S2;
return 0;
}
/*--------------------------------------------------------------------------
* hypre_BoomerAMGCorrectCFMarker : corrects CF_marker after aggr. coarsening
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGCorrectCFMarker(HYPRE_Int *CF_marker, HYPRE_Int num_var, HYPRE_Int *new_CF_marker)
{
HYPRE_Int i, cnt;
cnt = 0;
for (i=0; i < num_var; i++)
{
if (CF_marker[i] > 0 )
{
if (CF_marker[i] == 1) CF_marker[i] = new_CF_marker[cnt++];
else { CF_marker[i] = 1; cnt++;}
}
}
return 0;
}
/*--------------------------------------------------------------------------
* hypre_BoomerAMGCorrectCFMarker2 : corrects CF_marker after aggr. coarsening,
* but marks new F-points (previous C-points) as -2
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGCorrectCFMarker2(HYPRE_Int *CF_marker, HYPRE_Int num_var, HYPRE_Int *new_CF_marker)
{
HYPRE_Int i, cnt;
cnt = 0;
for (i=0; i < num_var; i++)
{
if (CF_marker[i] > 0 )
{
if (new_CF_marker[cnt] == -1) CF_marker[i] = -2;
else CF_marker[i] = 1;
cnt++;
}
}
return 0;
}
|
GB_reduce_to_scalar_template.c | //------------------------------------------------------------------------------
// GB_reduce_to_scalar_template: s=reduce(A), reduce a matrix to a scalar
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Reduce a matrix to a scalar, with typecasting and generic operators.
// No panel is used.
{
//--------------------------------------------------------------------------
// get A
//--------------------------------------------------------------------------
const int8_t *restrict Ab = A->b ;
const int64_t *restrict Ai = A->i ;
const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ;
int64_t anz = GB_nnz_held (A) ;
ASSERT (anz > 0) ;
const bool A_has_zombies = (A->nzombies > 0) ;
ASSERT (!A->iso) ;
//--------------------------------------------------------------------------
// reduce A to a scalar
//--------------------------------------------------------------------------
if (nthreads == 1)
{
//----------------------------------------------------------------------
// single thread
//----------------------------------------------------------------------
for (int64_t p = 0 ; p < anz ; p++)
{
// skip if the entry is a zombie or if not in the bitmap
if (A_has_zombies && GB_IS_ZOMBIE (Ai [p])) continue ;
if (!GBB (Ab, p)) continue ;
// s = op (s, (ztype) Ax [p])
GB_ADD_CAST_ARRAY_TO_SCALAR (s, Ax, p) ;
// check for early exit
#if GB_HAS_TERMINAL
if (GB_IS_TERMINAL (s)) break ;
#endif
}
}
else
{
//----------------------------------------------------------------------
// each thread reduces its own slice in parallel
//----------------------------------------------------------------------
bool early_exit = false ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t pstart, pend ;
GB_PARTITION (pstart, pend, anz, tid, ntasks) ;
// ztype t = identity
GB_SCALAR_IDENTITY (t) ;
bool my_exit, found = false ;
GB_ATOMIC_READ
my_exit = early_exit ;
if (!my_exit)
{
for (int64_t p = pstart ; p < pend ; p++)
{
// skip if the entry is a zombie or if not in the bitmap
if (A_has_zombies && GB_IS_ZOMBIE (Ai [p])) continue ;
if (!GBB (Ab, p)) continue ;
found = true ;
// t = op (t, (ztype) Ax [p]), with typecast
GB_ADD_CAST_ARRAY_TO_SCALAR (t, Ax, p) ;
// check for early exit
#if GB_HAS_TERMINAL
if (GB_IS_TERMINAL (t))
{
// tell the other tasks to exit early
GB_ATOMIC_WRITE
early_exit = true ;
break ;
}
#endif
}
}
F [tid] = found ;
// W [tid] = t, no typecast
GB_COPY_SCALAR_TO_ARRAY (W, tid, t) ;
}
//----------------------------------------------------------------------
// sum up the results of each slice using a single thread
//----------------------------------------------------------------------
for (int tid = 0 ; tid < ntasks ; tid++)
{
if (F [tid])
{
// s = op (s, W [tid]), no typecast
GB_ADD_ARRAY_TO_SCALAR (s, W, tid) ;
}
}
}
}
|
parallel_master_taskloop_simd_misc_messages.c | // RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 -triple x86_64-unknown-unknown %s -Wuninitialized
// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=50 -verify=expected,omp50 -triple x86_64-unknown-unknown %s -Wuninitialized
// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 -verify=expected,omp45 -triple x86_64-unknown-unknown %s -Wuninitialized
// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=50 -verify=expected,omp50 -triple x86_64-unknown-unknown %s -Wuninitialized
void xxx(int argc) {
int x; // expected-note {{initialize the variable 'x' to silence this warning}}
#pragma omp parallel master taskloop simd
for (int i = 0; i < 10; ++i)
argc = x; // expected-warning {{variable 'x' is uninitialized when used here}}
}
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp parallel master taskloop simd'}}
#pragma omp parallel master taskloop simd
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp parallel master taskloop simd'}}
#pragma omp parallel master taskloop simd foo
void test_no_clause(void) {
int i;
#pragma omp parallel master taskloop simd
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{statement after '#pragma omp parallel master taskloop simd' must be a for loop}}
#pragma omp parallel master taskloop simd
++i;
}
void test_branch_protected_scope(void) {
int i = 0;
L1:
++i;
int x[24];
#pragma omp parallel
#pragma omp parallel master taskloop simd
for (i = 0; i < 16; ++i) {
if (i == 5)
goto L1; // expected-error {{use of undeclared label 'L1'}}
else if (i == 6)
return; // expected-error {{cannot return from OpenMP region}}
else if (i == 7)
goto L2;
else if (i == 8) {
L2:
x[i]++;
}
}
if (x[0] == 0)
goto L2; // expected-error {{use of undeclared label 'L2'}}
else if (x[1] == 1)
goto L1;
}
void test_invalid_clause(void) {
int i, a;
// expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel master taskloop simd' are ignored}}
#pragma omp parallel master taskloop simd foo bar
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{directive '#pragma omp parallel master taskloop simd' cannot contain more than one 'nogroup' clause}}
#pragma omp parallel master taskloop simd nogroup nogroup
for (i = 0; i < 16; ++i)
;
// expected-error@+1 {{unexpected OpenMP clause 'in_reduction' in directive '#pragma omp parallel master taskloop simd'}}
#pragma omp parallel master taskloop simd in_reduction(+:a)
for (i = 0; i < 16; ++i)
;
}
void test_non_identifiers(void) {
int i, x;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel master taskloop simd' are ignored}}
#pragma omp parallel master taskloop simd;
for (i = 0; i < 16; ++i)
;
// expected-warning@+2 {{extra tokens at the end of '#pragma omp parallel master taskloop simd' are ignored}}
#pragma omp parallel
#pragma omp parallel master taskloop simd linear(x);
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel master taskloop simd' are ignored}}
#pragma omp parallel master taskloop simd private(x);
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp parallel master taskloop simd' are ignored}}
#pragma omp parallel master taskloop simd, private(x);
for (i = 0; i < 16; ++i)
;
}
extern int foo(void);
void test_collapse(void) {
int i;
#pragma omp parallel
// expected-error@+1 {{expected '('}}
#pragma omp parallel master taskloop simd collapse
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp parallel master taskloop simd collapse(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd collapse()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp parallel master taskloop simd collapse(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp parallel master taskloop simd collapse(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+2 {{extra tokens at the end of '#pragma omp parallel master taskloop simd' are ignored}}
// expected-error@+1 {{expected '('}}
#pragma omp parallel master taskloop simd collapse 4)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp parallel master taskloop simd collapse(4
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp parallel master taskloop simd', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp parallel master taskloop simd collapse(4,
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp parallel master taskloop simd', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp parallel master taskloop simd collapse(4, )
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp parallel master taskloop simd', but found only 1}}
#pragma omp parallel
// expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp parallel master taskloop simd collapse(4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp parallel master taskloop simd', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp parallel master taskloop simd collapse(4 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp parallel master taskloop simd', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp parallel master taskloop simd collapse(4, , 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp parallel master taskloop simd', but found only 1}}
#pragma omp parallel
#pragma omp parallel master taskloop simd collapse(4)
for (int i1 = 0; i1 < 16; ++i1)
for (int i2 = 0; i2 < 16; ++i2)
for (int i3 = 0; i3 < 16; ++i3)
for (int i4 = 0; i4 < 16; ++i4)
foo();
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp parallel master taskloop simd collapse(4, 8)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp parallel master taskloop simd', but found only 1}}
#pragma omp parallel
// expected-error@+1 {{integer constant expression}}
#pragma omp parallel master taskloop simd collapse(2.5)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{integer constant expression}}
#pragma omp parallel master taskloop simd collapse(foo())
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}}
#pragma omp parallel master taskloop simd collapse(-5)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}}
#pragma omp parallel master taskloop simd collapse(0)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}}
#pragma omp parallel master taskloop simd collapse(5 - 5)
for (i = 0; i < 16; ++i)
;
}
void test_private(void) {
int i;
#pragma omp parallel
// expected-error@+2 {{expected expression}}
// expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp parallel master taskloop simd private(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp parallel master taskloop simd private(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp parallel master taskloop simd private(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd private()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd private(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp parallel master taskloop simd private(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp parallel master taskloop simd private(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp parallel master taskloop simd private(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp parallel master taskloop simd private(x, y, z)
for (i = 0; i < 16; ++i) {
x = y * i + z;
}
}
void test_lastprivate(void) {
int i;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd lastprivate(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp parallel master taskloop simd lastprivate(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp parallel master taskloop simd lastprivate(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd lastprivate()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd lastprivate(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp parallel master taskloop simd lastprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp parallel master taskloop simd lastprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp parallel master taskloop simd lastprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp parallel master taskloop simd lastprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_firstprivate(void) {
int i;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd firstprivate(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp parallel master taskloop simd firstprivate(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp parallel master taskloop simd firstprivate(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd firstprivate()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd firstprivate(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp parallel master taskloop simd firstprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp parallel master taskloop simd lastprivate(x) firstprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp parallel master taskloop simd lastprivate(x, y) firstprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp parallel master taskloop simd lastprivate(x, y, z) firstprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_loop_messages(void) {
float a[100], b[100], c[100];
#pragma omp parallel
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp parallel master taskloop simd
for (float fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
#pragma omp parallel
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp parallel master taskloop simd
for (double fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
// expected-warning@+2 {{OpenMP loop iteration variable cannot have more than 64 bits size and will be narrowed}}
#pragma omp parallel master taskloop simd
for (__int128 ii = 0; ii < 10; ii++) {
c[ii] = a[ii] + b[ii];
}
}
void test_nontemporal(void) {
int i;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp parallel master taskloop simd nontemporal(
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 2 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp parallel master taskloop simd nontemporal(,
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 2 {{expected expression}}
#pragma omp parallel master taskloop simd nontemporal(, )
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd nontemporal()
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{expected expression}}
#pragma omp parallel master taskloop simd nontemporal(int)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} omp50-error@+1 {{expected variable name}}
#pragma omp parallel master taskloop simd nontemporal(0)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{use of undeclared identifier 'x'}}
#pragma omp parallel master taskloop simd nontemporal(x)
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{use of undeclared identifier 'x'}}
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{use of undeclared identifier 'y'}}
#pragma omp parallel master taskloop simd nontemporal(x, y)
for (i = 0; i < 16; ++i)
;
// expected-error@+3 {{use of undeclared identifier 'x'}}
// expected-error@+2 {{use of undeclared identifier 'y'}}
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{use of undeclared identifier 'z'}}
#pragma omp parallel master taskloop simd nontemporal(x, y, z)
for (i = 0; i < 16; ++i)
;
int x, y;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp parallel master taskloop simd nontemporal(x :)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}}
#pragma omp parallel master taskloop simd nontemporal(x :, )
for (i = 0; i < 16; ++i)
;
// omp50-note@+2 {{defined as nontemporal}}
// omp45-error@+1 2 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} omp50-error@+1 {{a variable cannot appear in more than one nontemporal clause}}
#pragma omp parallel master taskloop simd nontemporal(x) nontemporal(x)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}}
#pragma omp parallel master taskloop simd private(x) nontemporal(x)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}}
#pragma omp parallel master taskloop simd nontemporal(x) private(x)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}}
#pragma omp parallel master taskloop simd nontemporal(x, y : 0)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}}
#pragma omp parallel master taskloop simd nontemporal(x) lastprivate(x)
for (i = 0; i < 16; ++i)
;
// omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp parallel master taskloop simd'}}
#pragma omp parallel master taskloop simd lastprivate(x) nontemporal(x)
for (i = 0; i < 16; ++i)
;
}
|
residualbased_block_builder_and_solver.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Riccardo Rossi
// Collaborators: Vicente Mataix
//
//
#if !defined(KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER )
#define KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER
/* System includes */
#include <unordered_set>
/* External includes */
#ifdef KRATOS_SMP_OPENMP
#include <omp.h>
#endif
/* Project includes */
#include "includes/define.h"
#include "solving_strategies/builder_and_solvers/builder_and_solver.h"
#include "includes/model_part.h"
#include "includes/key_hash.h"
#include "utilities/timer.h"
#include "utilities/variable_utils.h"
#include "includes/kratos_flags.h"
#include "includes/lock_object.h"
#include "utilities/sparse_matrix_multiplication_utility.h"
#include "utilities/builtin_timer.h"
#include "utilities/atomic_utilities.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class ResidualBasedEliminationBuilderAndSolver
* @ingroup KratosCore
* @brief Current class provides an implementation for standard builder and solving operations.
* @details The RHS is constituted by the unbalanced loads (residual)
* Degrees of freedom are reordered putting the restrained degrees of freedom at
* the end of the system ordered in reverse order with respect to the DofSet.
* Imposition of the dirichlet conditions is naturally dealt with as the residual already contains
* this information.
* Calculation of the reactions involves a cost very similiar to the calculation of the total residual
* @tparam TSparseSpace The sparse system considered
* @tparam TDenseSpace The dense system considered
* @tparam TLinearSolver The linear solver considered
* @author Riccardo Rossi
*/
template<class TSparseSpace,
class TDenseSpace, //= DenseSpace<double>,
class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace>
>
class ResidualBasedBlockBuilderAndSolver
: public BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver >
{
public:
///@name Type Definitions
///@{
/// Definition of the flags
KRATOS_DEFINE_LOCAL_FLAG( SILENT_WARNINGS );
// Scaling enum
enum class SCALING_DIAGONAL {NO_SCALING = 0, CONSIDER_NORM_DIAGONAL = 1, CONSIDER_MAX_DIAGONAL = 2, CONSIDER_PRESCRIBED_DIAGONAL = 3};
/// Definition of the pointer
KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedBlockBuilderAndSolver);
/// Definition of the base class
typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType;
/// The definition of the current class
typedef ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> ClassType;
// The size_t types
typedef std::size_t SizeType;
typedef std::size_t IndexType;
/// Definition of the classes from the base class
typedef typename BaseType::TSchemeType TSchemeType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType;
typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType;
typedef typename BaseType::NodesArrayType NodesArrayType;
typedef typename BaseType::ElementsArrayType ElementsArrayType;
typedef typename BaseType::ConditionsArrayType ConditionsArrayType;
/// Additional definitions
typedef PointerVectorSet<Element, IndexedObject> ElementsContainerType;
typedef Element::EquationIdVectorType EquationIdVectorType;
typedef Element::DofsVectorType DofsVectorType;
typedef boost::numeric::ublas::compressed_matrix<double> CompressedMatrixType;
/// DoF types definition
typedef Node<3> NodeType;
typedef typename NodeType::DofType DofType;
typedef typename DofType::Pointer DofPointerType;
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor
*/
explicit ResidualBasedBlockBuilderAndSolver() : BaseType()
{
}
/**
* @brief Default constructor. (with parameters)
*/
explicit ResidualBasedBlockBuilderAndSolver(
typename TLinearSolver::Pointer pNewLinearSystemSolver,
Parameters ThisParameters
) : BaseType(pNewLinearSystemSolver)
{
// Validate and assign defaults
ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters());
this->AssignSettings(ThisParameters);
}
/**
* @brief Default constructor.
*/
explicit ResidualBasedBlockBuilderAndSolver(typename TLinearSolver::Pointer pNewLinearSystemSolver)
: BaseType(pNewLinearSystemSolver)
{
mScalingDiagonal = SCALING_DIAGONAL::NO_SCALING;
}
/** Destructor.
*/
~ResidualBasedBlockBuilderAndSolver() override
{
}
/**
* @brief Create method
* @param pNewLinearSystemSolver The linear solver for the system of equations
* @param ThisParameters The configuration parameters
*/
typename BaseType::Pointer Create(
typename TLinearSolver::Pointer pNewLinearSystemSolver,
Parameters ThisParameters
) const override
{
return Kratos::make_shared<ClassType>(pNewLinearSystemSolver,ThisParameters);
}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief Function to perform the build of the RHS. The vector could be sized as the total number
* of dofs or as the number of unrestrained ones
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param A The LHS matrix
* @param b The RHS vector
*/
void Build(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& A,
TSystemVectorType& b) override
{
KRATOS_TRY
KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl;
// Getting the elements from the model
const int nelements = static_cast<int>(rModelPart.Elements().size());
// Getting the array of the conditions
const int nconditions = static_cast<int>(rModelPart.Conditions().size());
const ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo();
ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin();
ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin();
//contributions to the system
LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0);
LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0);
//vector containing the localization in the system of the different
//terms
Element::EquationIdVectorType EquationId;
// Assemble all elements
const auto timer = BuiltinTimer();
#pragma omp parallel firstprivate(nelements,nconditions, LHS_Contribution, RHS_Contribution, EquationId )
{
# pragma omp for schedule(guided, 512) nowait
for (int k = 0; k < nelements; k++)
{
ModelPart::ElementsContainerType::iterator it = el_begin + k;
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool element_is_active = true;
if ((it)->IsDefined(ACTIVE))
element_is_active = (it)->Is(ACTIVE);
if (element_is_active)
{
//calculate elemental contribution
pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo);
//assemble the elemental contribution
Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId);
}
}
#pragma omp for schedule(guided, 512)
for (int k = 0; k < nconditions; k++)
{
ModelPart::ConditionsContainerType::iterator it = cond_begin + k;
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool condition_is_active = true;
if ((it)->IsDefined(ACTIVE))
condition_is_active = (it)->Is(ACTIVE);
if (condition_is_active)
{
//calculate elemental contribution
pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo);
//assemble the elemental contribution
Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId);
}
}
}
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >= 1) << "Build time: " << timer.ElapsedSeconds() << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building" << std::endl;
KRATOS_CATCH("")
}
/**
* @brief Function to perform the building of the LHS
* @details Depending on the implementation choosen the size of the matrix could
* be equal to the total number of Dofs or to the number of unrestrained dofs
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param A The LHS matrix
*/
void BuildLHS(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA
) override
{
KRATOS_TRY
KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl;
// Getting the elements from the model
const int nelements = static_cast<int>(rModelPart.Elements().size());
// Getting the array of the conditions
const int nconditions = static_cast<int>(rModelPart.Conditions().size());
const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
const auto it_elem_begin = rModelPart.ElementsBegin();
const auto it_cond_begin = rModelPart.ConditionsBegin();
// Contributions to the system
LocalSystemMatrixType lhs_contribution(0, 0);
// Vector containing the localization in the system of the different terms
Element::EquationIdVectorType equation_id;
// Assemble all elements
const auto timer = BuiltinTimer();
#pragma omp parallel firstprivate(nelements, nconditions, lhs_contribution, equation_id )
{
# pragma omp for schedule(guided, 512) nowait
for (int k = 0; k < nelements; ++k) {
auto it_elem = it_elem_begin + k;
// Detect if the element is active or not. If the user did not make any choice the element is active by default
bool element_is_active = true;
if (it_elem->IsDefined(ACTIVE))
element_is_active = it_elem->Is(ACTIVE);
if (element_is_active) {
// Calculate elemental contribution
pScheme->CalculateLHSContribution(*it_elem, lhs_contribution, equation_id, r_current_process_info);
// Assemble the elemental contribution
AssembleLHS(rA, lhs_contribution, equation_id);
}
}
#pragma omp for schedule(guided, 512)
for (int k = 0; k < nconditions; ++k) {
auto it_cond = it_cond_begin + k;
// Detect if the element is active or not. If the user did not make any choice the element is active by default
bool condition_is_active = true;
if (it_cond->IsDefined(ACTIVE))
condition_is_active = it_cond->Is(ACTIVE);
if (condition_is_active)
{
// Calculate elemental contribution
pScheme->CalculateLHSContribution(*it_cond, lhs_contribution, equation_id, r_current_process_info);
// Assemble the elemental contribution
AssembleLHS(rA, lhs_contribution, equation_id);
}
}
}
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >= 1) << "Build time LHS: " << timer.ElapsedSeconds() << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 2) << "Finished parallel building LHS" << std::endl;
KRATOS_CATCH("")
}
/**
* @brief Build a rectangular matrix of size n*N where "n" is the number of unrestrained degrees of freedom
* and "N" is the total number of degrees of freedom involved.
* @details This matrix is obtained by building the total matrix without the lines corresponding to the fixed
* degrees of freedom (but keeping the columns!!)
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param A The LHS matrix
*/
void BuildLHS_CompleteOnFreeRows(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& A) override
{
KRATOS_TRY
TSystemVectorType tmp(A.size1(), 0.0);
this->Build(pScheme, rModelPart, A, tmp);
KRATOS_CATCH("")
}
/**
* @brief This is a call to the linear system solver
* @param A The LHS matrix
* @param Dx The Unknowns vector
* @param b The RHS vector
*/
void SystemSolve(
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b
) override
{
KRATOS_TRY
double norm_b;
if (TSparseSpace::Size(b) != 0)
norm_b = TSparseSpace::TwoNorm(b);
else
norm_b = 0.00;
if (norm_b != 0.00)
{
//do solve
BaseType::mpLinearSystemSolver->Solve(A, Dx, b);
}
else
TSparseSpace::SetToZero(Dx);
if(mT.size1() != 0) //if there are master-slave constraints
{
//recover solution of the original problem
TSystemVectorType Dxmodified = Dx;
TSparseSpace::Mult(mT, Dxmodified, Dx);
}
//prints informations about the current time
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl;
KRATOS_CATCH("")
}
/**
* @brief This is a call to the linear system solver (taking into account some physical particularities of the problem)
* @param rA The LHS matrix
* @param rDx The Unknowns vector
* @param rb The RHS vector
* @param rModelPart The model part of the problem to solve
*/
virtual void SystemSolveWithPhysics(
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb,
ModelPart& rModelPart
)
{
if(rModelPart.MasterSlaveConstraints().size() != 0) {
TSystemVectorType Dxmodified(rb.size());
InternalSystemSolveWithPhysics(rA, Dxmodified, rb, rModelPart);
//recover solution of the original problem
TSparseSpace::Mult(mT, Dxmodified, rDx);
} else {
InternalSystemSolveWithPhysics(rA, rDx, rb, rModelPart);
}
}
/**
*@brief This is a call to the linear system solver (taking into account some physical particularities of the problem)
* @param A The LHS matrix
* @param Dx The Unknowns vector
* @param b The RHS vector
* @param rModelPart The model part of the problem to solve
*/
void InternalSystemSolveWithPhysics(
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b,
ModelPart& rModelPart
)
{
KRATOS_TRY
double norm_b;
if (TSparseSpace::Size(b) != 0)
norm_b = TSparseSpace::TwoNorm(b);
else
norm_b = 0.00;
if (norm_b != 0.00) {
//provide physical data as needed
if(BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded() )
BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, rModelPart);
//do solve
BaseType::mpLinearSystemSolver->Solve(A, Dx, b);
} else {
TSparseSpace::SetToZero(Dx);
KRATOS_WARNING_IF("ResidualBasedBlockBuilderAndSolver", mOptions.IsNot(SILENT_WARNINGS)) << "ATTENTION! setting the RHS to zero!" << std::endl;
}
// Prints informations about the current time
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() > 1) << *(BaseType::mpLinearSystemSolver) << std::endl;
KRATOS_CATCH("")
}
/**
* @brief Function to perform the building and solving phase at the same time.
* @details It is ideally the fastest and safer function to use when it is possible to solve
* just after building
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param A The LHS matrix
* @param Dx The Unknowns vector
* @param b The RHS vector
*/
void BuildAndSolve(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b) override
{
KRATOS_TRY
Timer::Start("Build");
Build(pScheme, rModelPart, A, b);
Timer::Stop("Build");
if(rModelPart.MasterSlaveConstraints().size() != 0) {
const auto timer_constraints = BuiltinTimer();
Timer::Start("ApplyConstraints");
ApplyConstraints(pScheme, rModelPart, A, b);
Timer::Stop("ApplyConstraints");
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >=1) << "Constraints build time: " << timer_constraints.ElapsedSeconds() << std::endl;
}
ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b);
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl;
const auto timer = BuiltinTimer();
Timer::Start("Solve");
SystemSolveWithPhysics(A, Dx, b, rModelPart);
Timer::Stop("Solve");
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >=1) << "System solve time: " << timer.ElapsedSeconds() << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl;
KRATOS_CATCH("")
}
/**
* @brief Function to perform the building and solving phase at the same time Linearizing with the database at the old iteration
* @details It is ideally the fastest and safer function to use when it is possible to solve just after building
* @param pScheme The pointer to the integration scheme
* @param rModelPart The model part to compute
* @param rA The LHS matrix of the system of equations
* @param rDx The vector of unkowns
* @param rb The RHS vector of the system of equations
* @param MoveMesh tells if the update of the scheme needs to be performed when calling the Update of the scheme
*/
void BuildAndSolveLinearizedOnPreviousIteration(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb,
const bool MoveMesh
) override
{
Timer::Start("Linearizing on Old iteration");
KRATOS_INFO_IF("BlockBuilderAndSolver", this->GetEchoLevel() > 0) << "Linearizing on Old iteration" << std::endl;
KRATOS_ERROR_IF(rModelPart.GetBufferSize() == 1) << "BlockBuilderAndSolver: \n"
<< "The buffer size needs to be at least 2 in order to use \n"
<< "BuildAndSolveLinearizedOnPreviousIteration \n"
<< "current buffer size for modelpart: " << rModelPart.Name() << std::endl
<< "is :" << rModelPart.GetBufferSize()
<< " Please set IN THE STRATEGY SETTINGS "
<< " UseOldStiffnessInFirstIteration=false " << std::endl;
DofsArrayType fixed_dofs;
for(auto& r_dof : BaseType::mDofSet){
if(r_dof.IsFixed()){
fixed_dofs.push_back(&r_dof);
r_dof.FreeDof();
}
}
//TODO: Here we need to take the vector from other ones because
// We cannot create a trilinos vector without a communicator. To be improved!
TSystemVectorType dx_prediction(rDx);
TSystemVectorType rhs_addition(rb); //we know it is zero here, so we do not need to set it
// Here we bring back the database to before the prediction,
// but we store the prediction increment in dx_prediction.
// The goal is that the stiffness is computed with the
// converged configuration at the end of the previous step.
block_for_each(BaseType::mDofSet, [&](Dof<double>& rDof){
// NOTE: this is initialzed to - the value of dx prediction
dx_prediction[rDof.EquationId()] = -(rDof.GetSolutionStepValue() - rDof.GetSolutionStepValue(1));
});
// Use UpdateDatabase to bring back the solution to how it was at the end of the previous step
pScheme->Update(rModelPart, BaseType::mDofSet, rA, dx_prediction, rb);
if (MoveMesh) {
VariableUtils().UpdateCurrentPosition(rModelPart.Nodes(),DISPLACEMENT,0);
}
Timer::Stop("Linearizing on Old iteration");
Timer::Start("Build");
this->Build(pScheme, rModelPart, rA, rb);
Timer::Stop("Build");
// Put back the prediction into the database
TSparseSpace::InplaceMult(dx_prediction, -1.0); //change sign to dx_prediction
TSparseSpace::UnaliasedAdd(rDx, 1.0, dx_prediction);
// Use UpdateDatabase to bring back the solution
// to where it was taking into account BCs
// it is done here so that constraints are correctly taken into account right after
pScheme->Update(rModelPart, BaseType::mDofSet, rA, dx_prediction, rb);
if (MoveMesh) {
VariableUtils().UpdateCurrentPosition(rModelPart.Nodes(),DISPLACEMENT,0);
}
// Apply rb -= A*dx_prediction
TSparseSpace::Mult(rA, dx_prediction, rhs_addition);
TSparseSpace::UnaliasedAdd(rb, -1.0, rhs_addition);
for(auto& dof : fixed_dofs)
dof.FixDof();
if (!rModelPart.MasterSlaveConstraints().empty()) {
const auto timer_constraints = BuiltinTimer();
Timer::Start("ApplyConstraints");
this->ApplyConstraints(pScheme, rModelPart, rA, rb);
Timer::Stop("ApplyConstraints");
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >=1) << "Constraints build time: " << timer_constraints.ElapsedSeconds() << std::endl;
}
this->ApplyDirichletConditions(pScheme, rModelPart, rA, rDx, rb);
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl;
const auto timer = BuiltinTimer();
Timer::Start("Solve");
this->SystemSolveWithPhysics(rA, rDx, rb, rModelPart);
Timer::Stop("Solve");
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >=1) << "System solve time: " << timer.ElapsedSeconds() << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl;
}
/**
* @brief Corresponds to the previews, but the System's matrix is considered already built and only the RHS is built again
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rA The LHS matrix
* @param rDx The Unknowns vector
* @param rb The RHS vector
*/
void BuildRHSAndSolve(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY
BuildRHS(pScheme, rModelPart, rb);
if(rModelPart.MasterSlaveConstraints().size() != 0) {
Timer::Start("ApplyRHSConstraints");
ApplyRHSConstraints(pScheme, rModelPart, rb);
Timer::Stop("ApplyRHSConstraints");
}
ApplyDirichletConditions(pScheme, rModelPart, rA, rDx, rb);
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl;
const auto timer = BuiltinTimer();
Timer::Start("Solve");
SystemSolveWithPhysics(rA, rDx, rb, rModelPart);
Timer::Stop("Solve");
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", this->GetEchoLevel() >=1) << "System solve time: " << timer.ElapsedSeconds() << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl;
KRATOS_CATCH("")
}
/**
* @brief Function to perform the build of the RHS.
* @details The vector could be sized as the total number of dofs or as the number of unrestrained ones
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
*/
void BuildRHS(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& b) override
{
KRATOS_TRY
Timer::Start("BuildRHS");
BuildRHSNoDirichlet(pScheme,rModelPart,b);
//NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver
block_for_each(BaseType::mDofSet, [&](Dof<double>& rDof){
const std::size_t i = rDof.EquationId();
if (rDof.IsFixed())
b[i] = 0.0;
});
Timer::Stop("BuildRHS");
KRATOS_CATCH("")
}
/**
* @brief Builds the list of the DofSets involved in the problem by "asking" to each element
* and condition its Dofs.
* @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the
* way the matrix and RHS are built
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
*/
void SetUpDofSet(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart
) override
{
KRATOS_TRY;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Setting up the dofs" << std::endl;
//Gets the array of elements from the modeler
ElementsArrayType& r_elements_array = rModelPart.Elements();
const int number_of_elements = static_cast<int>(r_elements_array.size());
DofsVectorType dof_list, second_dof_list; // NOTE: The second dof list is only used on constraints to include master/slave relations
unsigned int nthreads = ParallelUtilities::GetNumThreads();
typedef std::unordered_set < NodeType::DofType::Pointer, DofPointerHasher> set_type;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Number of threads" << nthreads << "\n" << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing element loop" << std::endl;
/**
* Here we declare three sets.
* - The global set: Contains all the DoF of the system
* - The slave set: The DoF that are not going to be solved, due to MPC formulation
*/
set_type dof_global_set;
dof_global_set.reserve(number_of_elements*20);
#pragma omp parallel firstprivate(dof_list, second_dof_list)
{
const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// We cleate the temporal set and we reserve some space on them
set_type dofs_tmp_set;
dofs_tmp_set.reserve(20000);
// Gets the array of elements from the modeler
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i < number_of_elements; ++i) {
auto it_elem = r_elements_array.begin() + i;
// Gets list of Dof involved on every element
pScheme->GetDofList(*it_elem, dof_list, r_current_process_info);
dofs_tmp_set.insert(dof_list.begin(), dof_list.end());
}
// Gets the array of conditions from the modeler
ConditionsArrayType& r_conditions_array = rModelPart.Conditions();
const int number_of_conditions = static_cast<int>(r_conditions_array.size());
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i < number_of_conditions; ++i) {
auto it_cond = r_conditions_array.begin() + i;
// Gets list of Dof involved on every element
pScheme->GetDofList(*it_cond, dof_list, r_current_process_info);
dofs_tmp_set.insert(dof_list.begin(), dof_list.end());
}
// Gets the array of constraints from the modeler
auto& r_constraints_array = rModelPart.MasterSlaveConstraints();
const int number_of_constraints = static_cast<int>(r_constraints_array.size());
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i < number_of_constraints; ++i) {
auto it_const = r_constraints_array.begin() + i;
// Gets list of Dof involved on every element
it_const->GetDofList(dof_list, second_dof_list, r_current_process_info);
dofs_tmp_set.insert(dof_list.begin(), dof_list.end());
dofs_tmp_set.insert(second_dof_list.begin(), second_dof_list.end());
}
// We merge all the sets in one thread
#pragma omp critical
{
dof_global_set.insert(dofs_tmp_set.begin(), dofs_tmp_set.end());
}
}
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Initializing ordered array filling\n" << std::endl;
DofsArrayType Doftemp;
BaseType::mDofSet = DofsArrayType();
Doftemp.reserve(dof_global_set.size());
for (auto it= dof_global_set.begin(); it!= dof_global_set.end(); it++)
{
Doftemp.push_back( *it );
}
Doftemp.Sort();
BaseType::mDofSet = Doftemp;
//Throws an exception if there are no Degrees Of Freedom involved in the analysis
KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2)) << "Number of degrees of freedom:" << BaseType::mDofSet.size() << std::endl;
BaseType::mDofSetIsInitialized = true;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolver", ( this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished setting up the dofs" << std::endl;
#ifdef KRATOS_DEBUG
// If reactions are to be calculated, we check if all the dofs have reactions defined
// This is tobe done only in debug mode
if (BaseType::GetCalculateReactionsFlag()) {
for (auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) {
KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " <<std::endl
<< "Node : "<<dof_iterator->Id()<< std::endl
<< "Dof : "<<(*dof_iterator)<<std::endl<<"Not possible to calculate reactions."<<std::endl;
}
}
#endif
KRATOS_CATCH("");
}
/**
* @brief Organises the dofset in order to speed up the building phase
* @param rModelPart The model part of the problem to solve
*/
void SetUpSystem(
ModelPart& rModelPart
) override
{
//int free_id = 0;
BaseType::mEquationSystemSize = BaseType::mDofSet.size();
IndexPartition<std::size_t>(BaseType::mDofSet.size()).for_each([&, this](std::size_t Index){
typename DofsArrayType::iterator dof_iterator = this->mDofSet.begin() + Index;
dof_iterator->SetEquationId(Index);
});
}
//**************************************************************************
//**************************************************************************
void ResizeAndInitializeVectors(
typename TSchemeType::Pointer pScheme,
TSystemMatrixPointerType& pA,
TSystemVectorPointerType& pDx,
TSystemVectorPointerType& pb,
ModelPart& rModelPart
) override
{
KRATOS_TRY
if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix
{
TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0));
pA.swap(pNewA);
}
if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix
{
TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0));
pDx.swap(pNewDx);
}
if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix
{
TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0));
pb.swap(pNewb);
}
TSystemMatrixType& A = *pA;
TSystemVectorType& Dx = *pDx;
TSystemVectorType& b = *pb;
//resizing the system vectors and matrix
if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized
{
A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false);
ConstructMatrixStructure(pScheme, A, rModelPart);
}
else
{
if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize)
{
KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl;
A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true);
ConstructMatrixStructure(pScheme, A, rModelPart);
}
}
if (Dx.size() != BaseType::mEquationSystemSize)
Dx.resize(BaseType::mEquationSystemSize, false);
TSparseSpace::SetToZero(Dx);
if (b.size() != BaseType::mEquationSystemSize) {
b.resize(BaseType::mEquationSystemSize, false);
}
TSparseSpace::SetToZero(b);
ConstructMasterSlaveConstraintsStructure(rModelPart);
KRATOS_CATCH("")
}
//**************************************************************************
//**************************************************************************
void CalculateReactions(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b) override
{
TSparseSpace::SetToZero(b);
//refresh RHS to have the correct reactions
BuildRHSNoDirichlet(pScheme, rModelPart, b);
//NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver
block_for_each(BaseType::mDofSet, [&](Dof<double>& rDof){
const std::size_t i = rDof.EquationId();
rDof.GetSolutionStepReactionValue() = -b[i];
});
}
/**
* @brief Applies the dirichlet conditions. This operation may be very heavy or completely
* unexpensive depending on the implementation choosen and on how the System Matrix is built.
* @details For explanation of how it works for a particular implementation the user
* should refer to the particular Builder And Solver choosen
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rA The LHS matrix
* @param rDx The Unknowns vector
* @param rb The RHS vector
*/
void ApplyDirichletConditions(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
const std::size_t system_size = rA.size1();
Vector scaling_factors (system_size);
const auto it_dof_iterator_begin = BaseType::mDofSet.begin();
// NOTE: dofs are assumed to be numbered consecutively in the BlockBuilderAndSolver
IndexPartition<std::size_t>(BaseType::mDofSet.size()).for_each([&](std::size_t Index){
auto it_dof_iterator = it_dof_iterator_begin + Index;
if (it_dof_iterator->IsFixed()) {
scaling_factors[Index] = 0.0;
} else {
scaling_factors[Index] = 1.0;
}
});
double* Avalues = rA.value_data().begin();
std::size_t* Arow_indices = rA.index1_data().begin();
std::size_t* Acol_indices = rA.index2_data().begin();
// The diagonal considered
mScaleFactor = GetScaleNorm(rModelPart, rA);
// Detect if there is a line of all zeros and set the diagonal to a 1 if this happens
IndexPartition<std::size_t>(system_size).for_each([&](std::size_t Index){
bool empty = true;
const std::size_t col_begin = Arow_indices[Index];
const std::size_t col_end = Arow_indices[Index + 1];
for (std::size_t j = col_begin; j < col_end; ++j) {
if(Avalues[j] != 0.0) {
empty = false;
break;
}
}
if(empty) {
rA(Index, Index) = mScaleFactor;
rb[Index] = 0.0;
}
});
IndexPartition<std::size_t>(system_size).for_each([&](std::size_t Index){
const std::size_t col_begin = Arow_indices[Index];
const std::size_t col_end = Arow_indices[Index+1];
const double k_factor = scaling_factors[Index];
if (k_factor == 0.0) {
// Zero out the whole row, except the diagonal
for (std::size_t j = col_begin; j < col_end; ++j)
if (Acol_indices[j] != Index )
Avalues[j] = 0.0;
// Zero out the RHS
rb[Index] = 0.0;
} else {
// Zero out the column which is associated with the zero'ed row
for (std::size_t j = col_begin; j < col_end; ++j)
if(scaling_factors[ Acol_indices[j] ] == 0 )
Avalues[j] = 0.0;
}
});
}
/**
* @brief Applies the constraints with master-slave relation matrix (RHS only)
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rb The RHS vector
*/
void ApplyRHSConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& rb
) override
{
KRATOS_TRY
if (rModelPart.MasterSlaveConstraints().size() != 0) {
BuildMasterSlaveConstraints(rModelPart);
// We compute the transposed matrix of the global relation matrix
TSystemMatrixType T_transpose_matrix(mT.size2(), mT.size1());
SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, mT, 1.0);
TSystemVectorType b_modified(rb.size());
TSparseSpace::Mult(T_transpose_matrix, rb, b_modified);
TSparseSpace::Copy(b_modified, rb);
// Apply diagonal values on slaves
IndexPartition<std::size_t>(mSlaveIds.size()).for_each([&](std::size_t Index){
const IndexType slave_equation_id = mSlaveIds[Index];
if (mInactiveSlaveDofs.find(slave_equation_id) == mInactiveSlaveDofs.end()) {
rb[slave_equation_id] = 0.0;
}
});
}
KRATOS_CATCH("")
}
/**
* @brief Applies the constraints with master-slave relation matrix
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param rA The LHS matrix
* @param rb The RHS vector
*/
void ApplyConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rb
) override
{
KRATOS_TRY
if (rModelPart.MasterSlaveConstraints().size() != 0) {
BuildMasterSlaveConstraints(rModelPart);
// We compute the transposed matrix of the global relation matrix
TSystemMatrixType T_transpose_matrix(mT.size2(), mT.size1());
SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, mT, 1.0);
TSystemVectorType b_modified(rb.size());
TSparseSpace::Mult(T_transpose_matrix, rb, b_modified);
TSparseSpace::Copy(b_modified, rb);
TSystemMatrixType auxiliar_A_matrix(mT.size2(), rA.size2());
SparseMatrixMultiplicationUtility::MatrixMultiplication(T_transpose_matrix, rA, auxiliar_A_matrix); //auxiliar = T_transpose * rA
T_transpose_matrix.resize(0, 0, false); //free memory
SparseMatrixMultiplicationUtility::MatrixMultiplication(auxiliar_A_matrix, mT, rA); //A = auxilar * T NOTE: here we are overwriting the old A matrix!
auxiliar_A_matrix.resize(0, 0, false); //free memory
const double max_diag = GetMaxDiagonal(rA);
// Apply diagonal values on slaves
IndexPartition<std::size_t>(mSlaveIds.size()).for_each([&](std::size_t Index){
const IndexType slave_equation_id = mSlaveIds[Index];
if (mInactiveSlaveDofs.find(slave_equation_id) == mInactiveSlaveDofs.end()) {
rA(slave_equation_id, slave_equation_id) = max_diag;
rb[slave_equation_id] = 0.0;
}
});
}
KRATOS_CATCH("")
}
/**
* @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed
*/
void Clear() override
{
BaseType::Clear();
mSlaveIds.clear();
mMasterIds.clear();
mInactiveSlaveDofs.clear();
mT.resize(0,0,false);
mConstantVector.resize(0,false);
}
/**
* @brief This function is designed to be called once to perform all the checks needed
* on the input provided. Checks can be "expensive" as the function is designed
* to catch user's errors.
* @param rModelPart The model part of the problem to solve
* @return 0 all ok
*/
int Check(ModelPart& rModelPart) override
{
KRATOS_TRY
return 0;
KRATOS_CATCH("");
}
/**
* @brief This method provides the defaults parameters to avoid conflicts between the different constructors
* @return The default parameters
*/
Parameters GetDefaultParameters() const override
{
Parameters default_parameters = Parameters(R"(
{
"name" : "block_builder_and_solver",
"block_builder" : true,
"diagonal_values_for_dirichlet_dofs" : "use_max_diagonal",
"silent_warnings" : false
})");
// Getting base class default parameters
const Parameters base_default_parameters = BaseType::GetDefaultParameters();
default_parameters.RecursivelyAddMissingParameters(base_default_parameters);
return default_parameters;
}
/**
* @brief Returns the name of the class as used in the settings (snake_case format)
* @return The name of the class
*/
static std::string Name()
{
return "block_builder_and_solver";
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "ResidualBasedBlockBuilderAndSolver";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << Info();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
rOStream << Info();
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
TSystemMatrixType mT; /// This is matrix containing the global relation for the constraints
TSystemVectorType mConstantVector; /// This is vector containing the rigid movement of the constraint
std::vector<IndexType> mSlaveIds; /// The equation ids of the slaves
std::vector<IndexType> mMasterIds; /// The equation ids of the master
std::unordered_set<IndexType> mInactiveSlaveDofs; /// The set containing the inactive slave dofs
double mScaleFactor = 1.0; /// The manuallyset scale factor
SCALING_DIAGONAL mScalingDiagonal; /// We identify the scaling considered for the dirichlet dofs
Flags mOptions; /// Some flags used internally
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
void BuildRHSNoDirichlet(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart,
TSystemVectorType& b)
{
KRATOS_TRY
//Getting the Elements
ElementsArrayType& pElements = rModelPart.Elements();
//getting the array of the conditions
ConditionsArrayType& ConditionsArray = rModelPart.Conditions();
const ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo();
//contributions to the system
LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0);
LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0);
//vector containing the localization in the system of the different
//terms
Element::EquationIdVectorType EquationId;
// assemble all elements
//for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it)
const int nelements = static_cast<int>(pElements.size());
#pragma omp parallel firstprivate(nelements, RHS_Contribution, EquationId)
{
#pragma omp for schedule(guided, 512) nowait
for (int i=0; i<nelements; i++) {
typename ElementsArrayType::iterator it = pElements.begin() + i;
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool element_is_active = true;
if( (it)->IsDefined(ACTIVE) ) {
element_is_active = (it)->Is(ACTIVE);
}
if(element_is_active) {
//calculate elemental Right Hand Side Contribution
pScheme->CalculateRHSContribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo);
//assemble the elemental contribution
AssembleRHS(b, RHS_Contribution, EquationId);
}
}
LHS_Contribution.resize(0, 0, false);
RHS_Contribution.resize(0, false);
// assemble all conditions
const int nconditions = static_cast<int>(ConditionsArray.size());
#pragma omp for schedule(guided, 512)
for (int i = 0; i<nconditions; i++) {
auto it = ConditionsArray.begin() + i;
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool condition_is_active = true;
if( (it)->IsDefined(ACTIVE) ) {
condition_is_active = (it)->Is(ACTIVE);
}
if(condition_is_active) {
//calculate elemental contribution
pScheme->CalculateRHSContribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo);
//assemble the elemental contribution
AssembleRHS(b, RHS_Contribution, EquationId);
}
}
}
KRATOS_CATCH("")
}
virtual void ConstructMasterSlaveConstraintsStructure(ModelPart& rModelPart)
{
if (rModelPart.MasterSlaveConstraints().size() > 0) {
Timer::Start("ConstraintsRelationMatrixStructure");
const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// Vector containing the localization in the system of the different terms
DofsVectorType slave_dof_list, master_dof_list;
// Constraint initial iterator
const auto it_const_begin = rModelPart.MasterSlaveConstraints().begin();
std::vector<std::unordered_set<IndexType>> indices(BaseType::mDofSet.size());
std::vector<LockObject> lock_array(indices.size());
#pragma omp parallel firstprivate(slave_dof_list, master_dof_list)
{
Element::EquationIdVectorType slave_ids(3);
Element::EquationIdVectorType master_ids(3);
std::unordered_map<IndexType, std::unordered_set<IndexType>> temp_indices;
#pragma omp for schedule(guided, 512) nowait
for (int i_const = 0; i_const < static_cast<int>(rModelPart.MasterSlaveConstraints().size()); ++i_const) {
auto it_const = it_const_begin + i_const;
// Detect if the constraint is active or not. If the user did not make any choice the constraint
// It is active by default
bool constraint_is_active = true;
if( it_const->IsDefined(ACTIVE) ) {
constraint_is_active = it_const->Is(ACTIVE);
}
if(constraint_is_active) {
it_const->EquationIdVector(slave_ids, master_ids, r_current_process_info);
// Slave DoFs
for (auto &id_i : slave_ids) {
temp_indices[id_i].insert(master_ids.begin(), master_ids.end());
}
}
}
// Merging all the temporal indexes
for (int i = 0; i < static_cast<int>(temp_indices.size()); ++i) {
lock_array[i].lock();
indices[i].insert(temp_indices[i].begin(), temp_indices[i].end());
lock_array[i].unlock();
}
}
mSlaveIds.clear();
mMasterIds.clear();
for (int i = 0; i < static_cast<int>(indices.size()); ++i) {
if (indices[i].size() == 0) // Master dof!
mMasterIds.push_back(i);
else // Slave dof
mSlaveIds.push_back(i);
indices[i].insert(i); // Ensure that the diagonal is there in T
}
// Count the row sizes
std::size_t nnz = 0;
for (IndexType i = 0; i < indices.size(); ++i)
nnz += indices[i].size();
mT = TSystemMatrixType(indices.size(), indices.size(), nnz);
mConstantVector.resize(indices.size(), false);
double *Tvalues = mT.value_data().begin();
IndexType *Trow_indices = mT.index1_data().begin();
IndexType *Tcol_indices = mT.index2_data().begin();
// Filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP!
Trow_indices[0] = 0;
for (int i = 0; i < static_cast<int>(mT.size1()); i++)
Trow_indices[i + 1] = Trow_indices[i] + indices[i].size();
IndexPartition<std::size_t>(mT.size1()).for_each([&](std::size_t Index){
const IndexType row_begin = Trow_indices[Index];
const IndexType row_end = Trow_indices[Index + 1];
IndexType k = row_begin;
for (auto it = indices[Index].begin(); it != indices[Index].end(); ++it) {
Tcol_indices[k] = *it;
Tvalues[k] = 0.0;
k++;
}
indices[Index].clear(); //deallocating the memory
std::sort(&Tcol_indices[row_begin], &Tcol_indices[row_end]);
});
mT.set_filled(indices.size() + 1, nnz);
Timer::Stop("ConstraintsRelationMatrixStructure");
}
}
virtual void BuildMasterSlaveConstraints(ModelPart& rModelPart)
{
KRATOS_TRY
TSparseSpace::SetToZero(mT);
TSparseSpace::SetToZero(mConstantVector);
// The current process info
const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// Vector containing the localization in the system of the different terms
DofsVectorType slave_dof_list, master_dof_list;
// Contributions to the system
Matrix transformation_matrix = LocalSystemMatrixType(0, 0);
Vector constant_vector = LocalSystemVectorType(0);
// Vector containing the localization in the system of the different terms
Element::EquationIdVectorType slave_equation_ids, master_equation_ids;
const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
// We clear the set
mInactiveSlaveDofs.clear();
#pragma omp parallel firstprivate(transformation_matrix, constant_vector, slave_equation_ids, master_equation_ids)
{
std::unordered_set<IndexType> auxiliar_inactive_slave_dofs;
#pragma omp for schedule(guided, 512)
for (int i_const = 0; i_const < number_of_constraints; ++i_const) {
auto it_const = rModelPart.MasterSlaveConstraints().begin() + i_const;
// Detect if the constraint is active or not. If the user did not make any choice the constraint
// It is active by default
bool constraint_is_active = true;
if (it_const->IsDefined(ACTIVE))
constraint_is_active = it_const->Is(ACTIVE);
if (constraint_is_active) {
it_const->CalculateLocalSystem(transformation_matrix, constant_vector, r_current_process_info);
it_const->EquationIdVector(slave_equation_ids, master_equation_ids, r_current_process_info);
for (IndexType i = 0; i < slave_equation_ids.size(); ++i) {
const IndexType i_global = slave_equation_ids[i];
// Assemble matrix row
AssembleRowContribution(mT, transformation_matrix, i_global, i, master_equation_ids);
// Assemble constant vector
const double constant_value = constant_vector[i];
double& r_value = mConstantVector[i_global];
AtomicAdd(r_value, constant_value);
}
} else { // Taking into account inactive constraints
it_const->EquationIdVector(slave_equation_ids, master_equation_ids, r_current_process_info);
auxiliar_inactive_slave_dofs.insert(slave_equation_ids.begin(), slave_equation_ids.end());
}
}
// We merge all the sets in one thread
#pragma omp critical
{
mInactiveSlaveDofs.insert(auxiliar_inactive_slave_dofs.begin(), auxiliar_inactive_slave_dofs.end());
}
}
// Setting the master dofs into the T and C system
for (auto eq_id : mMasterIds) {
mConstantVector[eq_id] = 0.0;
mT(eq_id, eq_id) = 1.0;
}
// Setting inactive slave dofs in the T and C system
for (auto eq_id : mInactiveSlaveDofs) {
mConstantVector[eq_id] = 0.0;
mT(eq_id, eq_id) = 1.0;
}
KRATOS_CATCH("")
}
virtual void ConstructMatrixStructure(
typename TSchemeType::Pointer pScheme,
TSystemMatrixType& A,
ModelPart& rModelPart)
{
//filling with zero the matrix (creating the structure)
Timer::Start("MatrixStructure");
const ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo();
const std::size_t equation_size = BaseType::mEquationSystemSize;
std::vector< LockObject > lock_array(equation_size);
std::vector<std::unordered_set<std::size_t> > indices(equation_size);
block_for_each(indices, [](std::unordered_set<std::size_t>& rIndices){
rIndices.reserve(40);
});
Element::EquationIdVectorType ids(3, 0);
block_for_each(rModelPart.Elements(), ids, [&](Element& rElem, Element::EquationIdVectorType& rIdsTLS){
pScheme->EquationId(rElem, rIdsTLS, CurrentProcessInfo);
for (std::size_t i = 0; i < rIdsTLS.size(); i++) {
lock_array[rIdsTLS[i]].lock();
auto& row_indices = indices[rIdsTLS[i]];
row_indices.insert(rIdsTLS.begin(), rIdsTLS.end());
lock_array[rIdsTLS[i]].unlock();
}
});
block_for_each(rModelPart.Conditions(), ids, [&](Condition& rCond, Element::EquationIdVectorType& rIdsTLS){
pScheme->EquationId(rCond, rIdsTLS, CurrentProcessInfo);
for (std::size_t i = 0; i < rIdsTLS.size(); i++) {
lock_array[rIdsTLS[i]].lock();
auto& row_indices = indices[rIdsTLS[i]];
row_indices.insert(rIdsTLS.begin(), rIdsTLS.end());
lock_array[rIdsTLS[i]].unlock();
}
});
if (rModelPart.MasterSlaveConstraints().size() != 0) {
struct TLS
{
Element::EquationIdVectorType master_ids = Element::EquationIdVectorType(3,0);
Element::EquationIdVectorType slave_ids = Element::EquationIdVectorType(3,0);
};
TLS tls;
block_for_each(rModelPart.MasterSlaveConstraints(), tls, [&](MasterSlaveConstraint& rConst, TLS& rTls){
rConst.EquationIdVector(rTls.slave_ids, rTls.master_ids, CurrentProcessInfo);
for (std::size_t i = 0; i < rTls.slave_ids.size(); i++) {
lock_array[rTls.slave_ids[i]].lock();
auto& row_indices = indices[rTls.slave_ids[i]];
row_indices.insert(rTls.slave_ids[i]);
lock_array[rTls.slave_ids[i]].unlock();
}
for (std::size_t i = 0; i < rTls.master_ids.size(); i++) {
lock_array[rTls.master_ids[i]].lock();
auto& row_indices = indices[rTls.master_ids[i]];
row_indices.insert(rTls.master_ids[i]);
lock_array[rTls.master_ids[i]].unlock();
}
});
}
//destroy locks
lock_array = std::vector< LockObject >();
//count the row sizes
unsigned int nnz = 0;
for (unsigned int i = 0; i < indices.size(); i++) {
nnz += indices[i].size();
}
A = CompressedMatrixType(indices.size(), indices.size(), nnz);
double* Avalues = A.value_data().begin();
std::size_t* Arow_indices = A.index1_data().begin();
std::size_t* Acol_indices = A.index2_data().begin();
//filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP!
Arow_indices[0] = 0;
for (int i = 0; i < static_cast<int>(A.size1()); i++) {
Arow_indices[i+1] = Arow_indices[i] + indices[i].size();
}
IndexPartition<std::size_t>(A.size1()).for_each([&](std::size_t i){
const unsigned int row_begin = Arow_indices[i];
const unsigned int row_end = Arow_indices[i+1];
unsigned int k = row_begin;
for (auto it = indices[i].begin(); it != indices[i].end(); it++) {
Acol_indices[k] = *it;
Avalues[k] = 0.0;
k++;
}
indices[i].clear(); //deallocating the memory
std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]);
});
A.set_filled(indices.size()+1, nnz);
Timer::Stop("MatrixStructure");
}
void Assemble(
TSystemMatrixType& A,
TSystemVectorType& b,
const LocalSystemMatrixType& LHS_Contribution,
const LocalSystemVectorType& RHS_Contribution,
Element::EquationIdVectorType& EquationId
)
{
unsigned int local_size = LHS_Contribution.size1();
for (unsigned int i_local = 0; i_local < local_size; i_local++) {
unsigned int i_global = EquationId[i_local];
double& r_a = b[i_global];
const double& v_a = RHS_Contribution(i_local);
AtomicAdd(r_a, v_a);
AssembleRowContribution(A, LHS_Contribution, i_global, i_local, EquationId);
}
}
//**************************************************************************
void AssembleLHS(
TSystemMatrixType& rA,
const LocalSystemMatrixType& rLHSContribution,
Element::EquationIdVectorType& rEquationId
)
{
const SizeType local_size = rLHSContribution.size1();
for (IndexType i_local = 0; i_local < local_size; i_local++) {
const IndexType i_global = rEquationId[i_local];
AssembleRowContribution(rA, rLHSContribution, i_global, i_local, rEquationId);
}
}
//**************************************************************************
void AssembleRHS(
TSystemVectorType& b,
LocalSystemVectorType& RHS_Contribution,
Element::EquationIdVectorType& EquationId
)
{
unsigned int local_size = RHS_Contribution.size();
for (unsigned int i_local = 0; i_local < local_size; i_local++) {
unsigned int i_global = EquationId[i_local];
// ASSEMBLING THE SYSTEM VECTOR
double& b_value = b[i_global];
const double& rhs_value = RHS_Contribution[i_local];
AtomicAdd(b_value, rhs_value);
}
}
inline void AssembleRowContribution(TSystemMatrixType& A, const Matrix& Alocal, const unsigned int i, const unsigned int i_local, Element::EquationIdVectorType& EquationId)
{
double* values_vector = A.value_data().begin();
std::size_t* index1_vector = A.index1_data().begin();
std::size_t* index2_vector = A.index2_data().begin();
size_t left_limit = index1_vector[i];
// size_t right_limit = index1_vector[i+1];
//find the first entry
size_t last_pos = ForwardFind(EquationId[0],left_limit,index2_vector);
size_t last_found = EquationId[0];
double& r_a = values_vector[last_pos];
const double& v_a = Alocal(i_local,0);
AtomicAdd(r_a, v_a);
//now find all of the other entries
size_t pos = 0;
for (unsigned int j=1; j<EquationId.size(); j++) {
unsigned int id_to_find = EquationId[j];
if(id_to_find > last_found) {
pos = ForwardFind(id_to_find,last_pos+1,index2_vector);
} else if(id_to_find < last_found) {
pos = BackwardFind(id_to_find,last_pos-1,index2_vector);
} else {
pos = last_pos;
}
double& r = values_vector[pos];
const double& v = Alocal(i_local,j);
AtomicAdd(r, v);
last_found = id_to_find;
last_pos = pos;
}
}
/**
* @brief This method returns the scale norm considering for scaling the diagonal
* @param rModelPart The problem model part
* @param rA The LHS matrix
* @return The scale norm
*/
double GetScaleNorm(
ModelPart& rModelPart,
TSystemMatrixType& rA
)
{
switch (mScalingDiagonal) {
case SCALING_DIAGONAL::NO_SCALING:
return 1.0;
case SCALING_DIAGONAL::CONSIDER_PRESCRIBED_DIAGONAL: {
const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
KRATOS_ERROR_IF_NOT(r_current_process_info.Has(BUILD_SCALE_FACTOR)) << "Scale factor not defined at process info" << std::endl;
return r_current_process_info.GetValue(BUILD_SCALE_FACTOR);
}
case SCALING_DIAGONAL::CONSIDER_NORM_DIAGONAL:
return GetDiagonalNorm(rA)/static_cast<double>(rA.size1());
case SCALING_DIAGONAL::CONSIDER_MAX_DIAGONAL:
return GetMaxDiagonal(rA);
// return TSparseSpace::TwoNorm(rA)/static_cast<double>(rA.size1());
default:
return GetMaxDiagonal(rA);
}
}
/**
* @brief This method returns the diagonal norm considering for scaling the diagonal
* @param rA The LHS matrix
* @return The diagonal norm
*/
double GetDiagonalNorm(TSystemMatrixType& rA)
{
double diagonal_norm = 0.0;
diagonal_norm = IndexPartition<std::size_t>(TSparseSpace::Size1(rA)).for_each<SumReduction<double>>([&](std::size_t Index){
return std::pow(rA(Index,Index), 2);
});
return std::sqrt(diagonal_norm);
}
/**
* @brief This method returns the diagonal max value
* @param rA The LHS matrix
* @return The diagonal max value
*/
double GetAveragevalueDiagonal(TSystemMatrixType& rA)
{
return 0.5 * (GetMaxDiagonal(rA) + GetMinDiagonal(rA));
}
/**
* @brief This method returns the diagonal max value
* @param rA The LHS matrix
* @return The diagonal max value
*/
double GetMaxDiagonal(TSystemMatrixType& rA)
{
// // NOTE: Reduction failing in MSVC
// double max_diag = 0.0;
// #pragma omp parallel for reduction(max:max_diag)
// for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) {
// max_diag = std::max(max_diag, std::abs(rA(i,i)));
// }
// return max_diag;
// Creating a buffer for parallel vector fill
const int num_threads = ParallelUtilities::GetNumThreads();
Vector max_vector(num_threads, 0.0);
#pragma omp parallel for
for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) {
const int id = OpenMPUtils::ThisThread();
const double abs_value_ii = std::abs(rA(i,i));
if (abs_value_ii > max_vector[id])
max_vector[id] = abs_value_ii;
}
double max_diag = 0.0;
for(int i = 0; i < num_threads; ++i) {
max_diag = std::max(max_diag, max_vector[i]);
}
return max_diag;
}
/**
* @brief This method returns the diagonal min value
* @param rA The LHS matrix
* @return The diagonal min value
*/
double GetMinDiagonal(TSystemMatrixType& rA)
{
// // NOTE: Reduction failing in MSVC
// double min_diag = std::numeric_limits<double>::max();
// #pragma omp parallel for reduction(min:min_diag)
// for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) {
// min_diag = std::min(min_diag, std::abs(rA(i,i)));
// }
// return min_diag;
// Creating a buffer for parallel vector fill
const int num_threads = ParallelUtilities::GetNumThreads();
Vector min_vector(num_threads, std::numeric_limits<double>::max());
#pragma omp parallel for
for(int i = 0; i < static_cast<int>(TSparseSpace::Size1(rA)); ++i) {
const int id = OpenMPUtils::ThisThread();
const double abs_value_ii = std::abs(rA(i,i));
if (abs_value_ii < min_vector[id])
min_vector[id] = abs_value_ii;
}
double min_diag = std::numeric_limits<double>::max();
for(int i = 0; i < num_threads; ++i) {
min_diag = std::min(min_diag, min_vector[i]);
}
return min_diag;
}
/**
* @brief This method assigns settings to member variables
* @param ThisParameters Parameters that are assigned to the member variables
*/
void AssignSettings(const Parameters ThisParameters) override
{
BaseType::AssignSettings(ThisParameters);
// Setting flags<
const std::string& r_diagonal_values_for_dirichlet_dofs = ThisParameters["diagonal_values_for_dirichlet_dofs"].GetString();
std::set<std::string> available_options_for_diagonal = {"no_scaling","use_max_diagonal","use_diagonal_norm","defined_in_process_info"};
if (available_options_for_diagonal.find(r_diagonal_values_for_dirichlet_dofs) == available_options_for_diagonal.end()) {
std::stringstream msg;
msg << "Currently prescribed diagonal values for dirichlet dofs : " << r_diagonal_values_for_dirichlet_dofs << "\n";
msg << "Admissible values for the diagonal scaling are : no_scaling, use_max_diagonal, use_diagonal_norm, or defined_in_process_info" << "\n";
KRATOS_ERROR << msg.str() << std::endl;
}
// The first option will not consider any scaling (the diagonal values will be replaced with 1)
if (r_diagonal_values_for_dirichlet_dofs == "no_scaling") {
mScalingDiagonal = SCALING_DIAGONAL::NO_SCALING;
} else if (r_diagonal_values_for_dirichlet_dofs == "use_max_diagonal") {
mScalingDiagonal = SCALING_DIAGONAL::CONSIDER_MAX_DIAGONAL;
} else if (r_diagonal_values_for_dirichlet_dofs == "use_diagonal_norm") { // On this case the norm of the diagonal will be considered
mScalingDiagonal = SCALING_DIAGONAL::CONSIDER_NORM_DIAGONAL;
} else { // Otherwise we will assume we impose a numerical value
mScalingDiagonal = SCALING_DIAGONAL::CONSIDER_PRESCRIBED_DIAGONAL;
}
mOptions.Set(SILENT_WARNINGS, ThisParameters["silent_warnings"].GetBool());
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
inline void AddUnique(std::vector<std::size_t>& v, const std::size_t& candidate)
{
std::vector<std::size_t>::iterator i = v.begin();
std::vector<std::size_t>::iterator endit = v.end();
while (i != endit && (*i) != candidate) {
i++;
}
if (i == endit) {
v.push_back(candidate);
}
}
//******************************************************************************************
//******************************************************************************************
inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, DenseVector<unsigned int>& partitions)
{
partitions.resize(number_of_threads + 1);
int partition_size = number_of_rows / number_of_threads;
partitions[0] = 0;
partitions[number_of_threads] = number_of_rows;
for (unsigned int i = 1; i < number_of_threads; i++) {
partitions[i] = partitions[i - 1] + partition_size;
}
}
inline unsigned int ForwardFind(const unsigned int id_to_find,
const unsigned int start,
const size_t* index_vector)
{
unsigned int pos = start;
while(id_to_find != index_vector[pos]) pos++;
return pos;
}
inline unsigned int BackwardFind(const unsigned int id_to_find,
const unsigned int start,
const size_t* index_vector)
{
unsigned int pos = start;
while(id_to_find != index_vector[pos]) pos--;
return pos;
}
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class ResidualBasedBlockBuilderAndSolver */
///@}
///@name Type Definitions
///@{
// Here one should use the KRATOS_CREATE_LOCAL_FLAG, but it does not play nice with template parameters
template<class TSparseSpace, class TDenseSpace, class TLinearSolver>
const Kratos::Flags ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>::SILENT_WARNINGS(Kratos::Flags::Create(0));
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
|
apm.c | /**
* APPROXIMATE PATTERN MATCHING
*
* INF560 X2016
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <mpi.h>
#include <omp.h>
#define APM_DEBUG 0
char *
read_input_file( char * filename, int * size )
{
char * buf ;
off_t fsize;
int fd = 0 ;
int n_bytes = 1 ;
/* Open the text file */
fd = open( filename, O_RDONLY ) ;
if ( fd == -1 )
{
fprintf( stderr, "Unable to open the text file <%s>\n", filename ) ;
return NULL ;
}
/* Get the number of characters in the textfile */
fsize = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
/* TODO check return of lseek */
#if APM_DEBUG
printf( "File length: %lld\n", fsize ) ;
#endif
/* Allocate data to copy the target text */
buf = (char *)malloc( fsize * sizeof ( char ) ) ;
if ( buf == NULL )
{
fprintf( stderr, "Unable to allocate %lld byte(s) for main array\n",
fsize ) ;
return NULL ;
}
n_bytes = read( fd, buf, fsize ) ;
if ( n_bytes != fsize )
{
fprintf( stderr,
"Unable to copy %lld byte(s) from text file (%d byte(s) copied)\n",
fsize, n_bytes) ;
return NULL ;
}
#if APM_DEBUG
printf( "Number of read bytes: %d\n", n_bytes ) ;
#endif
*size = n_bytes ;
close( fd ) ;
return buf ;
}
#define MIN3(a, b, c) ((a) < (b) ? ((a) < (c) ? (a) : (c)) : ((b) < (c) ? (b) : (c)))
int levenshtein(char *s1, char *s2, int len, int * column) {
unsigned int x, y, lastdiag, olddiag;
for (y = 1; y <= len; y++)
{
column[y] = y;
}
for (x = 1; x <= len; x++) {
column[0] = x;
lastdiag = x-1 ;
for (y = 1; y <= len; y++) {
olddiag = column[y];
column[y] = MIN3(
column[y] + 1,
column[y-1] + 1,
lastdiag + (s1[y-1] == s2[x-1] ? 0 : 1)
);
lastdiag = olddiag;
}
}
return(column[len]);
}
int
main( int argc, char ** argv )
{
/* MPI initialisation
*/
int nb_nodes;
int rank;
MPI_Status status;
int required = MPI_THREAD_FUNNELED;
int provided;
MPI_Init_thread(&argc, &argv, required, &provided);
MPI_Comm_size(MPI_COMM_WORLD, &nb_nodes);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#if APM_DEBUG
char hostname[256];
gethostname(hostname, sizeof(hostname));
printf("Process MPI rank %d of PID %d on %s ready for attach\n",rank, getpid(), hostname);
#endif
char ** pattern ;
char * filename ;
int approx_factor = 0 ;
int nb_patterns = 0 ;
int i, j ;
char * buf ;
struct timeval t1, t2;
double duration ;
int n_bytes ;
int tmp_matches ;
int * n_matches ;
int * global_matches;
/* Check number of arguments */
if ( argc < 4 )
{
printf( "Usage: %s approximation_factor "
"dna_database pattern1 pattern2 ...\n",
argv[0] ) ;
return 1 ;
}
/* Get the distance factor */
approx_factor = atoi( argv[1] ) ;
/* Grab the filename containing the target text */
filename = argv[2] ;
/* Get the number of patterns that the user wants to search for */
nb_patterns = argc - 3 ;
/* Fill the pattern array */
pattern = (char **)malloc( nb_patterns * sizeof( char * ) ) ;
if ( pattern == NULL )
{
fprintf( stderr,
"Unable to allocate array of pattern of size %d\n",
nb_patterns ) ;
return 1 ;
}
/* Grab the patterns */
int max_len_pattern = 0;
for ( i = 0 ; i < nb_patterns ; i++ )
{
int l ;
l = strlen(argv[i+3]) ;
if ( l <= 0 )
{
fprintf( stderr, "Error while parsing argument %d\n", i+3 ) ;
return 1 ;
} else if (l > max_len_pattern)
{
max_len_pattern = l;
}
pattern[i] = (char *)malloc( (l+1) * sizeof( char ) ) ;
if ( pattern[i] == NULL )
{
fprintf( stderr, "Unable to allocate string of size %d\n", l ) ;
return 1 ;
}
strncpy( pattern[i], argv[i+3], (l+1) ) ;
}
printf( "Approximate Pattern Mathing: "
"looking for %d pattern(s) in file %s w/ distance of %d\n",
nb_patterns, filename, approx_factor ) ;
/* Allocate the array of local matches */
n_matches = (int *)malloc( nb_patterns * sizeof( int ) ) ;
if ( n_matches == NULL )
{
fprintf( stderr, "Error: unable to allocate memory for %ldB\n",
nb_patterns * sizeof( int ) ) ;
return 1 ;
}
/* Allocate the array of global matches for the reductin of local n_matches*/
global_matches = (int *)malloc( nb_patterns * sizeof( int ) ) ;
if ( global_matches == NULL )
{
fprintf( stderr, "Error: unable to allocate memory for %ldB\n",
nb_patterns * sizeof( int ) ) ;
return 1 ;
}
/*****
* BEGIN MAIN LOOP
******/
/* Timer start */
gettimeofday(&t1, NULL);
/* Since we have nb_nodes MPI process we are going to divide our textfile into
nb_nodes parts while taking care that the biggest pattern have access to all
it needs.
rank 0 treats from 0 to n_bytes//nb_nodes - 1 + (max_len_pattern - 1)
rank 1 treats from n_bytes//nb_nodes to 2*(n_bytes//size) - 1 + (max_len_pattern - 1)
.
rank i treat from i*(n_bytes//nb_nodes) to (i+1)*(n_bytes//size) - 1 + (max_len_pattern - 1)
.
rank (nb_nodes-1) treat from (nb_nodes-1)*(n_bytes//nb_nodes) to END
*/
/* rank 0 play the role of divider */
int part_bytes; // the number of bytes of the process part textfile
MPI_Request requests[nb_nodes-1];
MPI_Status statutes[nb_nodes-1];
if (rank == 0) {
/* reading input file */
buf = read_input_file( filename, &n_bytes ) ;
if ( buf == NULL )
{
return 1 ;
}
int start = 0; // start index of process
int end = n_bytes/nb_nodes - 1 + (max_len_pattern - 1); // end index of process
#if APM_DEBUG
printf( "MPI rank 0 will treat from bytes %d to %d\n", start, end);
#endif
for (int i = 1; i < nb_nodes; i++) {
/* Index and process part bytes */
start += (n_bytes/nb_nodes);
end += (n_bytes/nb_nodes);
if (i == nb_nodes - 1 || end > n_bytes) {
end = n_bytes;
}
part_bytes = end - start + 1 ;
#if APM_DEBUG
printf("MPI rank %d will treat from bytes %d to %d\n",i,start,end);
#endif
/* Sending to each process other than 0*/
/* the part_bytes so they how much memory to allocate */
MPI_Send(&part_bytes,1,MPI_INTEGER,i,0,MPI_COMM_WORLD);
#if APM_DEBUG
printf("Rank 0 sended part_bytes : %d to rank %d\n",part_bytes,i);
#endif
MPI_Send(&buf[start],part_bytes,MPI_BYTE,i,1,MPI_COMM_WORLD);
#if APM_DEBUG
printf("Rank 0 sended a part_buffer to rank %d\n",i);
#endif
/* the start & end index of their part */
}
// Reset part_bytes for process 0 :
part_bytes = n_bytes/nb_nodes - 1 + max_len_pattern - 1;
} else {
// other process receive :
// first : part_bytes :
MPI_Recv(&part_bytes,1,MPI_INTEGER,0,0,MPI_COMM_WORLD,&status);
// so they know how much to allocate
buf = (char *) malloc((part_bytes+1)*sizeof(char));
if ( buf == NULL )
{
fprintf( stderr, "Unable to allocate %ld byte(s) for buf array\n",part_bytes);
return -1;
}
// secondly : part textfile :
MPI_Recv(buf,part_bytes,MPI_BYTE,0,1,MPI_COMM_WORLD,&status);
}
for ( i = 0 ; i < nb_patterns ; i++ )
{
int size_pattern = strlen(pattern[i]) ;
int * column ;
n_matches[i] = 0 ;
tmp_matches = 0 ;
#pragma omp parallel
{
int j_end = (rank == nb_nodes-1) ? part_bytes : part_bytes - size_pattern + 1;
#pragma omp for schedule(guided) reduction(+:tmp_matches)
for ( j = 0 ; j < j_end ; j++ )
{
column = (int *)malloc( (size_pattern+1) * sizeof( int ) ) ;
if ( column == NULL ) {
fprintf( stderr, "Error: unable to allocate memory for column (%ldB)\n",
(size_pattern+1) * sizeof( int ) ) ;
exit(1);
}
int distance = 0 ;
int size ;
#if APM_DEBUG
if ( j % 10000 == 0 )
{
printf( "MPI rank %d : Processing byte %d (out of %d)\n",rank, j, part_bytes ) ;
printf("local matches of rank %d: ",rank);
for (int i = 0; i < nb_patterns; i++)
{
printf("%d,",n_matches[i]);
}
printf("\n");
}
#endif
size = size_pattern ;
// modifying the edge case for the last MPI process
if ( part_bytes - j < size_pattern )
{
size = part_bytes - j ;
}
distance = levenshtein( pattern[i], &buf[j], size, column ) ;
if ( distance <= approx_factor ) {
tmp_matches = tmp_matches + 1 ;
}
}
}
free( column );
n_matches[i] = tmp_matches;
}
/* Sum the matches of each process with a MPI reduction */
MPI_Reduce(n_matches, global_matches, nb_patterns, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
/* Timer stop */
gettimeofday(&t2, NULL);
duration = (t2.tv_sec -t1.tv_sec)+((t2.tv_usec-t1.tv_usec)/1e6);
#if APM_DEBUG
printf("Rank %d finished :",rank);
for ( i = 0 ; i < nb_patterns ; i++ ) {
printf( "%d, ",n_matches[i] ) ;
}
printf("=============\n");
#endif
/*****
* END MAIN LOOP
******/
if (rank == 0)
{
printf( "APM done in %lf s\n", duration ) ;
for ( i = 0 ; i < nb_patterns ; i++ ) {
printf( "Number of matches for pattern <%s>: %d\n",
pattern[i], global_matches[i] ) ;
}
}
MPI_Finalize();
return 0 ;
}
|
GB_unaryop__abs_uint64_int32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_uint64_int32
// op(A') function: GB_tran__abs_uint64_int32
// C type: uint64_t
// A type: int32_t
// cast: uint64_t cij = (uint64_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, aij) \
uint64_t z = (uint64_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_UINT64 || GxB_NO_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_uint64_int32
(
uint64_t *Cx, // Cx and Ax may be aliased
int32_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_uint64_int32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
fx.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF X X %
% F X X %
% FFF X %
% F X X %
% F X X %
% %
% %
% MagickCore Image Special Effects Methods %
% %
% Software Design %
% snibgo (Alan Gibson) %
% January 2022 %
% %
% %
% %
% Copyright @ 2022 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/accelerate-private.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/decorate.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/fx-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/policy.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
#define MaxTokenLen 100
#define RpnInit 100
#define TableExtend 0.1
#define InitNumOprStack 50
#define MinValStackSize 100
#define InitNumUserSymbols 50
typedef long double fxFltType;
typedef enum {
oAddEq,
oSubtractEq,
oMultiplyEq,
oDivideEq,
oPlusPlus,
oSubSub,
oAdd,
oSubtract,
oMultiply,
oDivide,
oModulus,
oUnaryPlus,
oUnaryMinus,
oLshift,
oRshift,
oEq,
oNotEq,
oLtEq,
oGtEq,
oLt,
oGt,
oLogAnd,
oLogOr,
oLogNot,
oBitAnd,
oBitOr,
oBitNot,
oPow,
oQuery,
oColon,
oOpenParen,
oCloseParen,
oOpenBracket,
oCloseBracket,
oOpenBrace,
oCloseBrace,
oAssign,
oNull
} OperatorE;
typedef struct {
OperatorE op;
const char * str;
int precedence; /* Higher number is higher precedence */
int nArgs;
} OperatorT;
static const OperatorT Operators[] = {
{oAddEq, "+=", 12, 1},
{oSubtractEq, "-=", 12, 1},
{oMultiplyEq, "*=", 13, 1},
{oDivideEq, "/=", 13, 1},
{oPlusPlus, "++", 12, 0},
{oSubSub, "--", 12, 0},
{oAdd, "+", 12, 2},
{oSubtract, "-", 12, 2},
{oMultiply, "*", 13, 2},
{oDivide, "/", 13, 2},
{oModulus, "%", 13, 2},
{oUnaryPlus, "+", 14, 1},
{oUnaryMinus, "-", 14, 1},
{oLshift, "<<", 11, 2},
{oRshift, ">>", 11, 2},
{oEq, "==", 9, 2},
{oNotEq, "!=", 9, 2},
{oLtEq, "<=", 10, 2},
{oGtEq, ">=", 10, 2},
{oLt, "<", 10, 2},
{oGt, ">", 10, 2},
{oLogAnd, "&&", 6, 2},
{oLogOr, "||", 5, 2},
{oLogNot, "!", 16, 1},
{oBitAnd, "&", 8, 2},
{oBitOr, "|", 7, 2},
{oBitNot, "~", 16, 1},
{oPow, "^", 15, 2},
{oQuery, "?", 4, 1},
{oColon, ":", 4, 1},
{oOpenParen, "(", 0, 0},
{oCloseParen, ")", 0, 0},
{oOpenBracket, "[", 0, 0},
{oCloseBracket,"]", 0, 0},
{oOpenBrace, "{", 0, 0},
{oCloseBrace, "}", 0, 0},
{oAssign, "=", 3, 1},
{oNull, "onull", 17, 0}
};
typedef enum {
cEpsilon,
cE,
cOpaque,
cPhi,
cPi,
cQuantumRange,
cQuantumScale,
cTransparent,
cMaxRgb,
cNull
} ConstantE;
typedef struct {
ConstantE cons;
fxFltType val;
const char * str;
} ConstantT;
static const ConstantT Constants[] = {
{cEpsilon, MagickEpsilon, "epsilon"},
{cE, 2.7182818284590452354, "e"},
{cOpaque, 1.0, "opaque"},
{cPhi, MagickPHI, "phi"},
{cPi, MagickPI, "pi"},
{cQuantumRange, QuantumRange, "quantumrange"},
{cQuantumScale, QuantumScale, "quantumscale"},
{cTransparent, 0.0, "transparent"},
{cMaxRgb, QuantumRange, "MaxRGB"},
{cNull, 0.0, "cnull"}
};
#define FirstFunc ((FunctionE) (oNull+1))
typedef enum {
fAbs = oNull+1,
#if defined(MAGICKCORE_HAVE_ACOSH)
fAcosh,
#endif
fAcos,
#if defined(MAGICKCORE_HAVE_J1)
fAiry,
#endif
fAlt,
#if defined(MAGICKCORE_HAVE_ASINH)
fAsinh,
#endif
fAsin,
#if defined(MAGICKCORE_HAVE_ATANH)
fAtanh,
#endif
fAtan2,
fAtan,
fCeil,
fChannel,
fClamp,
fCosh,
fCos,
fDebug,
fDrc,
#if defined(MAGICKCORE_HAVE_ERF)
fErf,
#endif
fExp,
fFloor,
fGauss,
fGcd,
fHypot,
fInt,
fIsnan,
#if defined(MAGICKCORE_HAVE_J0)
fJ0,
#endif
#if defined(MAGICKCORE_HAVE_J1)
fJ1,
#endif
#if defined(MAGICKCORE_HAVE_J1)
fJinc,
#endif
fLn,
fLogtwo,
fLog,
fMax,
fMin,
fMod,
fNot,
fPow,
fRand,
fRound,
fSign,
fSinc,
fSinh,
fSin,
fSqrt,
fSquish,
fTanh,
fTan,
fTrunc,
fDo,
fFor,
fIf,
fWhile,
fU,
fU0,
fUP,
fS,
fV,
fP,
fSP,
fVP,
fNull
} FunctionE;
typedef struct {
FunctionE func;
const char * str;
int nArgs;
} FunctionT;
static const FunctionT Functions[] = {
{fAbs, "abs" , 1},
#if defined(MAGICKCORE_HAVE_ACOSH)
{fAcosh, "acosh" , 1},
#endif
{fAcos, "acos" , 1},
#if defined(MAGICKCORE_HAVE_J1)
{fAiry, "airy" , 1},
#endif
{fAlt, "alt" , 1},
#if defined(MAGICKCORE_HAVE_ASINH)
{fAsinh, "asinh" , 1},
#endif
{fAsin, "asin" , 1},
#if defined(MAGICKCORE_HAVE_ATANH)
{fAtanh, "atanh" , 1},
#endif
{fAtan2, "atan2" , 2},
{fAtan, "atan" , 1},
{fCeil, "ceil" , 1},
{fChannel, "channel", 5}, /* Special case: allow zero to five arguments. */
{fClamp, "clamp" , 1},
{fCosh, "cosh" , 1},
{fCos, "cos" , 1},
{fDebug, "debug" , 1},
{fDrc, "drc" , 2},
#if defined(MAGICKCORE_HAVE_ERF)
{fErf, "erf" , 1},
#endif
{fExp, "exp" , 1},
{fFloor, "floor" , 1},
{fGauss, "gauss" , 2},
{fGcd, "gcd" , 2},
{fHypot, "hypot" , 2},
{fInt, "int" , 1},
{fIsnan, "isnan" , 1},
#if defined(MAGICKCORE_HAVE_J0)
{fJ0, "j0" , 1},
#endif
#if defined(MAGICKCORE_HAVE_J1)
{fJ1, "j1" , 1},
#endif
#if defined(MAGICKCORE_HAVE_J1)
{fJinc, "jinc" , 1},
#endif
{fLn, "ln" , 1},
{fLogtwo, "logtwo", 1},
{fLog, "log" , 1},
{fMax, "max" , 2},
{fMin, "min" , 2},
{fMod, "mod" , 2},
{fNot, "not" , 1},
{fPow, "pow" , 2},
{fRand, "rand" , 0},
{fRound, "round" , 1},
{fSign, "sign" , 1},
{fSinc, "sinc" , 1},
{fSinh, "sinh" , 1},
{fSin, "sin" , 1},
{fSqrt, "sqrt" , 1},
{fSquish, "squish", 1},
{fTanh, "tanh" , 1},
{fTan, "tan" , 1},
{fTrunc, "trunc" , 1},
{fDo, "do", 2},
{fFor, "for", 3},
{fIf, "if", 3},
{fWhile, "while", 2},
{fU, "u", 1},
{fU0, "u0", 0},
{fUP, "up", 3},
{fS, "s", 0},
{fV, "v", 0},
{fP, "p", 2},
{fSP, "sp", 2},
{fVP, "vp", 2},
{fNull, "fnull" , 0}
};
#define FirstImgAttr ((ImgAttrE) (fNull+1))
typedef enum {
aDepth = fNull+1,
aExtent,
aKurtosis,
aMaxima,
aMean,
aMedian,
aMinima,
aPage,
aPageX,
aPageY,
aPageWid,
aPageHt,
aPrintsize,
aPrintsizeX,
aPrintsizeY,
aQuality,
aRes,
aResX,
aResY,
aSkewness,
aStdDev,
aH,
aN,
aT,
aW,
aZ,
aNull
} ImgAttrE;
typedef struct {
ImgAttrE attr;
const char * str;
int NeedStats;
} ImgAttrT;
static const ImgAttrT ImgAttrs[] = {
{aDepth, "depth", 1},
{aExtent, "extent", 0},
{aKurtosis, "kurtosis", 1},
{aMaxima, "maxima", 1},
{aMean, "mean", 1},
{aMedian, "median", 1},
{aMinima, "minima", 1},
{aPage, "page", 0},
{aPageX, "page.x", 0},
{aPageY, "page.y", 0},
{aPageWid, "page.width", 0},
{aPageHt, "page.height", 0},
{aPrintsize, "printsize", 0},
{aPrintsizeX, "printsize.x", 0},
{aPrintsizeY, "printsize.y", 0},
{aQuality, "quality", 0},
{aRes, "resolution", 0},
{aResX, "resolution.x", 0},
{aResY, "resolution.y", 0},
{aSkewness, "skewness", 1},
{aStdDev, "standard_deviation", 1},
{aH, "h", 0},
{aN, "n", 0},
{aT, "t", 0},
{aW, "w", 0},
{aZ, "z", 0},
{aNull, "anull", 0},
{aNull, "anull", 0},
{aNull, "anull", 0},
{aNull, "anull", 0}
};
#define FirstSym ((SymbolE) (aNull+1))
typedef enum {
sHue = aNull+1,
sIntensity,
sLightness,
sLuma,
sLuminance,
sSaturation,
sA,
sB,
sC,
sG,
sI,
sJ,
sK,
sM,
sO,
sR,
sY,
sNull
} SymbolE;
typedef struct {
SymbolE sym;
const char * str;
} SymbolT;
static const SymbolT Symbols[] = {
{sHue, "hue"},
{sIntensity, "intensity"},
{sLightness, "lightness"},
{sLuma, "luma"},
{sLuminance, "luminance"},
{sSaturation, "saturation"},
{sA, "a"},
{sB, "b"},
{sC, "c"},
{sG, "g"},
{sI, "i"},
{sJ, "j"},
{sK, "k"},
{sM, "m"},
{sO, "o"},
{sR, "r"},
{sY, "y"},
{sNull, "snull"}
};
/*
There is no way to access new value of pixels. This might be a future enhancement, eg "q".
fP, oU and oV can have channel qualifier such as "u.r".
For meta channels, we might also allow numbered channels eg "u.2" or "u.16".
... or have extra argument to p[].
*/
#define FirstCont (sNull+1)
/* Run-time controls are in the RPN, not explicitly in the input string. */
typedef enum {
rGoto = FirstCont,
rIfZeroGoto,
rIfNotZeroGoto,
rCopyFrom,
rCopyTo,
rZerStk,
rNull
} ControlE;
typedef struct {
ControlE cont;
const char * str;
int nArgs;
} ControlT;
static const ControlT Controls[] = {
{rGoto, "goto", 0},
{rIfZeroGoto, "ifzerogoto", 1},
{rIfNotZeroGoto, "ifnotzerogoto", 1},
{rCopyFrom, "copyfrom", 0},
{rCopyTo, "copyto", 1},
{rZerStk, "zerstk", 0},
{rNull, "rnull", 0}
};
#define NULL_ADDRESS -2
typedef struct {
int addrQuery;
int addrColon;
} TernaryT;
typedef struct {
const char * str;
PixelChannel pixChan;
} ChannelT;
#define NO_CHAN_QUAL ((PixelChannel) (-1))
#define THIS_CHANNEL ((PixelChannel) (-2))
#define HUE_CHANNEL ((PixelChannel) (-3))
#define SAT_CHANNEL ((PixelChannel) (-4))
#define LIGHT_CHANNEL ((PixelChannel) (-5))
#define INTENSITY_CHANNEL ((PixelChannel) (-6))
static const ChannelT Channels[] = {
{"r", RedPixelChannel},
{"g", GreenPixelChannel},
{"b", BluePixelChannel},
{"c", CyanPixelChannel},
{"m", MagentaPixelChannel},
{"y", YellowPixelChannel},
{"k", BlackPixelChannel},
{"a", AlphaPixelChannel},
{"o", AlphaPixelChannel},
{"hue", HUE_CHANNEL},
{"saturation", SAT_CHANNEL},
{"lightness", LIGHT_CHANNEL},
{"intensity", INTENSITY_CHANNEL},
{"all", CompositePixelChannel},
{"this", THIS_CHANNEL},
{"", NO_CHAN_QUAL}
};
/* The index into UserSymbols is also the index into run-time UserSymVals.
*/
typedef struct {
char * pex;
size_t len;
} UserSymbolT;
typedef enum {
etOperator,
etConstant,
etFunction,
etImgAttr,
etSymbol,
etColourConstant,
etControl
} ElementTypeE;
static const char * sElementTypes[] = {
"Operator",
"Constant",
"Function",
"ImgAttr",
"Symbol",
"ColConst",
"Control"
};
typedef struct {
ElementTypeE type;
fxFltType
val, val1, val2;
int oprNum;
int nArgs;
MagickBooleanType IsRelative;
MagickBooleanType DoPush;
int EleNdx;
int nDest; /* Number of Elements that "goto" this element */
PixelChannel ChannelQual;
ImgAttrE ImgAttrQual;
char * pExpStart;
int lenExp;
} ElementT;
typedef enum {
rtUnknown,
rtEntireImage,
rtCornerOnly
} RunTypeE;
typedef struct {
CacheView *View;
/* Other per-image metadata could go here. */
} ImgT;
typedef struct {
RandomInfo * magick_restrict random_info;
int numValStack;
int usedValStack;
fxFltType * ValStack;
fxFltType * UserSymVals;
Quantum * thisPixel;
} fxRtT;
struct _FxInfo {
Image * image;
size_t ImgListLen;
ssize_t ImgNum;
MagickBooleanType NeedStats;
MagickBooleanType GotStats;
MagickBooleanType NeedHsl;
MagickBooleanType DebugOpt; /* Whether "-debug" option is in effect */
MagickBooleanType ContainsDebug; /* Whether expression contains "debug ()" function */
char * expression;
char * pex;
char ShortExp[MagickPathExtent]; /* for reporting */
int teDepth;
char token[MagickPathExtent];
size_t lenToken;
int numElements;
int usedElements;
ElementT * Elements; /* Elements is read-only at runtime. */
int numUserSymbols;
int usedUserSymbols;
UserSymbolT * UserSymbols;
int numOprStack;
int usedOprStack;
int maxUsedOprStack;
OperatorE * OperatorStack;
ChannelStatistics ** statistics;
int precision;
RunTypeE runType;
RandomInfo
**magick_restrict random_infos;
ImgT * Imgs;
Image ** Images;
ExceptionInfo * exception;
fxRtT * fxrts;
};
/* Forward declarations for recursion.
*/
static MagickBooleanType TranslateStatementList
(FxInfo * pfx, const char * strLimit, char * chLimit);
static MagickBooleanType TranslateExpression
(FxInfo * pfx, const char * strLimit, char * chLimit, MagickBooleanType * needPopAll);
static MagickBooleanType GetFunction (FxInfo * pfx, FunctionE fe);
static MagickBooleanType InitFx (FxInfo * pfx, const Image * img,
MagickBooleanType CalcAllStats, ExceptionInfo *exception)
{
ssize_t i=0;
const Image * next;
pfx->ImgListLen = GetImageListLength (img);
pfx->ImgNum = GetImageIndexInList (img);
pfx->image = (Image *)img;
pfx->NeedStats = MagickFalse;
pfx->GotStats = MagickFalse;
pfx->NeedHsl = MagickFalse;
pfx->DebugOpt = IsStringTrue (GetImageArtifact (img, "fx:debug"));
pfx->statistics = NULL;
pfx->Imgs = NULL;
pfx->Images = NULL;
pfx->exception = exception;
pfx->precision = GetMagickPrecision ();
pfx->random_infos = AcquireRandomInfoTLS ();
pfx->ContainsDebug = MagickFalse;
pfx->runType = (CalcAllStats) ? rtEntireImage : rtCornerOnly;
pfx->Imgs = (ImgT *)AcquireQuantumMemory (pfx->ImgListLen, sizeof (ImgT));
if (!pfx->Imgs) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"Imgs", "%lu",
(unsigned long) pfx->ImgListLen);
return MagickFalse;
}
next = GetFirstImageInList (img);
for ( ; next != (Image *) NULL; next=next->next)
{
ImgT * pimg = &pfx->Imgs[i];
pimg->View = AcquireVirtualCacheView (next, pfx->exception);
if (!pimg->View) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"View", "[%li]",
(long) i);
/* dealloc any done so far, and Imgs */
for ( ; i > 0; i--) {
pimg = &pfx->Imgs[i-1];
pimg->View = DestroyCacheView (pimg->View);
}
pfx->Imgs=(ImgT *) RelinquishMagickMemory (pfx->Imgs);
return MagickFalse;
}
i++;
}
pfx->Images = ImageListToArray (img, pfx->exception);
return MagickTrue;
}
static MagickBooleanType DeInitFx (FxInfo * pfx)
{
ssize_t i;
if (pfx->Images) pfx->Images = (Image**) RelinquishMagickMemory (pfx->Images);
if (pfx->Imgs) {
for (i = (ssize_t)GetImageListLength(pfx->image); i > 0; i--) {
ImgT * pimg = &pfx->Imgs[i-1];
pimg->View = DestroyCacheView (pimg->View);
}
pfx->Imgs=(ImgT *) RelinquishMagickMemory (pfx->Imgs);
}
pfx->random_infos = DestroyRandomInfoTLS (pfx->random_infos);
if (pfx->statistics) {
for (i = (ssize_t)GetImageListLength(pfx->image); i > 0; i--) {
pfx->statistics[i-1]=(ChannelStatistics *) RelinquishMagickMemory (pfx->statistics[i-1]);
}
pfx->statistics = (ChannelStatistics**) RelinquishMagickMemory(pfx->statistics);
}
return MagickTrue;
}
static ElementTypeE TypeOfOpr (int op)
{
if (op < oNull) return etOperator;
if (op == oNull) return etConstant;
if (op <= fNull) return etFunction;
if (op <= aNull) return etImgAttr;
if (op <= sNull) return etSymbol;
if (op <= rNull) return etControl;
return (ElementTypeE) 0;
}
static char * SetPtrShortExp (FxInfo * pfx, char * pExp, size_t len)
{
#define MaxLen 20
size_t slen;
char * p;
*pfx->ShortExp = '\0';
if (pExp && len) {
slen = CopyMagickString (pfx->ShortExp, pExp, len);
if (slen > MaxLen) {
(void) CopyMagickString (pfx->ShortExp+MaxLen, "...", 4);
}
p = strchr (pfx->ShortExp, '\n');
if (p) (void) CopyMagickString (p, "...", 4);
p = strchr (pfx->ShortExp, '\r');
if (p) (void) CopyMagickString (p, "...", 4);
}
return pfx->ShortExp;
}
static char * SetShortExp (FxInfo * pfx)
{
return SetPtrShortExp (pfx, pfx->pex, MaxTokenLen-1);
}
static int FindUserSymbol (FxInfo * pfx, char * name)
/* returns index into pfx->UserSymbols, and thus into pfxrt->UserSymVals,
or NULL_ADDRESS if not found.
*/
{
int i;
size_t lenName;
lenName = strlen (name);
for (i=0; i < pfx->usedUserSymbols; i++) {
UserSymbolT *pus = &pfx->UserSymbols[i];
if (lenName == pus->len && LocaleNCompare (name, pus->pex, lenName)==0) break;
}
if (i == pfx->usedUserSymbols) return NULL_ADDRESS;
return i;
}
static MagickBooleanType ExtendUserSymbols (FxInfo * pfx)
{
pfx->numUserSymbols = (int) ceil (pfx->numUserSymbols * (1 + TableExtend));
pfx->UserSymbols = (UserSymbolT*) ResizeMagickMemory (pfx->UserSymbols, pfx->numUserSymbols * sizeof(UserSymbolT));
if (!pfx->UserSymbols) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"UserSymbols", "%i",
pfx->numUserSymbols);
return MagickFalse;
}
return MagickTrue;
}
static int AddUserSymbol (FxInfo * pfx, char * pex, size_t len)
{
UserSymbolT *pus;
if (++pfx->usedUserSymbols >= pfx->numUserSymbols) {
if (!ExtendUserSymbols (pfx)) return -1;
}
pus = &pfx->UserSymbols[pfx->usedUserSymbols-1];
pus->pex = pex;
pus->len = len;
return pfx->usedUserSymbols-1;
}
static void DumpTables (FILE * fh)
{
int i;
for (i=0; i <= rNull; i++) {
const char * str = "";
if ( i < oNull) str = Operators[i].str;
if (i >= FirstFunc && i < fNull) str = Functions[i-FirstFunc].str;
if (i >= FirstImgAttr && i < aNull) str = ImgAttrs[i-FirstImgAttr].str;
if (i >= FirstSym && i < sNull) str = Symbols[i-FirstSym].str;
if (i >= FirstCont && i < rNull) str = Controls[i-FirstCont].str;
if (i==0 ) fprintf (stderr, "Operators:\n ");
else if (i==oNull) fprintf (stderr, "\nFunctions:\n ");
else if (i==fNull) fprintf (stderr, "\nImage attributes:\n ");
else if (i==aNull) fprintf (stderr, "\nSymbols:\n ");
else if (i==sNull) fprintf (stderr, "\nControls:\n ");
fprintf (fh, " %s", str);
}
fprintf (fh, "\n");
}
static char * NameOfUserSym (FxInfo * pfx, int ndx, char * buf)
{
UserSymbolT * pus;
assert (ndx >= 0 && ndx < pfx->usedUserSymbols);
pus = &pfx->UserSymbols[ndx];
(void) CopyMagickString (buf, pus->pex, pus->len+1);
return buf;
}
static void DumpUserSymbols (FxInfo * pfx, FILE * fh)
{
char UserSym[MagickPathExtent];
int i;
fprintf (fh, "UserSymbols (%i)\n", pfx->usedUserSymbols);
for (i=0; i < pfx->usedUserSymbols; i++) {
fprintf (fh, " %i: '%s'\n", i, NameOfUserSym (pfx, i, UserSym));
}
}
static MagickBooleanType BuildRPN (FxInfo * pfx)
{
pfx->numUserSymbols = InitNumUserSymbols;
pfx->usedUserSymbols = 0;
pfx->UserSymbols = (UserSymbolT*) AcquireMagickMemory (pfx->numUserSymbols * sizeof(UserSymbolT));
if (!pfx->UserSymbols) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"UserSymbols", "%i",
pfx->numUserSymbols);
return MagickFalse;
}
pfx->numElements = RpnInit;
pfx->usedElements = 0;
pfx->Elements = NULL;
pfx->Elements = (ElementT*) AcquireMagickMemory (pfx->numElements * sizeof(ElementT));
if (!pfx->Elements) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"Elements", "%i",
pfx->numElements);
return MagickFalse;
}
pfx->usedOprStack = 0;
pfx->maxUsedOprStack = 0;
pfx->numOprStack = InitNumOprStack;
pfx->OperatorStack = (OperatorE*) AcquireMagickMemory (pfx->numOprStack * sizeof(OperatorE));
if (!pfx->OperatorStack) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"OperatorStack", "%i",
pfx->numOprStack);
return MagickFalse;
}
return MagickTrue;
}
static MagickBooleanType AllocFxRt (FxInfo * pfx, fxRtT * pfxrt)
{
int nRnd;
int i;
pfxrt->random_info = AcquireRandomInfo ();
pfxrt->thisPixel = NULL;
nRnd = 20 + 10 * (int) GetPseudoRandomValue (pfxrt->random_info);
for (i=0; i < nRnd; i++) (void) GetPseudoRandomValue (pfxrt->random_info);;
pfxrt->usedValStack = 0;
pfxrt->numValStack = 2 * pfx->maxUsedOprStack;
if (pfxrt->numValStack < MinValStackSize) pfxrt->numValStack = MinValStackSize;
pfxrt->ValStack = (fxFltType*) AcquireMagickMemory (pfxrt->numValStack * sizeof(fxFltType));
if (!pfxrt->ValStack) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"ValStack", "%i",
pfxrt->numValStack);
return MagickFalse;
}
pfxrt->UserSymVals = NULL;
if (pfx->usedUserSymbols) {
pfxrt->UserSymVals = (fxFltType*) AcquireMagickMemory (pfx->usedUserSymbols * sizeof(fxFltType));
if (!pfxrt->UserSymVals) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"UserSymVals", "%i",
pfx->usedUserSymbols);
return MagickFalse;
}
for (i = 0; i < pfx->usedUserSymbols; i++) pfxrt->UserSymVals[i] = (fxFltType) 0;
}
return MagickTrue;
}
static MagickBooleanType ExtendRPN (FxInfo * pfx)
{
pfx->numElements = (int) ceil (pfx->numElements * (1 + TableExtend));
pfx->Elements = (ElementT*) ResizeMagickMemory (pfx->Elements, pfx->numElements * sizeof(ElementT));
if (!pfx->Elements) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"Elements", "%i",
pfx->numElements);
return MagickFalse;
}
return MagickTrue;
}
static MagickBooleanType inline OprInPlace (int op)
{
return (op >= oAddEq && op <= oSubSub ? MagickTrue : MagickFalse);
}
static const char * OprStr (int oprNum)
{
const char * str;
if (oprNum < 0) str = "bad OprStr";
else if (oprNum <= oNull) str = Operators[oprNum].str;
else if (oprNum <= fNull) str = Functions[oprNum-FirstFunc].str;
else if (oprNum <= aNull) str = ImgAttrs[oprNum-FirstImgAttr].str;
else if (oprNum <= sNull) str = Symbols[oprNum-FirstSym].str;
else if (oprNum <= rNull) str = Controls[oprNum-FirstCont].str;
else {
str = "bad OprStr";
}
return str;
}
static MagickBooleanType DumpRPN (FxInfo * pfx, FILE * fh)
{
int i;
fprintf (fh, "DumpRPN:");
fprintf (fh, " numElements=%i", pfx->numElements);
fprintf (fh, " usedElements=%i", pfx->usedElements);
fprintf (fh, " maxUsedOprStack=%i", pfx->maxUsedOprStack);
fprintf (fh, " ImgListLen=%g", (double) pfx->ImgListLen);
fprintf (fh, " NeedStats=%s", pfx->NeedStats ? "yes" : "no");
fprintf (fh, " GotStats=%s", pfx->GotStats ? "yes" : "no");
fprintf (fh, " NeedHsl=%s\n", pfx->NeedHsl ? "yes" : "no");
if (pfx->runType==rtEntireImage) fprintf (stderr, "EntireImage");
else if (pfx->runType==rtCornerOnly) fprintf (stderr, "CornerOnly");
fprintf (fh, "\n");
for (i=0; i < pfx->usedElements; i++) {
ElementT * pel = &pfx->Elements[i];
pel->nDest = 0;
}
for (i=0; i < pfx->usedElements; i++) {
ElementT * pel = &pfx->Elements[i];
if (pel->oprNum == rGoto || pel->oprNum == rIfZeroGoto || pel->oprNum == rIfNotZeroGoto) {
if (pel->EleNdx >= 0 && pel->EleNdx < pfx->numElements) {
ElementT * pelDest = &pfx->Elements[pel->EleNdx];
pelDest->nDest++;
}
}
}
for (i=0; i < pfx->usedElements; i++) {
char UserSym[MagickPathExtent];
ElementT * pel = &pfx->Elements[i];
const char * str = OprStr (pel->oprNum);
const char *sRelAbs = "";
if (pel->oprNum == fP || pel->oprNum == fUP || pel->oprNum == fVP || pel->oprNum == fSP)
sRelAbs = pel->IsRelative ? "[]" : "{}";
if (pel->type == etColourConstant)
fprintf (fh, " %i: %s vals=%.*Lg,%.*Lg,%.*Lg '%s%s' nArgs=%i ndx=%i %s",
i, sElementTypes[pel->type],
pfx->precision, pel->val, pfx->precision, pel->val1, pfx->precision, pel->val2,
str, sRelAbs, pel->nArgs, pel->EleNdx,
pel->DoPush ? "push" : "NO push");
else
fprintf (fh, " %i: %s val=%.*Lg '%s%s' nArgs=%i ndx=%i %s",
i, sElementTypes[pel->type], pfx->precision, pel->val, str, sRelAbs,
pel->nArgs, pel->EleNdx,
pel->DoPush ? "push" : "NO push");
if (pel->ImgAttrQual != aNull)
fprintf (fh, " ia=%s", OprStr(pel->ImgAttrQual));
if (pel->ChannelQual != NO_CHAN_QUAL) {
if (pel->ChannelQual == THIS_CHANNEL) fprintf (stderr, " ch=this");
else fprintf (stderr, " ch=%i", pel->ChannelQual);
}
if (pel->oprNum == rCopyTo) {
fprintf (fh, " CopyTo ==> %s", NameOfUserSym (pfx, pel->EleNdx, UserSym));
} else if (pel->oprNum == rCopyFrom) {
fprintf (fh, " CopyFrom <== %s", NameOfUserSym (pfx, pel->EleNdx, UserSym));
} else if (OprInPlace (pel->oprNum)) {
fprintf (fh, " <==> %s", NameOfUserSym (pfx, pel->EleNdx, UserSym));
}
if (pel->nDest > 0) fprintf (fh, " <==dest(%i)", pel->nDest);
fprintf (fh, "\n");
}
return MagickTrue;
}
static void DestroyRPN (FxInfo * pfx)
{
pfx->numOprStack = 0;
pfx->usedOprStack = 0;
if (pfx->OperatorStack) pfx->OperatorStack = (OperatorE*) RelinquishMagickMemory (pfx->OperatorStack);
pfx->numElements = 0;
pfx->usedElements = 0;
if (pfx->Elements) pfx->Elements = (ElementT*) RelinquishMagickMemory (pfx->Elements);
pfx->usedUserSymbols = 0;
if (pfx->UserSymbols) pfx->UserSymbols = (UserSymbolT*) RelinquishMagickMemory (pfx->UserSymbols);
}
static void DestroyFxRt (fxRtT * pfxrt)
{
pfxrt->usedValStack = 0;
if (pfxrt->ValStack) pfxrt->ValStack = (fxFltType*) RelinquishMagickMemory (pfxrt->ValStack);
if (pfxrt->UserSymVals) pfxrt->UserSymVals = (fxFltType*) RelinquishMagickMemory (pfxrt->UserSymVals);
pfxrt->random_info = DestroyRandomInfo (pfxrt->random_info);
}
static size_t GetToken (FxInfo * pfx)
/* Returns length of token that starts with an alpha,
or 0 if it isn't a token that starts with an alpha.
j0 and j1 have trailing digit.
Also colours like "gray47" have more trailing digits.
After intial alpha(s) also allow single "_", eg "standard_deviation".
Does not advance pfx->pex.
This splits "mean.r" etc.
*/
{
char * p = pfx->pex;
size_t len = 0;
*pfx->token = '\0';
pfx->lenToken = 0;
if (!isalpha((int)*p)) return 0;
/* Regard strings that start "icc-" or "device-",
followed by any number of alphas,
as a token.
*/
if (LocaleNCompare (p, "icc-", 4) == 0) {
len = 4;
p += 4;
while (isalpha ((int)*p)) { len++; p++; }
} else if (LocaleNCompare (p, "device-", 7) == 0) {
len = 7;
p += 7;
while (isalpha ((int)*p)) { len++; p++; }
} else {
while (isalpha ((int)*p)) { len++; p++; }
if (*p == '_') { len++; p++; }
while (isalpha ((int)*p)) { len++; p++; }
while (isdigit ((int)*p)) { len++; p++; }
}
if (len >= MaxTokenLen) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"GetToken: too long", "%g at '%s'",
(double) len, SetShortExp(pfx));
len = MaxTokenLen;
}
if (len) {
(void) CopyMagickString (pfx->token, pfx->pex, (len+1<MaxTokenLen)?len+1:MaxTokenLen);
}
pfx->lenToken = strlen (pfx->token);
return len;
}
static MagickBooleanType TokenMaybeUserSymbol (FxInfo * pfx)
{
char * p = pfx->token;
int i = 0;
while (*p) {
if (!isalpha ((int)*p++)) return MagickFalse;
i++;
}
if (i < 2) return MagickFalse;
return MagickTrue;
}
static MagickBooleanType AddElement (FxInfo * pfx, fxFltType val, int oprNum)
{
ElementT * pel;
assert (oprNum <= rNull);
if (++pfx->usedElements >= pfx->numElements) {
if (!ExtendRPN (pfx)) return MagickFalse;
}
pel = &pfx->Elements[pfx->usedElements-1];
pel->type = TypeOfOpr (oprNum);
pel->val = val;
pel->val1 = (fxFltType) 0;
pel->val2 = (fxFltType) 0;
pel->oprNum = oprNum;
pel->DoPush = MagickTrue;
pel->EleNdx = 0;
pel->ChannelQual = NO_CHAN_QUAL;
pel->ImgAttrQual = aNull;
pel->nDest = 0;
pel->pExpStart = NULL;
pel->lenExp = 0;
if (oprNum <= oNull) pel->nArgs = Operators[oprNum].nArgs;
else if (oprNum <= fNull) pel->nArgs = Functions[oprNum-FirstFunc].nArgs;
else if (oprNum <= aNull) pel->nArgs = 0;
else if (oprNum <= sNull) pel->nArgs = 0;
else pel->nArgs = Controls[oprNum-FirstCont].nArgs;
return MagickTrue;
}
static MagickBooleanType AddAddressingElement (FxInfo * pfx, int oprNum, int EleNdx)
{
ElementT * pel;
if (!AddElement (pfx, (fxFltType) 0, oprNum)) return MagickFalse;
pel = &pfx->Elements[pfx->usedElements-1];
pel->EleNdx = EleNdx;
if (oprNum == rGoto || oprNum == rIfZeroGoto || oprNum == rIfNotZeroGoto
|| oprNum == rZerStk)
{
pel->DoPush = MagickFalse;
}
/* Note: for() may or may not need pushing,
depending on whether the value is needed, eg "for(...)+2" or debug(for(...)).
*/
return MagickTrue;
}
static MagickBooleanType AddColourElement (FxInfo * pfx, fxFltType val0, fxFltType val1, fxFltType val2)
{
ElementT * pel;
if (!AddElement (pfx, val0, oNull)) return MagickFalse;
pel = &pfx->Elements[pfx->usedElements-1];
pel->val1 = val1;
pel->val2 = val2;
pel->type = etColourConstant;
return MagickTrue;
}
static void inline SkipSpaces (FxInfo * pfx)
{
while (isspace ((int)*pfx->pex)) pfx->pex++;
}
static char inline PeekChar (FxInfo * pfx)
{
SkipSpaces (pfx);
return *pfx->pex;
}
static MagickBooleanType inline PeekStr (FxInfo * pfx, const char * str)
{
SkipSpaces (pfx);
return (LocaleNCompare (pfx->pex, str, strlen(str))==0 ? MagickTrue : MagickFalse);
}
static MagickBooleanType ExpectChar (FxInfo * pfx, char c)
{
if (PeekChar (pfx) != c) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Expected char", "'%c' at '%s'", c, SetShortExp (pfx));
return MagickFalse;
}
pfx->pex++;
return MagickTrue;
}
static int MaybeXYWH (FxInfo * pfx, ImgAttrE * pop)
/* If ".x" or ".y" or ".width" or ".height" increments *pop and returns 1 to 4 .
Otherwise returns 0.
*/
{
int ret=0;
if (*pop != aPage && *pop != aPrintsize && *pop != aRes) return 0;
if (PeekChar (pfx) != '.') return 0;
if (!ExpectChar (pfx, '.')) return 0;
(void) GetToken (pfx);
if (LocaleCompare ("x", pfx->token)==0) ret=1;
else if (LocaleCompare ("y", pfx->token)==0) ret=2;
else if (LocaleCompare ("width", pfx->token)==0) ret=3;
else if (LocaleCompare ("height", pfx->token)==0) ret=4;
if (!ret)
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Invalid 'x' or 'y' or 'width' or 'height' token=", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
if (*pop == aPage) (*pop) = (ImgAttrE) (*pop + ret);
else {
if (ret > 2) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Invalid 'width' or 'height' token=", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
} else {
(*pop) = (ImgAttrE) (*pop + ret);
}
}
pfx->pex+=pfx->lenToken;
return ret;
}
static MagickBooleanType ExtendOperatorStack (FxInfo * pfx)
{
pfx->numOprStack = (int) ceil (pfx->numOprStack * (1 + TableExtend));
pfx->OperatorStack = (OperatorE*) ResizeMagickMemory (pfx->OperatorStack, pfx->numOprStack * sizeof(OperatorE));
if (!pfx->OperatorStack) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"OprStack", "%i",
pfx->numOprStack);
return MagickFalse;
}
return MagickTrue;
}
static MagickBooleanType PushOperatorStack (FxInfo * pfx, int op)
{
if (++pfx->usedOprStack >= pfx->numOprStack) {
if (!ExtendOperatorStack (pfx))
return MagickFalse;
}
pfx->OperatorStack[pfx->usedOprStack-1] = (OperatorE) op;
if (pfx->maxUsedOprStack < pfx->usedOprStack)
pfx->maxUsedOprStack = pfx->usedOprStack;
return MagickTrue;
}
static OperatorE GetLeadingOp (FxInfo * pfx)
{
OperatorE op = oNull;
if (*pfx->pex == '-') op = oUnaryMinus;
else if (*pfx->pex == '+') op = oUnaryPlus;
else if (*pfx->pex == '~') op = oBitNot;
else if (*pfx->pex == '!') op = oLogNot;
else if (*pfx->pex == '(') op = oOpenParen;
return op;
}
static MagickBooleanType inline OprIsUnaryPrefix (OperatorE op)
{
return (op == oUnaryMinus || op == oUnaryPlus || op == oBitNot || op == oLogNot ? MagickTrue : MagickFalse);
}
static MagickBooleanType TopOprIsUnaryPrefix (FxInfo * pfx)
{
if (!pfx->usedOprStack) return MagickFalse;
return OprIsUnaryPrefix (pfx->OperatorStack[pfx->usedOprStack-1]);
}
static MagickBooleanType PopOprOpenParen (FxInfo * pfx, OperatorE op)
{
if (!pfx->usedOprStack) return MagickFalse;
if (pfx->OperatorStack[pfx->usedOprStack-1] != op) return MagickFalse;
pfx->usedOprStack--;
return MagickTrue;
}
static int GetCoordQualifier (FxInfo * pfx, int op)
/* Returns -1 if invalid CoordQualifier, +1 if valid and appropriate.
*/
{
if (op != fU && op != fV && op != fS) return -1;
(void) GetToken (pfx);
if (pfx->lenToken != 1) {
return -1;
}
if (*pfx->token != 'p' && *pfx->token != 'P') return -1;
if (!GetFunction (pfx, fP)) return -1;
return 1;
}
static PixelChannel GetChannelQualifier (FxInfo * pfx, int op)
{
if (op == fU || op == fV || op == fP ||
op == fUP || op == fVP ||
op == fS || (op >= FirstImgAttr && op <= aNull)
)
{
const ChannelT * pch = &Channels[0];
(void) GetToken (pfx);
while (*pch->str) {
if (LocaleCompare (pch->str, pfx->token)==0) {
if (op >= FirstImgAttr && op <= (OperatorE)aNull &&
(pch->pixChan == HUE_CHANNEL ||
pch->pixChan == SAT_CHANNEL ||
pch->pixChan == LIGHT_CHANNEL)
)
{
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Can't have image attribute with HLS qualifier at", "'%s'",
SetShortExp(pfx));
return NO_CHAN_QUAL;
}
pfx->pex += pfx->lenToken;
return pch->pixChan;
}
pch++;
}
}
return NO_CHAN_QUAL;
}
static ImgAttrE GetImgAttrToken (FxInfo * pfx)
{
ImgAttrE ia = aNull;
const char * iaStr;
for (ia = FirstImgAttr; ia < aNull; ia=(ImgAttrE) (ia+1)) {
iaStr = ImgAttrs[ia-FirstImgAttr].str;
if (LocaleCompare (iaStr, pfx->token)==0) {
pfx->pex += strlen(pfx->token);
if (ImgAttrs[ia-FirstImgAttr].NeedStats == 1) pfx->NeedStats = MagickTrue;
MaybeXYWH (pfx, &ia);
break;
}
}
if (ia == aPage || ia == aPrintsize || ia == aRes) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Attribute", "'%s' needs qualifier at '%s'",
iaStr, SetShortExp(pfx));
}
return ia;
}
static ImgAttrE GetImgAttrQualifier (FxInfo * pfx, int op)
{
ImgAttrE ia = aNull;
if (op == (OperatorE)fU || op == (OperatorE)fV || op == (OperatorE)fP || op == (OperatorE)fS) {
(void) GetToken (pfx);
if (pfx->lenToken == 0) {
return aNull;
}
ia = GetImgAttrToken (pfx);
}
return ia;
}
static MagickBooleanType IsQualifier (FxInfo * pfx)
{
if (PeekChar (pfx) == '.') {
pfx->pex++;
return MagickTrue;
}
return MagickFalse;
}
static ssize_t GetProperty (FxInfo * pfx, fxFltType *val)
/* returns number of character to swallow.
"-1" means invalid input
"0" means no relevant input (don't swallow, but not an error)
*/
{
if (PeekStr (pfx, "%[")) {
int level = 0;
size_t len;
char sProperty [MagickPathExtent];
char * p = pfx->pex + 2;
while (*p) {
if (*p == '[') level++;
else if (*p == ']') {
if (level == 0) break;
level--;
}
p++;
}
if (!*p || level != 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"After '%[' expected ']' at", "'%s'",
SetShortExp(pfx));
return -1;
}
len = (size_t) (p - pfx->pex + 1);
if (len > MaxTokenLen) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Too much text between '%[' and ']' at", "'%s'",
SetShortExp(pfx));
return -1;
}
(void) CopyMagickString (sProperty, pfx->pex, len+1);
sProperty[len] = '\0';
{
char * tailptr;
char * text;
text = InterpretImageProperties (pfx->image->image_info, pfx->image,
sProperty, pfx->exception);
if (!text || !*text) {
text = DestroyString(text);
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Unknown property", "'%s' at '%s'",
sProperty, SetShortExp(pfx));
return -1;
}
*val = strtold (text, &tailptr);
if (text == tailptr) {
text = DestroyString(text);
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Property", "'%s' text '%s' is not a number at '%s'",
sProperty, text, SetShortExp(pfx));
return -1;
}
text = DestroyString(text);
}
return ((ssize_t) len);
}
return 0;
}
static ssize_t inline GetConstantColour (FxInfo * pfx, fxFltType *v0, fxFltType *v1, fxFltType *v2)
/* Finds named colour such as "blue" and colorspace function such as "lab(10,20,30)".
Returns number of characters to swallow.
Return -1 means apparantly a constant colour, but with an error.
Return 0 means not a constant colour, but not an error.
*/
{
PixelInfo
colour;
ExceptionInfo
*dummy_exception = AcquireExceptionInfo ();
char
*p;
MagickBooleanType
IsGray,
IsIcc,
IsDev;
char ColSp[MagickPathExtent];
(void) CopyMagickString (ColSp, pfx->token, MaxTokenLen);
p = ColSp + pfx->lenToken - 1;
if (*p == 'a' || *p == 'A') *p = '\0';
(void) GetPixelInfo (pfx->image, &colour);
/* "gray" is both a colorspace and a named colour. */
IsGray = (LocaleCompare (ColSp, "gray") == 0) ? MagickTrue : MagickFalse;
IsIcc = (LocaleCompare (ColSp, "icc-color") == 0) ? MagickTrue : MagickFalse;
IsDev = (LocaleNCompare (ColSp, "device-", 7) == 0) ? MagickTrue : MagickFalse;
/* QueryColorCompliance will raise a warning if it isn't a colour, so we discard any exceptions.
*/
if (!QueryColorCompliance (pfx->token, AllCompliance, &colour, dummy_exception) || IsGray) {
ssize_t type = ParseCommandOption (MagickColorspaceOptions, MagickFalse, ColSp);
if (type >= 0 || IsIcc || IsDev) {
char * q = pfx->pex + pfx->lenToken;
while (isspace((int) ((unsigned char) *q))) q++;
if (*q == '(') {
size_t lenfun;
char sFunc[MagickPathExtent];
while (*q && *q != ')') q++;
if (!*q) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"constant color missing ')'", "at '%s'",
SetShortExp(pfx));
dummy_exception = DestroyExceptionInfo (dummy_exception);
return -1;
}
lenfun = (size_t) (q - pfx->pex + 1);
if (lenfun > MaxTokenLen) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"lenfun too long", "'%lu' at '%s'",
(unsigned long) lenfun, SetShortExp(pfx));
dummy_exception = DestroyExceptionInfo (dummy_exception);
return -1;
}
(void) CopyMagickString (sFunc, pfx->pex, lenfun+1);
if (QueryColorCompliance (sFunc, AllCompliance, &colour, dummy_exception)) {
*v0 = colour.red / QuantumRange;
*v1 = colour.green / QuantumRange;
*v2 = colour.blue / QuantumRange;
dummy_exception = DestroyExceptionInfo (dummy_exception);
return (ssize_t)lenfun;
}
} else {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"colorspace but not a valid color with '(...)' at", "'%s'",
SetShortExp(pfx));
dummy_exception = DestroyExceptionInfo (dummy_exception);
return -1;
}
}
if (!IsGray) {
dummy_exception = DestroyExceptionInfo (dummy_exception);
return 0;
}
}
*v0 = colour.red / QuantumRange;
*v1 = colour.green / QuantumRange;
*v2 = colour.blue / QuantumRange;
dummy_exception = DestroyExceptionInfo (dummy_exception);
return (ssize_t)strlen (pfx->token);
}
static ssize_t inline GetHexColour (FxInfo * pfx, fxFltType *v0, fxFltType *v1, fxFltType *v2)
/* Returns number of characters to swallow.
Negative return means it starts with '#', but invalid hex number.
*/
{
char * p;
size_t len;
PixelInfo colour;
if (*pfx->pex != '#') return 0;
/* find end of hex digits. */
p = pfx->pex + 1;
while (isxdigit ((int)*p)) p++;
if (isalpha ((int)*p)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Bad hex number at", "'%s'",
SetShortExp(pfx));
return -1;
}
len = (size_t) (p - pfx->pex);
if (len < 1) return 0;
if (len >= MaxTokenLen) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Hex colour too long at", "'%s'",
SetShortExp(pfx));
return -1;
}
(void) CopyMagickString (pfx->token, pfx->pex, len+1);
(void) GetPixelInfo (pfx->image, &colour);
if (!QueryColorCompliance (pfx->token, AllCompliance, &colour, pfx->exception)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"QueryColorCompliance rejected", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
return -1;
}
*v0 = colour.red / QuantumRange;
*v1 = colour.green / QuantumRange;
*v2 = colour.blue / QuantumRange;
return (ssize_t) len;
}
static MagickBooleanType GetFunction (FxInfo * pfx, FunctionE fe)
{
/* A function, so get open-parens, n args, close-parens
*/
const char * funStr = Functions[fe-FirstFunc].str;
int nArgs = Functions[fe-FirstFunc].nArgs;
char chLimit = ')';
char expChLimit = ')';
const char *strLimit = ",)";
OperatorE pushOp = oOpenParen;
char * pExpStart;
int lenExp = 0;
int FndArgs = 0;
int ndx0 = NULL_ADDRESS, ndx1 = NULL_ADDRESS, ndx2 = NULL_ADDRESS, ndx3 = NULL_ADDRESS;
MagickBooleanType coordQual = MagickFalse;
PixelChannel chQual = NO_CHAN_QUAL;
ImgAttrE iaQual = aNull;
pfx->pex += pfx->lenToken;
if (fe == fP) {
char p = PeekChar (pfx);
if (p=='{') {
(void) ExpectChar (pfx, '{');
pushOp = oOpenBrace;
strLimit = ",}";
chLimit = '}';
expChLimit = '}';
} else if (p=='[') {
(void) ExpectChar (pfx, '[');
pushOp = oOpenBracket;
strLimit = ",]";
chLimit = ']';
expChLimit = ']';
} else {
nArgs = 0;
chLimit = ']';
expChLimit = ']';
}
} else if (fe == fU) {
char p = PeekChar (pfx);
if (p=='[') {
(void) ExpectChar (pfx, '[');
pushOp = oOpenBracket;
strLimit = ",]";
chLimit = ']';
expChLimit = ']';
} else {
nArgs = 0;
chLimit = ']';
expChLimit = ']';
}
} else if (fe == fV || fe == fS) {
nArgs = 0;
pushOp = oOpenBracket;
chLimit = ']';
expChLimit = ']';
} else {
if (!ExpectChar (pfx, '(')) return MagickFalse;
}
if (!PushOperatorStack (pfx, pushOp)) return MagickFalse;
pExpStart = pfx->pex;
ndx0 = pfx->usedElements;
if (fe==fDo) {
(void) AddAddressingElement (pfx, rGoto, NULL_ADDRESS); /* address will be ndx1+1 */
}
while (nArgs > 0) {
int FndOne = 0;
if (TranslateStatementList (pfx, strLimit, &chLimit)) {
FndOne = 1;
} else {
/* Maybe don't break because other expressions may be not empty. */
if (!chLimit) break;
if (fe == fP || fe == fS|| fe == fIf) {
(void) AddElement (pfx, (fxFltType) 0, oNull);
FndOne = 1;
}
}
if (strchr (strLimit, chLimit)==NULL) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' expected one of '%s' after expression but found '%c' at '%s'",
funStr, strLimit, chLimit ? chLimit : ' ', SetShortExp(pfx));
return MagickFalse;
}
if (FndOne) {
FndArgs++;
nArgs--;
}
switch (FndArgs) {
case 1:
if (ndx1 != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' required argument is missing at '%s'",
funStr, SetShortExp(pfx));
return MagickFalse;
}
ndx1 = pfx->usedElements;
if (fe==fWhile) {
(void) AddAddressingElement (pfx, rIfZeroGoto, NULL_ADDRESS); /* address will be ndx2+1 */
} else if (fe==fDo) {
(void) AddAddressingElement (pfx, rIfZeroGoto, NULL_ADDRESS); /* address will be ndx2+1 */
} else if (fe==fFor) {
pfx->Elements[pfx->usedElements-1].DoPush = MagickFalse;
} else if (fe==fIf) {
(void) AddAddressingElement (pfx, rIfZeroGoto, NULL_ADDRESS); /* address will be ndx2 + 1 */
pfx->Elements[pfx->usedElements-1].DoPush = MagickTrue; /* we may need return from if() */
}
break;
case 2:
if (ndx2 != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' required argument is missing at '%s'",
funStr, SetShortExp(pfx));
return MagickFalse;
}
ndx2 = pfx->usedElements;
if (fe==fWhile) {
pfx->Elements[pfx->usedElements-1].DoPush = MagickFalse;
(void) AddAddressingElement (pfx, rGoto, ndx0);
} else if (fe==fDo) {
pfx->Elements[pfx->usedElements-1].DoPush = MagickFalse;
(void) AddAddressingElement (pfx, rGoto, ndx0 + 1);
} else if (fe==fFor) {
(void) AddAddressingElement (pfx, rIfZeroGoto, NULL_ADDRESS); /* address will be ndx3 */
pfx->Elements[pfx->usedElements-1].DoPush = MagickTrue; /* we may need return from for() */
(void) AddAddressingElement (pfx, rZerStk, NULL_ADDRESS);
} else if (fe==fIf) {
(void) AddAddressingElement (pfx, rGoto, NULL_ADDRESS); /* address will be ndx3 */
}
break;
case 3:
if (ndx3 != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' required argument is missing at '%s'",
funStr, SetShortExp(pfx));
return MagickFalse;
}
if (fe==fFor) {
pfx->Elements[pfx->usedElements-1].DoPush = MagickFalse;
(void) AddAddressingElement (pfx, rGoto, ndx1);
}
ndx3 = pfx->usedElements;
break;
default:
break;
}
if (chLimit == expChLimit) {
lenExp = pfx->pex - pExpStart - 1;
break;
}
} /* end while args of a function */
if (chLimit && chLimit != expChLimit && chLimit != ',' ) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' expected '%c', found '%c' at '%s'",
funStr, expChLimit, chLimit ? chLimit : ' ', SetShortExp(pfx));
return MagickFalse;
}
if (fe == fP || fe == fS || fe == fU || fe == fChannel) {
while (FndArgs < Functions[fe-FirstFunc].nArgs) {
(void) AddElement (pfx, (fxFltType) 0, oNull);
FndArgs++;
}
}
if (FndArgs > Functions[fe-FirstFunc].nArgs)
{
if (fe==fChannel) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' expected up to %i arguments, found '%i' at '%s'",
funStr, Functions[fe-FirstFunc].nArgs, FndArgs, SetShortExp(pfx));
} else {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' expected %i arguments, found '%i' at '%s'",
funStr, Functions[fe-FirstFunc].nArgs, FndArgs, SetShortExp(pfx));
}
return MagickFalse;
}
if (FndArgs < Functions[fe-FirstFunc].nArgs) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s' expected %i arguments, found too few (%i) at '%s'",
funStr, Functions[fe-FirstFunc].nArgs, FndArgs, SetShortExp(pfx));
return MagickFalse;
}
if (fe != fS && fe != fV && FndArgs == 0 && Functions[fe-FirstFunc].nArgs == 0) {
/* This is for "rand()" and similar. */
chLimit = expChLimit;
if (!ExpectChar (pfx, ')')) return MagickFalse;
}
if (chLimit != expChLimit) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s', arguments don't end with '%c' at '%s'",
funStr, expChLimit, SetShortExp(pfx));
return MagickFalse;
}
if (!PopOprOpenParen (pfx, pushOp)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Bug: For function", "'%s' tos not '%s' at '%s'",
funStr, Operators[pushOp].str, SetShortExp(pfx));
return MagickFalse;
}
if (IsQualifier (pfx)) {
if (fe == fU || fe == fV || fe == fS) {
coordQual = (GetCoordQualifier (pfx, fe) == 1) ? MagickTrue : MagickFalse;
if (coordQual) {
/* Remove last element, which should be fP */
ElementT * pel = &pfx->Elements[pfx->usedElements-1];
if (pel->oprNum != fP) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Bug: For function", "'%s' last element not 'p' at '%s'",
funStr, SetShortExp(pfx));
return MagickFalse;
}
chQual = pel->ChannelQual;
expChLimit = (pel->IsRelative) ? ']' : '}';
pfx->usedElements--;
if (fe == fU) fe = fUP;
else if (fe == fV) fe = fVP;
else if (fe == fS) fe = fSP;
funStr = Functions[fe-FirstFunc].str;
}
}
if ( chQual == NO_CHAN_QUAL &&
(fe == fP || fe == fS || fe == fSP || fe == fU || fe == fUP || fe == fV || fe == fVP)
)
{
chQual = GetChannelQualifier (pfx, fe);
}
if (chQual == NO_CHAN_QUAL && (fe == fU || fe == fV || fe == fS)) {
/* Note: we don't allow "p.mean" etc. */
iaQual = GetImgAttrQualifier (pfx, fe);
}
if (IsQualifier (pfx) && chQual == NO_CHAN_QUAL && iaQual != aNull) {
chQual = GetChannelQualifier (pfx, fe);
}
if (coordQual && iaQual != aNull) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s', can't have qualifiers 'p' and image attribute '%s' at '%s'",
funStr, pfx->token, SetShortExp(pfx));
return MagickFalse;
}
if (!coordQual && chQual == NO_CHAN_QUAL && iaQual == aNull) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s', bad qualifier '%s' at '%s'",
funStr, pfx->token, SetShortExp(pfx));
return MagickFalse;
}
if (!coordQual && chQual == CompositePixelChannel && iaQual == aNull) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"For function", "'%s', bad composite qualifier '%s' at '%s'",
funStr, pfx->token, SetShortExp(pfx));
return MagickFalse;
}
if (chQual == HUE_CHANNEL || chQual == SAT_CHANNEL || chQual == LIGHT_CHANNEL) {
pfx->NeedHsl = MagickTrue;
if (iaQual >= FirstImgAttr && iaQual < aNull) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Can't have image attribute with HLS qualifier at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
}
}
if (fe==fWhile) {
pfx->Elements[ndx1].EleNdx = ndx2+1;
} else if (fe==fDo) {
pfx->Elements[ndx0].EleNdx = ndx1+1;
pfx->Elements[ndx1].EleNdx = ndx2+1;
} else if (fe==fFor) {
pfx->Elements[ndx2].EleNdx = ndx3;
} else if (fe==fIf) {
pfx->Elements[ndx1].EleNdx = ndx2 + 1;
pfx->Elements[ndx2].EleNdx = ndx3;
} else {
if (fe == fU && iaQual == aNull) {
ElementT * pel = &pfx->Elements[pfx->usedElements-1];
if (pel->type == etConstant && pel->val == 0.0) {
pfx->usedElements--;
fe = fU0;
}
}
(void) AddElement (pfx, (fxFltType) 0, fe);
if (fe == fP || fe == fU || fe == fU0 || fe == fUP ||
fe == fV || fe == fVP || fe == fS || fe == fSP)
{
ElementT * pel = &pfx->Elements[pfx->usedElements-1];
pel->IsRelative = (expChLimit == ']' ? MagickTrue : MagickFalse);
if (chQual >= 0) pel->ChannelQual = chQual;
if (iaQual != aNull && (fe == fU || fe == fV || fe == fS)) {
/* Note: we don't allow "p[2,3].mean" or "p.mean" etc. */
pel->ImgAttrQual = iaQual;
}
}
}
if (pExpStart && lenExp) {
ElementT * pel = &pfx->Elements[pfx->usedElements-1];
pel->pExpStart = pExpStart;
pel->lenExp = lenExp;
}
if (fe == fDebug)
pfx->ContainsDebug = MagickTrue;
return MagickTrue;
}
static MagickBooleanType IsStealth (int op)
{
return (op == fU0 || op == fUP || op == fSP || op == fVP ||
(op >= FirstCont && op <= rNull) ? MagickTrue : MagickFalse
);
}
static MagickBooleanType GetOperand (
FxInfo * pfx, MagickBooleanType * UserSymbol, MagickBooleanType * NewUserSymbol, int * UserSymNdx,
MagickBooleanType * needPopAll)
{
*NewUserSymbol = *UserSymbol = MagickFalse;
*UserSymNdx = NULL_ADDRESS;
SkipSpaces (pfx);
if (!*pfx->pex) return MagickFalse;
(void) GetToken (pfx);
if (pfx->lenToken==0) {
/* Try '(' or unary prefix
*/
OperatorE op = GetLeadingOp (pfx);
if (op==oOpenParen) {
char chLimit = '\0';
if (!PushOperatorStack (pfx, op)) return MagickFalse;
pfx->pex++;
if (!TranslateExpression (pfx, ")", &chLimit, needPopAll)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Empty expression in parentheses at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (chLimit != ')') {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"'(' but no ')' at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
/* Top of opr stack should be '('. */
if (!PopOprOpenParen (pfx, oOpenParen)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Bug: tos not '(' at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
return MagickTrue;
} else if (OprIsUnaryPrefix (op)) {
if (!PushOperatorStack (pfx, op)) return MagickFalse;
pfx->pex++;
SkipSpaces (pfx);
if (!*pfx->pex) return MagickFalse;
if (!GetOperand (pfx, UserSymbol, NewUserSymbol, UserSymNdx, needPopAll)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"After unary, bad operand at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (*NewUserSymbol) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"After unary, NewUserSymbol at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (*UserSymbol) {
(void) AddAddressingElement (pfx, rCopyFrom, *UserSymNdx);
*UserSymNdx = NULL_ADDRESS;
*UserSymbol = MagickFalse;
*NewUserSymbol = MagickFalse;
}
(void) GetToken (pfx);
return MagickTrue;
} else if (*pfx->pex == '#') {
fxFltType v0=0, v1=0, v2=0;
ssize_t lenToken = GetHexColour (pfx, &v0, &v1, &v2);
if (lenToken < 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Bad hex number at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
} else if (lenToken > 0) {
(void) AddColourElement (pfx, v0, v1, v2);
pfx->pex+=lenToken;
}
return MagickTrue;
}
/* Try a constant number.
*/
{
char * tailptr;
ssize_t lenOptArt;
fxFltType val = strtold (pfx->pex, &tailptr);
if (pfx->pex != tailptr) {
pfx->pex = tailptr;
if (*tailptr) {
/* Could have "prefix" K, Ki, M etc.
See https://en.wikipedia.org/wiki/Metric_prefix
and https://en.wikipedia.org/wiki/Binary_prefix
*/
double Pow = 0.0;
const char Prefices[] = "yzafpnum.kMGTPEZY";
const char * pSi = strchr (Prefices, *tailptr);
if (pSi && *pSi != '.') Pow = (pSi - Prefices) * 3 - 24;
else if (*tailptr == 'c') Pow = -2;
else if (*tailptr == 'h') Pow = 2;
else if (*tailptr == 'k') Pow = 3;
if (Pow != 0.0) {
if (*(++pfx->pex) == 'i') {
val *= pow (2.0, Pow/0.3);
pfx->pex++;
} else {
val *= pow (10.0, Pow);
}
}
}
(void) AddElement (pfx, val, oNull);
return MagickTrue;
}
val = (fxFltType) 0;
lenOptArt = GetProperty (pfx, &val);
if (lenOptArt < 0) return MagickFalse;
if (lenOptArt > 0) {
(void) AddElement (pfx, val, oNull);
pfx->pex += lenOptArt;
return MagickTrue;
}
}
} /* end of lenToken==0 */
if (pfx->lenToken > 0) {
/* Try a constant
*/
{
ConstantE ce;
for (ce = (ConstantE)0; ce < cNull; ce=(ConstantE) (ce+1)) {
const char * ceStr = Constants[ce].str;
if (LocaleCompare (ceStr, pfx->token)==0) {
break;
}
}
if (ce != cNull) {
(void) AddElement (pfx, Constants[ce].val, oNull);
pfx->pex += pfx->lenToken;
return MagickTrue;
}
}
/* Try a function
*/
{
FunctionE fe;
for (fe = FirstFunc; fe < fNull; fe=(FunctionE) (fe+1)) {
const char * feStr = Functions[fe-FirstFunc].str;
if (LocaleCompare (feStr, pfx->token)==0) {
break;
}
}
if (fe == fV && pfx->ImgListLen < 2) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Symbol 'v' but fewer than two images at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (IsStealth (fe)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Function", "'%s' not permitted at '%s'",
pfx->token, SetShortExp(pfx));
}
if (fe == fDo || fe == fFor || fe == fIf || fe == fWhile) {
*needPopAll = MagickTrue;
}
if (fe != fNull) return (GetFunction (pfx, fe));
}
/* Try image attribute
*/
{
ImgAttrE ia = GetImgAttrToken (pfx);
if (ia != aNull) {
fxFltType val = 0;
(void) AddElement (pfx, val, ia);
if (ImgAttrs[ia-FirstImgAttr].NeedStats==1) {
if (IsQualifier (pfx)) {
PixelChannel chQual = GetChannelQualifier (pfx, ia);
ElementT * pel;
if (chQual == NO_CHAN_QUAL) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Bad channel qualifier at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
/* Adjust the element */
pel = &pfx->Elements[pfx->usedElements-1];
pel->ChannelQual = chQual;
}
}
return MagickTrue;
}
}
/* Try symbol
*/
{
SymbolE se;
for (se = FirstSym; se < sNull; se=(SymbolE) (se+1)) {
const char * seStr = Symbols[se-FirstSym].str;
if (LocaleCompare (seStr, pfx->token)==0) {
break;
}
}
if (se != sNull) {
fxFltType val = 0;
(void) AddElement (pfx, val, se);
pfx->pex += pfx->lenToken;
if (se==sHue || se==sSaturation || se==sLightness) pfx->NeedHsl = MagickTrue;
return MagickTrue;
}
}
/* Try constant colour.
*/
{
fxFltType v0, v1, v2;
ssize_t ColLen = GetConstantColour (pfx, &v0, &v1, &v2);
if (ColLen < 0) return MagickFalse;
if (ColLen > 0) {
(void) AddColourElement (pfx, v0, v1, v2);
pfx->pex+=ColLen;
return MagickTrue;
}
}
/* Try image artifact.
*/
{
const char *artifact;
artifact = GetImageArtifact (pfx->image, pfx->token);
if (artifact != (const char *) NULL) {
char * tailptr;
fxFltType val = strtold (artifact, &tailptr);
if (pfx->token == tailptr) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Artifact", "'%s' has value '%s', not a number, at '%s'",
pfx->token, artifact, SetShortExp(pfx));
return MagickFalse;
}
(void) AddElement (pfx, val, oNull);
pfx->pex+=pfx->lenToken;
return MagickTrue;
}
}
/* Try user symbols. If it is, don't AddElement yet.
*/
if (TokenMaybeUserSymbol (pfx)) {
*UserSymbol = MagickTrue;
*UserSymNdx = FindUserSymbol (pfx, pfx->token);
if (*UserSymNdx == NULL_ADDRESS) {
*UserSymNdx = AddUserSymbol (pfx, pfx->pex, pfx->lenToken);
*NewUserSymbol = MagickTrue;
} else {
}
pfx->pex += pfx->lenToken;
return MagickTrue;
}
}
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Expected operand at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
static MagickBooleanType inline IsRealOperator (OperatorE op)
{
return (op < oOpenParen || op > oCloseBrace) ? MagickTrue : MagickFalse;
}
static MagickBooleanType inline ProcessTernaryOpr (FxInfo * pfx, TernaryT * ptern)
/* Ternary operator "... ? ... : ..."
returns false iff we have exception
*/
{
if (pfx->usedOprStack == 0)
return MagickFalse;
if (pfx->OperatorStack[pfx->usedOprStack-1] == oQuery) {
if (ptern->addrQuery != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Already have '?' in sub-expression at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (ptern->addrColon != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Already have ':' in sub-expression at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
pfx->usedOprStack--;
ptern->addrQuery = pfx->usedElements;
(void) AddAddressingElement (pfx, rIfZeroGoto, NULL_ADDRESS);
/* address will be one after the Colon address. */
}
else if (pfx->OperatorStack[pfx->usedOprStack-1] == oColon) {
if (ptern->addrQuery == NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Need '?' in sub-expression at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (ptern->addrColon != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Already have ':' in sub-expression at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
pfx->usedOprStack--;
ptern->addrColon = pfx->usedElements;
pfx->Elements[pfx->usedElements-1].DoPush = MagickTrue;
(void) AddAddressingElement (pfx, rGoto, NULL_ADDRESS);
/* address will be after the subexpression */
}
return MagickTrue;
}
static MagickBooleanType GetOperator (
FxInfo * pfx,
MagickBooleanType * Assign, MagickBooleanType * Update, MagickBooleanType * IncrDecr)
{
OperatorE op;
size_t len = 0;
MagickBooleanType DoneIt = MagickFalse;
SkipSpaces (pfx);
for (op = (OperatorE)0; op != oNull; op=(OperatorE) (op+1)) {
const char * opStr = Operators[op].str;
len = strlen(opStr);
if (LocaleNCompare (opStr, pfx->pex, len)==0) {
break;
}
}
if (!IsRealOperator (op)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Not a real operator at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (op==oNull) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Expected operator at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
*Assign = (op==oAssign) ? MagickTrue : MagickFalse;
*Update = OprInPlace (op);
*IncrDecr = (op == oPlusPlus || op == oSubSub) ? MagickTrue : MagickFalse;
/* while top of OperatorStack is not empty and is not open-parens or assign,
and top of OperatorStack is higher precedence than new op,
then move top of OperatorStack to Element list.
*/
while (pfx->usedOprStack > 0) {
OperatorE top = pfx->OperatorStack[pfx->usedOprStack-1];
int precTop, precNew;
if (top == oOpenParen || top == oAssign || OprInPlace (top)) break;
precTop = Operators[top].precedence;
precNew = Operators[op].precedence;
/* Assume left associativity.
If right assoc, this would be "<=".
*/
if (precTop < precNew) break;
(void) AddElement (pfx, (fxFltType) 0, top);
pfx->usedOprStack--;
}
/* If new op is close paren, and stack top is open paren,
remove stack top.
*/
if (op==oCloseParen) {
if (pfx->usedOprStack == 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Found ')' but nothing on stack at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (pfx->OperatorStack[pfx->usedOprStack-1] != oOpenParen) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Found ')' but no '(' on stack at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
pfx->usedOprStack--;
DoneIt = MagickTrue;
}
if (!DoneIt) {
if (!PushOperatorStack (pfx, op)) return MagickFalse;
}
pfx->pex += len;
return MagickTrue;
}
static MagickBooleanType ResolveTernaryAddresses (FxInfo * pfx, TernaryT * ptern)
{
if (ptern->addrQuery == NULL_ADDRESS && ptern->addrColon == NULL_ADDRESS)
return MagickTrue;
if (ptern->addrQuery != NULL_ADDRESS && ptern->addrColon != NULL_ADDRESS) {
pfx->Elements[ptern->addrQuery].EleNdx = ptern->addrColon + 1;
pfx->Elements[ptern->addrColon].EleNdx = pfx->usedElements;
ptern->addrQuery = NULL_ADDRESS;
ptern->addrColon = NULL_ADDRESS;
} else if (ptern->addrQuery != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"'?' with no corresponding ':'", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
return MagickFalse;
} else if (ptern->addrColon != NULL_ADDRESS) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"':' with no corresponding '?'", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
return MagickFalse;
}
return MagickTrue;
}
static MagickBooleanType TranslateExpression (
FxInfo * pfx, const char * strLimit, char * chLimit, MagickBooleanType * needPopAll)
{
/* There should be only one New per expression (oAssign), but can be many Old.
*/
MagickBooleanType UserSymbol, NewUserSymbol;
int UserSymNdx0, UserSymNdx1;
MagickBooleanType
Assign = MagickFalse,
Update = MagickFalse,
IncrDecr = MagickFalse;
int StartEleNdx;
TernaryT ternary;
ternary.addrQuery = NULL_ADDRESS;
ternary.addrColon = NULL_ADDRESS;
pfx->teDepth++;
*chLimit = '\0';
StartEleNdx = pfx->usedElements-1;
if (StartEleNdx < 0) StartEleNdx = 0;
SkipSpaces (pfx);
if (!*pfx->pex) {
pfx->teDepth--;
return MagickFalse;
}
if (strchr(strLimit,*pfx->pex)!=NULL) {
*chLimit = *pfx->pex;
pfx->pex++;
pfx->teDepth--;
return MagickFalse;
}
if (!GetOperand (pfx, &UserSymbol, &NewUserSymbol, &UserSymNdx0, needPopAll)) return MagickFalse;
SkipSpaces (pfx);
/* Loop through Operator, Operand, Operator, Operand, ...
*/
while (*pfx->pex && (!*strLimit || (strchr(strLimit,*pfx->pex)==NULL))) {
if (!GetOperator (pfx, &Assign, &Update, &IncrDecr)) return MagickFalse;
SkipSpaces (pfx);
if (NewUserSymbol && !Assign) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Expected assignment after new UserSymbol", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
return MagickFalse;
}
if (!UserSymbol && Assign) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Attempted assignment to non-UserSymbol", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
return MagickFalse;
}
if (!UserSymbol && Update) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Attempted update to non-UserSymbol", "'%s' at '%s'",
pfx->token, SetShortExp(pfx));
return MagickFalse;
}
if (UserSymbol && (Assign || Update) && !IncrDecr) {
if (!TranslateExpression (pfx, strLimit, chLimit, needPopAll)) return MagickFalse;
if (!*pfx->pex) break;
if (!*strLimit) break;
if (strchr(strLimit,*chLimit)!=NULL) break;
}
if (UserSymbol && !Assign && !Update && UserSymNdx0 != NULL_ADDRESS) {
ElementT * pel;
(void) AddAddressingElement (pfx, rCopyFrom, UserSymNdx0);
UserSymNdx0 = NULL_ADDRESS;
pel = &pfx->Elements[pfx->usedElements-1];
pel->DoPush = MagickTrue;
}
if (UserSymbol) {
while (TopOprIsUnaryPrefix (pfx)) {
OperatorE op = pfx->OperatorStack[pfx->usedOprStack-1];
(void) AddElement (pfx, (fxFltType) 0, op);
pfx->usedOprStack--;
}
}
if (!ProcessTernaryOpr (pfx, &ternary)) return MagickFalse;
if (ternary.addrColon != NULL_ADDRESS) {
if (!TranslateExpression (pfx, ",);", chLimit, needPopAll)) return MagickFalse;
break;
}
UserSymbol = NewUserSymbol = MagickFalse;
if ( (!*pfx->pex) || (*strLimit && (strchr(strLimit,*pfx->pex)!=NULL) ) )
{
if (IncrDecr) break;
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Expected operand after operator", "at '%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (IncrDecr) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"'++' and '--' must be the final operators in an expression at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
if (!GetOperand (pfx, &UserSymbol, &NewUserSymbol, &UserSymNdx1, needPopAll)) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Expected operand at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
SkipSpaces (pfx);
if (NewUserSymbol && !Assign) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"NewUserSymbol", "'%s' after non-assignment operator at '%s'",
pfx->token, SetShortExp(pfx));
return MagickFalse;
}
if (UserSymbol && !NewUserSymbol) {
(void) AddAddressingElement (pfx, rCopyFrom, UserSymNdx1);
UserSymNdx1 = NULL_ADDRESS;
}
UserSymNdx0 = UserSymNdx1;
}
if (UserSymbol && !Assign && !Update && UserSymNdx0 != NULL_ADDRESS) {
ElementT * pel;
if (NewUserSymbol) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"NewUserSymbol", "'%s' needs assignment operator at '%s'",
pfx->token, SetShortExp(pfx));
return MagickFalse;
}
(void) AddAddressingElement (pfx, rCopyFrom, UserSymNdx0);
pel = &pfx->Elements[pfx->usedElements-1];
pel->DoPush = MagickTrue;
}
if (*pfx->pex && !*chLimit && (strchr(strLimit,*pfx->pex)!=NULL)) {
*chLimit = *pfx->pex;
pfx->pex++;
}
while (pfx->usedOprStack) {
OperatorE op = pfx->OperatorStack[pfx->usedOprStack-1];
if (op == oOpenParen || op == oOpenBracket || op == oOpenBrace) {
break;
}
if ( (op==oAssign && !Assign) || (OprInPlace(op) && !Update) ) {
break;
}
pfx->usedOprStack--;
(void) AddElement (pfx, (fxFltType) 0, op);
if (op == oAssign) {
if (UserSymNdx0 < 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Assignment to unknown user symbol at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
/* Adjust last element, by deletion and add.
*/
pfx->usedElements--;
(void) AddAddressingElement (pfx, rCopyTo, UserSymNdx0);
break;
} else if (OprInPlace (op)) {
if (UserSymNdx0 < 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Operator-in-place to unknown user symbol at", "'%s'",
SetShortExp(pfx));
return MagickFalse;
}
/* Modify latest element.
*/
pfx->Elements[pfx->usedElements-1].EleNdx = UserSymNdx0;
break;
}
}
if (ternary.addrQuery != NULL_ADDRESS) *needPopAll = MagickTrue;
(void) ResolveTernaryAddresses (pfx, &ternary);
pfx->teDepth--;
if (!pfx->teDepth && *needPopAll) {
(void) AddAddressingElement (pfx, rZerStk, NULL_ADDRESS);
*needPopAll = MagickFalse;
}
if (pfx->exception->severity != UndefinedException)
return MagickFalse;
return MagickTrue;
}
static MagickBooleanType TranslateStatement (FxInfo * pfx, char * strLimit, char * chLimit)
{
MagickBooleanType NeedPopAll = MagickFalse;
SkipSpaces (pfx);
if (!*pfx->pex) return MagickFalse;
if (!TranslateExpression (pfx, strLimit, chLimit, &NeedPopAll)) {
return MagickFalse;
}
if (pfx->usedElements && *chLimit==';') {
/* FIXME: not necessarily the last element,
but the last _executed_ element, eg "goto" in a "for()".,
Pending a fix, we will use rZerStk.
*/
ElementT * pel = &pfx->Elements[pfx->usedElements-1];
if (pel->DoPush) pel->DoPush = MagickFalse;
}
return MagickTrue;
}
static MagickBooleanType TranslateStatementList (FxInfo * pfx, const char * strLimit, char * chLimit)
{
#define MAX_SLIMIT 10
char sLimits[MAX_SLIMIT];
SkipSpaces (pfx);
if (!*pfx->pex) return MagickFalse;
(void) CopyMagickString (sLimits, strLimit, MAX_SLIMIT-1);
if (strchr(strLimit,';')==NULL)
(void) ConcatenateMagickString (sLimits, ";", MAX_SLIMIT);
for (;;) {
if (!TranslateStatement (pfx, sLimits, chLimit)) return MagickFalse;
if (!*pfx->pex) break;
if (*chLimit != ';') {
break;
}
}
if (pfx->exception->severity != UndefinedException)
return MagickFalse;
return MagickTrue;
}
/*--------------------------------------------------------------------
Run-time
*/
static ChannelStatistics *CollectOneImgStats (FxInfo * pfx, Image * img)
{
int ch;
ChannelStatistics * cs = GetImageStatistics (img, pfx->exception);
/* Use RelinquishMagickMemory() somewhere. */
if (cs == (ChannelStatistics *) NULL)
return((ChannelStatistics *) NULL);
for (ch=0; ch <= (int) MaxPixelChannels; ch++) {
cs[ch].mean *= QuantumScale;
cs[ch].median *= QuantumScale;
cs[ch].maxima *= QuantumScale;
cs[ch].minima *= QuantumScale;
cs[ch].standard_deviation *= QuantumScale;
cs[ch].kurtosis *= QuantumScale;
cs[ch].skewness *= QuantumScale;
cs[ch].entropy *= QuantumScale;
}
return cs;
}
static MagickBooleanType CollectStatistics (FxInfo * pfx)
{
Image * img = GetFirstImageInList (pfx->image);
size_t imgNum=0;
pfx->statistics = (ChannelStatistics**) AcquireMagickMemory (pfx->ImgListLen * sizeof (ChannelStatistics *));
if (!pfx->statistics) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"Statistics", "%lu",
(unsigned long) pfx->ImgListLen);
return MagickFalse;
}
for (;;) {
pfx->statistics[imgNum] = CollectOneImgStats (pfx, img);
if (++imgNum == pfx->ImgListLen) break;
img = GetNextImageInList (img);
assert (img != (Image *) NULL);
}
pfx->GotStats = MagickTrue;
return MagickTrue;
}
static MagickBooleanType inline PushVal (FxInfo * pfx, fxRtT * pfxrt, fxFltType val, int addr)
{
if (pfxrt->usedValStack >=pfxrt->numValStack) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"ValStack overflow at addr=", "%i",
addr);
return MagickFalse;
}
pfxrt->ValStack[pfxrt->usedValStack++] = val;
return MagickTrue;
}
static inline fxFltType PopVal (FxInfo * pfx, fxRtT * pfxrt, int addr)
{
if (pfxrt->usedValStack <= 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"ValStack underflow at addr=", "%i",
addr);
return (fxFltType) 0;
}
return pfxrt->ValStack[--pfxrt->usedValStack];
}
static inline fxFltType ImageStat (
FxInfo * pfx, ssize_t ImgNum, PixelChannel channel, ImgAttrE ia)
{
ChannelStatistics * cs = NULL;
fxFltType ret = 0;
MagickBooleanType NeedRelinq = MagickFalse;
assert (channel >= 0 && channel <= MaxPixelChannels);
if (pfx->GotStats) {
cs = pfx->statistics[ImgNum];
} else if (pfx->NeedStats) {
/* If we need more than one statistic per pixel, this is inefficient. */
cs = CollectOneImgStats (pfx, pfx->Images[ImgNum]);
NeedRelinq = MagickTrue;
}
switch (ia) {
case aDepth:
ret = (fxFltType) GetImageDepth (pfx->Images[ImgNum], pfx->exception);
break;
case aExtent:
ret = (fxFltType) GetBlobSize (pfx->image);
break;
case aKurtosis:
if (cs != (ChannelStatistics *) NULL)
ret = cs[channel].kurtosis;
break;
case aMaxima:
if (cs != (ChannelStatistics *) NULL)
ret = cs[channel].maxima;
break;
case aMean:
if (cs != (ChannelStatistics *) NULL)
ret = cs[channel].mean;
break;
case aMedian:
if (cs != (ChannelStatistics *) NULL)
ret = cs[channel].median;
break;
case aMinima:
if (cs != (ChannelStatistics *) NULL)
ret = cs[channel].minima;
break;
case aPage:
/* Do nothing */
break;
case aPageX:
ret = (fxFltType) pfx->Images[ImgNum]->page.x;
break;
case aPageY:
ret = (fxFltType) pfx->Images[ImgNum]->page.y;
break;
case aPageWid:
ret = (fxFltType) pfx->Images[ImgNum]->page.width;
break;
case aPageHt:
ret = (fxFltType) pfx->Images[ImgNum]->page.height;
break;
case aPrintsize:
/* Do nothing */
break;
case aPrintsizeX:
ret = (fxFltType) PerceptibleReciprocal (pfx->Images[ImgNum]->resolution.x)
* pfx->Images[ImgNum]->columns;
break;
case aPrintsizeY:
ret = (fxFltType) PerceptibleReciprocal (pfx->Images[ImgNum]->resolution.y)
* pfx->Images[ImgNum]->rows;
break;
case aQuality:
ret = (fxFltType) pfx->Images[ImgNum]->quality;
break;
case aRes:
/* Do nothing */
break;
case aResX:
ret = pfx->Images[ImgNum]->resolution.x;
break;
case aResY:
ret = pfx->Images[ImgNum]->resolution.y;
break;
case aSkewness:
if (cs != (ChannelStatistics *) NULL)
ret = cs[channel].skewness;
break;
case aStdDev:
if (cs != (ChannelStatistics *) NULL)
ret = cs[channel].standard_deviation;
break;
case aH:
ret = (fxFltType) pfx->Images[ImgNum]->rows;
break;
case aN:
ret = (fxFltType) pfx->ImgListLen;
break;
case aT: /* image index in list */
ret = (fxFltType) ImgNum;
break;
case aW:
ret = (fxFltType) pfx->Images[ImgNum]->columns;
break;
case aZ:
ret = (fxFltType) GetImageDepth (pfx->Images[ImgNum], pfx->exception);
break;
default:
(void) ThrowMagickException (pfx->exception,GetMagickModule(),OptionError,
"Unknown ia=","%i",ia);
}
if (NeedRelinq) cs = (ChannelStatistics *)RelinquishMagickMemory (cs);
return ret;
}
static fxFltType inline FxGcd (fxFltType x, fxFltType y, const size_t depth)
{
#define FxMaxFunctionDepth 200
if (x < y)
return (FxGcd (y, x, depth+1));
if ((fabs((double) y) < 0.001) || (depth >= FxMaxFunctionDepth))
return (x);
return (FxGcd (y, x-y*floor((double) (x/y)), depth+1));
}
static ssize_t inline ChkImgNum (FxInfo * pfx, fxFltType f)
/* Returns -1 if f is too large. */
{
ssize_t i = (ssize_t) floor ((double) f + 0.5);
if (i < 0) i += pfx->ImgListLen;
if (i < 0 || i >= (ssize_t)pfx->ImgListLen) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"ImgNum", "%lu bad for ImgListLen %lu",
(unsigned long) i, (unsigned long) pfx->ImgListLen);
i = -1;
}
return i;
}
#define WHICH_ATTR_CHAN \
(pel->ChannelQual == NO_CHAN_QUAL) ? CompositePixelChannel : \
(pel->ChannelQual == THIS_CHANNEL) ? channel : pel->ChannelQual
#define WHICH_NON_ATTR_CHAN \
(pel->ChannelQual == NO_CHAN_QUAL || \
pel->ChannelQual == THIS_CHANNEL || \
pel->ChannelQual == CompositePixelChannel \
) ? (channel == CompositePixelChannel ? RedPixelChannel: channel) \
: pel->ChannelQual
static fxFltType GetHslFlt (FxInfo * pfx, ssize_t ImgNum, const fxFltType fx, const fxFltType fy,
int channel)
{
Image * img = pfx->Images[ImgNum];
double red, green, blue;
double hue=0, saturation=0, lightness=0;
MagickBooleanType okay = MagickTrue;
if(!InterpolatePixelChannel (img, pfx->Imgs[ImgNum].View, RedPixelChannel, img->interpolate,
(double) fx, (double) fy, &red, pfx->exception)) okay = MagickFalse;
if(!InterpolatePixelChannel (img, pfx->Imgs[ImgNum].View, GreenPixelChannel, img->interpolate,
(double) fx, (double) fy, &green, pfx->exception)) okay = MagickFalse;
if(!InterpolatePixelChannel (img, pfx->Imgs[ImgNum].View, BluePixelChannel, img->interpolate,
(double) fx, (double) fy, &blue, pfx->exception)) okay = MagickFalse;
if (!okay)
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"GetHslFlt failure", "%lu %g,%g %i", (unsigned long) ImgNum,
(double) fx, (double) fy, channel);
ConvertRGBToHSL (
red, green, blue,
&hue, &saturation, &lightness);
if (channel == HUE_CHANNEL) return hue;
if (channel == SAT_CHANNEL) return saturation;
if (channel == LIGHT_CHANNEL) return lightness;
return 0.0;
}
static fxFltType GetHslInt (FxInfo * pfx, ssize_t ImgNum, const ssize_t imgx, const ssize_t imgy, int channel)
{
Image * img = pfx->Images[ImgNum];
double hue=0, saturation=0, lightness=0;
const Quantum * p = GetCacheViewVirtualPixels (pfx->Imgs[ImgNum].View, imgx, imgy, 1, 1, pfx->exception);
if (p == (const Quantum *) NULL)
{
(void) ThrowMagickException (pfx->exception,GetMagickModule(),
OptionError,"GetHslInt failure","%lu %li,%li %i",(unsigned long) ImgNum,
(long) imgx,(long) imgy,channel);
return(0.0);
}
ConvertRGBToHSL (
GetPixelRed (img, p), GetPixelGreen (img, p), GetPixelBlue (img, p),
&hue, &saturation, &lightness);
if (channel == HUE_CHANNEL) return hue;
if (channel == SAT_CHANNEL) return saturation;
if (channel == LIGHT_CHANNEL) return lightness;
return 0.0;
}
static fxFltType inline GetIntensity (FxInfo * pfx, ssize_t ImgNum, const fxFltType fx, const fxFltType fy)
{
Quantum
quantum_pixel[MaxPixelChannels];
PixelInfo
pixelinf;
Image * img = pfx->Images[ImgNum];
(void) GetPixelInfo (img, &pixelinf);
if (!InterpolatePixelInfo (img, pfx->Imgs[pfx->ImgNum].View, img->interpolate,
(double) fx, (double) fy, &pixelinf, pfx->exception))
{
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"GetIntensity failure", "%lu %g,%g", (unsigned long) ImgNum,
(double) fx, (double) fy);
}
SetPixelViaPixelInfo (img, &pixelinf, quantum_pixel);
return QuantumScale * GetPixelIntensity (img, quantum_pixel);
}
static MagickBooleanType ExecuteRPN (FxInfo * pfx, fxRtT * pfxrt, fxFltType *result,
const PixelChannel channel, const ssize_t imgx, const ssize_t imgy)
{
const Quantum * p = pfxrt->thisPixel;
fxFltType regA=0, regB=0, regC=0, regD=0, regE=0;
Image * img = pfx->image;
ChannelStatistics * cs = NULL;
MagickBooleanType NeedRelinq = MagickFalse;
double hue=0, saturation=0, lightness=0;
int i;
/* For -fx, this sets p to ImgNum 0.
for %[fx:...], this sets p to the currrent image.
Similarly img.
*/
if (!p) p = GetCacheViewVirtualPixels (
pfx->Imgs[pfx->ImgNum].View, imgx, imgy, 1, 1, pfx->exception);
if (p == (const Quantum *) NULL)
{
(void) ThrowMagickException (pfx->exception,GetMagickModule(),
OptionError,"GetHslInt failure","%lu %li,%li",(unsigned long)
pfx->ImgNum,(long) imgx,(long) imgy);
return(MagickFalse);
}
if (pfx->GotStats) {
cs = pfx->statistics[pfx->ImgNum];
} else if (pfx->NeedStats) {
cs = CollectOneImgStats (pfx, pfx->Images[pfx->ImgNum]);
NeedRelinq = MagickTrue;
}
/* Folllowing is only for expressions like "saturation", with no image specifier.
*/
if (pfx->NeedHsl) {
ConvertRGBToHSL (
GetPixelRed (img, p), GetPixelGreen (img, p), GetPixelBlue (img, p),
&hue, &saturation, &lightness);
}
for (i=0; i < pfx->usedElements; i++) {
ElementT *pel = &pfx->Elements[i];
switch (pel->nArgs) {
case 0:
break;
case 1:
regA = PopVal (pfx, pfxrt, i);
break;
case 2:
regB = PopVal (pfx, pfxrt, i);
regA = PopVal (pfx, pfxrt, i);
break;
case 3:
regC = PopVal (pfx, pfxrt, i);
regB = PopVal (pfx, pfxrt, i);
regA = PopVal (pfx, pfxrt, i);
break;
case 4:
regD = PopVal (pfx, pfxrt, i);
regC = PopVal (pfx, pfxrt, i);
regB = PopVal (pfx, pfxrt, i);
regA = PopVal (pfx, pfxrt, i);
break;
case 5:
regE = PopVal (pfx, pfxrt, i);
regD = PopVal (pfx, pfxrt, i);
regC = PopVal (pfx, pfxrt, i);
regB = PopVal (pfx, pfxrt, i);
regA = PopVal (pfx, pfxrt, i);
break;
default:
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Too many args:", "%i", pel->nArgs);
break;
}
switch (pel->oprNum) {
case oAddEq:
regA = (pfxrt->UserSymVals[pel->EleNdx] += regA);
break;
case oSubtractEq:
regA = (pfxrt->UserSymVals[pel->EleNdx] -= regA);
break;
case oMultiplyEq:
regA = (pfxrt->UserSymVals[pel->EleNdx] *= regA);
break;
case oDivideEq:
regA = (pfxrt->UserSymVals[pel->EleNdx] *= PerceptibleReciprocal((double)regA));
break;
case oPlusPlus:
regA = pfxrt->UserSymVals[pel->EleNdx]++;
break;
case oSubSub:
regA = pfxrt->UserSymVals[pel->EleNdx]--;
break;
case oAdd:
regA += regB;
break;
case oSubtract:
regA -= regB;
break;
case oMultiply:
regA *= regB;
break;
case oDivide:
regA *= PerceptibleReciprocal((double)regB);
break;
case oModulus:
regA = fmod ((double) regA, fabs(floor((double) regB+0.5)));
break;
case oUnaryPlus:
/* Do nothing. */
break;
case oUnaryMinus:
regA = -regA;
break;
case oLshift:
if ((size_t) (regB+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException ( pfx->exception, GetMagickModule(),
OptionError, "undefined shift", "%g", (double) regB);
regA = (fxFltType) 0.0;
break;
}
regA = (fxFltType) ((size_t)(regA+0.5) << (size_t)(regB+0.5));
break;
case oRshift:
if ((size_t) (regB+0.5) >= (8*sizeof(size_t)))
{
(void) ThrowMagickException ( pfx->exception, GetMagickModule(),
OptionError, "undefined shift", "%g", (double) regB);
regA = (fxFltType) 0.0;
break;
}
regA = (fxFltType) ((size_t)(regA+0.5) >> (size_t)(regB+0.5));
break;
case oEq:
regA = fabs((double) (regA-regB)) < MagickEpsilon ? 1.0 : 0.0;
break;
case oNotEq:
regA = fabs((double) (regA-regB)) >= MagickEpsilon ? 1.0 : 0.0;
break;
case oLtEq:
regA = (regA <= regB) ? 1.0 : 0.0;
break;
case oGtEq:
regA = (regA >= regB) ? 1.0 : 0.0;
break;
case oLt:
regA = (regA < regB) ? 1.0 : 0.0;
break;
case oGt:
regA = (regA > regB) ? 1.0 : 0.0;
break;
case oLogAnd:
regA = (regA<=0) ? 0.0 : (regB > 0) ? 1.0 : 0.0;
break;
case oLogOr:
regA = (regA>0) ? 1.0 : (regB > 0.0) ? 1.0 : 0.0;
break;
case oLogNot:
regA = (regA==0) ? 1.0 : 0.0;
break;
case oBitAnd:
regA = (fxFltType) ((size_t)(regA+0.5) & (size_t)(regB+0.5));
break;
case oBitOr:
regA = (fxFltType) ((size_t)(regA+0.5) | (size_t)(regB+0.5));
break;
case oBitNot:
/* Old fx doesn't add 0.5. */
regA = (fxFltType) (~(size_t)(regA+0.5));
break;
case oPow:
regA = pow ((double) regA, (double) regB);
break;
case oQuery:
case oColon:
break;
case oOpenParen:
case oCloseParen:
case oOpenBracket:
case oCloseBracket:
case oOpenBrace:
case oCloseBrace:
break;
case oAssign:
pel->val = regA;
break;
case oNull: {
if (pel->type == etColourConstant) {
switch (channel) {
default:
case 0:
regA = pel->val;
break;
case 1:
regA = pel->val1;
break;
case 2:
regA = pel->val2;
break;
}
} else {
regA = pel->val;
}
break;
}
case fAbs:
regA = fabs ((double) regA);
break;
#if defined(MAGICKCORE_HAVE_ACOSH)
case fAcosh:
regA = acosh ((double) regA);
break;
#endif
case fAcos:
regA = acos ((double) regA);
break;
#if defined(MAGICKCORE_HAVE_J1)
case fAiry:
if (regA==0) regA = 1.0;
else {
fxFltType gamma = 2.0 * j1 ((MagickPI*regA)) / (MagickPI*regA);
regA = gamma * gamma;
}
break;
#endif
case fAlt:
regA = (fxFltType) (((ssize_t) regA) & 0x01 ? -1.0 : 1.0);
break;
#if defined(MAGICKCORE_HAVE_ASINH)
case fAsinh:
regA = asinh ((double) regA);
break;
#endif
case fAsin:
regA = asin ((double) regA);
break;
#if defined(MAGICKCORE_HAVE_ATANH)
case fAtanh:
regA = atanh ((double) regA);
break;
#endif
case fAtan2:
regA = atan2 ((double) regA, (double) regB);
break;
case fAtan:
regA = atan ((double) regA);
break;
case fCeil:
regA = ceil ((double) regA);
break;
case fChannel:
switch (channel) {
case 0: break;
case 1: regA = regB; break;
case 2: regA = regC; break;
case 3: regA = regD; break;
case 4: regA = regE; break;
default: regA = 0.0;
}
break;
case fClamp:
if (regA < 0) regA = 0.0;
else if (regA > 1.0) regA = 1.0;
break;
case fCosh:
regA = cosh ((double) regA);
break;
case fCos:
regA = cos ((double) regA);
break;
case fDebug:
/* FIXME: debug() should give channel name. */
(void) fprintf (stderr, "%s[%g,%g].[%i]: %s=%.*g\n",
img->filename, (double) imgx, (double) imgy,
channel, SetPtrShortExp (pfx, pel->pExpStart, (size_t) (pel->lenExp+1)),
pfx->precision, (double) regA);
break;
case fDrc:
regA = regA / (regB*(regA-1.0) + 1.0);
break;
#if defined(MAGICKCORE_HAVE_ERF)
case fErf:
regA = erf ((double) regA);
break;
#endif
case fExp:
regA = exp ((double) regA);
break;
case fFloor:
regA = floor ((double) regA);
break;
case fGauss:
regA = exp((double) (-regA*regA/2.0))/sqrt(2.0*MagickPI);
break;
case fGcd:
if (!IsNaN(regA))
regA = FxGcd (regA, regB, 0);
break;
case fHypot:
regA = hypot ((double) regA, (double) regB);
break;
case fInt:
regA = floor ((double) regA);
break;
case fIsnan:
regA = (fxFltType) (!!IsNaN (regA));
break;
#if defined(MAGICKCORE_HAVE_J0)
case fJ0:
regA = j0 ((double) regA);
break;
#endif
#if defined(MAGICKCORE_HAVE_J1)
case fJ1:
regA = j1 ((double) regA);
break;
#endif
#if defined(MAGICKCORE_HAVE_J1)
case fJinc:
if (regA==0) regA = 1.0;
else regA = 2.0 * j1 ((MagickPI*regA))/(MagickPI*regA);
break;
#endif
case fLn:
regA = log ((double) regA);
break;
case fLogtwo:
regA = log10((double) regA) / log10(2.0);
break;
case fLog:
regA = log10 ((double) regA);
break;
case fMax:
regA = (regA > regB) ? regA : regB;
break;
case fMin:
regA = (regA < regB) ? regA : regB;
break;
case fMod:
regA = regA - floor((double) (regA*PerceptibleReciprocal((double) regB)))*regB;
break;
case fNot:
regA = (fxFltType) (regA < MagickEpsilon);
break;
case fPow:
regA = pow ((double) regA, (double) regB);
break;
case fRand: {
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ExecuteRPN)
#endif
regA = GetPseudoRandomValue (pfxrt->random_info);
break;
}
case fRound:
regA = floor ((double) regA + 0.5);
break;
case fSign:
regA = (regA < 0) ? -1.0 : 1.0;
break;
case fSinc:
regA = sin ((double) (MagickPI*regA)) / (MagickPI*regA);
break;
case fSinh:
regA = sinh ((double) regA);
break;
case fSin:
regA = sin ((double) regA);
break;
case fSqrt:
regA = sqrt ((double) regA);
break;
case fSquish:
regA = 1.0 / (1.0 + exp ((double) -regA));
break;
case fTanh:
regA = tanh ((double) regA);
break;
case fTan:
regA = tan ((double) regA);
break;
case fTrunc:
if (regA >= 0) regA = floor ((double) regA);
else regA = ceil ((double) regA);
break;
case fDo:
case fFor:
case fIf:
case fWhile:
break;
case fU: {
/* Note: 1 value is available, index into image list.
May have ImgAttr qualifier or channel qualifier or both.
*/
ssize_t ImgNum = ChkImgNum (pfx, regA);
if (ImgNum < 0) break;
regA = (fxFltType) 0;
if (ImgNum == 0) {
Image * pimg = pfx->Images[0];
int pech = (int)pel->ChannelQual;
if (pel->ImgAttrQual == aNull) {
if (pech < 0) {
if (pech == NO_CHAN_QUAL || pech == THIS_CHANNEL) {
if (pfx->ImgNum==0) {
regA = QuantumScale * p[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
} else {
const Quantum * pv = GetCacheViewVirtualPixels (
pfx->Imgs[0].View, imgx, imgy, 1,1, pfx->exception);
if (!pv) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fU can't get cache", "%lu", (unsigned long) ImgNum);
break;
}
regA = QuantumScale * pv[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
}
} else if (pech == HUE_CHANNEL || pech == SAT_CHANNEL ||
pech == LIGHT_CHANNEL) {
regA = GetHslInt (pfx, ImgNum, imgx, imgy, pech);
break;
} else if (pech == INTENSITY_CHANNEL) {
regA = GetIntensity (pfx, 0, (double) imgx, (double) imgy);
break;
}
} else {
if (pfx->ImgNum==0) {
regA = QuantumScale * p[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
} else {
const Quantum * pv = GetCacheViewVirtualPixels (
pfx->Imgs[0].View, imgx, imgy, 1,1, pfx->exception);
if (!pv) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fU can't get cache", "%lu", (unsigned long) ImgNum);
break;
}
regA = QuantumScale * pv[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
}
}
} else {
/* we have an image atttribute */
regA = ImageStat (pfx, 0, WHICH_ATTR_CHAN, pel->ImgAttrQual);
}
} else {
/* We have non-zero ImgNum. */
if (pel->ImgAttrQual == aNull) {
const Quantum * pv;
if ((int)pel->ChannelQual < 0) {
if (pel->ChannelQual == HUE_CHANNEL || pel->ChannelQual == SAT_CHANNEL ||
pel->ChannelQual == LIGHT_CHANNEL)
{
regA = GetHslInt (pfx, ImgNum, imgx, imgy, pel->ChannelQual);
break;
} else if (pel->ChannelQual == INTENSITY_CHANNEL)
{
regA = GetIntensity (pfx, ImgNum, (fxFltType) imgx, (fxFltType) imgy);
break;
}
}
pv = GetCacheViewVirtualPixels (
pfx->Imgs[ImgNum].View, imgx, imgy, 1,1, pfx->exception);
if (!pv) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fU can't get cache", "%lu", (unsigned long) ImgNum);
break;
}
regA = QuantumScale *
pv[pfx->Images[ImgNum]->channel_map[WHICH_NON_ATTR_CHAN].offset];
} else {
regA = ImageStat (pfx, ImgNum, WHICH_ATTR_CHAN, pel->ImgAttrQual);
}
}
break;
}
case fU0: {
/* No args. No image attribute. We may have a ChannelQual.
If called from %[fx:...], ChannelQual will be CompositePixelChannel.
*/
Image * pimg = pfx->Images[0];
int pech = (int)pel->ChannelQual;
if (pech < 0) {
if (pech == NO_CHAN_QUAL || pech == THIS_CHANNEL) {
if (pfx->ImgNum==0) {
regA = QuantumScale * p[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
} else {
const Quantum * pv = GetCacheViewVirtualPixels (
pfx->Imgs[0].View, imgx, imgy, 1,1, pfx->exception);
if (!pv) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fU0 can't get cache", "%i", 0);
break;
}
regA = QuantumScale * pv[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
}
} else if (pel->ChannelQual == HUE_CHANNEL || pel->ChannelQual == SAT_CHANNEL ||
pel->ChannelQual == LIGHT_CHANNEL) {
regA = GetHslInt (pfx, 0, imgx, imgy, pel->ChannelQual);
break;
} else if (pel->ChannelQual == INTENSITY_CHANNEL) {
regA = GetIntensity (pfx, 0, (fxFltType) imgx, (fxFltType) imgy);
}
} else {
if (pfx->ImgNum==0) {
regA = QuantumScale * p[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
} else {
const Quantum * pv = GetCacheViewVirtualPixels (
pfx->Imgs[0].View, imgx, imgy, 1,1, pfx->exception);
if (!pv) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fU0 can't get cache", "%i", 0);
break;
}
regA = QuantumScale * pv[pimg->channel_map[WHICH_NON_ATTR_CHAN].offset];
}
}
break;
}
case fUP: {
/* 3 args are: ImgNum, x, y */
ssize_t ImgNum = ChkImgNum (pfx, regA);
fxFltType fx, fy;
if (ImgNum < 0) break;
if (pel->IsRelative) {
fx = imgx + regB;
fy = imgy + regC;
} else {
fx = regB;
fy = regC;
}
if ((int)pel->ChannelQual < 0) {
if (pel->ChannelQual == HUE_CHANNEL || pel->ChannelQual == SAT_CHANNEL
|| pel->ChannelQual == LIGHT_CHANNEL) {
regA = GetHslFlt (pfx, ImgNum, fx, fy, pel->ChannelQual);
break;
} else if (pel->ChannelQual == INTENSITY_CHANNEL) {
regA = GetIntensity (pfx, ImgNum, fx, fy);
break;
}
}
{
double v;
Image * imUP = pfx->Images[ImgNum];
if (! InterpolatePixelChannel (imUP, pfx->Imgs[ImgNum].View, WHICH_NON_ATTR_CHAN,
imUP->interpolate, (double) fx, (double) fy, &v, pfx->exception))
{
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fUP can't get interpolate", "%lu", (unsigned long) ImgNum);
break;
}
regA = v * QuantumScale;
}
break;
}
case fS:
case fV: {
/* No args. */
ssize_t ImgNum = 1;
if (pel->oprNum == fS) ImgNum = pfx->ImgNum;
if (pel->ImgAttrQual == aNull) {
const Quantum * pv = GetCacheViewVirtualPixels (
pfx->Imgs[ImgNum].View, imgx, imgy, 1,1, pfx->exception);
if (!pv) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fV can't get cache", "%lu", (unsigned long) ImgNum);
break;
}
if ((int)pel->ChannelQual < 0) {
if (pel->ChannelQual == HUE_CHANNEL || pel->ChannelQual == SAT_CHANNEL ||
pel->ChannelQual == LIGHT_CHANNEL) {
regA = GetHslInt (pfx, ImgNum, imgx, imgy, pel->ChannelQual);
break;
} else if (pel->ChannelQual == INTENSITY_CHANNEL) {
regA = GetIntensity (pfx, ImgNum, (double) imgx, (double) imgy);
break;
}
}
regA = QuantumScale *
pv[pfx->Images[ImgNum]->channel_map[WHICH_NON_ATTR_CHAN].offset];
} else {
regA = ImageStat (pfx, ImgNum, WHICH_ATTR_CHAN, pel->ImgAttrQual);
}
break;
}
case fP:
case fSP:
case fVP: {
/* 2 args are: x, y */
fxFltType fx, fy;
ssize_t ImgNum = pfx->ImgNum;
if (pel->oprNum == fVP) ImgNum = 1;
if (pel->IsRelative) {
fx = imgx + regA;
fy = imgy + regB;
} else {
fx = regA;
fy = regB;
}
if ((int)pel->ChannelQual < 0) {
if (pel->ChannelQual == HUE_CHANNEL || pel->ChannelQual == SAT_CHANNEL ||
pel->ChannelQual == LIGHT_CHANNEL) {
regA = GetHslFlt (pfx, ImgNum, fx, fy, pel->ChannelQual);
break;
} else if (pel->ChannelQual == INTENSITY_CHANNEL) {
regA = GetIntensity (pfx, ImgNum, fx, fy);
}
}
{
double v;
if (! InterpolatePixelChannel (pfx->Images[ImgNum], pfx->Imgs[ImgNum].View,
WHICH_NON_ATTR_CHAN, pfx->Images[ImgNum]->interpolate,
(double) fx, (double) fy, &v, pfx->exception)
)
{
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"fSP or fVP can't get interp", "%lu", (unsigned long) ImgNum);
break;
}
regA = v * (fxFltType)QuantumScale;
}
break;
}
case fNull:
break;
case aDepth:
regA = (fxFltType) GetImageDepth (img, pfx->exception);
break;
case aExtent:
regA = (fxFltType) img->extent;
break;
case aKurtosis:
regA = cs[WHICH_ATTR_CHAN].kurtosis;
break;
case aMaxima:
regA = cs[WHICH_ATTR_CHAN].maxima;
break;
case aMean:
regA = cs[WHICH_ATTR_CHAN].mean;
break;
case aMedian:
regA = cs[WHICH_ATTR_CHAN].median;
break;
case aMinima:
regA = cs[WHICH_ATTR_CHAN].minima;
break;
case aPage:
break;
case aPageX:
regA = (fxFltType) img->page.x;
break;
case aPageY:
regA = (fxFltType) img->page.y;
break;
case aPageWid:
regA = (fxFltType) img->page.width;
break;
case aPageHt:
regA = (fxFltType) img->page.height;
break;
case aPrintsize:
break;
case aPrintsizeX:
regA = (fxFltType) PerceptibleReciprocal (img->resolution.x) * img->columns;
break;
case aPrintsizeY:
regA = (fxFltType) PerceptibleReciprocal (img->resolution.y) * img->rows;
break;
case aQuality:
regA = (fxFltType) img->quality;
break;
case aRes:
break;
case aResX:
regA = (fxFltType) img->resolution.x;
break;
case aResY:
regA = (fxFltType) img->resolution.y;
break;
case aSkewness:
regA = cs[WHICH_ATTR_CHAN].skewness;
break;
case aStdDev:
regA = cs[WHICH_ATTR_CHAN].standard_deviation;
break;
case aH: /* image->rows */
regA = (fxFltType) img->rows;
break;
case aN: /* image list length */
regA = (fxFltType) pfx->ImgListLen;
break;
case aT: /* image index in list */
regA = (fxFltType) pfx->ImgNum;
break;
case aW: /* image->columns */
regA = (fxFltType) img->columns;
break;
case aZ: /* image depth */
regA = (fxFltType) GetImageDepth (img, pfx->exception);
break;
case aNull:
break;
case sHue: /* of conversion to HSL */
regA = hue;
break;
case sIntensity:
regA = GetIntensity (pfx, pfx->ImgNum, (double) imgx, (double) imgy);
break;
case sLightness: /* of conversion to HSL */
regA = lightness;
break;
case sLuma: /* calculation */
case sLuminance: /* as Luma */
regA = QuantumScale * (0.212656 * GetPixelRed (img,p) +
0.715158 * GetPixelGreen (img,p) +
0.072186 * GetPixelBlue (img,p));
break;
case sSaturation: /* from conversion to HSL */
regA = saturation;
break;
case sA: /* alpha */
regA = QuantumScale * GetPixelAlpha (img, p);
break;
case sB: /* blue */
regA = QuantumScale * GetPixelBlue (img, p);
break;
case sC: /* red (ie cyan) */
regA = QuantumScale * GetPixelCyan (img, p);
break;
case sG: /* green */
regA = QuantumScale * GetPixelGreen (img, p);
break;
case sI: /* current x-coordinate */
regA = (fxFltType) imgx;
break;
case sJ: /* current y-coordinate */
regA = (fxFltType) imgy;
break;
case sK: /* black of CMYK */
regA = QuantumScale * GetPixelBlack (img, p);
break;
case sM: /* green (ie magenta) */
regA = QuantumScale * GetPixelGreen (img, p);
break;
case sO: /* alpha */
regA = QuantumScale * GetPixelAlpha (img, p);
break;
case sR:
regA = QuantumScale * GetPixelRed (img, p);
break;
case sY:
regA = QuantumScale * GetPixelYellow (img, p);
break;
case sNull:
break;
case rGoto:
assert (pel->EleNdx >= 0);
i = pel->EleNdx-1; /* -1 because 'for' loop will increment. */
break;
case rIfZeroGoto:
assert (pel->EleNdx >= 0);
if (fabs((double) regA) < MagickEpsilon) i = pel->EleNdx-1;
break;
case rIfNotZeroGoto:
assert (pel->EleNdx >= 0);
if (fabs((double) regA) > MagickEpsilon) i = pel->EleNdx-1;
break;
case rCopyFrom:
assert (pel->EleNdx >= 0);
regA = pfxrt->UserSymVals[pel->EleNdx];
break;
case rCopyTo:
assert (pel->EleNdx >= 0);
pfxrt->UserSymVals[pel->EleNdx] = regA;
break;
case rZerStk:
pfxrt->usedValStack = 0;
break;
case rNull:
break;
default:
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"pel->oprNum", "%i '%s' not yet implemented",
(int)pel->oprNum, OprStr(pel->oprNum));
break;
}
if (i < 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Bad run-time address", "%i", i);
}
if (pel->DoPush)
if (!PushVal (pfx, pfxrt, regA, i)) break;
}
if (pfxrt->usedValStack > 0) regA = PopVal (pfx, pfxrt, 9999);
*result = regA;
if (NeedRelinq) cs = (ChannelStatistics *)RelinquishMagickMemory (cs);
if (pfx->exception->severity != UndefinedException) {
return MagickFalse;
}
if (pfxrt->usedValStack != 0) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"ValStack not empty", "(%i)", pfxrt->usedValStack);
return MagickFalse;
}
return MagickTrue;
}
/* Following is substitute for FxEvaluateChannelExpression().
*/
MagickPrivate MagickBooleanType FxEvaluateChannelExpression (
FxInfo *pfx,
const PixelChannel channel, const ssize_t x, const ssize_t y,
double *result, ExceptionInfo *exception)
{
const int
id = GetOpenMPThreadId();
fxFltType ret;
assert (pfx != NULL);
assert (pfx->image != NULL);
assert (pfx->Images != NULL);
assert (pfx->Imgs != NULL);
assert (pfx->fxrts != NULL);
pfx->fxrts[id].thisPixel = NULL;
if (!ExecuteRPN (pfx, &pfx->fxrts[id], &ret, channel, x, y)) {
(void) ThrowMagickException (
exception, GetMagickModule(), OptionError,
"ExcuteRPN failed", " ");
return MagickFalse;
}
*result = (double) ret;
return MagickTrue;
}
static FxInfo *AcquireFxInfoPrivate (const Image * images, const char * expression,
MagickBooleanType CalcAllStats, ExceptionInfo *exception)
{
char chLimit;
FxInfo * pfx = (FxInfo*) AcquireCriticalMemory (sizeof (*pfx));
memset (pfx, 0, sizeof (*pfx));
if (!InitFx (pfx, images, CalcAllStats, exception)) {
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
if (!BuildRPN (pfx)) {
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return((FxInfo *) NULL);
}
if ((*expression == '@') && (strlen(expression) > 1))
{
MagickBooleanType
status;
/*
Read expression from a file.
*/
status=IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,expression);
if (status != MagickFalse)
pfx->expression=FileToString(expression+1,~0UL,exception);
else
{
errno=EPERM;
(void) ThrowMagickException(exception,GetMagickModule(),PolicyError,
"NotAuthorized","`%s'",expression);
}
}
if (pfx->expression == (char *) NULL)
pfx->expression=ConstantString(expression);
pfx->pex = (char *) pfx->expression;
pfx->teDepth = 0;
if (!TranslateStatementList (pfx, ";", &chLimit)) {
(void) DestroyRPN (pfx);
pfx->expression = DestroyString (pfx->expression);
pfx->pex = NULL;
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
if (pfx->teDepth) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"Translate expression depth", "(%i) not 0",
pfx->teDepth);
(void) DestroyRPN (pfx);
pfx->expression = DestroyString (pfx->expression);
pfx->pex = NULL;
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
if (chLimit != '\0' && chLimit != ';') {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), OptionError,
"AcquireFxInfo: TranslateExpression did not exhaust input", "(chLimit=%i) at'%s'",
(int)chLimit, pfx->pex);
(void) DestroyRPN (pfx);
pfx->expression = DestroyString (pfx->expression);
pfx->pex = NULL;
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
if (pfx->NeedStats && pfx->runType == rtEntireImage && !pfx->statistics) {
if (!CollectStatistics (pfx)) {
(void) DestroyRPN (pfx);
pfx->expression = DestroyString (pfx->expression);
pfx->pex = NULL;
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
}
if (pfx->DebugOpt) {
DumpTables (stderr);
DumpUserSymbols (pfx, stderr);
(void) DumpRPN (pfx, stderr);
}
{
size_t number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
ssize_t t;
pfx->fxrts = (fxRtT *)AcquireQuantumMemory (number_threads, sizeof(fxRtT));
if (!pfx->fxrts) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"fxrts", "%lu",
(unsigned long) number_threads);
(void) DestroyRPN (pfx);
pfx->expression = DestroyString (pfx->expression);
pfx->pex = NULL;
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
for (t=0; t < (ssize_t) number_threads; t++) {
if (!AllocFxRt (pfx, &pfx->fxrts[t])) {
(void) ThrowMagickException (
pfx->exception, GetMagickModule(), ResourceLimitFatalError,
"AllocFxRt t=", "%g",
(double) t);
{
ssize_t t2;
for (t2 = t-1; t2 >= 0; t2--) {
DestroyFxRt (&pfx->fxrts[t]);
}
}
pfx->fxrts = (fxRtT *) RelinquishMagickMemory (pfx->fxrts);
(void) DestroyRPN (pfx);
pfx->expression = DestroyString (pfx->expression);
pfx->pex = NULL;
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
}
}
return pfx;
}
FxInfo *AcquireFxInfo (const Image * images, const char * expression, ExceptionInfo *exception)
{
return AcquireFxInfoPrivate (images, expression, MagickFalse, exception);
}
FxInfo *DestroyFxInfo (FxInfo * pfx)
{
ssize_t t;
assert (pfx != NULL);
assert (pfx->image != NULL);
assert (pfx->Images != NULL);
assert (pfx->Imgs != NULL);
assert (pfx->fxrts != NULL);
for (t=0; t < (ssize_t) GetMagickResourceLimit(ThreadResource); t++) {
DestroyFxRt (&pfx->fxrts[t]);
}
pfx->fxrts = (fxRtT *) RelinquishMagickMemory (pfx->fxrts);
DestroyRPN (pfx);
pfx->expression = DestroyString (pfx->expression);
pfx->pex = NULL;
(void) DeInitFx (pfx);
pfx = (FxInfo*) RelinquishMagickMemory(pfx);
return NULL;
}
/* Following is substitute for FxImage().
*/
MagickExport Image *FxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
#define FxImageTag "FxNew/Image"
CacheView
*fx_view,
*image_view;
Image
*fx_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
FxInfo
*pfx;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (expression == (const char *) NULL)
return(CloneImage(image,0,0,MagickTrue,exception));
fx_image=CloneImage(image,0,0,MagickTrue,exception);
if (!fx_image) return NULL;
if (SetImageStorageClass(fx_image,DirectClass,exception) == MagickFalse) {
fx_image=DestroyImage(fx_image);
return NULL;
}
pfx = AcquireFxInfoPrivate (image, expression, MagickTrue, exception);
if (!pfx) {
fx_image=DestroyImage(fx_image);
return NULL;
}
assert (pfx->image != NULL);
assert (pfx->Images != NULL);
assert (pfx->Imgs != NULL);
assert (pfx->fxrts != NULL);
status=MagickTrue;
progress=0;
image_view = AcquireVirtualCacheView (image, pfx->exception);
fx_view = AcquireAuthenticCacheView (fx_image, pfx->exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic) shared(progress,status) \
magick_number_threads(image,fx_image,fx_image->rows, \
pfx->ContainsDebug ? 0 : 1)
#endif
for (y=0; y < (ssize_t) fx_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
fxFltType
result = 0.0;
if (status == MagickFalse)
continue;
p = GetCacheViewVirtualPixels (image_view, 0, y, image->columns, 1, pfx->exception);
q = QueueCacheViewAuthenticPixels (fx_view, 0, y, fx_image->columns, 1, pfx->exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) {
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) fx_image->columns; x++) {
ssize_t i;
pfx->fxrts[id].thisPixel = (Quantum *)p;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel (image, i);
PixelTrait traits = GetPixelChannelTraits (image, channel);
PixelTrait fx_traits = GetPixelChannelTraits (fx_image, channel);
if ((traits == UndefinedPixelTrait) ||
(fx_traits == UndefinedPixelTrait))
continue;
if ((fx_traits & CopyPixelTrait) != 0) {
SetPixelChannel (fx_image, channel, p[i], q);
continue;
}
if (!ExecuteRPN (pfx, &pfx->fxrts[id], &result, channel, x, y)) {
status=MagickFalse;
break;
}
q[i] = ClampToQuantum ((MagickRealType) (QuantumRange*result));
}
p+=GetPixelChannels (image);
q+=GetPixelChannels (fx_image);
}
if (SyncCacheViewAuthenticPixels(fx_view, pfx->exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed = SetImageProgress (image, FxImageTag, progress, image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
fx_view = DestroyCacheView (fx_view);
image_view = DestroyCacheView (image_view);
/* Before destroying the user symbol values, dump them to stderr.
*/
if (pfx->DebugOpt && pfx->usedUserSymbols) {
int t, i;
char UserSym[MagickPathExtent];
fprintf (stderr, "User symbols (%i):\n", pfx->usedUserSymbols);
for (t=0; t < (int) GetMagickResourceLimit(ThreadResource); t++) {
for (i = 0; i < (int) pfx->usedUserSymbols; i++) {
fprintf (stderr, "th=%i us=%i '%s': %.*Lg\n",
t, i, NameOfUserSym (pfx, i, UserSym), pfx->precision, pfx->fxrts[t].UserSymVals[i]);
}
}
}
if (pfx->exception->severity != UndefinedException) {
status = MagickFalse;
}
if (status == MagickFalse)
fx_image = DestroyImage (fx_image);
pfx = DestroyFxInfo (pfx);
return(fx_image);
}
|
bisection.c | #include "header.h"
/** Finds a zero, using bisection, in the interval [a, b] of the function
pointed to by fun_ptr. If no zero is found, the function returns -1.0. **/
double find_zero_bisection(double (*fun_ptr)(double), double a, double b) {
const int max_iter = 100; // maximum number of iterations
const double tol = 1e-8; // tolerance
int i = 0; double c;
/* perform bisection while the interval length is
longer than the tolerance, or the maximum number
of iterations has not been reached. */
do {
c = a + (b-a)*0.5; // mid-point
if ((*fun_ptr)(a) * (*fun_ptr)(c) > 0) { // check sign
a = c;
} else {
b = c;
}
i++;
} while (b-a > tol && i < max_iter);
/* if sgn(f(a)) == sgn(f(b)), no zero was found */
if ((*fun_ptr)(a) * (*fun_ptr)(b) > 0) {
return -1.0;
}
return c;
}
/** Finds all zeros in the interval [a, b]. This procedure
divides the interval [a, b] into N smaller interval and
then uses bisection on each of the subintervals. **/
array *find_all_zeros_bisection(double (*fun_ptr)(double), double a, double b, int N, int T) {
array *zeros = malloc(sizeof(array));
zeros->ptr = malloc(N*sizeof(double));
zeros->size = 0;
double dn = (b-a)/((double) N);
double xl, xu;
int chunk = ceil(N/(double)T);
#pragma omp parallel for num_threads(T) schedule(static, chunk) private(xl, xu)
for (int i = 0; i < N; i++) {
xl = a + dn*i;
xu = a + dn*(i+1);
zeros->ptr[i] = find_zero_bisection(fun_ptr, xl, xu);
}
/* collect the found zeros */
for (int i = 0; i < N; i++) {
if (zeros->ptr[i] != -1) {
zeros->ptr[zeros->size] = zeros->ptr[i];
zeros->size++;
}
}
zeros->ptr = realloc(zeros->ptr, zeros->size*sizeof(double));
return zeros;
}
|
LAGraph_bfs_pushpull.c | //------------------------------------------------------------------------------
// LAGraph_bfs_pushpull: push-pull breadth-first search
//------------------------------------------------------------------------------
/*
LAGraph: graph algorithms based on GraphBLAS
Copyright 2020 LAGraph Contributors.
(see Contributors.txt for a full list of Contributors; see
ContributionInstructions.txt for information on how you can Contribute to
this project).
All Rights Reserved.
NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH
CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH
RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
Released under a BSD license, please see the LICENSE file distributed with
this Software or contact permission@sei.cmu.edu for full terms.
Created, in part, with funding and support from the United States
Government. (see Acknowledgments.txt file).
This program includes and/or can make use of certain third party source
code, object code, documentation and other files ("Third Party Software").
See LICENSE file for more details.
*/
//------------------------------------------------------------------------------
// LAGraph_bfs_pushpull: direction-optimized push/pull breadth first search,
// contributed by Tim Davis, Texas A&M.
// LAGraph_bfs_pushpull computes the BFS of a graph from a single given
// source node. The result is a vector v where v(i)=k if node i was placed
// at level k in the BFS.
// Usage:
// info = LAGraph_bfs_pushpull (&v, &pi, A, AT, source, max_level, vsparse) ;
// GrB_Vector *v: a vector containing the result, created on output.
// v(i) = k is the BFS level of node i in the graph, where a source
// node has v(source)=1. v(i) is implicitly zero if it is unreachable
// from the source node. That is, GrB_Vector_nvals (&nreach,v) is the
// size of the reachable set of the source node, for a single-source
// BFS. v may be returned as sparse, or full. If full, v(i)=0
// indicates that node i was not reached. If sparse, the pattern of v
// indicates the set of nodes reached.
// GrB_Vector *pi: a vector containing the BFS tree, in 1-based indexing.
// pi(source) = source+1 for source node. pi(i) = p+1 if p is the
// parent of i. If pi is sparse, and pi(i) is not present, then node
// i has not been reached. Otherwise, if pi is full, then pi(i)=0
// indicates that node i was not reached.
// GrB_Matrix A: a square matrix of any type. The values of A are not
// accessed. The presence of the entry A(i,j) indicates the edge
// (i,j). That is, an explicit entry A(i,j)=0 is treated as an edge.
// GrB_Matrix AT: an optional matrix of any type. If NULL, the algorithm
// is a conventional push-only BFS. If not NULL, AT must be the
// transpose of A, and a push-pull algorithm is used (NOTE: this
// assumes GraphBLAS stores its matrix in CSR form; see discussion
// below). Results are undefined if AT is not NULL but not identical
// to the transpose of A.
// int64_t source: the source node for the BFS.
// int64_t max_level: An optional limit on the levels searched for the
// single-source BFS. If zero, then no limit is enforced. If > 0,
// then only nodes with v(i) <= max_level will be visited. That is:
// 1: just the source node, 2: the source and its neighbors, 3: the
// source node, its neighbors, and their neighbors, etc.
// bool vsparse: if the result v may remain very sparse, then set this
// parameter to true. If v might have many entries, set it false. If
// you are unsure, then set it to true. This parameter speeds up
// the handling of v. If you guess wrong, there is a slight
// performance penalty. The results are not affected by this
// parameter, just the performance. This parameter is used only for
// the single-source BFS.
// single-source BFS:
// Given a graph A, a source node, find all nodes reachable from the
// source node. v(source)=1, v(i)=2 if edge (source,i) appears in the
// graph, and so on. If node i is not reachable from source, then
// implicitly v(i)=0. v is returned as a sparse vector, and v(i) is not
// an entry in this vector.
// This algorithm can use the push-pull strategy, which requires both A and
// AT=A' to be passed in. If the graph is known to be symmetric, then the same
// matrix A can be passed in for both arguments. Results are undefined if AT
// is not the transpose of A.
// If only A or AT is passed in, then only single strategy will be used: push
// or pull, but not both. In general, push-only performs well. A pull-only
// strategy is possible but it is exceedingly slow. Assuming A and AT are both
// in CSR format, then (let s = source node):
// LAGraph_bfs_pushpull (..., A, AT, s, ...) ; // push-pull (fastest)
// LAGraph_bfs_pushpull (..., A, NULL, s, ...) ; // push-only (good)
// LAGraph_bfs_pushpull (..., NULL, AT, s, ...) ; // pull-only (slow!)
// If A and AT are both in CSC format, then:
// LAGraph_bfs_pushpull (..., A, AT, s, ...) ; // push-pull (fastest)
// LAGraph_bfs_pushpull (..., NULL, AT, s, ...) ; // push-only (good)
// LAGraph_bfs_pushpull (..., A, NULL, s, ...) ; // pull-only (slow!)
// Since the pull-only method is exceedingly slow, SuiteSparse:GraphBLAS
// detects this case and refuses to do it.
// The basic step of this algorithm computes A'*q where q is the 'queue' of
// nodes in the current level. This can be done with GrB_vxm(q,A) = (q'*A)' =
// A'*q, or by GrB_mxv(AT,q) = AT*q = A'*q. Both steps compute the same thing,
// just in a different way. In GraphBLAS, unlike MATLAB, a GrB_Vector is
// simultaneously a row and column vector, so q and q' are interchangeable.
// To implement an efficient BFS using GraphBLAS, an assumption must be made in
// LAGraph about how the matrix is stored, whether by row or by column (or
// perhaps some other opaque data structure). The storage format has a huge
// impact on the relative performance of vxm(q,A) and mxv(AT,q).
// Storing A by row, if A(i,j) is the edge (i,j), means that A(i,:) is easily
// accessible. In terms of the graph A, this means that the out-adjacency
// list of node i can be traversed in time O(out-degree of node i).
// If AT is stored by row, then AT(i,:) is the in-adjacency list of node i,
// and traversing row i of AT can be done in O(in-degree of node i) time.
// The CSR (Compressed Sparse Row) format is the default for
// SuiteSparse:GraphBLAS, but no assumption can be made about any particular
// GraphBLAS library implementation.
// If A and AT are both stored by column instead, then A(i,:) is not easy to
// access. Instead, A(:,i) is the easily-accessible in-adjacency of node i,
// and AT(:,i) is the out-adjancency.
// A push step requires the out-adjacencies of each node, where as
// a pull step requires the in-adjacencies of each node.
// vxm(q,A) = A'*q, with A stored by row: a push step
// mxv(AT,q) = A'*q, with AT stored by row: a pull step
// vxm(q,A) = A'*q, with A stored by col: a pull step
// mxv(AT,q) = A'*q, with AT stored by col: a push step
// The GraphBLAS data structure is opaque. An implementation may decide to
// store the matrix A in both formats, internally, so that it easily traverse
// both in- and out-adjacencies of each node (equivalently, A(i,:) and A(:,i)
// can both be easily traversed). This would make a push-pull BFS easy to
// implement using just the opaque GrB_Matrix A, but it doubles the storage.
// Deciding which format to use automatically is not a simple task,
// particularly since the decision must work well throughout GraphBLAS, not
// just for the BFS.
// MATLAB stores its sparse matrices in CSC format (Compressed Sparse Column).
// As a result, the MATLAB expression x=AT*q is a push step, computed using a
// saxpy-based algorithm internally, and x=A'*q is a pull step, computed using
// a dot product.
// SuiteSparse:GraphBLAS can store a matrix in either format, but this requires
// an extension to the GraphBLAS C API (GxB_set (A, GxB_FORMAT, f)). where
// f = GxB_BY_ROW (that is, CSR) or GxB_BY_COL (that is, CSC). The library
// could be augmented in the future with f = Gxb_BY_BOTH. It currently does
// not select the format automatically. As a result, if GxB_set is not used,
// all its GrB_Matrix objects are stored by row (CSR).
// SuiteSparse:GraphBLAS allows the user to query (via GxB_get) an set (via
// GxB_set) the format, whether by row or by column. The hypersparsity of
// A is selected automatically, with optional hints from the user application,
// but a selection between hypersparsity vs standard CSR and CSC has no effect
// on the push vs pull decision made here.
// The push/pull and saxpy/dot connection can be described as follows.
// Assume for these first two examples that MATLAB stores its matrices in CSR
// format, where accessing A(i,:) is fast.
// If A is stored by row, then x = vxm(q,A) = q'*A can be written in MATLAB
// notation as:
/*
function x = vxm (q,A)
% a push step: compute x = q'*A where q is a column vector
x = sparse (1,n)
for i = 1:n
% a saxpy operation, using the ith row of A and the scalar q(i)
x = x + q (i) * A (i,:)
end
*/
// If AT is stored by row, then x = mvx(AT,q) = AT*q = A'*q becomes
// a dot product:
/*
function x = mxv (AT,q)
% a pull step: compute x = AT*q where q is a column vector
for i = 1:n
% a dot-product of the ith row of AT and the column vector q
x (i) = AT (i,:) * q
end
*/
// The above snippets describe how SuiteSparse:GraphBLAS computes vxm(q,A) and
// mxv(AT,q) by default, where A and AT are stored by row by default. However,
// they would be very slow in MATLAB, since it stores its sparse matrices in
// CSC format. In that case, if A is stored by column and thus accessing
// A(:,j) is efficient, then x = vxm(q,A) = q'*A becomes the dot product
// instead. These two snippets assume the matrices are both in CSR for, and
// thus make more efficient use of MATLAB:
/*
function x = vxm (q,A)
% a pull step: compute x = q'*A where q is a column vector
for j = 1:n
% a dot product of the row vector q' and the jth column of A
x (j) = q' * A (:,j)
end
*/
// If AT is stored by column, then x = mvx(AT,q) is
/*
function x = mxv (AT,q)
% a push step: compute x = AT*q where q is a column vector
for j = 1:n
% a saxpy operation, using the jth column of AT and the scalar q(i)
x = x + AT (:,j) * q
end
*/
// In MATLAB, if q is a sparse column vector and A is a sparse matrix, then
// x=A*q does in fact use a saxpy-based method, internally, and x=A'*q uses a
// dot product. You can view the code used internally in MATLAB for its sparse
// matrix multiplication in the SuiteSparse/MATLAB_Tools/SSMULT and SFMULT
// packages, at http://suitesparse.com.
// This raises an interesting puzzle for LAGraph, which is intended on being a
// graph library that can be run on any implementation of GraphBLAS. There are
// no mechanisms in the GraphBLAS C API for LAGraph (or other external packages
// or user applications) to provide hints to GraphBLAS. Likely, there are no
// query mechanisms where LAGraph can ask GraphBLAS how its matrices might be
// stored (LAGraphs asks, "Is A(i,:) fast? Or A(:,j)? Or both?"; the answer
// from GraphBLAS is silence). The GraphBLAS data structure is opaque, and it
// does not answer this query.
// There are two solutions to this puzzle. The most elegant one is for
// GraphBLAS to handle all this internally, and change formats as needed. It
// could choose to store A in both CSR and CSC format, or use an entirely
// different data structure, and it would make the decision between the push or
// pull, at each step of the BFS. This is not a simple task since the API is
// complex. Furthermore, the selection of the data structure for A has
// implications on all other GraphBLAS operations (submatrix assignment and
// extraction, for example).
// However, if A were to be stored in both CSR and CSC format, inside the
// opaque GraphBLAS GrB_Matrix data structure, then LAGraph_bfs_simple would
// become a push-pull BFS.
// The second solution is to allow the user application or library such as
// LAGraph to provide hints and allow it to query the GraphBLAS library.
// There are no such features in the GraphBLAS C API.
// SuiteSparse:GraphBLAS takes the second approach: It adds two functions that
// are extensions to the API: GxB_set changes the format (CSR or CSC), and
// GxB_get can query the format. Even this this simplication,
// SuiteSparse:GraphBLAS uses 24 different algorithmic variants inside GrB_mxm
// (per semiring), and selects between them automatically. By default, all of
// its matrices are stored in CSR format (either sparse or hypersparse,
// selected automatically). So if no GxB_* extensions are used, all matrices
// are in CSR format.
// If a GraphBLAS library other than SuiteSparse:GraphBLAS is in use, this
// particular function assumes that its input matrices are in CSR format, or at
// least A(i,:) and AT(i,:) can be easily accessed. With this assumption, it
// is the responsibilty of this function to select between using a push or a
// pull, for each step in the BFS.
// The following analysis assumes CSR format, and it assumes that dot-product
// (a pull step) can terminate early via a short-circuit rule with the OR
// monoid, as soon as it encounters a TRUE value. This cuts the time for the
// dot-product. Not all GraphBLAS libraries may use this, but SuiteSparse:
// GraphBLAS does (in version 2.3.0 and later). Early termination cannot be
// done for the saxpy (push step) method.
// The work done by the push method (saxpy) is very predictable. BFS uses a
// complemented mask. There is no simple way to exploit a complemented mask,
// and saxpy has no early termination rule. If the set of nodes in the current
// level is q, the work is nnz(A(q,:)). If d = nnz(A)/n is the average degree,
// this becomes d*nq where nq = length (q):
// pushwork = d*nq
// The work done by the pull (dot product) method is less predictable. It can
// exploit the complemented mask, and so it only computes (n-nvisited) dot
// products, if nvisited is the # of nodes visited so far (in all levels).
// With no early-termination, the dot product will take d * log2 (nq) time,
// assuming that q is large and a binary search is used internally. That is,
// the dot product will scan through the d entries in A(i,:), and do a binary
// search for each entry in q. To account for the higher constant of a binary
// search, log2(nq) is replaced with (3*(1+log2(nq))). With early termination,
// d is too high. If the nodes are randomly marked, the probability of each
// node being marked is nvisited/n. The expected number of trials until
// success, for a sequence of events with probabilty p, is 1/p. Thus, the
// expected number of iterations in a dot product before an early termination
// is 1/p = (n/nvisited+1), where +1 is added to avoid a divide by zero.
// However, it cannot exceed d. Thus, the total work for the dot product
// (pull) method can be estimated as:
// per_dot = min (d, n / (nvisited+1))
// pullwork = (n-nvisited) * per_dot * (3 * (1 + log2 ((double) nq)))
// The above expressions are valid for SuiteSparse:GraphBLAS v2.3.0 and later,
// and may be reasonable for other GraphBLAS implementations. Push or pull
// is selected as the one with the least work.
// TODO: change the formula for v3.2.0
// The push/pull decision requires that both A and AT be passed in, but this
// function can use just one or the other. If only A is passed in and AT is
// NULL, then only vxm(q,A) will be used (a push step if A is CSR, or a pull
// step if A is CSC). If only AT is passed in and A is NULL, then only
// mxv(AT,q) will be used (a pull step if AT is CSR, or a push step if AT is
// CSC).
// In general, while a push-pull strategy is the fastest, a push-only BFS will
// give good peformance. In particular, the time to compute AT=A' plus the
// time for the push-pull BFS is typically higher than just a push-only BFS.
// This why this function does not compute AT=A'. To take advantage of the
// push-pull method, both A and AT must already be available, with the cost to
// construct them amortized across other computations such as this one.
// A pull-only strategy will be *exceeding* slow.
// The input matrix A must be square. It can be non-binary, but best
// performance will be obtained if it is GrB_BOOL. It can have explicit
// entries equal to zero. These are safely ignored, and are treated as
// non-edges.
// SuiteSparse:GraphBLAS can detect the CSR vs CSC format of its inputs.
// In this case, if both matrices are provided, they must be in the same
// format (both GxB_BY_ROW or both GxB_BY_COL). If the matrices are in CSC
// format, vxm(q,A) is the pull step and mxv(AT,q) is the push step.
// If only A or AT are provided, and the result is a pull-only algorithm,
// an error is returned.
// References:
// Carl Yang, Aydin Buluc, and John D. Owens. 2018. Implementing Push-Pull
// Efficiently in GraphBLAS. In Proceedings of the 47th International
// Conference on Parallel Processing (ICPP 2018). ACM, New York, NY, USA,
// Article 89, 11 pages. DOI: https://doi.org/10.1145/3225058.3225122
// Scott Beamer, Krste Asanovic and David A. Patterson,
// The GAP Benchmark Suite, http://arxiv.org/abs/1508.03619, 2015.
// http://gap.cs.berkeley.edu/
#include "LAGraph_bfs_pushpull.h"
#include "../configuration/config.h"
#define LAGRAPH_FREE_ALL \
{ \
GrB_free (&v) ; \
GrB_free (&t) ; \
GrB_free (&q) ; \
GrB_free (&pi) ; \
}
#define LAGRAPH_ERROR(message,info) \
{ \
fprintf (stderr, "LAGraph error: %s\n[%d]\nFile: %s Line: %d\n", \
message, info, __FILE__, __LINE__) ; \
LAGRAPH_FREE_ALL ; \
return (info) ; \
}
#define LAGRAPH_MAX(x,y) (((x) > (y)) ? (x) : (y))
#define LAGRAPH_MIN(x,y) (((x) < (y)) ? (x) : (y))
GrB_Info LAGraph_bfs_pushpull // push-pull BFS, or push-only if AT = NULL
(
GrB_Vector *v_output, // v(i) is the BFS level of node i in the graph
GrB_Vector *pi_output, // pi(i) = p+1 if p is the parent of node i.
// if NULL, the parent is not computed.
GrB_Matrix A, // input graph, treated as if boolean in semiring
GrB_Matrix AT, // transpose of A (optional; push-only if NULL)
int64_t source, // starting node of the BFS
int64_t *dest, // optional destination node of the BFS
int64_t max_level, // optional limit of # levels to search
bool vsparse // if true, v is expected to be very sparse
) {
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GrB_Info info ;
GrB_Vector q = NULL ; // nodes visited at each level
GrB_Vector v = NULL ; // result vector
GrB_Vector t = NULL ; // temporary vector
GrB_Vector pi = NULL ; // parent vector
if(v_output == NULL || (A == NULL && AT == NULL)) {
// required output argument is missing
LAGRAPH_ERROR("required arguments are NULL", GrB_NULL_POINTER) ;
}
(*v_output) = NULL ;
bool compute_tree = (pi_output != NULL) ;
GrB_Index nrows, ncols, nvalA, ignore, nvals ;
// A is provided. AT may or may not be provided
GrB_Matrix_nrows(&nrows, A) ;
GrB_Matrix_ncols(&ncols, A) ;
GrB_Matrix_nvals(&nvalA, A) ;
bool use_vxm_with_A = true ;
// push/pull requires both A and AT
bool push_pull = (A != NULL && AT != NULL) ;
if(nrows != ncols) {
// A must be square
LAGRAPH_ERROR("A must be square", GrB_NULL_POINTER) ;
}
//--------------------------------------------------------------------------
// initializations
//--------------------------------------------------------------------------
GrB_Index n = nrows ;
int nthreads;
Config_Option_get(Config_OPENMP_NTHREAD, &nthreads);
nthreads = LAGRAPH_MIN(n / 4096, nthreads) ;
nthreads = LAGRAPH_MAX(nthreads, 1) ;
// just traverse from the source node
max_level = (max_level <= 0) ? n : LAGRAPH_MIN(n, max_level) ;
// create an empty vector v
GrB_Type int_type = (n > INT32_MAX) ? GrB_INT64 : GrB_INT32 ;
GrB_Vector_new(&v, int_type, n) ;
// make v dense if requested
int64_t vlimit = LAGRAPH_MAX(256, sqrt((double) n)) ;
if(!vsparse) {
// v is expected to have many entries, so convert v to dense.
// If the guess is wrong, v can be made dense later on.
GrB_assign(v, NULL, NULL, 0, GrB_ALL, n, NULL) ;
}
// create a scalar to hold the destination value
GrB_Index dest_val ;
GrB_Semiring first_semiring, second_semiring ;
if(compute_tree) {
// create an integer vector q, and set q(source) to source+1
GrB_Vector_new(&q, int_type, n) ;
GrB_Vector_setElement(q, source + 1, source) ;
if(n > INT32_MAX) {
// terminates as soon as it finds any parent; nondeterministic
first_semiring = GxB_ANY_FIRST_INT64 ;
second_semiring = GxB_ANY_SECOND_INT64 ;
} else {
// terminates as soon as it finds any parent; nondeterministic
first_semiring = GxB_ANY_FIRST_INT32 ;
second_semiring = GxB_ANY_SECOND_INT32 ;
}
// create the empty parent vector
GrB_Vector_new(&pi, int_type, n) ;
if(!vsparse) {
// make pi a dense vector of all zeros
GrB_assign(pi, NULL, NULL, 0, GrB_ALL, n, NULL) ;
}
// pi (source) = source+1 denotes a root of the BFS tree
GrB_Vector_setElement(pi, source + 1, source) ;
} else {
// create a boolean vector q, and set q(source) to true
GrB_Vector_new(&q, GrB_BOOL, n) ;
GrB_Vector_setElement(q, true, source) ;
// terminates as soon as it finds any pair
first_semiring = GxB_ANY_PAIR_BOOL ;
second_semiring = GxB_ANY_PAIR_BOOL ;
}
// average node degree
double d = (n == 0) ? 0 : (((double) nvalA) / (double) n) ;
int64_t nvisited = 0 ; // # nodes visited so far
GrB_Index nq = 1 ; // number of nodes in the current level
//--------------------------------------------------------------------------
// BFS traversal and label the nodes
//--------------------------------------------------------------------------
for(int64_t level = 1 ; ; level++) {
//----------------------------------------------------------------------
// set v to the current level, for all nodes in q
//----------------------------------------------------------------------
// v<q> = level: set v(i) = level for all nodes i in q
GrB_assign(v, q, NULL, level, GrB_ALL, n, GrB_DESC_S) ;
//----------------------------------------------------------------------
// check if done
//----------------------------------------------------------------------
nvisited += nq ;
if(nq == 0 || nvisited == n || level >= max_level) break ;
//----------------------------------------------------------------------
// check if destination has been reached, if one is provided
//----------------------------------------------------------------------
if(dest) {
GrB_Info res = GrB_Vector_extractElement(&dest_val, v, *dest) ;
if(res != GrB_NO_VALUE) break ;
}
//----------------------------------------------------------------------
// check if v should be converted to dense
//----------------------------------------------------------------------
if(vsparse && nvisited > vlimit) {
// Convert v from sparse to dense to speed up the rest of the work.
// If this case is triggered, it would have been faster to pass in
// vsparse = false on input.
// v <!v> = 0
GrB_assign(v, v, NULL, 0, GrB_ALL, n, GrB_DESC_SC) ;
GrB_Vector_nvals(&ignore, v) ;
if(compute_tree) {
// Convert pi from sparse to dense, to speed up the work.
// pi<!pi> = 0
GrB_assign(pi, pi, NULL, 0, GrB_ALL, n, GrB_DESC_SC) ;
GrB_Vector_nvals(&ignore, pi) ;
}
vsparse = false ;
}
//----------------------------------------------------------------------
// select push vs pull
//----------------------------------------------------------------------
if(push_pull) {
double pushwork = d * nq ;
double expected = (double) n / (double)(nvisited + 1) ;
double per_dot = LAGRAPH_MIN(d, expected) ;
double binarysearch = (3 * (1 + log2((double) nq))) ;
double pullwork = (n - nvisited) * per_dot * binarysearch ;
use_vxm_with_A = (pushwork < pullwork) ;
}
//----------------------------------------------------------------------
// q = next level of the BFS
//----------------------------------------------------------------------
if(use_vxm_with_A) {
// q'<!v> = q'*A
// this is a push step if A is in CSR format; pull if CSC
GrB_vxm(q, v, NULL, first_semiring, q, A, GrB_DESC_RC) ;
} else {
// q<!v> = AT*q
// this is a pull step if AT is in CSR format; push if CSC
GrB_mxv(q, v, NULL, second_semiring, AT, q, GrB_DESC_RC) ;
}
//----------------------------------------------------------------------
// move to next level
//----------------------------------------------------------------------
if(compute_tree) {
//------------------------------------------------------------------
// assign parents
//------------------------------------------------------------------
// q(i) currently contains the parent of node i in tree (off by one
// so it won't have any zero values, for valued mask).
// pi<q> = q
GrB_assign(pi, q, NULL, q, GrB_ALL, n, GrB_DESC_S) ;
//------------------------------------------------------------------
// replace q with current node numbers
//------------------------------------------------------------------
// TODO this could be a unaryop
// q(i) = i+1 for all entries in q.
GrB_Index *qi ;
bool iso ;
bool jumbled ;
int64_t q_size ;
GrB_Index qi_size, qx_size ;
if(n > INT32_MAX) {
int64_t *qx ;
GxB_Vector_export_CSC(&q, &int_type, &n,
&qi, (void **) (&qx), &qi_size, &qx_size, &iso, &nq,
&jumbled, NULL) ;
int nth = LAGRAPH_MIN(nq / (64 * 1024), nthreads) ;
nth = LAGRAPH_MAX(nth, 1) ;
#pragma omp parallel for num_threads(nth) schedule(static)
for(int64_t k = 0 ; k < nq ; k++) {
qx [k] = qi [k] + 1 ;
}
GxB_Vector_import_CSC(&q, int_type, n,
&qi, (void **) (&qx), qi_size, qx_size, false, nq,
jumbled, NULL) ;
} else {
int32_t *qx ;
GxB_Vector_export_CSC(&q, &int_type, &n,
&qi, (void **) (&qx), &qi_size, &qx_size, &iso, &nq,
&jumbled, NULL) ;
int nth = LAGRAPH_MIN(nq / (64 * 1024), nthreads) ;
nth = LAGRAPH_MAX(nth, 1) ;
#pragma omp parallel for num_threads(nth) schedule(static)
for(int32_t k = 0 ; k < nq ; k++) {
qx [k] = qi [k] + 1 ;
}
GxB_Vector_import_CSC(&q, int_type, n,
&qi, (void **) (&qx), qi_size, qx_size, false, nq,
jumbled, NULL) ;
}
} else {
//------------------------------------------------------------------
// count the nodes in the current level
//------------------------------------------------------------------
GrB_Vector_nvals(&nq, q) ;
}
}
//--------------------------------------------------------------------------
// return the parent vector, if computed
//--------------------------------------------------------------------------
if(compute_tree) {
(*pi_output) = pi ;
pi = NULL ;
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
(*v_output) = v ; // return result
v = NULL ; // set to NULL so LAGRAPH_FREE_ALL doesn't free it
LAGRAPH_FREE_ALL ; // free all workspace (except for result v)
return (GrB_SUCCESS) ;
}
|
column_matrix.h | /*!
* Copyright 2017 by Contributors
* \file column_matrix.h
* \brief Utility for fast column-wise access
* \author Philip Cho
*/
#ifndef XGBOOST_COMMON_COLUMN_MATRIX_H_
#define XGBOOST_COMMON_COLUMN_MATRIX_H_
#include <limits>
#include <vector>
#include <memory>
#include "hist_util.h"
namespace xgboost {
namespace common {
class ColumnMatrix;
/*! \brief column type */
enum ColumnType {
kDenseColumn,
kSparseColumn
};
/*! \brief a column storage, to be used with ApplySplit. Note that each
bin id is stored as index[i] + index_base.
Different types of column index for each column allow
to reduce the memory usage. */
template <typename BinIdxType>
class Column {
public:
Column(ColumnType type, common::Span<const BinIdxType> index, const uint32_t index_base)
: type_(type),
index_(index),
index_base_(index_base) {}
uint32_t GetGlobalBinIdx(size_t idx) const {
return index_base_ + static_cast<uint32_t>(index_[idx]);
}
BinIdxType GetFeatureBinIdx(size_t idx) const { return index_[idx]; }
const uint32_t GetBaseIdx() const { return index_base_; }
common::Span<const BinIdxType> GetFeatureBinIdxPtr() const { return index_; }
ColumnType GetType() const { return type_; }
/* returns number of elements in column */
size_t Size() const { return index_.size(); }
private:
/* type of column */
ColumnType type_;
/* bin indexes in range [0, max_bins - 1] */
common::Span<const BinIdxType> index_;
/* bin index offset for specific feature */
const uint32_t index_base_;
};
template <typename BinIdxType>
class SparseColumn: public Column<BinIdxType> {
public:
SparseColumn(ColumnType type, common::Span<const BinIdxType> index,
uint32_t index_base, common::Span<const size_t> row_ind)
: Column<BinIdxType>(type, index, index_base),
row_ind_(row_ind) {}
const size_t* GetRowData() const { return row_ind_.data(); }
size_t GetRowIdx(size_t idx) const {
return row_ind_.data()[idx];
}
private:
/* indexes of rows */
common::Span<const size_t> row_ind_;
};
template <typename BinIdxType>
class DenseColumn: public Column<BinIdxType> {
public:
DenseColumn(ColumnType type, common::Span<const BinIdxType> index,
uint32_t index_base,
const std::vector<bool>::const_iterator missing_flags)
: Column<BinIdxType>(type, index, index_base),
missing_flags_(missing_flags) {}
bool IsMissing(size_t idx) const { return missing_flags_[idx]; }
private:
/* flags for missing values in dense columns */
std::vector<bool>::const_iterator missing_flags_;
};
/*! \brief a collection of columns, with support for construction from
GHistIndexMatrix. */
class ColumnMatrix {
public:
// get number of features
inline bst_uint GetNumFeature() const {
return static_cast<bst_uint>(type_.size());
}
// construct column matrix from GHistIndexMatrix
inline void Init(const GHistIndexMatrix& gmat,
double sparse_threshold) {
const int32_t nfeature = static_cast<int32_t>(gmat.cut.Ptrs().size() - 1);
const size_t nrow = gmat.row_ptr.size() - 1;
// identify type of each column
feature_counts_.resize(nfeature);
type_.resize(nfeature);
std::fill(feature_counts_.begin(), feature_counts_.end(), 0);
uint32_t max_val = std::numeric_limits<uint32_t>::max();
for (int32_t fid = 0; fid < nfeature; ++fid) {
CHECK_LE(gmat.cut.Ptrs()[fid + 1] - gmat.cut.Ptrs()[fid], max_val);
}
bool all_dense = gmat.IsDense();
gmat.GetFeatureCounts(&feature_counts_[0]);
// classify features
for (int32_t fid = 0; fid < nfeature; ++fid) {
if (static_cast<double>(feature_counts_[fid])
< sparse_threshold * nrow) {
type_[fid] = kSparseColumn;
all_dense = false;
} else {
type_[fid] = kDenseColumn;
}
}
// want to compute storage boundary for each feature
// using variants of prefix sum scan
feature_offsets_.resize(nfeature + 1);
size_t accum_index_ = 0;
feature_offsets_[0] = accum_index_;
for (int32_t fid = 1; fid < nfeature + 1; ++fid) {
if (type_[fid - 1] == kDenseColumn) {
accum_index_ += static_cast<size_t>(nrow);
} else {
accum_index_ += feature_counts_[fid - 1];
}
feature_offsets_[fid] = accum_index_;
}
SetTypeSize(gmat.max_num_bins);
index_.resize(feature_offsets_[nfeature] * bins_type_size_, 0);
if (!all_dense) {
row_ind_.resize(feature_offsets_[nfeature]);
}
// store least bin id for each feature
index_base_ = const_cast<uint32_t*>(gmat.cut.Ptrs().data());
const bool noMissingValues = NoMissingValues(gmat.row_ptr[nrow], nrow, nfeature);
if (noMissingValues) {
missing_flags_.resize(feature_offsets_[nfeature], false);
} else {
missing_flags_.resize(feature_offsets_[nfeature], true);
}
// pre-fill index_ for dense columns
if (all_dense) {
BinTypeSize gmat_bin_size = gmat.index.GetBinTypeSize();
if (gmat_bin_size == kUint8BinsTypeSize) {
SetIndexAllDense(gmat.index.data<uint8_t>(), gmat, nrow, nfeature, noMissingValues);
} else if (gmat_bin_size == kUint16BinsTypeSize) {
SetIndexAllDense(gmat.index.data<uint16_t>(), gmat, nrow, nfeature, noMissingValues);
} else {
CHECK_EQ(gmat_bin_size, kUint32BinsTypeSize);
SetIndexAllDense(gmat.index.data<uint32_t>(), gmat, nrow, nfeature, noMissingValues);
}
/* For sparse DMatrix gmat.index.getBinTypeSize() returns always kUint32BinsTypeSize
but for ColumnMatrix we still have a chance to reduce the memory consumption */
} else {
if (bins_type_size_ == kUint8BinsTypeSize) {
SetIndex<uint8_t>(gmat.index.data<uint32_t>(), gmat, nrow, nfeature);
} else if (bins_type_size_ == kUint16BinsTypeSize) {
SetIndex<uint16_t>(gmat.index.data<uint32_t>(), gmat, nrow, nfeature);
} else {
CHECK_EQ(bins_type_size_, kUint32BinsTypeSize);
SetIndex<uint32_t>(gmat.index.data<uint32_t>(), gmat, nrow, nfeature);
}
}
}
/* Set the number of bytes based on numeric limit of maximum number of bins provided by user */
void SetTypeSize(size_t max_num_bins) {
if ( (max_num_bins - 1) <= static_cast<int>(std::numeric_limits<uint8_t>::max()) ) {
bins_type_size_ = kUint8BinsTypeSize;
} else if ((max_num_bins - 1) <= static_cast<int>(std::numeric_limits<uint16_t>::max())) {
bins_type_size_ = kUint16BinsTypeSize;
} else {
bins_type_size_ = kUint32BinsTypeSize;
}
}
/* Fetch an individual column. This code should be used with type swith
to determine type of bin id's */
template <typename BinIdxType>
std::unique_ptr<const Column<BinIdxType> > GetColumn(unsigned fid) const {
CHECK_EQ(sizeof(BinIdxType), bins_type_size_);
const size_t feature_offset = feature_offsets_[fid]; // to get right place for certain feature
const size_t column_size = feature_offsets_[fid + 1] - feature_offset;
common::Span<const BinIdxType> bin_index = { reinterpret_cast<const BinIdxType*>(
&index_[feature_offset * bins_type_size_]),
column_size };
std::unique_ptr<const Column<BinIdxType> > res;
if (type_[fid] == ColumnType::kDenseColumn) {
std::vector<bool>::const_iterator column_iterator = missing_flags_.begin();
advance(column_iterator, feature_offset); // increment iterator to right position
res.reset(new DenseColumn<BinIdxType>(type_[fid], bin_index, index_base_[fid],
column_iterator));
} else {
res.reset(new SparseColumn<BinIdxType>(type_[fid], bin_index, index_base_[fid],
{&row_ind_[feature_offset], column_size}));
}
return res;
}
template<typename T>
inline void SetIndexAllDense(T* index, const GHistIndexMatrix& gmat, const size_t nrow,
const size_t nfeature, const bool noMissingValues) {
T* local_index = reinterpret_cast<T*>(&index_[0]);
/* missing values make sense only for column with type kDenseColumn,
and if no missing values were observed it could be handled much faster. */
if (noMissingValues) {
const int32_t nthread = omp_get_max_threads(); // NOLINT
#pragma omp parallel for num_threads(nthread)
for (omp_ulong rid = 0; rid < nrow; ++rid) {
const size_t ibegin = rid*nfeature;
const size_t iend = (rid+1)*nfeature;
size_t j = 0;
for (size_t i = ibegin; i < iend; ++i, ++j) {
const size_t idx = feature_offsets_[j];
local_index[idx + rid] = index[i];
}
}
} else {
/* to handle rows in all batches, sum of all batch sizes equal to gmat.row_ptr.size() - 1 */
size_t rbegin = 0;
for (const auto &batch : gmat.p_fmat->GetBatches<SparsePage>()) {
const xgboost::Entry* data_ptr = batch.data.HostVector().data();
const std::vector<bst_row_t>& offset_vec = batch.offset.HostVector();
const size_t batch_size = batch.Size();
CHECK_LT(batch_size, offset_vec.size());
for (size_t rid = 0; rid < batch_size; ++rid) {
const size_t size = offset_vec[rid + 1] - offset_vec[rid];
SparsePage::Inst inst = {data_ptr + offset_vec[rid], size};
const size_t ibegin = gmat.row_ptr[rbegin + rid];
const size_t iend = gmat.row_ptr[rbegin + rid + 1];
CHECK_EQ(ibegin + inst.size(), iend);
size_t j = 0;
size_t fid = 0;
for (size_t i = ibegin; i < iend; ++i, ++j) {
fid = inst[j].index;
const size_t idx = feature_offsets_[fid];
/* rbegin allows to store indexes from specific SparsePage batch */
local_index[idx + rbegin + rid] = index[i];
missing_flags_[idx + rbegin + rid] = false;
}
}
rbegin += batch.Size();
}
}
}
template<typename T>
inline void SetIndex(uint32_t* index, const GHistIndexMatrix& gmat,
const size_t nrow, const size_t nfeature) {
std::vector<size_t> num_nonzeros;
num_nonzeros.resize(nfeature);
std::fill(num_nonzeros.begin(), num_nonzeros.end(), 0);
T* local_index = reinterpret_cast<T*>(&index_[0]);
size_t rbegin = 0;
for (const auto &batch : gmat.p_fmat->GetBatches<SparsePage>()) {
const xgboost::Entry* data_ptr = batch.data.HostVector().data();
const std::vector<bst_row_t>& offset_vec = batch.offset.HostVector();
const size_t batch_size = batch.Size();
CHECK_LT(batch_size, offset_vec.size());
for (size_t rid = 0; rid < batch_size; ++rid) {
const size_t ibegin = gmat.row_ptr[rbegin + rid];
const size_t iend = gmat.row_ptr[rbegin + rid + 1];
size_t fid = 0;
const size_t size = offset_vec[rid + 1] - offset_vec[rid];
SparsePage::Inst inst = {data_ptr + offset_vec[rid], size};
CHECK_EQ(ibegin + inst.size(), iend);
size_t j = 0;
for (size_t i = ibegin; i < iend; ++i, ++j) {
const uint32_t bin_id = index[i];
fid = inst[j].index;
if (type_[fid] == kDenseColumn) {
T* begin = &local_index[feature_offsets_[fid]];
begin[rid + rbegin] = bin_id - index_base_[fid];
missing_flags_[feature_offsets_[fid] + rid + rbegin] = false;
} else {
T* begin = &local_index[feature_offsets_[fid]];
begin[num_nonzeros[fid]] = bin_id - index_base_[fid];
row_ind_[feature_offsets_[fid] + num_nonzeros[fid]] = rid + rbegin;
++num_nonzeros[fid];
}
}
}
rbegin += batch.Size();
}
}
const BinTypeSize GetTypeSize() const {
return bins_type_size_;
}
const bool NoMissingValues(const size_t n_elements,
const size_t n_row, const size_t n_features) {
return n_elements == n_features * n_row;
}
private:
std::vector<uint8_t> index_;
std::vector<size_t> feature_counts_;
std::vector<ColumnType> type_;
std::vector<size_t> row_ind_;
/* indicate where each column's index and row_ind is stored. */
std::vector<size_t> feature_offsets_;
// index_base_[fid]: least bin id for feature fid
uint32_t* index_base_;
std::vector<bool> missing_flags_;
BinTypeSize bins_type_size_;
};
} // namespace common
} // namespace xgboost
#endif // XGBOOST_COMMON_COLUMN_MATRIX_H_
|
GB_binop__min_uint8.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__min_uint8
// A.*B function (eWiseMult): GB_AemultB__min_uint8
// A*D function (colscale): GB_AxD__min_uint8
// D*A function (rowscale): GB_DxB__min_uint8
// C+=B function (dense accum): GB_Cdense_accumB__min_uint8
// C+=b function (dense accum): GB_Cdense_accumb__min_uint8
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__min_uint8
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__min_uint8
// C=scalar+B GB_bind1st__min_uint8
// C=scalar+B' GB_bind1st_tran__min_uint8
// C=A+scalar GB_bind2nd__min_uint8
// C=A'+scalar GB_bind2nd_tran__min_uint8
// C type: uint8_t
// A type: uint8_t
// B,b type: uint8_t
// BinaryOp: cij = GB_IMIN (aij, bij)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_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) \
uint8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint8_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = GB_IMIN (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_MIN || GxB_NO_UINT8 || GxB_NO_MIN_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB_Cdense_ewise3_accum__min_uint8
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__min_uint8
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__min_uint8
(
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__min_uint8
(
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 uint8_t
uint8_t bwork = (*((uint8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__min_uint8
(
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
uint8_t *GB_RESTRICT Cx = (uint8_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__min_uint8
(
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
uint8_t *GB_RESTRICT Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__min_uint8
(
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__min_uint8
(
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__min_uint8
(
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
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint8_t bij = Bx [p] ;
Cx [p] = GB_IMIN (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__min_uint8
(
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 ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint8_t aij = Ax [p] ;
Cx [p] = GB_IMIN (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = GB_IMIN (x, aij) ; \
}
GrB_Info GB_bind1st_tran__min_uint8
(
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 \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_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) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = GB_IMIN (aij, y) ; \
}
GrB_Info GB_bind2nd_tran__min_uint8
(
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
uint8_t y = (*((const uint8_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
mxEvaluateVertAverage.c | //
// main.c
// matEvaluateVertAverage
//
// Created by li12242 on 17/11/1.
// Copyright (c) 2017年 li12242. All rights reserved.
//
#include "mex.h"
#define INF 10.0e9
#ifdef _OPENMP
#include <omp.h>
#endif
#define max(a, b) ((a > b) ? a : b)
#define min(a, b) ((a < b) ? a : b)
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
/* check input & output */
if (nrhs != 5){
mexErrMsgIdAndTxt("Matlab:mxEvaluateVertAverage:InvalidNumberInput",
"4 inputs required.");
}
if (nlhs != 2){
mexErrMsgIdAndTxt("Matlab:mxEvaluateVertAverage:InvalidNumberOutput",
"1 output required.");
}
/* get inputs */
//double *cvar = mxGetPr(prhs[0]);
int Nv = (int)mxGetScalar(prhs[1]);
double *NkToV = mxGetPr(prhs[2]); // number of element connecting to each vertex
double *VToM = mxGetPr(prhs[3]);
double *VToK = mxGetPr(prhs[4]);
//double *VToW = mxGetPr(prhs[5]);
/* get dimensions */
size_t maxNk = mxGetM(prhs[3]); // maximum number of cells connecting to one vertex
// size_t K = mxGetN(prhs[2]); // number of elements
/* allocate output array */
plhs[0] = mxCreateDoubleMatrix((mwSize)Nv, (mwSize)1, mxREAL);
plhs[1] = mxCreateDoubleMatrix((mwSize)Nv, (mwSize)1, mxREAL);
double *fvmin = mxGetPr(plhs[0]);
double *fvmax = mxGetPr(plhs[1]);
#ifdef _OPENMP
#pragma omp parallel for num_threads(DG_THREADS)
#endif
for (int n=0; n<Nv; n++) {
int Nk = NkToV[n]; // number of cells connecting to vertex n
fvmax[n] = -INF;
fvmin[n] = INF;
for (int k=0; k<Nk; k++) {
int meshId = (int) VToM[n*maxNk + k] - 1;
int cellId = (int) VToK[n*maxNk + k] - 1;
//double w = VToW[n*maxNk + k];
mxArray *mcvar = mxGetCell(prhs[0], meshId);
if (mcvar == NULL) {
mexErrMsgIdAndTxt("Matlab:mxEvaluateVertAverage:AccessToMeshField",
"Access to the mesh field failed.");
}
double *cvar = mxGetPr(mcvar);
double temp = cvar[cellId];
//fvert[n] += w*temp;
fvmin[n] = min(fvmin[n], temp);
fvmax[n] = max(fvmax[n], temp);
}
}
return;
}
|
expt_sum_prod.c | #include "q_incs.h"
uint64_t num_ops;
extern int
sum_prod(
float **X, /* M vectors of length N */
uint64_t M,
uint64_t N,
double *w, /* vector of length N */
double **A /* M vectors of length M */
);
int
sum_prod(
float **X, /* M vectors of length N */
uint64_t M,
uint64_t N,
double *w, /* vector of length N */
double **A /* M vectors of length M */
)
{
int status = 0;
double *temp = NULL;
temp = malloc(N * sizeof(double));
return_if_malloc_failed(temp);
int block_size = 8192;
num_ops = 0;
uint32_t nT = sysconf(_SC_NPROCESSORS_ONLN);
printf("nT = %d \n", nT);
#pragma omp parallel for
for ( uint64_t i = 0; i < M; i++ ) {
memset(A[i], '\0', M*sizeof(double));
// num_ops += M;
}
for ( uint32_t c = 0; c <= M/nT ; c++ ) { // TODO CHECK
for ( uint64_t i = 0; i < M; i++ ) {
if ( ( i + (c*nT) ) >= M ) { break; }
float *Xi = X[i];
double *Ai = A[i];
#pragma omp simd
for ( uint32_t l = 0; l < N; l++ ) {
temp[l] = Xi[l] * w[l]; // num_ops++;
}
uint32_t j_lb = i + (c*nT);
if ( j_lb >= M ) { break; }
uint32_t j_ub = j_lb + nT;
if ( j_ub > M ) { j_ub = M; }
// printf("c = %d, i = %d, j = [%d, %d]\n", c, i, j_lb, j_ub);
// #pragma omp parallel for schedule (static, 1)
#pragma omp parallel for
for ( uint64_t j = j_lb; j < j_ub; j++ ) {
// printf("%d, %d, %d, %d \n", j, j_lb, j_ub, omp_get_thread_num());
double temp2[2*block_size];
double sum = 0;
float *Xj = X[j];
int num_blocks = N / block_size;
if ( ( num_blocks * block_size ) != (int)N ) { num_blocks++; }
for ( int b = 0; b < num_blocks; b++ ) {
uint64_t lb = b * block_size;
uint64_t ub = lb + block_size;
if ( b == (num_blocks-1) ) { ub = N; }
uint32_t tidx = 0;
#pragma omp simd
for ( uint32_t l = lb; l < ub; l++ ) {
temp2[tidx++] = Xj[l] * temp[l]; // num_ops++;
}
tidx = 0;
#pragma omp simd reduction(+:sum)
for ( tidx = 0; tidx < ub-lb; tidx++ ) {
sum += temp2[tidx]; // num_ops++;
}
}
#pragma omp critical (_sum_prod)
{
Ai[j] = sum;
}
}
}
}
BYE:
free_if_non_null(temp);
return status;
}
int
main(
)
{
int status = 0;
uint64_t N = 128 * 1024;
uint64_t M = 1024;
double **A = NULL;
float **X = NULL;
double *w = NULL;
clock_t start_t, stop_t, total_t;
w = malloc(N * sizeof(double));
for ( int i = 0; i < N; i++ ) {
w[i] = 1.0 /(i+1);
}
X = malloc(M * sizeof(float *));
for ( uint64_t i = 0; i < M; i++ ) {
X[i] = malloc(N * sizeof(float));
}
for ( uint64_t i = 0; i < M; i++ ) {
for ( uint64_t j = 0; j < N; j++ ) {
X[i][j] = (i+j+1);
}
}
A = malloc(M * sizeof(double *));
for ( uint64_t i = 0; i < M; i++ ) {
A[i] = malloc(M * sizeof(double));
}
system("date");
start_t = clock();
status = sum_prod(X, M, N, w, A);
stop_t = clock();
system("date");
fprintf(stderr, "Num clocks = %llu \n", stop_t - start_t);
fprintf(stderr, "Num Ops = %llu \n", (unsigned long long)num_ops);
double chk = 0;
int ii = 2, jj = 2;
for ( unsigned int l = 0; l < N; l++ ) {
chk += (X[ii][l] * X[jj][l] * w[l]);
}
if ( ( ( A[ii][jj] - chk) / chk ) > 0.001 ) {
fprintf(stderr, "chk = %lf, A = %lf \n", chk, A[ii][jj]);
go_BYE(-1);
}
for ( uint64_t i = 0; i < M; i++ ) {
for ( uint64_t j = i; j < M; j++ ) {
if ( A[i][j] == 0 ) { go_BYE(-1);
}
}
for ( uint64_t j = 0; j < i; j++ ) {
if ( A[i][j] != 0 ) { go_BYE(-1);
}
}
}
/* num_ops = 146231168000 */
/* gcc -std=gnu99 -O4 expt_sum_prod.c -I../../../UTILS/inc/ -o a.out -fopenmp -lgomp*/
BYE:
free_if_non_null(w);
for ( uint64_t i = 0; i < M; i++ ) { free_if_non_null(A[i]); }
free_if_non_null(A);
for ( uint64_t i = 0; i < M; i++ ) { free_if_non_null(X[i]); }
free_if_non_null(X);
return status;
}
|
mixed_tentusscher_myo_epi_2004_S2_10.c | // Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium)
// (AP + max:dvdt)
#include <stdio.h>
#include "mixed_tentusscher_myo_epi_2004_S2_10.h"
GET_CELL_MODEL_DATA(init_cell_model_data)
{
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu)
{
static bool first_call = true;
if(first_call)
{
print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n");
first_call = false;
}
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
// Initial conditions for TenTusscher myocardium
if (mapping[sv_id] == 0)
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
// Initial conditions for TenTusscher epicardium
else
{
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.6190487792098,0.00127615275701324,0.780956535094998,0.780847063341448,0.000173448982750495,0.485618885325203,0.00292967767959199,0.999998364838194,1.91717709945144e-08,1.87830179933651e-05,0.999774468479350,1.00704023911659,0.999994520006527,4.64680265082926e-05,0.570657756232895,10.2852308259172,139.261705705374};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu)
{
// Get the mapping array
uint32_t *mapping = NULL;
if(extra_data)
{
mapping = (uint32_t*)extra_data;
}
else
{
print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n");
}
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++)
{
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = (uint32_t )i;
for (int j = 0; j < num_steps; ++j)
{
if (mapping[i] == 0)
solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]);
else
solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_myo(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Myocardium cell
real Gks=0.062;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Myocardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
Irel=A*sd*sg;
Ileak=0.00008f*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
// [!] Myocardium cell
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current)
{
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu_epi(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt)
{
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
// [!] Epicardium cell
real Gks=0.245;
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
// [!] Epicardium cell
real Gto=0.294;
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={14.4075043407048,2.30190614350519e-05,0.000132186955734266,0.000460438593474590,0.230805741240155,0.128769301850520,0.167089340366410,4.76580224949500,0.0120157545262487,1.45704463630229,1089.95375481761,0.000516367300199849,0.468938665984628,0.0163624321716470,0.00234457045494790,4.25912616439814e-05}; GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
//TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
openmp_unlock.c | #include <stdio.h>
#include <omp.h>
int main(){
int data=0;
#pragma omp parallel num_threads(3)
{
for(int i = 0; i < 100; i++){
data = data + 1;
}
}
printf("data = %d.\n", data);
return 0;
} |
bml_allocate_dense_typed.c | #include "../../macros.h"
#include "../../typed.h"
#include "../bml_allocate.h"
#include "../bml_logger.h"
#include "../bml_types.h"
#include "bml_allocate_dense.h"
#include "bml_types_dense.h"
#include "bml_utilities_dense.h"
#ifdef BML_USE_MAGMA
#include "magma_v2.h"
#endif
#include <complex.h>
#include <string.h>
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/** Clear the matrix.
*
* All values are zeroed.
*
* \ingroup allocate_group
*
* \param A The matrix.
*/
void TYPED_FUNC(
bml_clear_dense) (
bml_matrix_dense_t * A)
{
#ifdef BML_USE_MAGMA
MAGMA_T zero = MAGMACOMPLEX(MAKE) (0., 0.);
MAGMABLAS(laset) (MagmaFull, A->N, A->N, zero, zero, A->matrix, A->ld,
A->queue);
#else
memset(A->matrix, 0.0, A->N * A->ld * sizeof(REAL_T));
#endif
}
/** Allocate the zero matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param matrix_dimension The matrix size.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_zero_matrix_dense) (
bml_matrix_dimension_t matrix_dimension,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dense_t *A = NULL;
A = bml_allocate_memory(sizeof(bml_matrix_dense_t));
A->matrix_type = dense;
A->matrix_precision = MATRIX_PRECISION;
A->N = matrix_dimension.N_rows;
A->distribution_mode = distrib_mode;
#ifdef BML_USE_MAGMA
A->ld = magma_roundup(matrix_dimension.N_rows, 32);
int device;
magma_getdevice(&device);
magma_queue_create(device, &A->queue);
magma_int_t ret = MAGMA(malloc) ((MAGMA_T **) & A->matrix,
A->ld * matrix_dimension.N_rows);
assert(ret == MAGMA_SUCCESS);
bml_clear_dense(A);
#else
A->ld = matrix_dimension.N_rows;
A->matrix =
bml_allocate_memory(sizeof(REAL_T) * matrix_dimension.N_rows *
matrix_dimension.N_rows);
#endif
A->domain =
bml_default_domain(matrix_dimension.N_rows, matrix_dimension.N_rows,
distrib_mode);
A->domain2 =
bml_default_domain(matrix_dimension.N_rows, matrix_dimension.N_rows,
distrib_mode);
return A;
}
/** Allocate a banded matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param N The matrix size.
* \param M The bandwidth (the number of non-zero elements per row).
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_banded_matrix_dense) (
int N,
int M,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dimension_t matrix_dimension = { N, N, M };
bml_matrix_dense_t *A =
TYPED_FUNC(bml_zero_matrix_dense) (matrix_dimension, distrib_mode);
#ifdef BML_USE_MAGMA
MAGMA_T *A_dense = bml_allocate_memory(N * N * sizeof(REAL_T));
#else
REAL_T *A_dense = A->matrix;
#endif
#pragma omp parallel for shared(A_dense)
for (int i = 0; i < N; i++)
{
for (int j = (i - M / 2 >= 0 ? i - M / 2 : 0);
j < (i - M / 2 + M <= N ? i - M / 2 + M : N); j++)
{
#ifdef BML_USE_MAGMA
A_dense[ROWMAJOR(i, j, N, N)] =
MAGMACOMPLEX(MAKE) (rand() / (double) RAND_MAX, 0.);
#else
A_dense[ROWMAJOR(i, j, N, N)] = rand() / (double) RAND_MAX;
#endif
}
}
#ifdef BML_USE_MAGMA
MAGMA(setmatrix) (N, N, A_dense, N, A->matrix, A->ld, A->queue);
bml_free_memory(A_dense);
#endif
return A;
}
/** Allocate a random matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param N The matrix size.
* \param distrib_mode The distribution mode.
* \return The matrix.
*
* Note: Do not use OpenMP when setting values for a random matrix,
* this makes the operation non-repeatable.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_random_matrix_dense) (
int N,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dimension_t matrix_dimension = { N, N, N };
bml_matrix_dense_t *A =
TYPED_FUNC(bml_zero_matrix_dense) (matrix_dimension, distrib_mode);
#ifdef BML_USE_MAGMA
MAGMA_T *A_dense = bml_noinit_allocate_memory(N * N * sizeof(REAL_T));
#else
REAL_T *A_dense = A->matrix;
#endif
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
#ifdef BML_USE_MAGMA
A_dense[ROWMAJOR(i, j, N, N)] =
MAGMACOMPLEX(MAKE) (rand() / (double) RAND_MAX, 0.);
#else
A_dense[ROWMAJOR(i, j, N, N)] = rand() / (double) RAND_MAX;
#endif
}
}
#ifdef BML_USE_MAGMA
MAGMA(setmatrix) (N, N, A_dense, N, A->matrix, A->ld, A->queue);
bml_free_memory(A_dense);
#endif
return A;
}
/** Allocate the identity matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param N The matrix size.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_identity_matrix_dense) (
int N,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dimension_t matrix_dimension = { N, N, N };
bml_matrix_dense_t *A =
TYPED_FUNC(bml_zero_matrix_dense) (matrix_dimension, distrib_mode);
#ifdef BML_USE_MAGMA
MAGMA_T *A_dense = bml_allocate_memory(N * N * sizeof(REAL_T));
#else
REAL_T *A_dense = A->matrix;
#endif
#pragma omp parallel for shared(A_dense)
for (int i = 0; i < N; i++)
{
#ifdef BML_USE_MAGMA
A_dense[ROWMAJOR(i, i, N, N)] = MAGMACOMPLEX(MAKE) (1, 0);
#else
A_dense[ROWMAJOR(i, i, N, N)] = 1;
#endif
}
#ifdef BML_USE_MAGMA
MAGMA(setmatrix) (N, N, A_dense, N, A->matrix, A->ld, A->queue);
bml_free_memory(A_dense);
#endif
return A;
}
|
opencl_strip_fmt_plug.c | /* STRIP Password Manager cracker patch for JtR. Hacked together during
* September of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> */
#ifdef HAVE_OPENCL
#if FMT_EXTERNS_H
extern struct fmt_main fmt_opencl_strip;
#elif FMT_REGISTERS_H
john_register_one(&fmt_opencl_strip);
#else
#include <string.h>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "arch.h"
#include "aes.h"
#include "formats.h"
#include "options.h"
#include "common.h"
#include "misc.h"
#include "common-opencl.h"
#define FORMAT_LABEL "strip-opencl"
#define FORMAT_NAME "STRIP Password Manager"
#define FORMAT_TAG "$strip$*"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL"
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define BINARY_SIZE 0
#define PLAINTEXT_LENGTH 64
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 1
#define SALT_ALIGN 4
#define ITERATIONS 4000
#define FILE_HEADER_SZ 16
#define SQLITE_FILE_HEADER "SQLite format 3"
#define HMAC_SALT_MASK 0x3a
#define FAST_PBKDF2_ITER 2
#define SQLITE_MAX_PAGE_SIZE 65536
static struct fmt_tests strip_tests[] = {
/* test vector created by STRIP for Windows */
{"$strip$*66cd7a4ff7716f7b86cf587ce18eb39518e096eb152615ada8d007d9f035c20c711e62cbde96d8c3aad2a4658497a6119addc97ed3c970580cd666f301c63ce041a1748ee5c3861ada3cd6ee75b5d68891f731b3c2e3294b08e10ce3c23c2bfac158f8c45d0332791f64d1e3ad55e936d17a42fef5228e713b8188050c9a61c7f026af6203172cf2fc54c8b439e2260d7a00a4156713f92f8466de5c05cd8701e0d3d9cb3f392ae918e6900d5363886d4e1ed7e90da76b180ef9555c1cd358f6d1ee3755a208fee4d5aa1c776a0888200b21a3da6614d5fe2303e78c09563d862d19deecdc9f0ec7fbc015689a74f4eb477d9f22298b1b3f866ca4cb772d74821a1f8d03fd5fd0d020ffd41dd449b431ddf3bbfba3399311d9827be428202ee56e2c2a4e91f3415b4282c691f16cd447cf877b576ab963ea4ea3dc7d8c433febdc36607fd2372c4165abb59e3e75c28142f1f2575ecca6d97a9f782c3410151f8bbcbc65a42fdc59fdc4ecd8214a2bbd3a4562fac21c48f7fc69a4ecbcf664b4e435d7734fde5494e4d80019a0302e22565ed6a49b29cecf81077fd92f0105d18a421e04ee0deaca6389214abc7182db7003da7e267816531010b236eadfea20509718ff743ed5ad2828b6501dd84a371feed26f0514bbda69118a69048ebb71e3e2c54fb918422f1320724a353fe8d81a562197454d2c67443be8a4008a756aec0998386a5fd48e379befe966b42dfa6684ff049a61b51de5f874a12ab7d9ab33dc84738e036e294c22a07bebcc95be9999ab988a1fa1c944ab95be970045accb661249be8cc34fcc0680cb1aff8dfee21f586c571b1d09bf370c6fc131418201e0414acb2e4005b0b6fda1f3d73b7865823a008d1d3f45492a960dbdd6331d78d9e2e6a368f08ee3456b6d78df1d5630f825c536fff60bad23fb164d151d80a03b0c78edbfdee5c7183d7527e289428cf554ad05c9d75011f6b233744f12cd85fbb62f5d1ae22f43946f24a483a64377bf3fa16bf32cea1ab4363ef36206a5989e97ff847e5d645791571b9ecd1db194119b7663897b9175dd9cc123bcc7192eaf56d4a2779c502700e88c5c20b962943084bcdf024dc4f19ca649a860bdbd8f8f9b4a9d03027ae80f4a3168fc030859acb08a871950b024d27306cdc1a408b2b3799bb8c1f4b6ac3593aab42c962c979cd9e6f59d029f8d392315830cfcf4066bf03e0fc5c0f3630e9c796ddb38f51a2992b0a61d6ef115cb34d36c7d94b6c9d49dfe8d064d92b483f12c14fa10bf1170a575e4571836cef0a1fbf9f8b6968abda5e964bb16fd62fde1d1df0f5ee9c68ce568014f46f1717b6cd948b0da9a6f4128da338960dbbcbc9c9c3b486859c06e5e2338db3458646054ccd59bb940c7fc60cda34f633c26dde83bb717b75fefcbd09163f147d59a6524752a47cd94", "openwall"},
/* test vector created by STRIP Password Manager (for Android) */
{"$strip$*78adb0052203efa1bd1b02cac098cc9af1bf7e84ee2eaebaaba156bdcfe729ab12ee7ba8a84e79d11dbd67eee82bcb24be99dbd5db7f4c3a62f188ce4b48edf4ebf6cbf5a5869a61f83fbdb3cb4bf79b3c2c898f422d71eab31afdf3a8d4e97204dedbe7bd8b5e4c891f4880ca917c8b2f67ca06035e7f8db1fae91c45db6a08adf96ec5ddcb9e60b648acf883a7550ea5b67e2d27623e8de315f29cba48b8b1d1bde62283615ab88293b29ad73ae404a42b13e35a95770a504d81e335c00328a6290e411fa2708a697fab7c2d17ff5d0a3fe508118bb43c3d5e72ef563e0ffd337f559085a1373651ca2b8444f4437d8ac0c19aa0a24b248d1d283062afbc3b4ccc9b1861f59518eba771f1d9707affe0222ff946da7c014265ab4ba1f6417dd22d92e4adf5b7e462588f0a42e061a3dad041cbb312d8862aed3cf490df50b710a695517b0c8771a01f82db09231d392d825f5667012e349d2ed787edf8448bbb1ff548bee3a33392cd209e8b6c1de8202f6527d354c3858b5e93790c4807a8967b4c0321ed3a1d09280921650ac33308bd04f35fb72d12ff64a05300053358c5d018a62841290f600f7df0a7371b6fac9b41133e2509cb90f774d02e7202185b9641d063ed38535afb81590bfd5ad9a90107e4ff6d097ac8f35435f307a727f5021f190fc157956414bfce4818a1e5c6af187485683498dcc1d56c074c534a99125c6cfbf5242087c6b0ae10971b0ff6114a93616e1a346a22fcac4c8f6e5c4a19f049bbc7a02d2a31d39548f12440c36dbb253299a11b630e8fd88e7bfe58545d60dce5e8566a0a190d816cb775bd859b8623a7b076bce82c52e9cff6a2d221f9d3fd888ac30c7e3000ba8ed326881ffe911e27bb8982b56caa9a12065721269976517d2862e4a486b7ed143ee42c6566bba04c41c3371220f4843f26e328c33a5fb8450dadc466202ffc5c49cc95827916771e49e0602c3f8468537a81cf2fa1db34c090fccab6254436c05657cf29c3c415bb22a42adeac7870858bf96039b81c42c3d772509fdbe9a94eaf99ee9c59bac3ea97da31e9feac14ed53a0af5c5ebd2e81e40a5140da4f8a44048d5f414b0ba9bfb8024c7abaf5346fde6368162a045d1196f81d55ed746cc6cbd7a7c9cdbfa392279169626437da15a62730c2990772e106a5b84a60edaa6c5b8030e1840aa6361f39a12121a1e33b9e63fb2867d6241de1fb6e2cd1bd9a78c7122258d052ea53a4bff4e097ed49fc17b9ec196780f4c6506e74a5abb10c2545e6f7608d2eefad179d54ad31034576be517affeb3964c65562538dd6ea7566a52c75e4df593895539609a44097cb6d31f438e8f7717ce2bf777c76c22d60b15affeb89f08084e8f316be3f4aefa4fba8ec2cc1dc845c7affbc0ce5ebccdbfde5ebab080a285f02bdfb76c6dbd243e5ee1e5d", "p@$$w0rD"},
{NULL}
};
typedef struct {
uint32_t length;
uint8_t v[PLAINTEXT_LENGTH];
} strip_password;
typedef struct {
uint32_t v[32/4];
} strip_hash;
typedef struct {
uint32_t iterations;
uint32_t outlen;
uint32_t skip_bytes;
uint8_t length;
uint8_t salt[64];
} strip_salt;
static int *cracked;
static int any_cracked;
static struct custom_salt {
unsigned char salt[16];
unsigned char data[1024];
} *cur_salt;
static cl_int cl_error;
static strip_password *inbuffer;
static strip_hash *outbuffer;
static strip_salt currentsalt;
static cl_mem mem_in, mem_out, mem_setting;
static struct fmt_main *self;
static size_t insize, outsize, settingsize, cracked_size;
#define STEP 0
#define SEED 256
// This file contains auto-tuning routine(s). Has to be included after formats definitions.
#include "opencl_autotune.h"
#include "memdbg.h"
static const char * warn[] = {
"xfer: ", ", crypt: ", ", xfer: "
};
/* ------- Helper functions ------- */
static size_t get_task_max_work_group_size()
{
return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel);
}
static void create_clobj(size_t gws, struct fmt_main *self)
{
insize = sizeof(strip_password) * gws;
outsize = sizeof(strip_hash) * gws;
settingsize = sizeof(strip_salt);
cracked_size = sizeof(*cracked) * gws;
inbuffer = mem_calloc(1, insize);
outbuffer = mem_alloc(outsize);
cracked = mem_calloc(1, cracked_size);
/// Allocate memory
mem_in =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL,
&cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem in");
mem_setting =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize,
NULL, &cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem setting");
mem_out =
clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL,
&cl_error);
HANDLE_CLERROR(cl_error, "Error allocating mem out");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in),
&mem_in), "Error while setting mem_in kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out),
&mem_out), "Error while setting mem_out kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting),
&mem_setting), "Error while setting mem_salt kernel argument");
}
static void release_clobj(void)
{
if (inbuffer) {
HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in");
HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting");
HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out");
MEM_FREE(inbuffer);
MEM_FREE(outbuffer);
MEM_FREE(cracked);
}
}
static void done(void)
{
if (autotuned) {
release_clobj();
HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel");
HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program");
autotuned--;
}
}
static void init(struct fmt_main *_self)
{
self = _self;
opencl_prepare_dev(gpu_id);
}
static void reset(struct db_main *db)
{
if (!autotuned) {
char build_opts[64];
snprintf(build_opts, sizeof(build_opts),
"-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d",
PLAINTEXT_LENGTH,
(int)sizeof(currentsalt.salt),
(int)sizeof(outbuffer->v));
opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl",
gpu_id, build_opts);
crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error);
HANDLE_CLERROR(cl_error, "Error creating kernel");
// Initialize openCL tuning (library) for this format.
opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self,
create_clobj, release_clobj,
sizeof(strip_password), 0, db);
// Auto tune execution from shared/included code.
autotune_run(self, 1, 0, 1000);
}
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy;
char *keeptr;
char *p;
int extra;
if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN))
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += FORMAT_TAG_LEN; /* skip over "$strip$" and first '*' */
if ((p = strtokm(ctcopy, "*")) == NULL) /* salt + data */
goto err;
if (hexlenl(p, &extra) != 2048 || extra)
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *p;
int i;
static struct custom_salt *cs;
if (!cs)
cs = mem_alloc_tiny(sizeof(struct custom_salt), 4);
memset(cs, 0, sizeof(struct custom_salt));
ctcopy += FORMAT_TAG_LEN; /* skip over "$strip$" and first '*' */
p = strtokm(ctcopy, "*");
for (i = 0; i < 16; i++)
cs->salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
for (; i < 1024; i++)
cs->data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
return (void *)cs;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
memcpy((char*)currentsalt.salt, cur_salt->salt, 16);
currentsalt.length = 16;
currentsalt.iterations = ITERATIONS;
currentsalt.outlen = 32;
currentsalt.skip_bytes = 0;
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting,
CL_FALSE, 0, settingsize, ¤tsalt, 0, NULL, NULL),
"Copy salt to gpu");
}
#undef set_key
static void set_key(char *key, int index)
{
uint8_t length = strlen(key);
if (length > PLAINTEXT_LENGTH)
length = PLAINTEXT_LENGTH;
inbuffer[index].length = length;
memcpy(inbuffer[index].v, key, length);
}
static char *get_key(int index)
{
static char ret[PLAINTEXT_LENGTH + 1];
uint8_t length = inbuffer[index].length;
memcpy(ret, inbuffer[index].v, length);
ret[length] = '\0';
return ret;
}
/* verify validity of page */
static int verify_page(unsigned char *page1)
{
uint32_t pageSize;
uint32_t usableSize;
//if (memcmp(page1, SQLITE_FILE_HEADER, 16) != 0) {
// return -1;
//}
if (page1[19] > 2) {
return -1;
}
if (memcmp(&page1[21], "\100\040\040", 3) != 0) {
return -1;
}
pageSize = (page1[16] << 8) | (page1[17] << 16);
if (((pageSize - 1) & pageSize) != 0 || pageSize > SQLITE_MAX_PAGE_SIZE || pageSize <= 256) {
return -1;
}
if ((pageSize & 7) != 0) {
return -1;
}
usableSize = pageSize - page1[20];
if (usableSize < 480) {
return -1;
}
return 0;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index;
size_t *lws = local_work_size ? &local_work_size : NULL;
global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size);
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
/// Copy data to gpu
BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0,
insize, inbuffer, 0, NULL, multi_profilingEvent[0]),
"Copy data to gpu");
/// Run kernel
BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1,
NULL, &global_work_size, lws, 0, NULL,
multi_profilingEvent[1]), "Run kernel");
/// Read the result back
BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0,
outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back");
if (ocl_autotune_running)
return count;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
{
unsigned char master[32];
unsigned char output[24];
unsigned char *iv_in;
unsigned char iv_out[16];
int size;
int page_sz = 1008; /* 1024 - strlen(SQLITE_FILE_HEADER) */
int reserve_sz = 16; /* for HMAC off case */
AES_KEY akey;
memcpy(master, outbuffer[index].v, 32);
//memcpy(output, SQLITE_FILE_HEADER, FILE_HEADER_SZ);
size = page_sz - reserve_sz;
iv_in = cur_salt->data + size + 16;
memcpy(iv_out, iv_in, 16);
AES_set_decrypt_key(master, 256, &akey);
/*
* decrypting 8 bytes from offset 16 is enough since the
* verify_page function looks at output[16..23] only.
*/
AES_cbc_encrypt(cur_salt->data + 16, output + 16, 8, &akey, iv_out, AES_DECRYPT);
if (verify_page(output) == 0)
{
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
struct fmt_main fmt_opencl_strip = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT | FMT_HUGE_INPUT,
{ NULL },
{ FORMAT_TAG },
strip_tests
}, {
init,
done,
reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
#endif /* HAVE_OPENCL */
|
GB_unop__identity_fc64_int64.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_fc64_int64)
// op(A') function: GB (_unop_tran__identity_fc64_int64)
// C type: GxB_FC64_t
// A type: int64_t
// cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
GxB_FC64_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) \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \
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_FC64 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fc64_int64)
(
GxB_FC64_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 ;
// TODO: if OP is ONE and uniform-valued matrices are exploited, then
// do this in O(1) time
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (int64_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
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 ;
int64_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fc64_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
|
ndvi.c | #include<stdio.h>
#include "gdal.h"
#include<omp.h>
/* MODLAND QA Bits 500m long int bits[0-1]
* 00 -> class 0: Corrected product produced at ideal quality -- all bands
* 01 -> class 1: Corrected product produced at less than idel quality -- some or all bands
* 10 -> class 2: Corrected product NOT produced due to cloud effect -- all bands
* 11 -> class 3: Corrected product NOT produced due to other reasons -- some or all bands mayb be fill value (Note that a value of [11] overrides a value of [01])
*/
unsigned int mod09GQa(unsigned int pixel)
{
/* Select bit 0 and 1 (right-side).
* hexadecimal "0x03" => binary "11"
* this will set all other bits to null */
return (pixel & 0x03);
}
/* Band-wise Data Quality 500m long Int
* bits[2-5][6-9][10-13][14-17][18-21][22-25][26-29]
* 0000 -> class 0: highest quality
* 0111 -> class 1: noisy detector
* 1000 -> class 2: dead detector; data interpolated in L1B
* 1001 -> class 3: solar zenith >= 86 degrees
* 1010 -> class 4: solar zenith >= 85 and < 86 degrees
* 1011 -> class 5: missing input
* 1100 -> class 6: internal constant used in place of climatological data for at least one atmospheric constant
* 1101 -> class 7: correction out of bounds, pixel constrained to extreme allowable value
* 1110 -> class 8: L1B data faulty
* 1111 -> class 9: not processed due to deep ocean or cloud
* Class 10-15: Combination of bits unused
*/
unsigned int mod09GQc(unsigned int pixel, int bandno)
{
unsigned int qctemp;
pixel >>= 4 + (4 * (bandno - 1)); /* bitshift [] to [0-3] etc. */
qctemp = pixel & 0x0F;
return qctemp;
}
void usage()
{
printf( "-----------------------------------------\n");
printf( "--Modis Processing chain--Serial code----\n");
printf( "-----------------------------------------\n");
printf( "./ndvi inB1 inB2 inQC inB3\n");
printf( "\toutNDVI\n");
printf( "-----------------------------------------\n");
printf( "inB1/B2\t\tModis MOD09GQ B1 B2 250m\n");
printf( "inQC\t\tModis MOD09GQ QC 250m\n");
printf( "inB3\t\tModis MOD09GA B3 QC corrected 250m\n");
printf( "outNDVI\tQA corrected NDVI 250m output [-]\n");
return;
}
int main( int argc, char *argv[] )
{
if( argc < 5 ) {
//usage();
return 1;
}
char *inB1 = argv[1]; //B1 250m
char *inB2 = argv[2]; //B2 250m
char *inQC = argv[3]; //QC 250m
char *inB3 = argv[4]; //B3 500m
char *ndviF = argv[5];
GDALAllRegister();
GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//B1
GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//B2
GDALDatasetH hDQC = GDALOpen(inQC,GA_ReadOnly);//QC
GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//B3 500m
if(hD1==NULL||hD2==NULL||hDQC==NULL||hD3==NULL){
printf("One or more input files ");
printf("could not be loaded\n");
exit(1);
}
GDALDriverH hDr1 = GDALGetDatasetDriver(hD1);
char **options = NULL;
options = CSLSetNameValue( options, "TILED", "YES" );
options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" );
options = CSLSetNameValue( options, "PREDICTOR", "2" );
GDALDatasetH hDOut = GDALCreateCopy(hDr1,ndviF,hD1,FALSE,options,NULL,NULL);
GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1);
GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//B1
GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//B2
GDALRasterBandH hBQC = GDALGetRasterBand(hDQC,1);//QC
GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//B3 500m
int nX = GDALGetRasterBandXSize(hB1);
int nY = GDALGetRasterBandYSize(hB1);
int N = nX*nY;
float *l1 = (float *) malloc(sizeof(float)*N);
float *l2 = (float *) malloc(sizeof(float)*N);
int *lQC = (int *) malloc(sizeof(int)*N);
float *l3 = (float *) malloc(sizeof(float)*N);
float *lOut = (float *) malloc(sizeof(float)*N);
int rowcol, qa, qa1, qa2;
GDALRasterIO(hB1,GF_Read,0,0,nX,nY,l1,nX,nY,GDT_Float32,0,0);
GDALRasterIO(hB2,GF_Read,0,0,nX,nY,l2,nX,nY,GDT_Float32,0,0);
GDALRasterIO(hBQC,GF_Read,0,0,nX,nY,lQC,nX,nY,GDT_Int32,0,0);
GDALRasterIO(hB3,GF_Read,0,0,nX/2,nY/2,l3,nX,nY,GDT_Float32,0,0);
#pragma omp parallel for default(none) \
private (rowcol,qa,qa1,qa2) shared (N, l1, l2, lQC, l3, lOut)
for(rowcol=0;rowcol<N;rowcol++){
qa=mod09GQa(lQC[rowcol]);
qa1=mod09GQc(lQC[rowcol],1);
qa2=mod09GQc(lQC[rowcol],2);
if( qa == 0 && qa1 == 0 && qa2 == 0 && l3[rowcol] > 0.18 && (l1[rowcol]+l2[rowcol]) != 0.0)
lOut[rowcol] = 1000*(l2[rowcol]-l1[rowcol])/(l2[rowcol]+l1[rowcol]);
else lOut[rowcol] = -28672;
}
#pragma omp barrier
GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,lOut,nX,nY,GDT_Float32,0,0);
if( l1 != NULL ) free( l1 );
if( l2 != NULL ) free( l2 );
if( lQC != NULL ) free( lQC );
if( l3 != NULL ) free( l3 );
GDALClose(hD1);
GDALClose(hD2);
GDALClose(hDQC);
GDALClose(hD3);
GDALClose(hDOut);
return(EXIT_SUCCESS);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.