source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
mandatory_but_no_devices.c | // Check that mandatory offloading causes various offloading directives to fail
// when omp_get_num_devices() == 0 even if the requested device is the initial
// device. This behavior is proposed for OpenMP 5.2 in OpenMP spec github
// issue 2669.
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda -DDIR=target
// RUN: env OMP_TARGET_OFFLOAD=mandatory CUDA_VISIBLE_DEVICES= \
// RUN: %libomptarget-run-fail-nvptx64-nvidia-cuda 2>&1 | \
// RUN: %fcheck-nvptx64-nvidia-cuda
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda -DDIR='target teams'
// RUN: env OMP_TARGET_OFFLOAD=mandatory CUDA_VISIBLE_DEVICES= \
// RUN: %libomptarget-run-fail-nvptx64-nvidia-cuda 2>&1 | \
// RUN: %fcheck-nvptx64-nvidia-cuda
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda -DDIR='target data map(X)'
// RUN: env OMP_TARGET_OFFLOAD=mandatory CUDA_VISIBLE_DEVICES= \
// RUN: %libomptarget-run-fail-nvptx64-nvidia-cuda 2>&1 | \
// RUN: %fcheck-nvptx64-nvidia-cuda
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda \
// RUN: -DDIR='target enter data map(to:X)'
// RUN: env OMP_TARGET_OFFLOAD=mandatory CUDA_VISIBLE_DEVICES= \
// RUN: %libomptarget-run-fail-nvptx64-nvidia-cuda 2>&1 | \
// RUN: %fcheck-nvptx64-nvidia-cuda
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda \
// RUN: -DDIR='target exit data map(from:X)'
// RUN: env OMP_TARGET_OFFLOAD=mandatory CUDA_VISIBLE_DEVICES= \
// RUN: %libomptarget-run-fail-nvptx64-nvidia-cuda 2>&1 | \
// RUN: %fcheck-nvptx64-nvidia-cuda
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda \
// RUN: -DDIR='target update to(X)'
// RUN: env OMP_TARGET_OFFLOAD=mandatory CUDA_VISIBLE_DEVICES= \
// RUN: %libomptarget-run-fail-nvptx64-nvidia-cuda 2>&1 | \
// RUN: %fcheck-nvptx64-nvidia-cuda
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda \
// RUN: -DDIR='target update from(X)'
// RUN: env OMP_TARGET_OFFLOAD=mandatory CUDA_VISIBLE_DEVICES= \
// RUN: %libomptarget-run-fail-nvptx64-nvidia-cuda 2>&1 | \
// RUN: %fcheck-nvptx64-nvidia-cuda
#include <omp.h>
#include <stdio.h>
// CHECK: Libomptarget fatal error 1: failure of target construct while offloading is mandatory
int main(void) {
int X;
#pragma omp DIR device(omp_get_initial_device())
;
return 0;
}
|
detector.c | #include "darknet.h"
static int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90};
void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear)
{
list *options = read_data_cfg(datacfg);
char *train_images = option_find_str(options, "train", "data/train.list");
char *backup_directory = option_find_str(options, "backup", "/backup/");
srand(time(0));
char *base = basecfg(cfgfile);
printf("%s\n", base);
float avg_loss = -1;
network **nets = calloc(ngpus, sizeof(network));
srand(time(0));
int seed = rand();
int i;
for(i = 0; i < ngpus; ++i){
srand(seed);
#ifdef GPU
cuda_set_device(gpus[i]);
#endif
nets[i] = load_network(cfgfile, weightfile, clear);
nets[i]->learning_rate *= ngpus;
}
srand(time(0));
network *net = nets[0];
int imgs = net->batch * net->subdivisions * ngpus;
printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
data train, buffer;
layer l = net->layers[net->n - 1];
int classes = l.classes;
float jitter = l.jitter;
list *plist = get_paths(train_images);
//int N = plist->size;
char **paths = (char **)list_to_array(plist);
load_args args = get_base_args(net);
args.coords = l.coords;
args.paths = paths;
args.n = imgs;
args.m = plist->size;
args.classes = classes;
args.jitter = jitter;
args.num_boxes = l.max_boxes;
args.d = &buffer;
args.type = DETECTION_DATA;
//args.type = INSTANCE_DATA;
args.threads = 64;
pthread_t load_thread = load_data(args);
double time;
int count = 0;
//while(i*imgs < N*120){
while(get_current_batch(net) < net->max_batches){
if(l.random && count++%10 == 0){
printf("Resizing\n");
int dim = (rand() % 10 + 10) * 32;
if (get_current_batch(net)+200 > net->max_batches) dim = 608;
//int dim = (rand() % 4 + 16) * 32;
printf("%d\n", dim);
args.w = dim;
args.h = dim;
pthread_join(load_thread, 0);
train = buffer;
free_data(train);
load_thread = load_data(args);
#pragma omp parallel for
for(i = 0; i < ngpus; ++i){
resize_network(nets[i], dim, dim);
}
net = nets[0];
}
time=what_time_is_it_now();
pthread_join(load_thread, 0);
train = buffer;
load_thread = load_data(args);
/*
int k;
for(k = 0; k < l.max_boxes; ++k){
box b = float_to_box(train.y.vals[10] + 1 + k*5);
if(!b.x) break;
printf("loaded: %f %f %f %f\n", b.x, b.y, b.w, b.h);
}
*/
/*
int zz;
for(zz = 0; zz < train.X.cols; ++zz){
image im = float_to_image(net->w, net->h, 3, train.X.vals[zz]);
int k;
for(k = 0; k < l.max_boxes; ++k){
box b = float_to_box(train.y.vals[zz] + k*5, 1);
printf("%f %f %f %f\n", b.x, b.y, b.w, b.h);
draw_bbox(im, b, 1, 1,0,0);
}
show_image(im, "truth11");
cvWaitKey(0);
save_image(im, "truth11");
}
*/
printf("Loaded: %lf seconds\n", what_time_is_it_now()-time);
time=what_time_is_it_now();
float loss = 0;
#ifdef GPU
if(ngpus == 1){
loss = train_network(net, train);
} else {
loss = train_networks(nets, ngpus, train, 4);
}
#else
loss = train_network(net, train);
#endif
if (avg_loss < 0) avg_loss = loss;
avg_loss = avg_loss*.9 + loss*.1;
i = get_current_batch(net);
printf("%ld: %f, %f avg, %f rate, %lf seconds, %d images\n", get_current_batch(net), loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, i*imgs);
if(i%100==0){
#ifdef GPU
if(ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
char buff[256];
sprintf(buff, "%s/%s.backup", backup_directory, base);
save_weights(net, buff);
}
if(i%10000==0 || (i < 1000 && i%100 == 0)){
#ifdef GPU
if(ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
char buff[256];
sprintf(buff, "%s/%s_%d.weights", backup_directory, base, i);
save_weights(net, buff);
}
free_data(train);
}
#ifdef GPU
if(ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
char buff[256];
sprintf(buff, "%s/%s_final.weights", backup_directory, base);
save_weights(net, buff);
}
static int get_coco_image_id(char *filename)
{
char *p = strrchr(filename, '/');
char *c = strrchr(filename, '_');
if(c) p = c;
return atoi(p+1);
}
static void print_cocos(FILE *fp, char *image_path, detection *dets, int num_boxes, int classes, int w, int h)
{
int i, j;
int image_id = get_coco_image_id(image_path);
for(i = 0; i < num_boxes; ++i){
float xmin = dets[i].bbox.x - dets[i].bbox.w/2.;
float xmax = dets[i].bbox.x + dets[i].bbox.w/2.;
float ymin = dets[i].bbox.y - dets[i].bbox.h/2.;
float ymax = dets[i].bbox.y + dets[i].bbox.h/2.;
if (xmin < 0) xmin = 0;
if (ymin < 0) ymin = 0;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
float bx = xmin;
float by = ymin;
float bw = xmax - xmin;
float bh = ymax - ymin;
for(j = 0; j < classes; ++j){
if (dets[i].prob[j]) fprintf(fp, "{\"image_id\":%d, \"category_id\":%d, \"bbox\":[%f, %f, %f, %f], \"score\":%f},\n", image_id, coco_ids[j], bx, by, bw, bh, dets[i].prob[j]);
}
}
}
void print_detector_detections(FILE **fps, char *id, detection *dets, int total, int classes, int w, int h)
{
int i, j;
for(i = 0; i < total; ++i){
float xmin = dets[i].bbox.x - dets[i].bbox.w/2. + 1;
float xmax = dets[i].bbox.x + dets[i].bbox.w/2. + 1;
float ymin = dets[i].bbox.y - dets[i].bbox.h/2. + 1;
float ymax = dets[i].bbox.y + dets[i].bbox.h/2. + 1;
if (xmin < 1) xmin = 1;
if (ymin < 1) ymin = 1;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
for(j = 0; j < classes; ++j){
if (dets[i].prob[j]) fprintf(fps[j], "%s %f %f %f %f %f\n", id, dets[i].prob[j],
xmin, ymin, xmax, ymax);
}
}
}
void print_imagenet_detections(FILE *fp, int id, detection *dets, int total, int classes, int w, int h)
{
int i, j;
for(i = 0; i < total; ++i){
float xmin = dets[i].bbox.x - dets[i].bbox.w/2.;
float xmax = dets[i].bbox.x + dets[i].bbox.w/2.;
float ymin = dets[i].bbox.y - dets[i].bbox.h/2.;
float ymax = dets[i].bbox.y + dets[i].bbox.h/2.;
if (xmin < 0) xmin = 0;
if (ymin < 0) ymin = 0;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
for(j = 0; j < classes; ++j){
int class = j;
if (dets[i].prob[class]) fprintf(fp, "%d %d %f %f %f %f %f\n", id, j+1, dets[i].prob[class],
xmin, ymin, xmax, ymax);
}
}
}
void validate_detector_flip(char *datacfg, char *cfgfile, char *weightfile, char *outfile)
{
int j;
list *options = read_data_cfg(datacfg);
char *valid_images = option_find_str(options, "valid", "data/train.list");
char *name_list = option_find_str(options, "names", "data/names.list");
char *prefix = option_find_str(options, "results", "results");
char **names = get_labels(name_list);
char *mapf = option_find_str(options, "map", 0);
int *map = 0;
if (mapf) map = read_map(mapf);
network *net = load_network(cfgfile, weightfile, 0);
set_batch_network(net, 2);
fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
srand(time(0));
list *plist = get_paths(valid_images);
char **paths = (char **)list_to_array(plist);
layer l = net->layers[net->n-1];
int classes = l.classes;
char buff[1024];
char *type = option_find_str(options, "eval", "voc");
FILE *fp = 0;
FILE **fps = 0;
int coco = 0;
int imagenet = 0;
if(0==strcmp(type, "coco")){
if(!outfile) outfile = "coco_results";
snprintf(buff, 1024, "%s/%s.json", prefix, outfile);
fp = fopen(buff, "w");
fprintf(fp, "[\n");
coco = 1;
} else if(0==strcmp(type, "imagenet")){
if(!outfile) outfile = "imagenet-detection";
snprintf(buff, 1024, "%s/%s.txt", prefix, outfile);
fp = fopen(buff, "w");
imagenet = 1;
classes = 200;
} else {
if(!outfile) outfile = "comp4_det_test_";
fps = calloc(classes, sizeof(FILE *));
for(j = 0; j < classes; ++j){
snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]);
fps[j] = fopen(buff, "w");
}
}
int m = plist->size;
int i=0;
int t;
float thresh = .005;
float nms = .45;
int nthreads = 4;
image *val = calloc(nthreads, sizeof(image));
image *val_resized = calloc(nthreads, sizeof(image));
image *buf = calloc(nthreads, sizeof(image));
image *buf_resized = calloc(nthreads, sizeof(image));
pthread_t *thr = calloc(nthreads, sizeof(pthread_t));
image input = make_image(net->w, net->h, net->c*2);
load_args args = {0};
args.w = net->w;
args.h = net->h;
//args.type = IMAGE_DATA;
args.type = LETTERBOX_DATA;
for(t = 0; t < nthreads; ++t){
args.path = paths[i+t];
args.im = &buf[t];
args.resized = &buf_resized[t];
thr[t] = load_data_in_thread(args);
}
double start = what_time_is_it_now();
for(i = nthreads; i < m+nthreads; i += nthreads){
fprintf(stderr, "%d\n", i);
for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
pthread_join(thr[t], 0);
val[t] = buf[t];
val_resized[t] = buf_resized[t];
}
for(t = 0; t < nthreads && i+t < m; ++t){
args.path = paths[i+t];
args.im = &buf[t];
args.resized = &buf_resized[t];
thr[t] = load_data_in_thread(args);
}
for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
char *path = paths[i+t-nthreads];
char *id = basecfg(path);
copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data, 1);
flip_image(val_resized[t]);
copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data + net->w*net->h*net->c, 1);
network_predict(net, input.data);
int w = val[t].w;
int h = val[t].h;
int num = 0;
detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &num);
if (nms) do_nms_sort(dets, num, classes, nms);
if (coco){
print_cocos(fp, path, dets, num, classes, w, h);
} else if (imagenet){
print_imagenet_detections(fp, i+t-nthreads+1, dets, num, classes, w, h);
} else {
print_detector_detections(fps, id, dets, num, classes, w, h);
}
free_detections(dets, num);
free(id);
free_image(val[t]);
free_image(val_resized[t]);
}
}
for(j = 0; j < classes; ++j){
if(fps) fclose(fps[j]);
}
if(coco){
fseek(fp, -2, SEEK_CUR);
fprintf(fp, "\n]\n");
fclose(fp);
}
fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start);
}
void validate_detector(char *datacfg, char *cfgfile, char *weightfile, char *outfile)
{
int j;
list *options = read_data_cfg(datacfg);
char *valid_images = option_find_str(options, "valid", "data/train.list");
char *name_list = option_find_str(options, "names", "data/names.list");
char *prefix = option_find_str(options, "results", "results");
char **names = get_labels(name_list);
char *mapf = option_find_str(options, "map", 0);
int *map = 0;
if (mapf) map = read_map(mapf);
network *net = load_network(cfgfile, weightfile, 0);
set_batch_network(net, 1);
fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
srand(time(0));
list *plist = get_paths(valid_images);
char **paths = (char **)list_to_array(plist);
layer l = net->layers[net->n-1];
int classes = l.classes;
char buff[1024];
char *type = option_find_str(options, "eval", "voc");
FILE *fp = 0;
FILE **fps = 0;
int coco = 0;
int imagenet = 0;
if(0==strcmp(type, "coco")){
if(!outfile) outfile = "coco_results";
snprintf(buff, 1024, "%s/%s.json", prefix, outfile);
fp = fopen(buff, "w");
fprintf(fp, "[\n");
coco = 1;
} else if(0==strcmp(type, "imagenet")){
if(!outfile) outfile = "imagenet-detection";
snprintf(buff, 1024, "%s/%s.txt", prefix, outfile);
fp = fopen(buff, "w");
imagenet = 1;
classes = 200;
} else {
if(!outfile) outfile = "comp4_det_test_";
fps = calloc(classes, sizeof(FILE *));
for(j = 0; j < classes; ++j){
snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]);
fps[j] = fopen(buff, "w");
}
}
int m = plist->size;
int i=0;
int t;
float thresh = .005;
float nms = .45;
int nthreads = 4;
image *val = calloc(nthreads, sizeof(image));
image *val_resized = calloc(nthreads, sizeof(image));
image *buf = calloc(nthreads, sizeof(image));
image *buf_resized = calloc(nthreads, sizeof(image));
pthread_t *thr = calloc(nthreads, sizeof(pthread_t));
load_args args = {0};
args.w = net->w;
args.h = net->h;
//args.type = IMAGE_DATA;
args.type = LETTERBOX_DATA;
for(t = 0; t < nthreads; ++t){
args.path = paths[i+t];
args.im = &buf[t];
args.resized = &buf_resized[t];
thr[t] = load_data_in_thread(args);
}
double start = what_time_is_it_now();
for(i = nthreads; i < m+nthreads; i += nthreads){
fprintf(stderr, "%d\n", i);
for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
pthread_join(thr[t], 0);
val[t] = buf[t];
val_resized[t] = buf_resized[t];
}
for(t = 0; t < nthreads && i+t < m; ++t){
args.path = paths[i+t];
args.im = &buf[t];
args.resized = &buf_resized[t];
thr[t] = load_data_in_thread(args);
}
for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
char *path = paths[i+t-nthreads];
char *id = basecfg(path);
float *X = val_resized[t].data;
network_predict(net, X);
int w = val[t].w;
int h = val[t].h;
int nboxes = 0;
detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &nboxes);
if (nms) do_nms_sort(dets, nboxes, classes, nms);
if (coco){
print_cocos(fp, path, dets, nboxes, classes, w, h);
} else if (imagenet){
print_imagenet_detections(fp, i+t-nthreads+1, dets, nboxes, classes, w, h);
} else {
print_detector_detections(fps, id, dets, nboxes, classes, w, h);
}
free_detections(dets, nboxes);
free(id);
free_image(val[t]);
free_image(val_resized[t]);
}
}
for(j = 0; j < classes; ++j){
if(fps) fclose(fps[j]);
}
if(coco){
fseek(fp, -2, SEEK_CUR);
fprintf(fp, "\n]\n");
fclose(fp);
}
fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start);
}
void validate_detector_recall(char *cfgfile, char *weightfile)
{
network *net = load_network(cfgfile, weightfile, 0);
set_batch_network(net, 1);
fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
srand(time(0));
list *plist = get_paths("data/coco_val_5k.list");
char **paths = (char **)list_to_array(plist);
layer l = net->layers[net->n-1];
int j, k;
int m = plist->size;
int i=0;
float thresh = .001;
float iou_thresh = .5;
float nms = .4;
int total = 0;
int correct = 0;
int proposals = 0;
float avg_iou = 0;
for(i = 0; i < m; ++i){
char *path = paths[i];
image orig = load_image_color(path, 0, 0);
image sized = resize_image(orig, net->w, net->h);
char *id = basecfg(path);
network_predict(net, sized.data);
int nboxes = 0;
detection *dets = get_network_boxes(net, sized.w, sized.h, thresh, .5, 0, 1, &nboxes);
if (nms) do_nms_obj(dets, nboxes, 1, nms);
char labelpath[4096];
find_replace(path, "images", "labels", labelpath);
find_replace(labelpath, "JPEGImages", "labels", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
int num_labels = 0;
box_label *truth = read_boxes(labelpath, &num_labels);
for(k = 0; k < nboxes; ++k){
if(dets[k].objectness > thresh){
++proposals;
}
}
for (j = 0; j < num_labels; ++j) {
++total;
box t = {truth[j].x, truth[j].y, truth[j].w, truth[j].h};
float best_iou = 0;
for(k = 0; k < l.w*l.h*l.n; ++k){
float iou = box_iou(dets[k].bbox, t);
if(dets[k].objectness > thresh && iou > best_iou){
best_iou = iou;
}
}
avg_iou += best_iou;
if(best_iou > iou_thresh){
++correct;
}
}
fprintf(stderr, "%5d %5d %5d\tRPs/Img: %.2f\tIOU: %.2f%%\tRecall:%.2f%%\n", i, correct, total, (float)proposals/(i+1), avg_iou*100/total, 100.*correct/total);
free(id);
free_image(orig);
free_image(sized);
}
}
void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh, char *outfile, int fullscreen)
{
list *options = read_data_cfg(datacfg);
char *name_list = option_find_str(options, "names", "data/names.list");
char **names = get_labels(name_list);
image **alphabet = load_alphabet();
network *net = load_network(cfgfile, weightfile, 0);
set_batch_network(net, 1);
srand(2222222);
double time;
char buff[256];
char *input = buff;
float nms=.45;
while(1){
if(filename){
strncpy(input, filename, 256);
} else {
printf("Enter Image Path: ");
fflush(stdout);
input = fgets(input, 256, stdin);
if(!input) return;
strtok(input, "\n");
}
image im = load_image_color(input,0,0);
image sized = letterbox_image(im, net->w, net->h);
//image sized = resize_image(im, net->w, net->h);
//image sized2 = resize_max(im, net->w);
//image sized = crop_image(sized2, -((net->w - sized2.w)/2), -((net->h - sized2.h)/2), net->w, net->h);
//resize_network(net, sized.w, sized.h);
layer l = net->layers[net->n-1];
float *X = sized.data;
time=what_time_is_it_now();
network_predict(net, X);
printf("%s: Predicted in %f seconds.\n", input, what_time_is_it_now()-time);
int nboxes = 0;
detection *dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes);
printf("%d\n", nboxes);
for(int x=0;x<nboxes;x++)
{
if(dets[x].objectness > 0.0)
printf("[%3d]:h=%f,w=%f,x=%f,y=%f,objectness=%f\n",
x,dets[x].bbox.h,dets[x].bbox.w,dets[x].bbox.x,dets[x].bbox.y,dets[x].objectness);
}
//printf("%d\n", nboxes);
//if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms);
if (nms) do_nms_sort(dets, nboxes, l.classes, nms);
draw_detections(im, dets, nboxes, thresh, names, alphabet, l.classes);
free_detections(dets, nboxes);
if(outfile){
save_image(im, outfile);
}
else{
save_image(im, "predictions");
#ifdef OPENCV
make_window("predictions", 512, 512, 0);
show_image(im, "predictions", 0);
#endif
}
free_image(im);
free_image(sized);
if (filename) break;
}
}
/*
void censor_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip)
{
#ifdef OPENCV
char *base = basecfg(cfgfile);
network *net = load_network(cfgfile, weightfile, 0);
set_batch_network(net, 1);
srand(2222222);
CvCapture * cap;
int w = 1280;
int h = 720;
if(filename){
cap = cvCaptureFromFile(filename);
}else{
cap = cvCaptureFromCAM(cam_index);
}
if(w){
cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w);
}
if(h){
cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h);
}
if(!cap) error("Couldn't connect to webcam.\n");
cvNamedWindow(base, CV_WINDOW_NORMAL);
cvResizeWindow(base, 512, 512);
float fps = 0;
int i;
float nms = .45;
while(1){
image in = get_image_from_stream(cap);
//image in_s = resize_image(in, net->w, net->h);
image in_s = letterbox_image(in, net->w, net->h);
layer l = net->layers[net->n-1];
float *X = in_s.data;
network_predict(net, X);
int nboxes = 0;
detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 0, &nboxes);
//if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms);
if (nms) do_nms_sort(dets, nboxes, l.classes, nms);
for(i = 0; i < nboxes; ++i){
if(dets[i].prob[class] > thresh){
box b = dets[i].bbox;
int left = b.x-b.w/2.;
int top = b.y-b.h/2.;
censor_image(in, left, top, b.w, b.h);
}
}
show_image(in, base);
cvWaitKey(10);
free_detections(dets, nboxes);
free_image(in_s);
free_image(in);
float curr = 0;
fps = .9*fps + .1*curr;
for(i = 0; i < skip; ++i){
image in = get_image_from_stream(cap);
free_image(in);
}
}
#endif
}
void extract_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip)
{
#ifdef OPENCV
char *base = basecfg(cfgfile);
network *net = load_network(cfgfile, weightfile, 0);
set_batch_network(net, 1);
srand(2222222);
CvCapture * cap;
int w = 1280;
int h = 720;
if(filename){
cap = cvCaptureFromFile(filename);
}else{
cap = cvCaptureFromCAM(cam_index);
}
if(w){
cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w);
}
if(h){
cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h);
}
if(!cap) error("Couldn't connect to webcam.\n");
cvNamedWindow(base, CV_WINDOW_NORMAL);
cvResizeWindow(base, 512, 512);
float fps = 0;
int i;
int count = 0;
float nms = .45;
while(1){
image in = get_image_from_stream(cap);
//image in_s = resize_image(in, net->w, net->h);
image in_s = letterbox_image(in, net->w, net->h);
layer l = net->layers[net->n-1];
show_image(in, base);
int nboxes = 0;
float *X = in_s.data;
network_predict(net, X);
detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 1, &nboxes);
//if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms);
if (nms) do_nms_sort(dets, nboxes, l.classes, nms);
for(i = 0; i < nboxes; ++i){
if(dets[i].prob[class] > thresh){
box b = dets[i].bbox;
int size = b.w*in.w > b.h*in.h ? b.w*in.w : b.h*in.h;
int dx = b.x*in.w-size/2.;
int dy = b.y*in.h-size/2.;
image bim = crop_image(in, dx, dy, size, size);
char buff[2048];
sprintf(buff, "results/extract/%07d", count);
++count;
save_image(bim, buff);
free_image(bim);
}
}
free_detections(dets, nboxes);
free_image(in_s);
free_image(in);
float curr = 0;
fps = .9*fps + .1*curr;
for(i = 0; i < skip; ++i){
image in = get_image_from_stream(cap);
free_image(in);
}
}
#endif
}
*/
/*
void network_detect(network *net, image im, float thresh, float hier_thresh, float nms, detection *dets)
{
network_predict_image(net, im);
layer l = net->layers[net->n-1];
int nboxes = num_boxes(net);
fill_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 0, dets);
if (nms) do_nms_sort(dets, nboxes, l.classes, nms);
}
*/
void run_detector(int argc, char **argv)
{
char *prefix = find_char_arg(argc, argv, "-prefix", 0);
float thresh = find_float_arg(argc, argv, "-thresh", .5);
float hier_thresh = find_float_arg(argc, argv, "-hier", .5);
int cam_index = find_int_arg(argc, argv, "-c", 0);
int frame_skip = find_int_arg(argc, argv, "-s", 0);
int avg = find_int_arg(argc, argv, "-avg", 3);
if(argc < 4){
fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
return;
}
char *gpu_list = find_char_arg(argc, argv, "-gpus", 0);
char *outfile = find_char_arg(argc, argv, "-out", 0);
int *gpus = 0;
int gpu = 0;
int ngpus = 0;
if(gpu_list){
printf("%s\n", gpu_list);
int len = strlen(gpu_list);
ngpus = 1;
int i;
for(i = 0; i < len; ++i){
if (gpu_list[i] == ',') ++ngpus;
}
gpus = calloc(ngpus, sizeof(int));
for(i = 0; i < ngpus; ++i){
gpus[i] = atoi(gpu_list);
gpu_list = strchr(gpu_list, ',')+1;
}
} else {
gpu = gpu_index;
gpus = &gpu;
ngpus = 1;
}
int clear = find_arg(argc, argv, "-clear");
int fullscreen = find_arg(argc, argv, "-fullscreen");
int width = find_int_arg(argc, argv, "-w", 0);
int height = find_int_arg(argc, argv, "-h", 0);
int fps = find_int_arg(argc, argv, "-fps", 0);
//int class = find_int_arg(argc, argv, "-class", 0);
char *datacfg = argv[3];
char *cfg = argv[4];
char *weights = (argc > 5) ? argv[5] : 0;
char *filename = (argc > 6) ? argv[6]: 0;
if(0==strcmp(argv[2], "test")) test_detector(datacfg, cfg, weights, filename, thresh, hier_thresh, outfile, fullscreen);
else if(0==strcmp(argv[2], "train")) train_detector(datacfg, cfg, weights, gpus, ngpus, clear);
else if(0==strcmp(argv[2], "valid")) validate_detector(datacfg, cfg, weights, outfile);
else if(0==strcmp(argv[2], "valid2")) validate_detector_flip(datacfg, cfg, weights, outfile);
else if(0==strcmp(argv[2], "recall")) validate_detector_recall(cfg, weights);
else if(0==strcmp(argv[2], "demo")) {
list *options = read_data_cfg(datacfg);
int classes = option_find_int(options, "classes", 20);
char *name_list = option_find_str(options, "names", "data/names.list");
char **names = get_labels(name_list);
demo(cfg, weights, thresh, cam_index, filename, names, classes, frame_skip, prefix, avg, hier_thresh, width, height, fps, fullscreen);
}
//else if(0==strcmp(argv[2], "extract")) extract_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip);
//else if(0==strcmp(argv[2], "censor")) censor_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip);
}
|
GB_unaryop__minv_fp32_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__minv_fp32_fp64
// op(A') function: GB_tran__minv_fp32_fp64
// C type: float
// A type: double
// cast: float cij = (float) aij
// unaryop: cij = (1.0F)/aij
#define GB_ATYPE \
double
#define GB_CTYPE \
float
// 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 = (1.0F)/x ;
// casting
#define GB_CASTING(z, x) \
float z = (float) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_FP32 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_fp32_fp64
(
float *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__minv_fp32_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
|
floorplan.c | /**********************************************************************************************/
/* This program is part of the Barcelona OpenMP Tasks Suite */
/* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */
/* Copyright (C) 2009 Universitat Politecnica de Catalunya */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License, or */
/* (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
/**********************************************************************************************/
/* Original code from the Application Kernel Matrix by Cray */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "app-desc.h"
#include "bots.h"
#define ROWS 64
#define COLS 64
#define DMAX 64
#define max(a, b) ((a > b) ? a : b)
#define min(a, b) ((a < b) ? a : b)
int solution = -1;
typedef int coor[2];
typedef char ibrd[ROWS][COLS];
typedef char (*pibrd)[COLS];
FILE * inputFile;
struct cell {
int n;
coor *alt;
int top;
int bot;
int lhs;
int rhs;
int left;
int above;
int next;
};
struct cell * gcells;
int MIN_AREA;
ibrd BEST_BOARD;
coor MIN_FOOTPRINT;
int N;
/* compute all possible locations for nw corner for cell */
static int starts(int id, int shape, coor *NWS, struct cell *cells) {
int i, n, top, bot, lhs, rhs;
int rows, cols, left, above;
/* size of cell */
rows = cells[id].alt[shape][0];
cols = cells[id].alt[shape][1];
/* the cells to the left and above */
left = cells[id].left;
above = cells[id].above;
/* if there is a vertical and horizontal dependence */
if ((left >= 0) && (above >= 0)) {
top = cells[above].bot + 1;
lhs = cells[left].rhs + 1;
bot = top + rows;
rhs = lhs + cols;
/* if footprint of cell touches the cells to the left and above */
if ((top <= cells[left].bot) && (bot >= cells[left].top) &&
(lhs <= cells[above].rhs) && (rhs >= cells[above].lhs))
{ n = 1; NWS[0][0] = top; NWS[0][1] = lhs; }
else { n = 0; }
/* if there is only a horizontal dependence */
} else if (left >= 0) {
/* highest initial row is top of cell to the left - rows */
top = max(cells[left].top - rows + 1, 0);
/* lowest initial row is bottom of cell to the left */
bot = min(cells[left].bot, ROWS);
n = bot - top + 1;
for (i = 0; i < n; i++) {
NWS[i][0] = i + top;
NWS[i][1] = cells[left].rhs + 1;
}
} else {
/* leftmost initial col is lhs of cell above - cols */
lhs = max(cells[above].lhs - cols + 1, 0);
/* rightmost initial col is rhs of cell above */
rhs = min(cells[above].rhs, COLS);
n = rhs - lhs + 1;
for (i = 0; i < n; i++) {
NWS[i][0] = cells[above].bot + 1;
NWS[i][1] = i + lhs;
} }
return (n);
}
/* lay the cell down on the board in the rectangular space defined
by the cells top, bottom, left, and right edges. If the cell can
not be layed down, return 0; else 1.
*/
static int lay_down(int id, ibrd board, struct cell *cells) {
int i, j, top, bot, lhs, rhs;
top = cells[id].top;
bot = cells[id].bot;
lhs = cells[id].lhs;
rhs = cells[id].rhs;
for (i = top; i <= bot; i++) {
for (j = lhs; j <= rhs; j++) {
if (board[i][j] == 0) board[i][j] = (char)id;
else return(0);
} }
return (1);
}
#define read_integer(file,var) \
if ( fscanf(file, "%d", &var) == EOF ) {\
bots_message(" Bogus input file\n");\
exit(-1);\
}
static void read_inputs() {
int i, j, n;
read_integer(inputFile,n);
N = n;
gcells = (struct cell *) malloc((n + 1) * sizeof(struct cell));
gcells[0].n = 0;
gcells[0].alt = 0;
gcells[0].top = 0;
gcells[0].bot = 0;
gcells[0].lhs = -1;
gcells[0].rhs = -1;
gcells[0].left = 0;
gcells[0].above = 0;
gcells[0].next = 0;
for (i = 1; i < n + 1; i++) {
read_integer(inputFile, gcells[i].n);
gcells[i].alt = (coor *) malloc(gcells[i].n * sizeof(coor));
for (j = 0; j < gcells[i].n; j++) {
read_integer(inputFile, gcells[i].alt[j][0]);
read_integer(inputFile, gcells[i].alt[j][1]);
}
read_integer(inputFile, gcells[i].left);
read_integer(inputFile, gcells[i].above);
read_integer(inputFile, gcells[i].next);
}
if (!feof(inputFile)) {
read_integer(inputFile, solution);
}
}
static void write_outputs() {
int i, j;
bots_message("Minimum area = %d\n\n", MIN_AREA);
for (i = 0; i < MIN_FOOTPRINT[0]; i++) {
for (j = 0; j < MIN_FOOTPRINT[1]; j++) {
if (BEST_BOARD[i][j] == 0) {bots_message(" ");}
else bots_message("%c", 'A' + BEST_BOARD[i][j] - 1);
}
bots_message("\n");
}
}
#ifdef MANUAL_CUTOFF
static int add_cell_ser (int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS) {
int i, j, nn, nn2, area;
ibrd board;
coor footprint, NWS[DMAX];
nn2 = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nn2 += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
struct cell *cells = CELLS;
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
bots_debug("Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
bots_debug("N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nn2 += add_cell_ser(cells[id].next, footprint, board,cells);
/* if area is greater than or equal to best area, prune search */
} else {
bots_debug("T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
return nn2;
}
#endif
#if defined(IF_CUTOFF)
static int add_cell(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS,int level) {
int i, j, nn, area, nnc, nnl;
ibrd board;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task private(board, footprint,area) \
firstprivate(NWS,i,j,id,nn,level) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD,nnc,bots_verbose_mode) \
if(level<bots_cutoff_value)
{
struct cell cells[N+1];
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
bots_debug("Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
bots_debug("N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nnc += add_cell(cells[id].next, footprint, board,cells,level+1);
/* if area is greater than or equal to best area, prune search */
} else {
bots_debug("T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
#elif defined(FINAL_CUTOFF)
static int add_cell(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS,int level) {
int i, j, nn, area, nnc, nnl;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task private(footprint,area) \
firstprivate(NWS,i,j,id,nn,level,bots_cutoff_value) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD,nnc,bots_verbose_mode) \
final(level >= bots_cutoff_value) mergeable
{
ibrd board;
struct cell *cells;
if ( omp_in_final() && level > bots_cutoff_value ) {
cells = CELLS;
} else {
cells = alloca(sizeof(struct cell)*(N+1));
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
}
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
bots_debug("Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
bots_debug("N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nnc += add_cell(cells[id].next, footprint, board,cells,level+1);
/* if area is greater than or equal to best area, prune search */
} else {
bots_debug("T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
#elif defined(MANUAL_CUTOFF)
static int add_cell(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS,int level) {
int i, j, nn, area, nnc, nnl;
ibrd board;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task private(board, footprint,area) \
firstprivate(NWS,i,j,id,nn,level,bots_cutoff_value) shared(nnc) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD,bots_verbose_mode)
{
struct cell *cells;
cells = (struct cell*)alloca(sizeof(struct cell)*(N+1));
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
bots_debug("Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
bots_debug("N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
if(level+1 < bots_cutoff_value ) {
#pragma omp atomic
nnc += add_cell(cells[id].next, footprint, board,cells,level+1);
} else {
#pragma omp atomic
nnc += add_cell_ser(cells[id].next, footprint, board,cells);
}
/* if area is greater than or equal to best area, prune search */
} else {
bots_debug("T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
#else
static int add_cell(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS) {
int i, j, nn, area, nnc,nnl;
ibrd board;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task private(board, footprint,area) \
firstprivate(NWS,i,j,id,nn) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD,nnc,bots_verbose_mode)
{
struct cell cells[N+1];
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
bots_debug("Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
bots_debug("N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nnc += add_cell(cells[id].next, footprint, board,cells);
/* if area is greater than or equal to best area, prune search */
} else {
bots_debug("T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
#endif
ibrd board;
void floorplan_init (char *filename)
{
int i,j;
inputFile = fopen(filename, "r");
if(NULL == inputFile) {
bots_message("Couldn't open %s file for reading\n", filename);
exit(1);
}
/* read input file and initialize global minimum area */
read_inputs();
MIN_AREA = ROWS * COLS;
/* initialize board is empty */
for (i = 0; i < ROWS; i++)
for (j = 0; j < COLS; j++) board[i][j] = 0;
}
void compute_floorplan (void)
{
coor footprint;
/* footprint of initial board is zero */
footprint[0] = 0;
footprint[1] = 0;
bots_message("Computing floorplan ");
#pragma omp parallel
{
#pragma omp single
#if defined(MANUAL_CUTOFF) || defined(IF_CUTOFF) || defined(FINAL_CUTOFF)
bots_number_of_tasks = add_cell(1, footprint, board, gcells,0);
#else
bots_number_of_tasks = add_cell(1, footprint, board, gcells);
#endif
}
bots_message(" completed!\n");
}
void floorplan_end (void)
{
/* write results */
write_outputs();
}
int floorplan_verify (void)
{
if (solution != -1 )
return MIN_AREA == solution ? BOTS_RESULT_SUCCESSFUL : BOTS_RESULT_UNSUCCESSFUL;
else
return BOTS_RESULT_NA;
}
|
schur_eliminator_impl.h | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// 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 Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
//
// TODO(sameeragarwal): row_block_counter can perhaps be replaced by
// Chunk::start ?
#ifndef CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
#define CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
// Eigen has an internal threshold switching between different matrix
// multiplication algorithms. In particular for matrices larger than
// EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD it uses a cache friendly
// matrix matrix product algorithm that has a higher setup cost. For
// matrix sizes close to this threshold, especially when the matrices
// are thin and long, the default choice may not be optimal. This is
// the case for us, as the default choice causes a 30% performance
// regression when we moved from Eigen2 to Eigen3.
#define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 10
// This include must come before any #ifndef check on Ceres compile options.
#include "ceres/internal/port.h"
#ifdef CERES_USE_OPENMP
#include <omp.h>
#endif
#include <algorithm>
#include <map>
#include "ceres/block_random_access_matrix.h"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/fixed_array.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/map_util.h"
#include "ceres/schur_eliminator.h"
#include "ceres/small_blas.h"
#include "ceres/stl_util.h"
#include "Eigen/Dense"
#include "glog/logging.h"
namespace ceres {
namespace internal {
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::~SchurEliminator() {
STLDeleteElements(&rhs_locks_);
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
Init(int num_eliminate_blocks, const CompressedRowBlockStructure* bs) {
CHECK_GT(num_eliminate_blocks, 0)
<< "SchurComplementSolver cannot be initialized with "
<< "num_eliminate_blocks = 0.";
num_eliminate_blocks_ = num_eliminate_blocks;
const int num_col_blocks = int(bs->cols.size());
const int num_row_blocks = int(bs->rows.size());
buffer_size_ = 1;
chunks_.clear();
lhs_row_layout_.clear();
int lhs_num_rows = 0;
// Add a map object for each block in the reduced linear system
// and build the row/column block structure of the reduced linear
// system.
lhs_row_layout_.resize(num_col_blocks - num_eliminate_blocks_);
for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) {
lhs_row_layout_[i - num_eliminate_blocks_] = lhs_num_rows;
lhs_num_rows += bs->cols[i].size;
}
int r = 0;
// Iterate over the row blocks of A, and detect the chunks. The
// matrix should already have been ordered so that all rows
// containing the same y block are vertically contiguous. Along
// the way also compute the amount of space each chunk will need
// to perform the elimination.
while (r < num_row_blocks) {
const int chunk_block_id = bs->rows[r].cells.front().block_id;
if (chunk_block_id >= num_eliminate_blocks_) {
break;
}
chunks_.push_back(Chunk());
Chunk& chunk = chunks_.back();
chunk.size = 0;
chunk.start = r;
int buffer_size = 0;
const int e_block_size = bs->cols[chunk_block_id].size;
// Add to the chunk until the first block in the row is
// different than the one in the first row for the chunk.
while (r + chunk.size < num_row_blocks) {
const CompressedRow& row = bs->rows[r + chunk.size];
if (row.cells.front().block_id != chunk_block_id) {
break;
}
// Iterate over the blocks in the row, ignoring the first
// block since it is the one to be eliminated.
for (int c = 1; c < row.cells.size(); ++c) {
const Cell& cell = row.cells[c];
if (InsertIfNotPresent(
&(chunk.buffer_layout), cell.block_id, buffer_size)) {
buffer_size += e_block_size * bs->cols[cell.block_id].size;
}
}
buffer_size_ = max(buffer_size, buffer_size_);
++chunk.size;
}
CHECK_GT(chunk.size, 0);
r += chunk.size;
}
const Chunk& chunk = chunks_.back();
uneliminated_row_begins_ = chunk.start + chunk.size;
if (num_threads_ > 1) {
random_shuffle(chunks_.begin(), chunks_.end());
}
buffer_.reset(new double[buffer_size_ * num_threads_]);
// chunk_outer_product_buffer_ only needs to store e_block_size *
// f_block_size, which is always less than buffer_size_, so we just
// allocate buffer_size_ per thread.
chunk_outer_product_buffer_.reset(new double[buffer_size_ * num_threads_]);
STLDeleteElements(&rhs_locks_);
rhs_locks_.resize(num_col_blocks - num_eliminate_blocks_);
for (int i = 0; i < num_col_blocks - num_eliminate_blocks_; ++i) {
rhs_locks_[i] = new Mutex;
}
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
Eliminate(const BlockSparseMatrix* A,
const double* b,
const double* D,
BlockRandomAccessMatrix* lhs,
double* rhs) {
if (lhs->num_rows() > 0) {
lhs->SetZero();
VectorRef(rhs, lhs->num_rows()).setZero();
}
const CompressedRowBlockStructure* bs = A->block_structure();
const int num_col_blocks = int(bs->cols.size());
// Add the diagonal to the schur complement.
if (D != NULL) {
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) {
const int block_id = i - num_eliminate_blocks_;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block_id, block_id,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block_size = bs->cols[i].size;
typename EigenTypes<kFBlockSize>::ConstVectorRef
diag(D + bs->cols[i].position, block_size);
CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
m.block(r, c, block_size, block_size).diagonal()
+= diag.array().square().matrix();
}
}
}
// Eliminate y blocks one chunk at a time. For each chunk,x3
// compute the entries of the normal equations and the gradient
// vector block corresponding to the y block and then apply
// Gaussian elimination to them. The matrix ete stores the normal
// matrix corresponding to the block being eliminated and array
// buffer_ contains the non-zero blocks in the row corresponding
// to this y block in the normal equations. This computation is
// done in ChunkDiagonalBlockAndGradient. UpdateRhs then applies
// gaussian elimination to the rhs of the normal equations,
// updating the rhs of the reduced linear system by modifying rhs
// blocks for all the z blocks that share a row block/residual
// term with the y block. EliminateRowOuterProduct does the
// corresponding operation for the lhs of the reduced linear
// system.
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
for (int i = 0; i < chunks_.size(); ++i) {
#ifdef CERES_USE_OPENMP
int thread_id = omp_get_thread_num();
#else
int thread_id = 0;
#endif
double* buffer = buffer_.get() + thread_id * buffer_size_;
const Chunk& chunk = chunks_[i];
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
VectorRef(buffer, buffer_size_).setZero();
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix
ete(e_block_size, e_block_size);
if (D != NULL) {
const typename EigenTypes<kEBlockSize>::ConstVectorRef
diag(D + bs->cols[e_block_id].position, e_block_size);
ete = diag.array().square().matrix().asDiagonal();
} else {
ete.setZero();
}
FixedArray<double, 8> g(e_block_size);
typename EigenTypes<kEBlockSize>::VectorRef gref(g.get(), e_block_size);
gref.setZero();
// We are going to be computing
//
// S += F'F - F'E(E'E)^{-1}E'F
//
// for each Chunk. The computation is broken down into a number of
// function calls as below.
// Compute the outer product of the e_blocks with themselves (ete
// = E'E). Compute the product of the e_blocks with the
// corresonding f_blocks (buffer = E'F), the gradient of the terms
// in this chunk (g) and add the outer product of the f_blocks to
// Schur complement (S += F'F).
ChunkDiagonalBlockAndGradient(
chunk, A, b, chunk.start, &ete, g.get(), buffer, lhs);
// Normally one wouldn't compute the inverse explicitly, but
// e_block_size will typically be a small number like 3, in
// which case its much faster to compute the inverse once and
// use it to multiply other matrices/vectors instead of doing a
// Solve call over and over again.
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix inverse_ete =
ete
.template selfadjointView<Eigen::Upper>()
.llt()
.solve(Matrix::Identity(e_block_size, e_block_size));
// For the current chunk compute and update the rhs of the reduced
// linear system.
//
// rhs = F'b - F'E(E'E)^(-1) E'b
FixedArray<double, 8> inverse_ete_g(e_block_size);
MatrixVectorMultiply<kEBlockSize, kEBlockSize, 0>(
inverse_ete.data(),
e_block_size,
e_block_size,
g.get(),
inverse_ete_g.get());
UpdateRhs(chunk, A, b, chunk.start, inverse_ete_g.get(), rhs);
// S -= F'E(E'E)^{-1}E'F
ChunkOuterProduct(bs, inverse_ete, buffer, chunk.buffer_layout, lhs);
}
// For rows with no e_blocks, the schur complement update reduces to
// S += F'F.
NoEBlockRowsUpdate(A, b, uneliminated_row_begins_, lhs, rhs);
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
BackSubstitute(const BlockSparseMatrix* A,
const double* b,
const double* D,
const double* z,
double* y) {
const CompressedRowBlockStructure* bs = A->block_structure();
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
for (int i = 0; i < chunks_.size(); ++i) {
const Chunk& chunk = chunks_[i];
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
double* y_ptr = y + bs->cols[e_block_id].position;
typename EigenTypes<kEBlockSize>::VectorRef y_block(y_ptr, e_block_size);
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix
ete(e_block_size, e_block_size);
if (D != NULL) {
const typename EigenTypes<kEBlockSize>::ConstVectorRef
diag(D + bs->cols[e_block_id].position, e_block_size);
ete = diag.array().square().matrix().asDiagonal();
} else {
ete.setZero();
}
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[chunk.start + j];
const Cell& e_cell = row.cells.front();
DCHECK_EQ(e_block_id, e_cell.block_id);
FixedArray<double, 8> sj(row.block.size);
typename EigenTypes<kRowBlockSize>::VectorRef(sj.get(), row.block.size) =
typename EigenTypes<kRowBlockSize>::ConstVectorRef
(b + bs->rows[chunk.start + j].block.position, row.block.size);
for (int c = 1; c < row.cells.size(); ++c) {
const int f_block_id = row.cells[c].block_id;
const int f_block_size = bs->cols[f_block_id].size;
const int r_block = f_block_id - num_eliminate_blocks_;
MatrixVectorMultiply<kRowBlockSize, kFBlockSize, -1>(
values + row.cells[c].position, row.block.size, f_block_size,
z + lhs_row_layout_[r_block],
sj.get());
}
MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
sj.get(),
y_ptr);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + e_cell.position, row.block.size, e_block_size,
ete.data(), 0, 0, e_block_size, e_block_size);
}
ete.llt().solveInPlace(y_block);
}
}
// Update the rhs of the reduced linear system. Compute
//
// F'b - F'E(E'E)^(-1) E'b
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
UpdateRhs(const Chunk& chunk,
const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
const double* inverse_ete_g,
double* rhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
int b_pos = bs->rows[row_block_counter].block.position;
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[row_block_counter + j];
const Cell& e_cell = row.cells.front();
typename EigenTypes<kRowBlockSize>::Vector sj =
typename EigenTypes<kRowBlockSize>::ConstVectorRef
(b + b_pos, row.block.size);
MatrixVectorMultiply<kRowBlockSize, kEBlockSize, -1>(
values + e_cell.position, row.block.size, e_block_size,
inverse_ete_g, sj.data());
for (int c = 1; c < row.cells.size(); ++c) {
const int block_id = row.cells[c].block_id;
const int block_size = bs->cols[block_id].size;
const int block = block_id - num_eliminate_blocks_;
CeresMutexLock l(rhs_locks_[block]);
MatrixTransposeVectorMultiply<kRowBlockSize, kFBlockSize, 1>(
values + row.cells[c].position,
row.block.size, block_size,
sj.data(), rhs + lhs_row_layout_[block]);
}
b_pos += row.block.size;
}
}
// Given a Chunk - set of rows with the same e_block, e.g. in the
// following Chunk with two rows.
//
// E F
// [ y11 0 0 0 | z11 0 0 0 z51]
// [ y12 0 0 0 | z12 z22 0 0 0]
//
// this function computes twp matrices. The diagonal block matrix
//
// ete = y11 * y11' + y12 * y12'
//
// and the off diagonal blocks in the Guass Newton Hessian.
//
// buffer = [y11'(z11 + z12), y12' * z22, y11' * z51]
//
// which are zero compressed versions of the block sparse matrices E'E
// and E'F.
//
// and the gradient of the e_block, E'b.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
ChunkDiagonalBlockAndGradient(
const Chunk& chunk,
const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix* ete,
double* g,
double* buffer,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
int b_pos = bs->rows[row_block_counter].block.position;
const int e_block_size = ete->rows();
// Iterate over the rows in this chunk, for each row, compute the
// contribution of its F blocks to the Schur complement, the
// contribution of its E block to the matrix EE' (ete), and the
// corresponding block in the gradient vector.
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[row_block_counter + j];
if (row.cells.size() > 1) {
EBlockRowOuterProduct(A, row_block_counter + j, lhs);
}
// Extract the e_block, ETE += E_i' E_i
const Cell& e_cell = row.cells.front();
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + e_cell.position, row.block.size, e_block_size,
ete->data(), 0, 0, e_block_size, e_block_size);
// g += E_i' b_i
MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
b + b_pos,
g);
// buffer = E'F. This computation is done by iterating over the
// f_blocks for each row in the chunk.
for (int c = 1; c < row.cells.size(); ++c) {
const int f_block_id = row.cells[c].block_id;
const int f_block_size = bs->cols[f_block_id].size;
double* buffer_ptr =
buffer + FindOrDie(chunk.buffer_layout, f_block_id);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + row.cells[c].position, row.block.size, f_block_size,
buffer_ptr, 0, 0, e_block_size, f_block_size);
}
b_pos += row.block.size;
}
}
// Compute the outer product F'E(E'E)^{-1}E'F and subtract it from the
// Schur complement matrix, i.e
//
// S -= F'E(E'E)^{-1}E'F.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
ChunkOuterProduct(const CompressedRowBlockStructure* bs,
const Matrix& inverse_ete,
const double* buffer,
const BufferLayoutType& buffer_layout,
BlockRandomAccessMatrix* lhs) {
// This is the most computationally expensive part of this
// code. Profiling experiments reveal that the bottleneck is not the
// computation of the right-hand matrix product, but memory
// references to the left hand side.
const int e_block_size = inverse_ete.rows();
BufferLayoutType::const_iterator it1 = buffer_layout.begin();
#ifdef CERES_USE_OPENMP
int thread_id = omp_get_thread_num();
#else
int thread_id = 0;
#endif
double* b1_transpose_inverse_ete =
chunk_outer_product_buffer_.get() + thread_id * buffer_size_;
// S(i,j) -= bi' * ete^{-1} b_j
for (; it1 != buffer_layout.end(); ++it1) {
const int block1 = it1->first - num_eliminate_blocks_;
const int block1_size = bs->cols[it1->first].size;
MatrixTransposeMatrixMultiply
<kEBlockSize, kFBlockSize, kEBlockSize, kEBlockSize, 0>(
buffer + it1->second, e_block_size, block1_size,
inverse_ete.data(), e_block_size, e_block_size,
b1_transpose_inverse_ete, 0, 0, block1_size, e_block_size);
BufferLayoutType::const_iterator it2 = it1;
for (; it2 != buffer_layout.end(); ++it2) {
const int block2 = it2->first - num_eliminate_blocks_;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block2_size = bs->cols[it2->first].size;
CeresMutexLock l(&cell_info->m);
MatrixMatrixMultiply
<kFBlockSize, kEBlockSize, kEBlockSize, kFBlockSize, -1>(
b1_transpose_inverse_ete, block1_size, e_block_size,
buffer + it2->second, e_block_size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
// For rows with no e_blocks, the schur complement update reduces to S
// += F'F. This function iterates over the rows of A with no e_block,
// and calls NoEBlockRowOuterProduct on each row.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
NoEBlockRowsUpdate(const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
BlockRandomAccessMatrix* lhs,
double* rhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const double* values = A->values();
for (; row_block_counter < bs->rows.size(); ++row_block_counter) {
const CompressedRow& row = bs->rows[row_block_counter];
for (int c = 0; c < row.cells.size(); ++c) {
const int block_id = row.cells[c].block_id;
const int block_size = bs->cols[block_id].size;
const int block = block_id - num_eliminate_blocks_;
MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[c].position, row.block.size, block_size,
b + row.block.position,
rhs + lhs_row_layout_[block]);
}
NoEBlockRowOuterProduct(A, row_block_counter, lhs);
}
}
// A row r of A, which has no e_blocks gets added to the Schur
// Complement as S += r r'. This function is responsible for computing
// the contribution of a single row r to the Schur complement. It is
// very similar in structure to EBlockRowOuterProduct except for
// one difference. It does not use any of the template
// parameters. This is because the algorithm used for detecting the
// static structure of the matrix A only pays attention to rows with
// e_blocks. This is becase rows without e_blocks are rare and
// typically arise from regularization terms in the original
// optimization problem, and have a very different structure than the
// rows with e_blocks. Including them in the static structure
// detection will lead to most template parameters being set to
// dynamic. Since the number of rows without e_blocks is small, the
// lack of templating is not an issue.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
NoEBlockRowOuterProduct(const BlockSparseMatrix* A,
int row_block_index,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const CompressedRow& row = bs->rows[row_block_index];
const double* values = A->values();
for (int i = 0; i < row.cells.size(); ++i) {
const int block1 = row.cells[i].block_id - num_eliminate_blocks_;
DCHECK_GE(block1, 0);
const int block1_size = bs->cols[row.cells[i].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block1,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
CeresMutexLock l(&cell_info->m);
// This multiply currently ignores the fact that this is a
// symmetric outer product.
MatrixTransposeMatrixMultiply
<Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[i].position, row.block.size, block1_size,
cell_info->values, r, c, row_stride, col_stride);
}
for (int j = i + 1; j < row.cells.size(); ++j) {
const int block2 = row.cells[j].block_id - num_eliminate_blocks_;
DCHECK_GE(block2, 0);
DCHECK_LT(block1, block2);
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block2_size = bs->cols[row.cells[j].block_id].size;
CeresMutexLock l(&cell_info->m);
MatrixTransposeMatrixMultiply
<Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[j].position, row.block.size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
// For a row with an e_block, compute the contribition S += F'F. This
// function has the same structure as NoEBlockRowOuterProduct, except
// that this function uses the template parameters.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
EBlockRowOuterProduct(const BlockSparseMatrix* A,
int row_block_index,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const CompressedRow& row = bs->rows[row_block_index];
const double* values = A->values();
for (int i = 1; i < row.cells.size(); ++i) {
const int block1 = row.cells[i].block_id - num_eliminate_blocks_;
DCHECK_GE(block1, 0);
const int block1_size = bs->cols[row.cells[i].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block1,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
CeresMutexLock l(&cell_info->m);
// block += b1.transpose() * b1;
MatrixTransposeMatrixMultiply
<kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[i].position, row.block.size, block1_size,
cell_info->values, r, c, row_stride, col_stride);
}
for (int j = i + 1; j < row.cells.size(); ++j) {
const int block2 = row.cells[j].block_id - num_eliminate_blocks_;
DCHECK_GE(block2, 0);
DCHECK_LT(block1, block2);
const int block2_size = bs->cols[row.cells[j].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
// block += b1.transpose() * b2;
CeresMutexLock l(&cell_info->m);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[j].position, row.block.size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
} // namespace internal
} // namespace ceres
#endif // CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
|
gridify-1.c | void __attribute__((noinline, noclone))
foo (int n, int *a, int workgroup_size)
{
int i;
#pragma omp target
#pragma omp teams thread_limit(workgroup_size)
#pragma omp distribute parallel for shared(a) firstprivate(n) private(i)
for (i = 0; i < n; i++)
a[i]++;
}
int main (int argc, char **argv)
{
int n = 32;
int *a = __builtin_malloc (sizeof (int) * n);
int i;
__builtin_memset (a, 0, sizeof (int) * n);
foo (n, a, 32);
for (i = 0; i < n; i ++)
{
if (a[i] != 1)
__builtin_abort ();
}
return 0;
}
|
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;
}
|
HelloOpenMP_fix5.c | #include <stdio.h>
#include <omp.h>
int main(int argc, char *argv[]){
printf("Goodbye slow serial world and Hello OpenMP!\n");
#pragma omp parallel
if (omp_get_thread_num() == 0) {
printf(" I have %d thread(s) and my thread id is %d\n",
omp_get_num_threads(), omp_get_thread_num());
}
}
|
core_dsyr2k.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zsyr2k.c, normal z -> d, Fri Sep 28 17:38:23 2018
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "core_lapack.h"
/***************************************************************************//**
*
* @ingroup core_syr2k
*
* Performs one of the symmetric rank 2k operations
*
* \f[ C = \alpha A \times B^T + \alpha B \times A^T + \beta C, \f]
* or
* \f[ C = \alpha A^T \times B + \alpha B^T \times A + \beta C, \f]
*
* where alpha and beta are scalars,
* C is an n-by-n symmetric matrix, and A and B are n-by-k matrices
* in the first case and k-by-n matrices in the second case.
*
*******************************************************************************
*
* @param[in] uplo
* - PlasmaUpper: Upper triangle of C is stored;
* - PlasmaLower: Lower triangle of C is stored.
*
* @param[in] trans
* - PlasmaNoTrans:
* \f[ C = \alpha A \times B^T + \alpha B \times A^T + \beta C; \f]
* - PlasmaTrans:
* \f[ C = \alpha A^T \times B + \alpha B^T \times A + \beta C. \f]
*
* @param[in] n
* The order of the matrix C. n >= zero.
*
* @param[in] k
* If trans = PlasmaNoTrans, number of columns of the A and B matrices;
* if trans = PlasmaTrans, number of rows of the A and B matrices.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] A
* An lda-by-ka matrix.
* If trans = PlasmaNoTrans, ka = k;
* if trans = PlasmaTrans, ka = n.
*
* @param[in] lda
* The leading dimension of the array A.
* If trans = PlasmaNoTrans, lda >= max(1, n);
* if trans = PlasmaTrans, lda >= max(1, k).
*
* @param[in] B
* An ldb-by-kb matrix.
* If trans = PlasmaNoTrans, kb = k;
* if trans = PlasmaTrans, kb = n.
*
* @param[in] ldb
* The leading dimension of the array B.
* If trans = PlasmaNoTrans, ldb >= max(1, n);
* if trans = PlasmaTrans, ldb >= max(1, k).
*
* @param[in] beta
* The scalar beta.
*
* @param[in,out] C
* An ldc-by-n matrix.
* On exit, the uplo part of the matrix is overwritten
* by the uplo part of the updated matrix.
*
* @param[in] ldc
* The leading dimension of the array C. ldc >= max(1, n).
*
******************************************************************************/
__attribute__((weak))
void plasma_core_dsyr2k(plasma_enum_t uplo, plasma_enum_t trans,
int n, int k,
double alpha, const double *A, int lda,
const double *B, int ldb,
double beta, double *C, int ldc)
{
cblas_dsyr2k(CblasColMajor,
(CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans,
n, k,
(alpha), A, lda,
B, ldb,
(beta), C, ldc);
}
/******************************************************************************/
void plasma_core_omp_dsyr2k(
plasma_enum_t uplo, plasma_enum_t trans,
int n, int k,
double alpha, const double *A, int lda,
const double *B, int ldb,
double beta, double *C, int ldc,
plasma_sequence_t *sequence, plasma_request_t *request)
{
int ak;
int bk;
if (trans == PlasmaNoTrans) {
ak = k;
bk = k;
}
else {
ak = n;
bk = n;
}
#pragma omp task depend(in:A[0:lda*ak]) \
depend(in:B[0:ldb*bk]) \
depend(inout:C[0:ldc*n])
{
if (sequence->status == PlasmaSuccess)
plasma_core_dsyr2k(uplo, trans,
n, k,
alpha, A, lda,
B, ldb,
beta, C, ldc);
}
}
|
GB_binop__bshift_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_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bshift_int8)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__bshift_int8)
// A.*B function (eWiseMult): GB (_AemultB_03__bshift_int8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_int8)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((node))
// C+=B function (dense accum): GB (_Cdense_accumB__bshift_int8)
// C+=b function (dense accum): GB (_Cdense_accumb__bshift_int8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_int8)
// C=scalar+B GB (_bind1st__bshift_int8)
// C=scalar+B' GB (_bind1st_tran__bshift_int8)
// C=A+scalar GB (_bind2nd__bshift_int8)
// C=A'+scalar GB (_bind2nd_tran__bshift_int8)
// C type: int8_t
// A type: int8_t
// B,b type: int8_t
// BinaryOp: cij = GB_bitshift_int8 (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 = GB_bitshift_int8 (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BSHIFT || GxB_NO_INT8 || GxB_NO_BSHIFT_INT8)
//------------------------------------------------------------------------------
// 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__bshift_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__bshift_int8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bshift_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 GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t *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 GB ((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 *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
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bshift_int8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__bshift_int8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__bshift_int8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__bshift_int8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__bshift_int8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bshift_int8)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t 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] = GB_bitshift_int8 (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bshift_int8)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int8_t *Cx = (int8_t *) Cx_output ;
int8_t *Ax = (int8_t *) Ax_input ;
int8_t y = (*((int8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int8_t aij = Ax [p] ;
Cx [p] = GB_bitshift_int8 (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] = GB_bitshift_int8 (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__bshift_int8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t x = (*((const int8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int8_t aij = Ax [pA] ; \
Cx [pC] = GB_bitshift_int8 (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__bshift_int8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
phonon.c | /* Copyright (C) 2015 Atsushi Togo */
/* All rights reserved. */
/* This file is part of phonopy. */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions */
/* are met: */
/* * Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* * Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the */
/* distribution. */
/* * Neither the name of the phonopy project nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */
/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */
/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */
/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */
/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */
/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
#include <math.h>
#include <string.h>
#include <stddef.h>
#include "dynmat.h"
#include "phonon.h"
#include "lapack_wrapper.h"
static long collect_undone_grid_points(long *undone,
char *phonon_done,
const long num_grid_points,
const long *grid_points);
static void get_undone_phonons(double *frequencies,
lapack_complex_double *eigenvectors,
const long *undone_grid_points,
const long num_undone_grid_points,
const long (*grid_address)[3],
const double QDinv[3][3],
const double *fc2,
const double (*svecs_fc2)[3],
const long (*multi_fc2)[2],
const long num_patom,
const long num_satom,
const double *masses_fc2,
const long *p2s_fc2,
const long *s2p_fc2,
const double unit_conversion_factor,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const char uplo);
static void get_gonze_undone_phonons(double *frequencies,
lapack_complex_double *eigenvectors,
const long *undone_grid_points,
const long num_undone_grid_points,
const long (*grid_address)[3],
const double QDinv[3][3],
const double *fc2,
const double (*svecs_fc2)[3],
const long (*multi_fc2)[2],
const double (*positions)[3],
const long num_patom,
const long num_satom,
const double *masses_fc2,
const long *p2s_fc2,
const long *s2p_fc2,
const double unit_conversion_factor,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const double *dd_q0,
const double (*G_list)[3],
const long num_G_points,
const double lambda,
const char uplo);
static void get_phonons(lapack_complex_double *eigvecs,
const double q[3],
const double *fc2,
const double *masses,
const long *p2s,
const long *s2p,
const long (*multi)[2],
const long num_patom,
const long num_satom,
const double (*svecs)[3],
const long is_nac,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const double unit_conversion_factor);
static void get_gonze_phonons(lapack_complex_double *eigvecs,
const double q[3],
const double *fc2,
const double *masses,
const long *p2s,
const long *s2p,
const long (*multi)[2],
const double (*positions)[3],
const long num_patom,
const long num_satom,
const double (*svecs)[3],
const long is_nac,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const double *dd_q0,
const double (*G_list)[3],
const long num_G_points,
const double lambda);
static void
get_dynamical_matrix(lapack_complex_double *dynmat,
const double q[3],
const double *fc2,
const double *masses,
const long *p2s,
const long *s2p,
const long (*multi)[2],
const long num_patom,
const long num_satom,
const double (*svecs)[3],
const long is_nac,
const double (*born)[3][3], /* Wang NAC unless NULL */
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor);
static void get_charge_sum(double (*charge_sum)[3][3],
const long num_patom,
const long num_satom,
const double q[3],
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor);
static long needs_nac(const double (*born)[3][3],
const long (*grid_address)[3],
const long gp,
const double *q_direction);
void phn_get_phonons_at_gridpoints(double *frequencies,
lapack_complex_double *eigenvectors,
char *phonon_done,
const long num_phonons,
const long *grid_points,
const long num_grid_points,
const long (*grid_address)[3],
const double QDinv[3][3],
const double *fc2,
const double (*svecs_fc2)[3],
const long (*multi_fc2)[2],
const long num_patom,
const long num_satom,
const double *masses_fc2,
const long *p2s_fc2,
const long *s2p_fc2,
const double unit_conversion_factor,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction, /* must be pointer */
const double nac_factor,
const char uplo)
{
long num_undone;
long *undone;
undone = (long *)malloc(sizeof(long) * num_phonons);
num_undone = collect_undone_grid_points(undone,
phonon_done,
num_grid_points,
grid_points);
get_undone_phonons(frequencies,
eigenvectors,
undone,
num_undone,
grid_address,
QDinv,
fc2,
svecs_fc2,
multi_fc2,
num_patom,
num_satom,
masses_fc2,
p2s_fc2,
s2p_fc2,
unit_conversion_factor,
born,
dielectric,
reciprocal_lattice,
q_direction,
nac_factor,
uplo);
free(undone);
undone = NULL;
}
void phn_get_gonze_phonons_at_gridpoints(double *frequencies,
lapack_complex_double *eigenvectors,
char *phonon_done,
const long num_phonons,
const long *grid_points,
const long num_grid_points,
const long (*grid_address)[3],
const double QDinv[3][3],
const double *fc2,
const double (*svecs_fc2)[3],
const long (*multi_fc2)[2],
const double (*positions)[3],
const long num_patom,
const long num_satom,
const double *masses_fc2,
const long *p2s_fc2,
const long *s2p_fc2,
const double unit_conversion_factor,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction, /* pointer */
const double nac_factor,
const double *dd_q0,
const double (*G_list)[3],
const long num_G_points,
const double lambda,
const char uplo)
{
long num_undone;
long *undone;
undone = (long *)malloc(sizeof(long) * num_phonons);
num_undone = collect_undone_grid_points(undone,
phonon_done,
num_grid_points,
grid_points);
get_gonze_undone_phonons(frequencies,
eigenvectors,
undone,
num_undone,
grid_address,
QDinv,
fc2,
svecs_fc2,
multi_fc2,
positions,
num_patom,
num_satom,
masses_fc2,
p2s_fc2,
s2p_fc2,
unit_conversion_factor,
born,
dielectric,
reciprocal_lattice,
q_direction,
nac_factor,
dd_q0,
G_list,
num_G_points,
lambda,
uplo);
free(undone);
undone = NULL;
}
static long collect_undone_grid_points(long *undone,
char *phonon_done,
const long num_grid_points,
const long *grid_points)
{
long i, gp, num_undone;
num_undone = 0;
for (i = 0; i < num_grid_points; i++)
{
gp = grid_points[i];
if (phonon_done[gp] == 0)
{
undone[num_undone] = gp;
num_undone++;
phonon_done[gp] = 1;
}
}
return num_undone;
}
static void get_undone_phonons(double *frequencies,
lapack_complex_double *eigenvectors,
const long *undone_grid_points,
const long num_undone_grid_points,
const long (*grid_address)[3],
const double QDinv[3][3],
const double *fc2,
const double (*svecs_fc2)[3],
const long (*multi_fc2)[2],
const long num_patom,
const long num_satom,
const double *masses_fc2,
const long *p2s_fc2,
const long *s2p_fc2,
const double unit_conversion_factor,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const char uplo)
{
long i, j, gp, num_band;
long is_nac, info;
double q[3];
double *freqs_tmp;
num_band = num_patom * 3;
#ifdef PHPYOPENMP
#pragma omp parallel for private(j, q, gp, is_nac)
#endif
for (i = 0; i < num_undone_grid_points; i++)
{
gp = undone_grid_points[i];
for (j = 0; j < 3; j++)
{
q[j] = QDinv[j][0] * grid_address[gp][0] + QDinv[j][1] * grid_address[gp][1] + QDinv[j][2] * grid_address[gp][2];
}
is_nac = needs_nac(born, grid_address, gp, q_direction);
get_phonons(eigenvectors + num_band * num_band * gp,
q,
fc2,
masses_fc2,
p2s_fc2,
s2p_fc2,
multi_fc2,
num_patom,
num_satom,
svecs_fc2,
is_nac,
born,
dielectric,
reciprocal_lattice,
q_direction,
nac_factor,
unit_conversion_factor);
}
/* To avoid multithreaded BLAS in OpenMP loop */
#ifdef PHPYOPENMP
#ifndef MULTITHREADED_BLAS
#pragma omp parallel for private(j, gp, freqs_tmp, info)
#endif
#endif
for (i = 0; i < num_undone_grid_points; i++)
{
gp = undone_grid_points[i];
freqs_tmp = frequencies + num_band * gp;
/* Store eigenvalues in freqs array. */
/* Eigenvectors are overwritten on eigvecs array. */
info = phonopy_zheev(freqs_tmp,
eigenvectors + num_band * num_band * gp,
num_band,
uplo);
/* Sqrt of eigenvalues are re-stored in freqs array.*/
for (j = 0; j < num_band; j++)
{
freqs_tmp[j] = sqrt(fabs(freqs_tmp[j])) *
((freqs_tmp[j] > 0) - (freqs_tmp[j] < 0)) * unit_conversion_factor;
}
}
}
static void get_gonze_undone_phonons(double *frequencies,
lapack_complex_double *eigenvectors,
const long *undone_grid_points,
const long num_undone_grid_points,
const long (*grid_address)[3],
const double QDinv[3][3],
const double *fc2,
const double (*svecs_fc2)[3],
const long (*multi_fc2)[2],
const double (*positions)[3],
const long num_patom,
const long num_satom,
const double *masses_fc2,
const long *p2s_fc2,
const long *s2p_fc2,
const double unit_conversion_factor,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const double *dd_q0,
const double (*G_list)[3],
const long num_G_points,
const double lambda,
const char uplo)
{
long i, j, gp, num_band;
long is_nac, info;
double q[3];
double *freqs_tmp;
num_band = num_patom * 3;
#ifdef PHPYOPENMP
#pragma omp parallel for private(j, q, gp, is_nac)
#endif
for (i = 0; i < num_undone_grid_points; i++)
{
gp = undone_grid_points[i];
for (j = 0; j < 3; j++)
{
q[j] = QDinv[j][0] * grid_address[gp][0] + QDinv[j][1] * grid_address[gp][1] + QDinv[j][2] * grid_address[gp][2];
}
is_nac = needs_nac(born, grid_address, gp, q_direction);
get_gonze_phonons(eigenvectors + num_band * num_band * gp,
q,
fc2,
masses_fc2,
p2s_fc2,
s2p_fc2,
multi_fc2,
positions,
num_patom,
num_satom,
svecs_fc2,
is_nac,
born,
dielectric,
reciprocal_lattice,
q_direction,
nac_factor,
dd_q0,
G_list,
num_G_points,
lambda);
}
/* To avoid multithreaded BLAS in OpenMP loop */
#ifdef PHPYOPENMP
#ifndef MULTITHREADED_BLAS
#pragma omp parallel for private(j, gp, freqs_tmp, info)
#endif
#endif
for (i = 0; i < num_undone_grid_points; i++)
{
gp = undone_grid_points[i];
/* Store eigenvalues in freqs array. */
/* Eigenvectors are overwritten on eigvecs array. */
freqs_tmp = frequencies + num_band * gp;
info = phonopy_zheev(freqs_tmp,
eigenvectors + num_band * num_band * gp,
num_band,
uplo);
/* Sqrt of eigenvalues are re-stored in freqs array.*/
for (j = 0; j < num_band; j++)
{
freqs_tmp[j] = sqrt(fabs(freqs_tmp[j])) *
((freqs_tmp[j] > 0) - (freqs_tmp[j] < 0)) * unit_conversion_factor;
}
}
}
static void get_phonons(lapack_complex_double *eigvecs,
const double q[3],
const double *fc2,
const double *masses,
const long *p2s,
const long *s2p,
const long (*multi)[2],
const long num_patom,
const long num_satom,
const double (*svecs)[3],
const long is_nac,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const double unit_conversion_factor)
{
/* Store dynamical matrix in eigvecs array. */
get_dynamical_matrix(eigvecs,
q,
fc2,
masses,
p2s,
s2p,
multi,
num_patom,
num_satom,
svecs,
is_nac,
born,
dielectric,
reciprocal_lattice,
q_direction,
nac_factor);
}
static void get_gonze_phonons(lapack_complex_double *eigvecs,
const double q[3],
const double *fc2,
const double *masses,
const long *p2s,
const long *s2p,
const long (*multi)[2],
const double (*positions)[3],
const long num_patom,
const long num_satom,
const double (*svecs)[3],
const long is_nac,
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor,
const double *dd_q0,
const double (*G_list)[3],
const long num_G_points,
const double lambda)
{
long i, j, k, l, adrs, num_band;
double mm;
double q_cart[3];
double *q_dir_cart;
lapack_complex_double *dd;
dd = NULL;
q_dir_cart = NULL;
num_band = num_patom * 3;
dym_get_dynamical_matrix_at_q((double *)eigvecs,
num_patom,
num_satom,
fc2,
q,
svecs,
multi,
masses,
s2p,
p2s,
NULL,
0);
dd = (lapack_complex_double *)
malloc(sizeof(lapack_complex_double) * num_band * num_band);
for (i = 0; i < 3; i++)
{
q_cart[i] = 0;
for (j = 0; j < 3; j++)
{
q_cart[i] += reciprocal_lattice[i][j] * q[j];
}
}
if (q_direction)
{
q_dir_cart = (double *)malloc(sizeof(double) * 3);
for (i = 0; i < 3; i++)
{
q_dir_cart[i] = 0;
for (j = 0; j < 3; j++)
{
q_dir_cart[i] += reciprocal_lattice[i][j] * q_direction[j];
}
}
}
dym_get_recip_dipole_dipole((double *)dd,
dd_q0,
G_list,
num_G_points,
num_patom,
q_cart,
q_dir_cart,
born,
dielectric,
positions,
nac_factor,
lambda,
1e-5);
if (q_direction)
{
free(q_dir_cart);
q_dir_cart = NULL;
}
for (i = 0; i < num_patom; i++)
{
for (j = 0; j < num_patom; j++)
{
mm = sqrt(masses[i] * masses[j]);
for (k = 0; k < 3; k++)
{
for (l = 0; l < 3; l++)
{
adrs = i * num_patom * 9 + k * num_patom * 3 + j * 3 + l;
eigvecs[adrs] = lapack_make_complex_double(
lapack_complex_double_real(eigvecs[adrs]) +
lapack_complex_double_real(dd[adrs]) / mm,
lapack_complex_double_imag(eigvecs[adrs]) +
lapack_complex_double_imag(dd[adrs]) / mm);
}
}
}
}
free(dd);
dd = NULL;
}
static void
get_dynamical_matrix(lapack_complex_double *dynmat,
const double q[3],
const double *fc2,
const double *masses,
const long *p2s,
const long *s2p,
const long (*multi)[2],
const long num_patom,
const long num_satom,
const double (*svecs)[3],
const long is_nac,
const double (*born)[3][3], /* Wang NAC unless NULL */
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor)
{
double(*charge_sum)[3][3];
charge_sum = NULL;
if (is_nac)
{
charge_sum = (double(*)[3][3])
malloc(sizeof(double[3][3]) * num_patom * num_patom * 9);
get_charge_sum(charge_sum,
num_patom,
num_satom,
q,
born,
dielectric,
reciprocal_lattice,
q_direction,
nac_factor);
}
dym_get_dynamical_matrix_at_q((double *)dynmat,
num_patom,
num_satom,
fc2,
q,
svecs,
multi,
masses,
s2p,
p2s,
charge_sum,
0);
if (is_nac)
{
free(charge_sum);
charge_sum = NULL;
}
}
static void get_charge_sum(double (*charge_sum)[3][3],
const long num_patom,
const long num_satom,
const double q[3],
const double (*born)[3][3],
const double dielectric[3][3],
const double reciprocal_lattice[3][3],
const double *q_direction,
const double nac_factor)
{
long i, j;
double inv_dielectric_factor, dielectric_factor, tmp_val;
double q_cart[3];
if (q_direction)
{
for (i = 0; i < 3; i++)
{
q_cart[i] = 0.0;
for (j = 0; j < 3; j++)
{
q_cart[i] += reciprocal_lattice[i][j] * q_direction[j];
}
}
}
else
{
for (i = 0; i < 3; i++)
{
q_cart[i] = 0.0;
for (j = 0; j < 3; j++)
{
q_cart[i] += reciprocal_lattice[i][j] * q[j];
}
}
}
inv_dielectric_factor = 0.0;
for (i = 0; i < 3; i++)
{
tmp_val = 0.0;
for (j = 0; j < 3; j++)
{
tmp_val += dielectric[i][j] * q_cart[j];
}
inv_dielectric_factor += tmp_val * q_cart[i];
}
/* N = num_satom / num_patom = number of prim-cell in supercell */
/* N is used for Wang's method. */
dielectric_factor = nac_factor /
inv_dielectric_factor / num_satom * num_patom;
dym_get_charge_sum(charge_sum,
num_patom,
dielectric_factor,
q_cart,
born);
}
static long needs_nac(const double (*born)[3][3],
const long (*grid_address)[3],
const long gp,
const double *q_direction)
{
long is_nac;
if (born)
{
if (grid_address[gp][0] == 0 &&
grid_address[gp][1] == 0 &&
grid_address[gp][2] == 0 &&
q_direction == NULL)
{
is_nac = 0;
}
else
{
is_nac = 1;
}
}
else
{
is_nac = 0;
}
return is_nac;
}
|
array.h | #pragma once
#include <functional>
#include <numeric>
#include <algorithm>
#include <iostream>
#include <memory>
#include "mvector.h"
#include "spaces/ndspace.h"
#include "spaces/ndsymspace.h"
template <typename T, int rank_>
class Array
{
T *data;
mVector<unsigned, rank_> dim;
mVector<size_t, rank_> M;
size_t d_size;
std::shared_ptr<T> dyn;
// std::function<size_t (mVector<unsigned, rank_> const &)> metric;
public:
enum { rank = rank_ };
typedef T Type;
typedef mVector<unsigned, rank> Index;
// typedef std::function<size_t (Index const &)> Metric;
Array() {}
Array(mVector<unsigned, rank> const &dim_):
dim(dim_)
{
d_size = std::accumulate(dim.begin(), dim.end(),
size_t(1), std::multiplies<size_t>());
size_t rtm = 1;
for (unsigned k = 0; k < rank; ++k)
{ M[k] = rtm; rtm *= dim[k]; }
dyn = std::shared_ptr<T>(new T[d_size]);
data = dyn.get();
}
Array(T *data_, mVector<unsigned, rank_> const &dim_):
data(data_), dim(dim_)
{
size_t rtm = 1;
for (unsigned k = 0; k < rank; ++k)
{ M[k] = rtm; rtm *= dim[k]; }
d_size = std::accumulate(dim.begin(), dim.end(),
size_t(1), std::multiplies<size_t>());
// metric = [&M] (Index const &X) -> size_t
// {
// return dot(M, X);
// };
}
void set_data(T *d) { data = d; }
// void set_metric(Metric &m, Index const &dim_)
// {
// dim = dim_;
// metric = m;
//
// size = metric(dim);
// }
void set_dim(Index const &dim_)
{
dim = dim_;
size_t rtm = 1;
for (unsigned k = 0; k < rank; ++k)
{ M[k] = rtm; rtm *= dim[k]; }
//std::cout << dim << " | " << M << std::endl;
d_size = std::accumulate(dim.begin(), dim.end(),
size_t(1), std::multiplies<size_t>());
}
size_t size() const { return d_size; }
size_t metric(Index const &X)
{
return dot(X, M);
}
T &operator[](Index const &X)
{
size_t offset = metric(X);
// std::cout << offset << std::endl;
return data[offset];
}
template <typename F>
void map_indices(F f)
{
Spaces::NdSpace<rank> G(dim);
std::vector<mVector<unsigned, rank>> D(d_size);
std::copy(G.begin(), G.end(), D.begin());
T *loc = data;
#pragma omp parallel for
for (size_t i = 0; i < d_size; ++i)
{
loc[i] = f(D[i]);
}
}
template <typename F>
void map_sym_indices(F f)
{
Spaces::NdSymSpace<rank> G(dim);
std::vector<mVector<unsigned, rank>> D(d_size);
std::copy(G.begin(), G.end(), D.begin());
unsigned s = (dim[0] * (dim[0] + 1)) / 2;
#pragma omp parallel for
for (size_t i = 0; i < s; ++i)
{
T v = f(D[i]); (*this)[D[i]] = v;
while (std::prev_permutation(D[i].begin(), D[i].end()))
(*this)[D[i]] = v;
}
}
T *begin() { return data; }
T const *begin() const { return data; }
T *end() { return data + d_size; }
T const *end() const { return data + d_size; }
};
|
Example_async_target.2.c | /*
* @@name: async_target.2c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_4.0
*/
#include <stdlib.h>
#include <omp.h>
#pragma omp declare target
extern void init(float *, float *, int);
#pragma omp end declare target
extern void foo();
extern void output(float *, int);
void vec_mult(float *p, int N, int dev)
{
float *v1, *v2;
int i;
#pragma omp task shared(v1, v2) depend(out: v1, v2)
#pragma omp target device(dev) map(v1, v2)
{
// check whether on device dev
if (omp_is_initial_device())
abort();
v1 = (float *)malloc(N*sizeof(float));
v2 = (float *)malloc(N*sizeof(float));
init(v1, v2, N);
}
foo(); // execute other work asychronously
#pragma omp task shared(v1, v2, p) depend(in: v1, v2)
#pragma omp target device(dev) map(to: v1, v2) map(from: p[0:N])
{
// check whether on device dev
if (omp_is_initial_device())
abort();
#pragma omp parallel for
for (i=0; i<N; i++)
p[i] = v1[i] * v2[i];
free(v1);
free(v2);
}
#pragma omp taskwait
output(p, N);
}
|
GB_unaryop__lnot_bool_int16.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_bool_int16
// op(A') function: GB_tran__lnot_bool_int16
// C type: bool
// A type: int16_t
// cast: bool cij = (bool) aij
// unaryop: cij = !aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !x ;
// casting
#define GB_CASTING(z, x) \
bool z = (bool) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_BOOL || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_bool_int16
(
bool *restrict Cx,
const int16_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_bool_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
real_to_reciprocal.c | /* Copyright (C) 2015 Atsushi Togo */
/* All rights reserved. */
/* This file is part of phonopy. */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions */
/* are met: */
/* * Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* * Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the */
/* distribution. */
/* * Neither the name of the phonopy project nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */
/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */
/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */
/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */
/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */
/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
#include "real_to_reciprocal.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "lapack_wrapper.h"
#include "phonoc_array.h"
#include "phonoc_const.h"
static void real_to_reciprocal_single_thread(
lapack_complex_double *fc3_reciprocal, const double q_vecs[3][3],
const double *fc3, const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multiplicity)[2],
const long *p2s_map, const long *s2p_map);
static void real_to_reciprocal_openmp(
lapack_complex_double *fc3_reciprocal, const double q_vecs[3][3],
const double *fc3, const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multiplicity)[2],
const long *p2s_map, const long *s2p_map);
static void real_to_reciprocal_elements(
lapack_complex_double *fc3_rec_elem, const double q_vecs[3][3],
const double *fc3, const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multiplicity)[2], const long *p2s,
const long *s2p, const long pi0, const long pi1, const long pi2);
static lapack_complex_double get_phase_factor(const double q[3][3],
const long qi,
const double (*svecs)[3],
const long multi[2]);
static lapack_complex_double get_pre_phase_factor(const long i_patom,
const double q_vecs[3][3],
const double (*svecs)[3],
const long multi_dims[2],
const long (*multiplicity)[2],
const long *p2s_map);
/* fc3_reciprocal[num_patom, num_patom, num_patom, 3, 3, 3] */
void r2r_real_to_reciprocal(lapack_complex_double *fc3_reciprocal,
const double q_vecs[3][3], const double *fc3,
const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2],
const long (*multiplicity)[2], const long *p2s_map,
const long *s2p_map, const long openmp_at_bands) {
if (openmp_at_bands) {
real_to_reciprocal_openmp(fc3_reciprocal, q_vecs, fc3, is_compact_fc3,
svecs, multi_dims, multiplicity, p2s_map,
s2p_map);
} else {
real_to_reciprocal_single_thread(fc3_reciprocal, q_vecs, fc3,
is_compact_fc3, svecs, multi_dims,
multiplicity, p2s_map, s2p_map);
}
}
static void real_to_reciprocal_single_thread(
lapack_complex_double *fc3_reciprocal, const double q_vecs[3][3],
const double *fc3, const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multiplicity)[2],
const long *p2s_map, const long *s2p_map) {
long i, j, k, l, m, n;
long num_patom, num_band;
lapack_complex_double pre_phase_factor, fc3_rec_elem[27];
num_patom = multi_dims[1];
num_band = num_patom * 3;
for (i = 0; i < num_patom; i++) {
pre_phase_factor = get_pre_phase_factor(i, q_vecs, svecs, multi_dims,
multiplicity, p2s_map);
for (j = 0; j < num_patom; j++) {
for (k = 0; k < num_patom; k++) {
real_to_reciprocal_elements(
fc3_rec_elem, q_vecs, fc3, is_compact_fc3, svecs,
multi_dims, multiplicity, p2s_map, s2p_map, i, j, k);
for (l = 0; l < 3; l++) {
for (m = 0; m < 3; m++) {
for (n = 0; n < 3; n++) {
fc3_reciprocal[(i * 3 + l) * num_band * num_band +
(j * 3 + m) * num_band + k * 3 + n] =
phonoc_complex_prod(
fc3_rec_elem[l * 9 + m * 3 + n],
pre_phase_factor);
}
}
}
}
}
}
}
static void real_to_reciprocal_openmp(
lapack_complex_double *fc3_reciprocal, const double q_vecs[3][3],
const double *fc3, const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multiplicity)[2],
const long *p2s_map, const long *s2p_map) {
long i, j, k, l, m, n, jk;
long num_patom, num_band;
lapack_complex_double pre_phase_factor, fc3_rec_elem[27];
num_patom = multi_dims[1];
num_band = num_patom * 3;
for (i = 0; i < num_patom; i++) {
pre_phase_factor = get_pre_phase_factor(i, q_vecs, svecs, multi_dims,
multiplicity, p2s_map);
#ifdef _OPENMP
#pragma omp parallel for private(j, k, l, m, n, fc3_rec_elem)
#endif
for (jk = 0; jk < num_patom * num_patom; jk++) {
j = jk / num_patom;
k = jk % num_patom;
real_to_reciprocal_elements(
fc3_rec_elem, q_vecs, fc3, is_compact_fc3, svecs, multi_dims,
multiplicity, p2s_map, s2p_map, i, j, k);
for (l = 0; l < 3; l++) {
for (m = 0; m < 3; m++) {
for (n = 0; n < 3; n++) {
fc3_reciprocal[(i * 3 + l) * num_band * num_band +
(j * 3 + m) * num_band + k * 3 + n] =
phonoc_complex_prod(fc3_rec_elem[l * 9 + m * 3 + n],
pre_phase_factor);
}
}
}
}
}
}
static void real_to_reciprocal_elements(
lapack_complex_double *fc3_rec_elem, const double q_vecs[3][3],
const double *fc3, const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multiplicity)[2], const long *p2s,
const long *s2p, const long pi0, const long pi1, const long pi2) {
long i, j, k, l;
long num_satom, adrs_shift, adrs_vec1, adrs_vec2;
lapack_complex_double phase_factor, phase_factor1, phase_factor2;
double fc3_rec_real[27], fc3_rec_imag[27];
for (i = 0; i < 27; i++) {
fc3_rec_real[i] = 0;
fc3_rec_imag[i] = 0;
}
num_satom = multi_dims[0];
if (is_compact_fc3) {
i = pi0;
} else {
i = p2s[pi0];
}
for (j = 0; j < num_satom; j++) {
if (s2p[j] != p2s[pi1]) {
continue;
}
adrs_vec1 = j * multi_dims[1] + pi0;
phase_factor1 =
get_phase_factor(q_vecs, 1, svecs, multiplicity[adrs_vec1]);
for (k = 0; k < num_satom; k++) {
if (s2p[k] != p2s[pi2]) {
continue;
}
adrs_vec2 = k * multi_dims[1] + pi0;
phase_factor2 =
get_phase_factor(q_vecs, 2, svecs, multiplicity[adrs_vec2]);
adrs_shift =
i * 27 * num_satom * num_satom + j * 27 * num_satom + k * 27;
phase_factor = phonoc_complex_prod(phase_factor1, phase_factor2);
for (l = 0; l < 27; l++) {
fc3_rec_real[l] += lapack_complex_double_real(phase_factor) *
fc3[adrs_shift + l];
fc3_rec_imag[l] += lapack_complex_double_imag(phase_factor) *
fc3[adrs_shift + l];
}
}
}
for (i = 0; i < 27; i++) {
fc3_rec_elem[i] =
lapack_make_complex_double(fc3_rec_real[i], fc3_rec_imag[i]);
}
}
static lapack_complex_double get_pre_phase_factor(const long i_patom,
const double q_vecs[3][3],
const double (*svecs)[3],
const long multi_dims[2],
const long (*multiplicity)[2],
const long *p2s_map) {
long i, j, svecs_adrs;
double pre_phase, sum_real, sum_imag;
lapack_complex_double pre_phase_factor;
svecs_adrs = p2s_map[i_patom] * multi_dims[1];
sum_real = 0;
sum_imag = 0;
for (i = 0; i < multiplicity[svecs_adrs][0]; i++) {
pre_phase = 0;
for (j = 0; j < 3; j++) {
pre_phase += svecs[multiplicity[svecs_adrs][1] + i][j] *
(q_vecs[0][j] + q_vecs[1][j] + q_vecs[2][j]);
}
pre_phase *= M_2PI;
sum_real += cos(pre_phase);
sum_imag += sin(pre_phase);
}
sum_real /= multiplicity[svecs_adrs][0];
sum_imag /= multiplicity[svecs_adrs][0];
pre_phase_factor = lapack_make_complex_double(sum_real, sum_imag);
return pre_phase_factor;
}
static lapack_complex_double get_phase_factor(const double q[3][3],
const long qi,
const double (*svecs)[3],
const long multi[2]) {
long i, j;
double sum_real, sum_imag, phase;
sum_real = 0;
sum_imag = 0;
for (i = 0; i < multi[0]; i++) {
phase = 0;
for (j = 0; j < 3; j++) {
phase += q[qi][j] * svecs[multi[1] + i][j];
}
phase *= M_2PI;
sum_real += cos(phase);
sum_imag += sin(phase);
}
sum_real /= multi[0];
sum_imag /= multi[0];
return lapack_make_complex_double(sum_real, sum_imag);
}
|
GB_cast_array.c | //------------------------------------------------------------------------------
// GB_cast_array: typecast an array
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// Casts an input array Ax to an output array Cx with a different built-in
// type. Does not handle user-defined types.
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
#endif
void GB_cast_array // typecast an array
(
GB_void *Cx, // output array
const GB_Type_code code1, // type code for Cx
GB_void *Ax, // input array
const GB_Type_code code2, // type code for Ax
const int64_t anz, // number of entries in Cx and Ax
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
if (anz == 0)
{
// no work to do, and the Ax and Cx pointer may be NULL as well
return ;
}
ASSERT (Cx != NULL) ;
ASSERT (Ax != NULL) ;
ASSERT (anz > 0) ;
ASSERT (code1 <= GB_FP64_code) ;
ASSERT (code2 <= GB_FP64_code) ;
ASSERT (GB_code_compatible (code1, code2)) ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (anz, chunk, nthreads_max) ;
//--------------------------------------------------------------------------
// typecase the array
//--------------------------------------------------------------------------
#ifndef GBCOMPACT
//----------------------------------------------------------------------
// define the worker for the switch factory
//----------------------------------------------------------------------
#define GB_unop(zname,xname) GB_unop__identity ## zname ## xname
#define GB_WORKER(ignore1,zname,ztype,xname,xtype) \
{ \
GrB_Info info = GB_unop (zname,xname) ((ztype *) Cx, \
(xtype *) Ax, anz, nthreads) ; \
if (info == GrB_SUCCESS) return ; \
} \
break ;
//----------------------------------------------------------------------
// launch the switch factory
//----------------------------------------------------------------------
#include "GB_2type_factory.c"
#endif
//--------------------------------------------------------------------------
// generic worker: typecasting for compact case only
//--------------------------------------------------------------------------
// This is dead code unless GBCOMPACT is enabled.
GB_BURBLE_N (anz, "generic ") ;
int64_t csize = GB_code_size (code1, 1) ;
int64_t asize = GB_code_size (code2, 1) ;
GB_cast_function cast_A_to_C = GB_cast_factory (code1, code2) ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
// Cx [p] = Ax [p]
cast_A_to_C (Cx +(p*csize), Ax +(p*asize), asize) ;
}
}
|
fac_interp2.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$
***********************************************************************EHEADER*/
/******************************************************************************
* OpenMP Problems
*
* Not sure about performace yet, so leaving the '#if 1' blocks below.
*
******************************************************************************/
/******************************************************************************
* FAC composite level interpolation.
* Identity interpolation of values away from underlying refinement patches;
* linear inside patch.
******************************************************************************/
#include "_hypre_sstruct_ls.h"
#include "fac.h"
/*--------------------------------------------------------------------------
* hypre_FacSemiInterpData data structure
*--------------------------------------------------------------------------*/
typedef struct
{
HYPRE_Int nvars;
HYPRE_Int ndim;
hypre_Index stride;
hypre_SStructPVector *recv_cvectors;
HYPRE_Int **recv_boxnum_map; /* mapping between the boxes of the
recv_grid and the given grid */
hypre_BoxArrayArray **identity_arrayboxes;
hypre_BoxArrayArray **ownboxes;
HYPRE_Int ***own_cboxnums;
hypre_CommPkg **interlevel_comm;
hypre_CommPkg **gnodes_comm_pkg;
HYPRE_Real **weights;
} hypre_FacSemiInterpData2;
/*--------------------------------------------------------------------------
* hypre_FacSemiInterpCreate
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_FacSemiInterpCreate2( void **fac_interp_vdata_ptr )
{
HYPRE_Int ierr= 0;
hypre_FacSemiInterpData2 *fac_interp_data;
fac_interp_data = hypre_CTAlloc(hypre_FacSemiInterpData2, 1);
*fac_interp_vdata_ptr= (void *) fac_interp_data;
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_FacSemiInterpDestroy
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_FacSemiInterpDestroy2( void *fac_interp_vdata)
{
HYPRE_Int ierr = 0;
hypre_FacSemiInterpData2 *fac_interp_data = (hypre_FacSemiInterpData2 *)fac_interp_vdata;
HYPRE_Int i, j, size;
if (fac_interp_data)
{
hypre_SStructPVectorDestroy(fac_interp_data-> recv_cvectors);
for (i= 0; i< (fac_interp_data-> nvars); i++)
{
hypre_TFree(fac_interp_data -> recv_boxnum_map[i]);
hypre_BoxArrayArrayDestroy(fac_interp_data -> identity_arrayboxes[i]);
size= hypre_BoxArrayArraySize(fac_interp_data -> ownboxes[i]);
hypre_BoxArrayArrayDestroy(fac_interp_data -> ownboxes[i]);
for (j= 0; j< size; j++)
{
hypre_TFree(fac_interp_data -> own_cboxnums[i][j]);
}
hypre_TFree(fac_interp_data -> own_cboxnums[i]);
hypre_CommPkgDestroy(fac_interp_data -> gnodes_comm_pkg[i]);
hypre_CommPkgDestroy(fac_interp_data -> interlevel_comm[i]);
}
hypre_TFree(fac_interp_data -> recv_boxnum_map);
hypre_TFree(fac_interp_data -> identity_arrayboxes);
hypre_TFree(fac_interp_data -> ownboxes);
hypre_TFree(fac_interp_data -> own_cboxnums);
hypre_TFree(fac_interp_data -> gnodes_comm_pkg);
hypre_TFree(fac_interp_data -> interlevel_comm);
for (i= 0; i< (fac_interp_data -> ndim); i++)
{
hypre_TFree(fac_interp_data -> weights[i]);
}
hypre_TFree(fac_interp_data -> weights);
hypre_TFree(fac_interp_data);
}
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_FacSemiInterpSetup2:
* Note that an intermediate coarse SStruct_PVector is used in interpolating
* the interlevel communicated data (coarse data). The data in these
* intermediate vectors will be interpolated to the fine grid.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_FacSemiInterpSetup2( void *fac_interp_vdata,
hypre_SStructVector *e,
hypre_SStructPVector *ec,
hypre_Index rfactors)
{
HYPRE_Int ierr = 0;
hypre_FacSemiInterpData2 *fac_interp_data = (hypre_FacSemiInterpData2 *)fac_interp_vdata;
HYPRE_Int part_fine= 1;
HYPRE_Int part_crse= 0;
hypre_CommPkg **gnodes_comm_pkg;
hypre_CommPkg **interlevel_comm;
hypre_CommInfo *comm_info;
hypre_SStructPVector *recv_cvectors;
hypre_SStructPGrid *recv_cgrid;
HYPRE_Int **recv_boxnum_map;
hypre_SStructGrid *temp_grid;
hypre_SStructPGrid *pgrid;
hypre_SStructPVector *ef= hypre_SStructVectorPVector(e, part_fine);
hypre_StructVector *e_var, *s_rc, *s_cvector;
hypre_BoxArrayArray **identity_arrayboxes;
hypre_BoxArrayArray **ownboxes;
hypre_BoxArrayArray **send_boxes, *send_rboxes;
HYPRE_Int ***send_processes;
HYPRE_Int ***send_remote_boxnums;
hypre_BoxArrayArray **recv_boxes, *recv_rboxes;
HYPRE_Int ***recv_processes;
HYPRE_Int ***recv_remote_boxnums;
hypre_BoxArray *boxarray;
hypre_BoxArray *tmp_boxarray, *intersect_boxes;
hypre_Box box, scaled_box;
HYPRE_Int ***own_cboxnums;
hypre_BoxManager *boxman1;
hypre_BoxManEntry **boxman_entries;
HYPRE_Int nboxman_entries;
HYPRE_Int nvars= hypre_SStructPVectorNVars(ef);
HYPRE_Int vars;
hypre_Index zero_index, index;
hypre_Index ilower, iupper;
HYPRE_Int *num_ghost;
HYPRE_Int ndim, i, j, k, fi, ci;
HYPRE_Int cnt1, cnt2;
HYPRE_Int proc, myproc, tot_procs;
HYPRE_Int num_values;
HYPRE_Real **weights;
HYPRE_Real refine_factors_2recp[3];
hypre_Index refine_factors_half;
hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myproc);
hypre_MPI_Comm_size(hypre_MPI_COMM_WORLD, &tot_procs);
ndim= hypre_SStructPGridNDim(hypre_SStructPVectorPGrid(ef));
hypre_SetIndex3(zero_index, 0, 0, 0);
hypre_BoxInit(&box, ndim);
hypre_BoxInit(&scaled_box, ndim);
/*------------------------------------------------------------------------
* Intralevel communication structures-
* A communication pkg must be created for each StructVector. Stencils
* are needed in creating the packages- we are assuming that the same
* stencil pattern for each StructVector, i.e., linear interpolation for
* each variable.
*------------------------------------------------------------------------*/
gnodes_comm_pkg= hypre_CTAlloc(hypre_CommPkg *, nvars);
for (vars= 0; vars< nvars; vars++)
{
e_var= hypre_SStructPVectorSVector(ec, vars);
num_ghost= hypre_StructVectorNumGhost(e_var);
hypre_CreateCommInfoFromNumGhost(hypre_StructVectorGrid(e_var),
num_ghost, &comm_info);
hypre_CommPkgCreate(comm_info,
hypre_StructVectorDataSpace(e_var),
hypre_StructVectorDataSpace(e_var),
1, NULL, 0, hypre_StructVectorComm(e_var),
&gnodes_comm_pkg[vars]);
hypre_CommInfoDestroy(comm_info);
}
(fac_interp_data -> ndim) = ndim;
(fac_interp_data -> nvars) = nvars;
(fac_interp_data -> gnodes_comm_pkg)= gnodes_comm_pkg;
hypre_CopyIndex(rfactors, (fac_interp_data -> stride));
/*------------------------------------------------------------------------
* Interlevel communication structures.
*
* Algorithm for identity_boxes: For each cbox on this processor, refine
* it and intersect it with the fmap.
* (cbox - all coarsened fmap_intersect boxes)= identity chunks
* for cbox.
*
* Algorithm for own_boxes (fullwgted boxes on this processor): For each
* fbox, coarsen it and boxmap intersect it with cmap.
* (cmap_intersect boxes on myproc)= ownboxes
* for this fbox.
*
* Algorithm for recv_box: For each fbox, coarsen it and boxmap intersect
* it with cmap.
* (cmap_intersect boxes off_proc)= unstretched recv_boxes.
* These boxes are stretched by one in each direction so that the ghostlayer
* is also communicated. However, the recv_grid will consists of the
* unstretched boxes so that overlapping does not occur.
*--------------------------------------------------------------------------*/
identity_arrayboxes= hypre_CTAlloc(hypre_BoxArrayArray *, nvars);
pgrid= hypre_SStructPVectorPGrid(ec);
hypre_ClearIndex(index);
for (i= 0; i< ndim; i++)
{
index[i]= rfactors[i]-1;
}
tmp_boxarray = hypre_BoxArrayCreate(0, ndim);
for (vars= 0; vars< nvars; vars++)
{
boxman1= hypre_SStructGridBoxManager(hypre_SStructVectorGrid(e),
part_fine, vars);
boxarray= hypre_StructGridBoxes(hypre_SStructPGridSGrid(pgrid, vars));
identity_arrayboxes[vars]= hypre_BoxArrayArrayCreate(hypre_BoxArraySize(boxarray), ndim);
hypre_ForBoxI(ci, boxarray)
{
box= *hypre_BoxArrayBox(boxarray, ci);
hypre_AppendBox(&box,
hypre_BoxArrayArrayBoxArray(identity_arrayboxes[vars], ci));
hypre_StructMapCoarseToFine(hypre_BoxIMin(&box), zero_index,
rfactors, hypre_BoxIMin(&scaled_box));
hypre_StructMapCoarseToFine(hypre_BoxIMax(&box), index,
rfactors, hypre_BoxIMax(&scaled_box));
hypre_BoxManIntersect(boxman1, hypre_BoxIMin(&scaled_box),
hypre_BoxIMax(&scaled_box), &boxman_entries,
&nboxman_entries);
intersect_boxes= hypre_BoxArrayCreate(0, ndim);
for (i= 0; i< nboxman_entries; i++)
{
hypre_BoxManEntryGetExtents(boxman_entries[i], ilower, iupper);
hypre_BoxSetExtents(&box, ilower, iupper);
hypre_IntersectBoxes(&box, &scaled_box, &box);
/* contract this refined box so that only the coarse nodes on this
processor will be subtracted. */
for (j= 0; j< ndim; j++)
{
k= hypre_BoxIMin(&box)[j] % rfactors[j];
if (k)
{
hypre_BoxIMin(&box)[j]+= rfactors[j] - k;
}
}
hypre_StructMapFineToCoarse(hypre_BoxIMin(&box), zero_index,
rfactors, hypre_BoxIMin(&box));
hypre_StructMapFineToCoarse(hypre_BoxIMax(&box), zero_index,
rfactors, hypre_BoxIMax(&box));
hypre_AppendBox(&box, intersect_boxes);
}
hypre_SubtractBoxArrays(hypre_BoxArrayArrayBoxArray(identity_arrayboxes[vars], ci),
intersect_boxes, tmp_boxarray);
hypre_MinUnionBoxes(hypre_BoxArrayArrayBoxArray(identity_arrayboxes[vars], ci));
hypre_TFree(boxman_entries);
hypre_BoxArrayDestroy(intersect_boxes);
}
}
hypre_BoxArrayDestroy(tmp_boxarray);
fac_interp_data -> identity_arrayboxes= identity_arrayboxes;
/*--------------------------------------------------------------------------
* fboxes are coarsened. For each coarsened fbox, we need a boxarray of
* recvboxes or ownboxes.
*--------------------------------------------------------------------------*/
ownboxes= hypre_CTAlloc(hypre_BoxArrayArray *, nvars);
own_cboxnums= hypre_CTAlloc(HYPRE_Int **, nvars);
recv_boxes= hypre_CTAlloc(hypre_BoxArrayArray *, nvars);
recv_processes= hypre_CTAlloc(HYPRE_Int **, nvars);
/* dummy pointer for CommInfoCreate */
recv_remote_boxnums= hypre_CTAlloc(HYPRE_Int **, nvars);
hypre_ClearIndex(index);
for (i= 0; i< ndim; i++)
{
index[i]= 1;
}
for (vars= 0; vars< nvars; vars++)
{
boxman1= hypre_SStructGridBoxManager(hypre_SStructVectorGrid(e),
part_crse, vars);
pgrid= hypre_SStructPVectorPGrid(ef);
boxarray= hypre_StructGridBoxes(hypre_SStructPGridSGrid(pgrid, vars));
ownboxes[vars] = hypre_BoxArrayArrayCreate(hypre_BoxArraySize(boxarray), ndim);
own_cboxnums[vars]= hypre_CTAlloc(HYPRE_Int *, hypre_BoxArraySize(boxarray));
recv_boxes[vars] = hypre_BoxArrayArrayCreate(hypre_BoxArraySize(boxarray), ndim);
recv_processes[vars]= hypre_CTAlloc(HYPRE_Int *, hypre_BoxArraySize(boxarray));
recv_remote_boxnums[vars]= hypre_CTAlloc(HYPRE_Int *, hypre_BoxArraySize(boxarray));
hypre_ForBoxI(fi, boxarray)
{
box= *hypre_BoxArrayBox(boxarray, fi);
/*--------------------------------------------------------------------
* Adjust this box so that only the coarse nodes inside the fine box
* are extracted.
*--------------------------------------------------------------------*/
for (j= 0; j< ndim; j++)
{
k= hypre_BoxIMin(&box)[j] % rfactors[j];
if (k)
{
hypre_BoxIMin(&box)[j]+= rfactors[j] - k;
}
}
hypre_StructMapFineToCoarse(hypre_BoxIMin(&box), zero_index,
rfactors, hypre_BoxIMin(&scaled_box));
hypre_StructMapFineToCoarse(hypre_BoxIMax(&box), zero_index,
rfactors, hypre_BoxIMax(&scaled_box));
hypre_BoxManIntersect(boxman1, hypre_BoxIMin(&scaled_box),
hypre_BoxIMax(&scaled_box), &boxman_entries, &nboxman_entries);
cnt1= 0; cnt2= 0;
for (i= 0; i< nboxman_entries; i++)
{
hypre_SStructBoxManEntryGetProcess(boxman_entries[i], &proc);
if (proc == myproc)
{
cnt1++;
}
else
{
cnt2++;
}
}
own_cboxnums[vars][fi] = hypre_CTAlloc(HYPRE_Int, cnt1);
recv_processes[vars][fi]= hypre_CTAlloc(HYPRE_Int, cnt2);
recv_remote_boxnums[vars][fi]= hypre_CTAlloc(HYPRE_Int , cnt2);
cnt1= 0; cnt2= 0;
for (i= 0; i< nboxman_entries; i++)
{
hypre_BoxManEntryGetExtents(boxman_entries[i], ilower, iupper);
hypre_BoxSetExtents(&box, ilower, iupper);
hypre_IntersectBoxes(&box, &scaled_box, &box);
hypre_SStructBoxManEntryGetProcess(boxman_entries[i], &proc);
if (proc == myproc)
{
hypre_AppendBox(&box,
hypre_BoxArrayArrayBoxArray(ownboxes[vars], fi));
hypre_SStructBoxManEntryGetBoxnum(boxman_entries[i],
&own_cboxnums[vars][fi][cnt1]);
cnt1++;
}
else
{
/* extend the box so all the required data for interpolation is recvd. */
hypre_SubtractIndexes(hypre_BoxIMin(&box), index, 3,
hypre_BoxIMin(&box));
hypre_AddIndexes(hypre_BoxIMax(&box), index, 3, hypre_BoxIMax(&box));
hypre_AppendBox(&box,
hypre_BoxArrayArrayBoxArray(recv_boxes[vars], fi));
recv_processes[vars][fi][cnt2]= proc;
cnt2++;
}
}
hypre_TFree(boxman_entries);
} /* hypre_ForBoxI(fi, boxarray) */
} /* for (vars= 0; vars< nvars; vars++) */
(fac_interp_data -> ownboxes)= ownboxes;
(fac_interp_data -> own_cboxnums)= own_cboxnums;
/*--------------------------------------------------------------------------
* With the recv'ed boxes form a SStructPGrid and a SStructGrid. The
* SStructGrid is needed to generate a box_manager (so that a local box ordering
* for the remote_boxnums are obtained). Record the recv_boxnum/fbox_num
* mapping. That is, we interpolate a recv_box l to a fine box m, generally
* l != m since the recv_grid and fgrid do not agree.
*--------------------------------------------------------------------------*/
HYPRE_SStructGridCreate(hypre_SStructPVectorComm(ec),
ndim, 1, &temp_grid);
hypre_SStructPGridCreate(hypre_SStructPVectorComm(ec), ndim, &recv_cgrid);
recv_boxnum_map= hypre_CTAlloc(HYPRE_Int *, nvars);
cnt2= 0;
hypre_ClearIndex(index);
for (i= 0; i< ndim; i++)
{
index[i]= 1;
}
for (vars= 0; vars< nvars; vars++)
{
cnt1= 0;
hypre_ForBoxArrayI(i, recv_boxes[vars])
{
boxarray= hypre_BoxArrayArrayBoxArray(recv_boxes[vars], i);
cnt1+= hypre_BoxArraySize(boxarray);
}
recv_boxnum_map[vars]= hypre_CTAlloc(HYPRE_Int, cnt1);
cnt1= 0;
hypre_ForBoxArrayI(i, recv_boxes[vars])
{
boxarray= hypre_BoxArrayArrayBoxArray(recv_boxes[vars], i);
hypre_ForBoxI(j, boxarray)
{
box= *hypre_BoxArrayBox(boxarray, j);
/* contract the box its actual size. */
hypre_AddIndexes(hypre_BoxIMin(&box), index, 3, hypre_BoxIMin(&box));
hypre_SubtractIndexes(hypre_BoxIMax(&box), index, 3,
hypre_BoxIMax(&box));
hypre_SStructPGridSetExtents(recv_cgrid,
hypre_BoxIMin(&box),
hypre_BoxIMax(&box));
HYPRE_SStructGridSetExtents(temp_grid, 0,
hypre_BoxIMin(&box),
hypre_BoxIMax(&box));
recv_boxnum_map[vars][cnt1]= i; /* record the fbox num. i */
cnt1++;
cnt2++;
}
}
}
/*------------------------------------------------------------------------
* When there are no boxes to communicate, set the temp_grid to have a
* box of size zero. This is needed so that this SStructGrid can be
* assembled. This is done only when this only one processor.
*------------------------------------------------------------------------*/
if (cnt2 == 0)
{
/* min_index > max_index so that the box has volume zero. */
hypre_BoxSetExtents(&box, index, zero_index);
hypre_SStructPGridSetExtents(recv_cgrid,
hypre_BoxIMin(&box),
hypre_BoxIMax(&box));
HYPRE_SStructGridSetExtents(temp_grid, 0,
hypre_BoxIMin(&box),
hypre_BoxIMax(&box));
}
HYPRE_SStructGridSetVariables(temp_grid, 0,
hypre_SStructPGridNVars(pgrid),
hypre_SStructPGridVarTypes(pgrid));
HYPRE_SStructGridAssemble(temp_grid);
hypre_SStructPGridSetVariables(recv_cgrid, nvars,
hypre_SStructPGridVarTypes(pgrid) );
hypre_SStructPGridAssemble(recv_cgrid);
hypre_SStructPVectorCreate(hypre_SStructPGridComm(recv_cgrid), recv_cgrid,
&recv_cvectors);
hypre_SStructPVectorInitialize(recv_cvectors);
hypre_SStructPVectorAssemble(recv_cvectors);
fac_interp_data -> recv_cvectors = recv_cvectors;
fac_interp_data -> recv_boxnum_map= recv_boxnum_map;
/* pgrid recv_cgrid no longer needed. */
hypre_SStructPGridDestroy(recv_cgrid);
/*------------------------------------------------------------------------
* Send_boxes.
* Algorithm for send_boxes: For each cbox on this processor, box_map
* intersect it with temp_grid's map.
* (intersection boxes off-proc)= send_boxes for this cbox.
* Note that the send_boxes will be stretched to include the ghostlayers.
* This guarantees that all the data required for linear interpolation
* will be on the processor. Also, note that the remote_boxnums are
* with respect to the recv_cgrid box numbering.
*--------------------------------------------------------------------------*/
send_boxes= hypre_CTAlloc(hypre_BoxArrayArray *, nvars);
send_processes= hypre_CTAlloc(HYPRE_Int **, nvars);
send_remote_boxnums= hypre_CTAlloc(HYPRE_Int **, nvars);
hypre_ClearIndex(index);
for (i= 0; i< ndim; i++)
{
index[i]= 1;
}
for (vars= 0; vars< nvars; vars++)
{
/*-------------------------------------------------------------------
* send boxes: intersect with temp_grid that has all the recv boxes-
* These local box_nums may not be the same as the local box_nums of
* the coarse grid.
*-------------------------------------------------------------------*/
boxman1= hypre_SStructGridBoxManager(temp_grid, 0, vars);
pgrid= hypre_SStructPVectorPGrid(ec);
boxarray= hypre_StructGridBoxes(hypre_SStructPGridSGrid(pgrid, vars));
send_boxes[vars]= hypre_BoxArrayArrayCreate(hypre_BoxArraySize(boxarray), ndim);
send_processes[vars]= hypre_CTAlloc(HYPRE_Int *, hypre_BoxArraySize(boxarray));
send_remote_boxnums[vars]= hypre_CTAlloc(HYPRE_Int *, hypre_BoxArraySize(boxarray));
hypre_ForBoxI(ci, boxarray)
{
box= *hypre_BoxArrayBox(boxarray, ci);
hypre_BoxSetExtents(&scaled_box, hypre_BoxIMin(&box), hypre_BoxIMax(&box));
hypre_BoxManIntersect(boxman1, hypre_BoxIMin(&scaled_box),
hypre_BoxIMax(&scaled_box), &boxman_entries, &nboxman_entries);
cnt1= 0;
for (i= 0; i< nboxman_entries; i++)
{
hypre_SStructBoxManEntryGetProcess(boxman_entries[i], &proc);
if (proc != myproc)
{
cnt1++;
}
}
send_processes[vars][ci] = hypre_CTAlloc(HYPRE_Int, cnt1);
send_remote_boxnums[vars][ci]= hypre_CTAlloc(HYPRE_Int, cnt1);
cnt1= 0;
for (i= 0; i< nboxman_entries; i++)
{
hypre_BoxManEntryGetExtents(boxman_entries[i], ilower, iupper);
hypre_BoxSetExtents(&box, ilower, iupper);
hypre_IntersectBoxes(&box, &scaled_box, &box);
hypre_SStructBoxManEntryGetProcess(boxman_entries[i], &proc);
if (proc != myproc)
{
/* strech the box */
hypre_SubtractIndexes(hypre_BoxIMin(&box), index, 3,
hypre_BoxIMin(&box));
hypre_AddIndexes(hypre_BoxIMax(&box), index, 3, hypre_BoxIMax(&box));
hypre_AppendBox(&box,
hypre_BoxArrayArrayBoxArray(send_boxes[vars], ci));
send_processes[vars][ci][cnt1]= proc;
hypre_SStructBoxManEntryGetBoxnum(
boxman_entries[i], &send_remote_boxnums[vars][ci][cnt1]);
cnt1++;
}
}
hypre_TFree(boxman_entries);
} /* hypre_ForBoxI(ci, boxarray) */
} /* for (vars= 0; vars< nvars; vars++) */
/*--------------------------------------------------------------------------
* Can disgard temp_grid now- only needed it's box_man info,
*--------------------------------------------------------------------------*/
HYPRE_SStructGridDestroy(temp_grid);
/*--------------------------------------------------------------------------
* Can create the interlevel_comm.
*--------------------------------------------------------------------------*/
interlevel_comm= hypre_CTAlloc(hypre_CommPkg *, nvars);
num_values= 1;
for (vars= 0; vars< nvars; vars++)
{
s_rc= hypre_SStructPVectorSVector(ec, vars);
s_cvector= hypre_SStructPVectorSVector(recv_cvectors, vars);
send_rboxes= hypre_BoxArrayArrayDuplicate(send_boxes[vars]);
recv_rboxes= hypre_BoxArrayArrayDuplicate(recv_boxes[vars]);
hypre_CommInfoCreate(send_boxes[vars], recv_boxes[vars],
send_processes[vars], recv_processes[vars],
send_remote_boxnums[vars], recv_remote_boxnums[vars],
send_rboxes, recv_rboxes, 1, &comm_info);
hypre_CommPkgCreate(comm_info,
hypre_StructVectorDataSpace(s_rc),
hypre_StructVectorDataSpace(s_cvector),
num_values, NULL, 0,
hypre_StructVectorComm(s_rc),
&interlevel_comm[vars]);
hypre_CommInfoDestroy(comm_info);
}
hypre_TFree(send_boxes);
hypre_TFree(recv_boxes);
hypre_TFree(send_processes);
hypre_TFree(recv_processes);
hypre_TFree(send_remote_boxnums);
hypre_TFree(recv_remote_boxnums);
(fac_interp_data -> interlevel_comm)= interlevel_comm;
/* interpolation weights */
weights= hypre_TAlloc(HYPRE_Real *, ndim);
for (i= 0; i< ndim; i++)
{
weights[i]= hypre_CTAlloc(HYPRE_Real, rfactors[i]+1);
}
hypre_ClearIndex(refine_factors_half);
/* hypre_ClearIndex(refine_factors_2recp);*/
for (i= 0; i< ndim; i++)
{
refine_factors_half[i] = rfactors[i]/2;
refine_factors_2recp[i]= 1.0/(2.0*rfactors[i]);
}
for (i= 0; i< ndim; i++)
{
for (j= 0; j<= refine_factors_half[i]; j++)
{
weights[i][j]= refine_factors_2recp[i]*(rfactors[i] + 2*j - 1.0);
}
for (j= (refine_factors_half[i]+1); j<= rfactors[i]; j++)
{
weights[i][j]= refine_factors_2recp[i]*(2*j - rfactors[i] - 1.0);
}
}
(fac_interp_data -> weights)= weights;
return ierr;
}
HYPRE_Int
hypre_FAC_IdentityInterp2(void * fac_interp_vdata,
hypre_SStructPVector * xc,
hypre_SStructVector * e)
{
hypre_FacSemiInterpData2 *interp_data= (hypre_FacSemiInterpData2 *)fac_interp_vdata;
hypre_BoxArrayArray **identity_boxes= interp_data-> identity_arrayboxes;
HYPRE_Int part_crse= 0;
HYPRE_Int ierr = 0;
/*-----------------------------------------------------------------------
* Compute e at coarse points (injection).
* The pgrid of xc is the same as the part_csre pgrid of e.
*-----------------------------------------------------------------------*/
hypre_SStructPartialPCopy(xc,
hypre_SStructVectorPVector(e, part_crse),
identity_boxes);
return ierr;
}
/*-------------------------------------------------------------------------
* Linear interpolation. Interpolate the vector first by interpolating the
* values in ownboxes and then values in recv_cvectors (the interlevel
* communicated data).
*-------------------------------------------------------------------------*/
HYPRE_Int
hypre_FAC_WeightedInterp2(void *fac_interp_vdata,
hypre_SStructPVector *xc,
hypre_SStructVector *e_parts)
{
HYPRE_Int ierr = 0;
hypre_FacSemiInterpData2 *interp_data = (hypre_FacSemiInterpData2 *)fac_interp_vdata;
hypre_CommPkg **comm_pkg = interp_data-> gnodes_comm_pkg;
hypre_CommPkg **interlevel_comm= interp_data-> interlevel_comm;
hypre_SStructPVector *recv_cvectors = interp_data-> recv_cvectors;
HYPRE_Int **recv_boxnum_map= interp_data-> recv_boxnum_map;
hypre_BoxArrayArray **ownboxes = interp_data-> ownboxes;
HYPRE_Int ***own_cboxnums = interp_data-> own_cboxnums;
HYPRE_Real **weights = interp_data-> weights;
HYPRE_Int ndim = interp_data-> ndim;
hypre_CommHandle *comm_handle;
hypre_IndexRef stride; /* refinement factors */
hypre_SStructPVector *e;
hypre_StructGrid *fgrid;
hypre_BoxArray *fgrid_boxes;
hypre_Box *fbox;
hypre_BoxArrayArray *own_cboxes;
hypre_BoxArray *own_abox;
hypre_Box *ownbox;
HYPRE_Int **var_boxnums;
HYPRE_Int *cboxnums;
hypre_Box *xc_dbox;
hypre_Box *e_dbox;
hypre_Box refined_box, intersect_box;
hypre_StructVector *xc_var;
hypre_StructVector *e_var;
hypre_StructVector *recv_var;
HYPRE_Int xci;
HYPRE_Int ei;
HYPRE_Real ***xcp;
HYPRE_Real ***ep;
hypre_Index loop_size, lindex;
hypre_Index start, start_offset;
hypre_Index startc;
hypre_Index stridec;
hypre_Index refine_factors;
hypre_Index refine_factors_half;
hypre_Index intersect_size;
hypre_Index zero_index, temp_index1, temp_index2;
HYPRE_Int fi, bi;
HYPRE_Int nvars, var;
HYPRE_Int i, j, k, offset_ip1, offset_jp1, offset_kp1;
HYPRE_Int ishift, jshift, kshift;
HYPRE_Int ptr_ishift, ptr_jshift, ptr_kshift;
HYPRE_Int imax, jmax, kmax;
HYPRE_Int jsize, ksize;
HYPRE_Int part_fine= 1;
HYPRE_Real xweight1, xweight2;
HYPRE_Real yweight1, yweight2;
HYPRE_Real zweight1, zweight2;
/*-----------------------------------------------------------------------
* Initialize some things
*-----------------------------------------------------------------------*/
hypre_BoxInit(&refined_box, ndim);
hypre_BoxInit(&intersect_box, ndim);
stride = (interp_data -> stride);
hypre_SetIndex3(zero_index, 0, 0, 0);
hypre_CopyIndex(stride, refine_factors);
for (i= ndim; i< 3; i++)
{
refine_factors[i]= 1;
}
hypre_SetIndex3(stridec, 1, 1, 1);
for (i= 0; i< ndim; i++)
{
refine_factors_half[i]= refine_factors[i]/2;
}
/*-----------------------------------------------------------------------
* Compute e in the refined patch. But first communicate the coarse
* data. Will need a ghostlayer communication on the given level and an
* interlevel communication between levels.
*-----------------------------------------------------------------------*/
nvars= hypre_SStructPVectorNVars(xc);
for (var= 0; var< nvars; var++)
{
xc_var= hypre_SStructPVectorSVector(xc, var);
hypre_InitializeCommunication(comm_pkg[var],
hypre_StructVectorData(xc_var),
hypre_StructVectorData(xc_var), 0, 0,
&comm_handle);
hypre_FinalizeCommunication(comm_handle);
if (recv_cvectors != NULL)
{
recv_var= hypre_SStructPVectorSVector(recv_cvectors, var);
hypre_InitializeCommunication(interlevel_comm[var],
hypre_StructVectorData(xc_var),
hypre_StructVectorData(recv_var), 0, 0,
&comm_handle);
hypre_FinalizeCommunication(comm_handle);
}
}
e= hypre_SStructVectorPVector(e_parts, part_fine);
/*-----------------------------------------------------------------------
* Allocate memory for the data pointers. Assuming linear interpolation.
* We stride through the refinement patch by the refinement factors, and
* so we must have pointers to the intermediate fine nodes=> ep will
* be size refine_factors[2]*refine_factors[1]. This holds for all
* dimensions since refine_factors[i]= 1 for i>= ndim.
* Note that we need 3 coarse nodes per coordinate direction for the
* interpolating. This is dimensional dependent:
* ndim= 3 kplane= 0,1,2 & jplane= 0,1,2 **ptr size [3][3]
* ndim= 2 kplane= 0 & jplane= 0,1,2 **ptr size [1][3]
* ndim= 1 kplane= 0 & jplane= 0 **ptr size [1][1]
*-----------------------------------------------------------------------*/
ksize= 3;
jsize= 3;
if (ndim < 3)
{
ksize= 1;
}
if (ndim < 2)
{
jsize= 1;
}
xcp = hypre_TAlloc(HYPRE_Real **, ksize);
ep = hypre_TAlloc(HYPRE_Real **, refine_factors[2]);
for (k= 0; k< refine_factors[2]; k++)
{
ep[k]= hypre_TAlloc(HYPRE_Real *, refine_factors[1]);
}
for (k= 0; k< ksize; k++)
{
xcp[k]= hypre_TAlloc(HYPRE_Real *, jsize);
}
for (var= 0; var< nvars; var++)
{
xc_var= hypre_SStructPVectorSVector(xc, var);
e_var = hypre_SStructPVectorSVector(e, var);
fgrid = hypre_StructVectorGrid(e_var);
fgrid_boxes= hypre_StructGridBoxes(fgrid);
own_cboxes = ownboxes[var];
var_boxnums= own_cboxnums[var];
/*--------------------------------------------------------------------
* Interpolate the own_box coarse grid values.
*--------------------------------------------------------------------*/
hypre_ForBoxI(fi, fgrid_boxes)
{
fbox= hypre_BoxArrayBox(fgrid_boxes, fi);
e_dbox= hypre_BoxArrayBox(hypre_StructVectorDataSpace(e_var), fi);
own_abox= hypre_BoxArrayArrayBoxArray(own_cboxes, fi);
cboxnums= var_boxnums[fi];
/*--------------------------------------------------------------------
* Get the ptrs for the fine struct_vectors.
*--------------------------------------------------------------------*/
for (k= 0; k< refine_factors[2]; k++)
{
for (j=0; j< refine_factors[1]; j++)
{
hypre_SetIndex3(temp_index1, 0, j, k);
ep[k][j]= hypre_StructVectorBoxData(e_var, fi) +
hypre_BoxOffsetDistance(e_dbox, temp_index1);
}
}
hypre_ForBoxI(bi, own_abox)
{
ownbox= hypre_BoxArrayBox(own_abox, bi);
hypre_StructMapCoarseToFine(hypre_BoxIMin(ownbox), zero_index,
refine_factors, hypre_BoxIMin(&refined_box));
hypre_ClearIndex(temp_index1);
for (j= 0; j< ndim; j++)
{
temp_index1[j]= refine_factors[j]-1;
}
hypre_StructMapCoarseToFine(hypre_BoxIMax(ownbox), temp_index1,
refine_factors, hypre_BoxIMax(&refined_box));
hypre_IntersectBoxes(fbox, &refined_box, &intersect_box);
xc_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(xc_var),
cboxnums[bi]);
/*-----------------------------------------------------------------
* Get ptrs for the crse struct_vectors. For linear interpolation
* and arbitrary refinement factors, we need to point to the correct
* coarse grid nodes. Note that the ownboxes were created so that
* only the coarse nodes inside a fbox are contained in ownbox.
* Since we loop over the fine intersect box, we need to refine
* ownbox.
*-----------------------------------------------------------------*/
hypre_CopyIndex(hypre_BoxIMin(&intersect_box), start);
hypre_CopyIndex(hypre_BoxIMax(&intersect_box), intersect_size);
for (i= 0; i< 3; i++)
{
intersect_size[i]-= (start[i]-1);
}
/*------------------------------------------------------------------
* The fine intersection box may not be divisible by the refinement
* factor. This means that the interpolated coarse nodes and their
* wieghts must be carefully determined. We accomplish this using the
* offset away from a fine index that is divisible by the factor.
* Because the ownboxes were created so that only coarse nodes
* completely in the fbox are included, start is always divisible
* by refine_factors. We do the calculation anyways for future changes.
*------------------------------------------------------------------*/
hypre_ClearIndex(start_offset);
for (i= 0; i< ndim; i++)
{
start_offset[i]= start[i] % refine_factors[i];
}
ptr_kshift= 0;
if ( (start[2]%refine_factors[2] < refine_factors_half[2]) && ndim == 3 )
{
ptr_kshift= -1;
}
ptr_jshift= 0;
if ( start[1]%refine_factors[1] < refine_factors_half[1] && ndim >= 2 )
{
ptr_jshift= -1;
}
ptr_ishift= 0;
if ( start[0]%refine_factors[0] < refine_factors_half[0] )
{
ptr_ishift= -1;
}
for (k= 0; k< ksize; k++)
{
for (j=0; j< jsize; j++)
{
hypre_SetIndex3(temp_index2, ptr_ishift, j+ptr_jshift, k+ptr_kshift);
xcp[k][j]= hypre_StructVectorBoxData(xc_var, cboxnums[bi]) +
hypre_BoxOffsetDistance(xc_dbox, temp_index2);
}
}
hypre_CopyIndex(hypre_BoxIMin(ownbox), startc);
hypre_BoxGetSize(ownbox, loop_size);
hypre_BoxLoop2Begin(ndim, loop_size,
e_dbox, start, stride, ei,
xc_dbox, startc, stridec, xci);
#if 1
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,xci,lindex,imax,jmax,kmax,k,offset_kp1,zweight2,kshift,zweight1,j,offset_jp1,yweight2,jshift,yweight1,i,offset_ip1,xweight2,ishift,xweight1) HYPRE_SMP_SCHEDULE
#endif
#else
hypre_BoxLoopSetOneBlock();
#endif
hypre_BoxLoop2For(ei, xci)
{
/*--------------------------------------------------------
* Linear interpolation. Determine the weights and the
* correct coarse grid values to be weighted. All fine
* values in an agglomerated coarse cell or in the remainder
* agglomerated coarse cells are determined. The upper
* extents are needed.
*--------------------------------------------------------*/
hypre_BoxLoopGetIndex(lindex);
imax= hypre_min( (intersect_size[0]-lindex[0]*stride[0]),
refine_factors[0] );
jmax= hypre_min( (intersect_size[1]-lindex[1]*stride[1]),
refine_factors[1]);
kmax= hypre_min( (intersect_size[2]-lindex[2]*stride[2]),
refine_factors[2]);
for (k= 0; k< kmax; k++)
{
if (ndim == 3)
{
offset_kp1= start_offset[2]+k+1;
if (ptr_kshift == -1)
{
if (offset_kp1 <= refine_factors_half[2])
{
zweight2= weights[2][offset_kp1];
kshift= 0;
}
else
{
kshift= 1;
if (offset_kp1 > refine_factors_half[2] &&
offset_kp1 <= refine_factors[2])
{
zweight2= weights[2][offset_kp1];
}
else
{
zweight2= weights[2][offset_kp1-refine_factors[2]];
}
}
zweight1= 1.0 - zweight2;
}
else
{
if (offset_kp1 > refine_factors_half[2] &&
offset_kp1 <= refine_factors[2])
{
zweight2= weights[2][offset_kp1];
kshift= 0;
}
else
{
kshift= 0;
offset_kp1-= refine_factors[2];
if (offset_kp1 > 0 && offset_kp1 <= refine_factors_half[2])
{
zweight2= weights[2][offset_kp1];
}
else
{
zweight2= weights[2][offset_kp1];
kshift = 1;
}
}
zweight1= 1.0 - zweight2;
}
} /* if (ndim == 3) */
for (j= 0; j< jmax; j++)
{
if (ndim >= 2)
{
offset_jp1= start_offset[1]+j+1;
if (ptr_jshift == -1)
{
if (offset_jp1 <= refine_factors_half[1])
{
yweight2= weights[1][offset_jp1];
jshift= 0;
}
else
{
jshift= 1;
if (offset_jp1 > refine_factors_half[1] &&
offset_jp1 <= refine_factors[1])
{
yweight2= weights[1][offset_jp1];
}
else
{
yweight2= weights[1][offset_jp1-refine_factors[1]];
}
}
yweight1= 1.0 - yweight2;
}
else
{
if (offset_jp1 > refine_factors_half[1] &&
offset_jp1 <= refine_factors[1])
{
yweight2= weights[1][offset_jp1];
jshift= 0;
}
else
{
jshift= 0;
offset_jp1-= refine_factors[1];
if (offset_jp1 > 0 && offset_jp1 <= refine_factors_half[1])
{
yweight2= weights[1][offset_jp1];
}
else
{
yweight2= weights[1][offset_jp1];
jshift = 1;
}
}
yweight1= 1.0 - yweight2;
}
} /* if (ndim >= 2) */
for (i= 0; i< imax; i++)
{
offset_ip1= start_offset[0]+i+1;
if (ptr_ishift == -1)
{
if (offset_ip1 <= refine_factors_half[0])
{
xweight2= weights[0][offset_ip1];
ishift= 0;
}
else
{
ishift= 1;
if (offset_ip1 > refine_factors_half[0] &&
offset_ip1 <= refine_factors[0])
{
xweight2= weights[0][offset_ip1];
}
else
{
xweight2= weights[0][offset_ip1-refine_factors[0]];
}
}
xweight1= 1.0 - xweight2;
}
else
{
if (offset_ip1 > refine_factors_half[0] &&
offset_ip1 <= refine_factors[0])
{
xweight2= weights[0][offset_ip1];
ishift= 0;
}
else
{
ishift= 0;
offset_ip1-= refine_factors[0];
if (offset_ip1 > 0 && offset_ip1 <= refine_factors_half[0])
{
xweight2= weights[0][offset_ip1];
}
else
{
xweight2= weights[0][offset_ip1];
ishift = 1;
}
}
xweight1= 1.0 - xweight2;
}
if (ndim == 3)
{
ep[k][j][ei+i]= zweight1*(
yweight1*(
xweight1*xcp[kshift][jshift][ishift+xci]+
xweight2*xcp[kshift][jshift][ishift+xci+1])
+yweight2*(
xweight1*xcp[kshift][jshift+1][ishift+xci]+
xweight2*xcp[kshift][jshift+1][ishift+xci+1]) )
+ zweight2*(
yweight1*(
xweight1*xcp[kshift+1][jshift][ishift+xci]+
xweight2*xcp[kshift+1][jshift][ishift+xci+1])
+yweight2*(
xweight1*xcp[kshift+1][jshift+1][ishift+xci]+
xweight2*xcp[kshift+1][jshift+1][ishift+xci+1]) );
}
else if (ndim == 2)
{
ep[0][j][ei+i] = yweight1*(
xweight1*xcp[0][jshift][ishift+xci]+
xweight2*xcp[0][jshift][ishift+xci+1]);
ep[0][j][ei+i]+= yweight2*(
xweight1*xcp[0][jshift+1][ishift+xci]+
xweight2*xcp[0][jshift+1][ishift+xci+1]);
}
else
{
ep[0][0][ei+i] = xweight1*xcp[0][0][ishift+xci]+
xweight2*xcp[0][0][ishift+xci+1];
}
} /* for (i= 0; i< imax; i++) */
} /* for (j= 0; j< jmax; j++) */
} /* for (k= 0; k< kmax; k++) */
}
hypre_BoxLoop2End(ei, xci);
}/* hypre_ForBoxI(bi, own_abox) */
} /* hypre_ForBoxArray(fi, fgrid_boxes) */
/*--------------------------------------------------------------------
* Interpolate the off-processor coarse grid values. These are the
* recv_cvector values. We will use the ownbox ptrs.
* recv_vector is non-null even when it has a grid with zero-volume
* boxes.
*--------------------------------------------------------------------*/
recv_var = hypre_SStructPVectorSVector(recv_cvectors, var);
own_abox = hypre_StructGridBoxes(hypre_StructVectorGrid(recv_var));
cboxnums = recv_boxnum_map[var];
hypre_ForBoxI(bi, own_abox)
{
ownbox= hypre_BoxArrayBox(own_abox, bi);
/*check for boxes of volume zero- i.e., recv_cvectors is really null.*/
if (hypre_BoxVolume(ownbox))
{
xc_dbox= hypre_BoxArrayBox(
hypre_StructVectorDataSpace(recv_var), bi);
fi= cboxnums[bi];
fbox = hypre_BoxArrayBox(fgrid_boxes, fi);
e_dbox= hypre_BoxArrayBox(hypre_StructVectorDataSpace(e_var), fi);
/*------------------------------------------------------------------
* Get the ptrs for the fine struct_vectors.
*------------------------------------------------------------------*/
for (k= 0; k< refine_factors[2]; k++)
{
for (j=0; j< refine_factors[1]; j++)
{
hypre_SetIndex3(temp_index1, 0, j, k);
ep[k][j]= hypre_StructVectorBoxData(e_var, fi) +
hypre_BoxOffsetDistance(e_dbox, temp_index1);
}
}
hypre_StructMapCoarseToFine(hypre_BoxIMin(ownbox), zero_index,
refine_factors, hypre_BoxIMin(&refined_box));
hypre_ClearIndex(temp_index1);
for (j= 0; j< ndim; j++)
{
temp_index1[j]= refine_factors[j]-1;
}
hypre_StructMapCoarseToFine(hypre_BoxIMax(ownbox), temp_index1,
refine_factors, hypre_BoxIMax(&refined_box));
hypre_IntersectBoxes(fbox, &refined_box, &intersect_box);
/*-----------------------------------------------------------------
* Get ptrs for the crse struct_vectors. For linear interpolation
* and arbitrary refinement factors, we need to point to the correct
* coarse grid nodes. Note that the ownboxes were created so that
* only the coarse nodes inside a fbox are contained in ownbox.
* Since we loop over the fine intersect box, we need to refine
* ownbox.
*-----------------------------------------------------------------*/
hypre_CopyIndex(hypre_BoxIMin(&intersect_box), start);
hypre_CopyIndex(hypre_BoxIMax(&intersect_box), intersect_size);
for (i= 0; i< 3; i++)
{
intersect_size[i]-= (start[i]-1);
}
/*------------------------------------------------------------------
* The fine intersection box may not be divisible by the refinement
* factor. This means that the interpolated coarse nodes and their
* weights must be carefully determined. We accomplish this using the
* offset away from a fine index that is divisible by the factor.
* Because the ownboxes were created so that only coarse nodes
* completely in the fbox are included, start is always divisible
* by refine_factors. We do the calculation anyways for future changes.
*------------------------------------------------------------------*/
hypre_ClearIndex(start_offset);
for (i= 0; i< ndim; i++)
{
start_offset[i]= start[i] % refine_factors[i];
}
ptr_kshift= 0;
if ((start[2]%refine_factors[2]<refine_factors_half[2]) && ndim==3)
{
ptr_kshift= -1;
}
ptr_jshift= 0;
if ((start[1]%refine_factors[1]<refine_factors_half[1]) && ndim>=2)
{
ptr_jshift= -1;
}
ptr_ishift= 0;
if ( start[0]%refine_factors[0] < refine_factors_half[0] )
{
ptr_ishift= -1;
}
for (k= 0; k< ksize; k++)
{
for (j=0; j< jsize; j++)
{
hypre_SetIndex3(temp_index2,
ptr_ishift, j+ptr_jshift, k+ptr_kshift);
xcp[k][j]= hypre_StructVectorBoxData(recv_var, bi) +
hypre_BoxOffsetDistance(xc_dbox, temp_index2);
}
}
hypre_CopyIndex(hypre_BoxIMin(ownbox), startc);
hypre_BoxGetSize(ownbox, loop_size);
hypre_BoxLoop2Begin(ndim, loop_size,
e_dbox, start, stride, ei,
xc_dbox, startc, stridec, xci);
#if 1
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,xci,lindex,imax,jmax,kmax,k,offset_kp1,zweight2,kshift,zweight1,j,offset_jp1,yweight2,jshift,yweight1,i,offset_ip1,xweight2,ishift,xweight1) HYPRE_SMP_SCHEDULE
#endif
#else
hypre_BoxLoopSetOneBlock();
#endif
hypre_BoxLoop2For(ei, xci)
{
/*--------------------------------------------------------
* Linear interpolation. Determine the weights and the
* correct coarse grid values to be weighted. All fine
* values in an agglomerated coarse cell or in the remainder
* agglomerated coarse cells are determined. The upper
* extents are needed.
*--------------------------------------------------------*/
hypre_BoxLoopGetIndex(lindex);
imax= hypre_min( (intersect_size[0]-lindex[0]*stride[0]),
refine_factors[0] );
jmax= hypre_min( (intersect_size[1]-lindex[1]*stride[1]),
refine_factors[1]);
kmax= hypre_min( (intersect_size[2]-lindex[2]*stride[2]),
refine_factors[2]);
for (k= 0; k< kmax; k++)
{
if (ndim == 3)
{
offset_kp1= start_offset[2]+k+1;
if (ptr_kshift == -1)
{
if (offset_kp1 <= refine_factors_half[2])
{
zweight2= weights[2][offset_kp1];
kshift= 0;
}
else
{
kshift= 1;
if (offset_kp1 > refine_factors_half[2] &&
offset_kp1 <= refine_factors[2])
{
zweight2= weights[2][offset_kp1];
}
else
{
zweight2= weights[2][offset_kp1-refine_factors[2]];
}
}
zweight1= 1.0 - zweight2;
}
else
{
if (offset_kp1 > refine_factors_half[2] &&
offset_kp1 <= refine_factors[2])
{
zweight2= weights[2][offset_kp1];
kshift= 0;
}
else
{
kshift= 0;
offset_kp1-= refine_factors[2];
if (offset_kp1 > 0 && offset_kp1 <= refine_factors_half[2])
{
zweight2= weights[2][offset_kp1];
}
else
{
zweight2= weights[2][offset_kp1];
kshift = 1;
}
}
zweight1= 1.0 - zweight2;
}
} /* if (ndim == 3) */
for (j= 0; j< jmax; j++)
{
if (ndim >= 2)
{
offset_jp1= start_offset[1]+j+1;
if (ptr_jshift == -1)
{
if (offset_jp1 <= refine_factors_half[1])
{
yweight2= weights[1][offset_jp1];
jshift= 0;
}
else
{
jshift= 1;
if (offset_jp1 > refine_factors_half[1] &&
offset_jp1 <= refine_factors[1])
{
yweight2= weights[1][offset_jp1];
}
else
{
yweight2= weights[1][offset_jp1-refine_factors[1]];
}
}
yweight1= 1.0 - yweight2;
}
else
{
if (offset_jp1 > refine_factors_half[1] &&
offset_jp1 <= refine_factors[1])
{
yweight2= weights[1][offset_jp1];
jshift= 0;
}
else
{
jshift= 0;
offset_jp1-= refine_factors[1];
if (offset_jp1 > 0 && offset_jp1 <= refine_factors_half[1])
{
yweight2= weights[1][offset_jp1];
}
else
{
yweight2= weights[1][offset_jp1];
jshift = 1;
}
}
yweight1= 1.0 - yweight2;
}
} /* if (ndim >= 2) */
for (i= 0; i< imax; i++)
{
offset_ip1= start_offset[0]+i+1;
if (ptr_ishift == -1)
{
if (offset_ip1 <= refine_factors_half[0])
{
xweight2= weights[0][offset_ip1];
ishift= 0;
}
else
{
ishift= 1;
if (offset_ip1 > refine_factors_half[0] &&
offset_ip1 <= refine_factors[0])
{
xweight2= weights[0][offset_ip1];
}
else
{
xweight2= weights[0][offset_ip1-refine_factors[0]];
}
}
xweight1= 1.0 - xweight2;
}
else
{
if (offset_ip1 > refine_factors_half[0] &&
offset_ip1 <= refine_factors[0])
{
xweight2= weights[0][offset_ip1];
ishift= 0;
}
else
{
ishift= 0;
offset_ip1-= refine_factors[0];
if (offset_ip1 > 0 && offset_ip1 <= refine_factors_half[0])
{
xweight2= weights[0][offset_ip1];
}
else
{
xweight2= weights[0][offset_ip1];
ishift = 1;
}
}
xweight1= 1.0 - xweight2;
}
if (ndim == 3)
{
ep[k][j][ei+i]= zweight1*(
yweight1*(
xweight1*xcp[kshift][jshift][ishift+xci]+
xweight2*xcp[kshift][jshift][ishift+xci+1])
+yweight2*(
xweight1*xcp[kshift][jshift+1][ishift+xci]+
xweight2*xcp[kshift][jshift+1][ishift+xci+1]) )
+ zweight2*(
yweight1*(
xweight1*xcp[kshift+1][jshift][ishift+xci]+
xweight2*xcp[kshift+1][jshift][ishift+xci+1])
+yweight2*(
xweight1*xcp[kshift+1][jshift+1][ishift+xci]+
xweight2*xcp[kshift+1][jshift+1][ishift+xci+1]) );
}
else if (ndim == 2)
{
ep[0][j][ei+i] = yweight1*(
xweight1*xcp[0][jshift][ishift+xci]+
xweight2*xcp[0][jshift][ishift+xci+1]);
ep[0][j][ei+i]+= yweight2*(
xweight1*xcp[0][jshift+1][ishift+xci]+
xweight2*xcp[0][jshift+1][ishift+xci+1]);
}
else
{
ep[0][0][ei+i] = xweight1*xcp[0][0][ishift+xci]+
xweight2*xcp[0][0][ishift+xci+1];
}
} /* for (i= 0; i< imax; i++) */
} /* for (j= 0; j< jmax; j++) */
} /* for (k= 0; k< kmax; k++) */
}
hypre_BoxLoop2End(ei, xci);
} /* if (hypre_BoxVolume(ownbox)) */
} /* hypre_ForBoxI(bi, own_abox) */
} /* for (var= 0; var< nvars; var++)*/
for (k= 0; k< ksize; k++)
{
hypre_TFree(xcp[k]);
}
hypre_TFree(xcp);
for (k= 0; k< refine_factors[2]; k++)
{
hypre_TFree(ep[k]);
}
hypre_TFree(ep);
/*-----------------------------------------------------------------------
* Return
*-----------------------------------------------------------------------*/
return ierr;
}
|
NLmean_propag1dir_sspacing4_tspacing4_sim12_acc12_neighbor5_tau0100.c | /*
* compile: gcc -O3 -std=c99 -o [filename_out] -fopenmp [filename].c -lm -I/usr/include/netcdf-3/ -L/usr/lib64/ -lnetcdf -lnetcdf_c++
* in the terminal: export OMP_NUM_THREADS=3
*/
#include<stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <netcdf.h>
#include <omp.h>
/* This is the name of the data file we will read. */
#define FILENAME_RD "/data/PhDworks/isotropic/NLM/Udiff_spacespacing4.nc"
#define FILENAME_WR "/data/PhDworks/isotropic/NLM/NLmean_propag1dir_sspacing4_tspacing4_sim12_acc12_neighbor5_tau0100.nc"
/* all constants */
#define N_HR 96
#define SCALE_FACTOR_SPACE 4
#define SCALE_FACTOR_TIME 4
#define SIM_HAFTSIZE 12
#define ACC_HAFTSIZE 12
#define NEIGHBOR_HAFTSIZE 5
#define SIM_FULLSIZE (2 * SIM_HAFTSIZE + 1)
#define ACC_FULLSIZE (2 * ACC_HAFTSIZE + 1)
#define NEIGHBOR_FULLSIZE (2 * NEIGHBOR_HAFTSIZE + 1)
#define TAU 0.1
#define NUM_VARS 1
#define NUM_SCALES 2
#define NUM_3DSNAPS 37 /* #3D snapshots */
#define NUM_BLOCKS N_HR/SCALE_FACTOR_TIME - 1 /* #(1:SCALE_FACTOR_TIME:N_HR) - 1*/
#define NUM_2DSNAPS (SCALE_FACTOR_TIME * NUM_BLOCKS + 1) /* #2D snapshots in each 3D block */
#define NDIMS 4
/* Handle errors by printing an error message and exiting with a non-zero status. */
#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}
/* **********************************************************************************/
/* ****************************** USEFUL FUNCTIONS **********************************/
/* **********************************************************************************/
/*
* get_onesnap: take part of a big array(arr1) and put to small one (arr2): arr2 = arr1[id_start:id_end]
*/
void get_onesnap(double *arr1,double *arr2, int id_start, int id_end)
{
for (int i = id_start; i < id_end + 1; i++)
arr2[i - id_start] = arr1[i];
}
/*
* put_onesnap: assign small array (arr2) into biger one (arr1): arr1[id_start:id_end] = arr2
*/
void put_onesnap(double *arr1,double *arr2, int id_start, int id_end)
{
for (int i = id_start; i < id_end + 1; i++)
arr1[i] = arr2[i - id_start];
}
/*
* norm_by_weight: normalize x[dim] by weight W[dim]
*/
void norm_by_weight(int dim, double *x, double *W)
{
for (int k = 0; k < dim; k++)
x[k] = x[k]/W[k];
}
void add_mat(int dim, double *sum, double *x1, double *x2)
{
for (int k = 0; k < dim; k++)
sum[k] = x1[k] + x2[k];
}
void initialize(int dim, double *x, double val)
{
for (int k = 0; k < dim; k++)
x[k] = val;
}
/* **********************************************************************************/
/* ****************************** NETCDF UTILS **************************************/
/* **********************************************************************************/
/*
* creat_netcdf: create the netcdf file [filename] contain [num_vars] variables
* variable names are [varname]
*/
void create_netcdf(char *filename, int num_vars, char *varname[num_vars])
{
int ncid_wr, retval_wr;
int vel_varid_wr;
int Nt, Nx, Ny, Nz;
int dimids[NDIMS];
/* Create the file. */
if ((retval_wr = nc_create(filename, NC_CLOBBER, &ncid_wr)))
ERR(retval_wr);
/* Define the dimensions. The record dimension is defined to have
* unlimited length - it can grow as needed.*/
if ((retval_wr = nc_def_dim(ncid_wr, "Ny", N_HR, &Ny)))
ERR(retval_wr);
if ((retval_wr = nc_def_dim(ncid_wr, "Nz", N_HR, &Nz)))
ERR(retval_wr);
if ((retval_wr = nc_def_dim(ncid_wr, "Nt", NC_UNLIMITED, &Nt)))
ERR(retval_wr);
/* Define the netCDF variables for the data. */
dimids[0] = Nt;
dimids[1] = Nx;
dimids[2] = Ny;
dimids[3] = Nz;
for (int i = 0; i<num_vars; i++)
{
if ((retval_wr = nc_def_var(ncid_wr, varname[i], NC_FLOAT, NDIMS, dimids, &vel_varid_wr)))
ERR(retval_wr);
}
/* End define mode (SHOULD NOT FORGET THIS!). */
if ((retval_wr = nc_enddef(ncid_wr)))
ERR(retval_wr);
/* Close the file. */
if ((retval_wr = nc_close(ncid_wr)))
ERR(retval_wr);
printf("\n *** SUCCESS creating file: %s!\n", filename);
}
/*
* write_netcdf:
* write into [filename], variable [varname] [snap_end - snap_start + 1 ] snapshots [snaps] started at [snap_start]
*/
void write_netcdf(char *filename, char *varname, size_t *start, size_t *count, double *snaps)
{
int ncid_wr, retval_wr;
int vel_varid_wr;
/* Open the file. NC_WRITE tells netCDF we want read-only access to the file.*/
if ((retval_wr = nc_open(filename, NC_WRITE, &ncid_wr)))
ERR(retval_wr);
/* Get variable*/
if ((retval_wr = nc_inq_varid(ncid_wr, varname, &vel_varid_wr)))
ERR(retval_wr);;
/* Put variable*/
if ((retval_wr = nc_put_vara_double(ncid_wr, vel_varid_wr, start, count, &snaps[0])))
ERR(retval_wr);
/* Close the file. */
if ((retval_wr = nc_close(ncid_wr)))
ERR(retval_wr);
printf("\n *** SUCCESS writing variables \"%s\" to \"%s\"!\n", varname, filename);
}
/*
* read_netcdf: read from [filename], variable [varname] [snap_end - snap_start + 1 ] snapshots [snaps]
* started at [snap_start]
*/
void read_netcdf(char *filename, char *varname, size_t *start, size_t *count, double *snaps)
{
int ncid_rd, retval_rd;
int vel_varid_rd;
/* ******** PREPARE TO READ ************* */
/* Open the file. NC_NOWRITE tells netCDF we want read-only access to the file.*/
if ((retval_rd = nc_open(filename, NC_NOWRITE, &ncid_rd)))
ERR(retval_rd);
/* Get the varids of the velocity in netCDF */
if ((retval_rd = nc_inq_varid(ncid_rd, varname, &vel_varid_rd)))
ERR(retval_rd);
if ((retval_rd = nc_get_vara_double(ncid_rd, vel_varid_rd, start, count, &snaps[0])))
ERR(retval_rd);
/* Close the file, freeing all resources. */
if ((retval_rd = nc_close(ncid_rd)))
ERR(retval_rd);
printf("\n *** SUCCESS reading variables \"%s\" from \"%s\" \n", varname, filename);
}
/* **********************************************************************************/
/* ****************************** ESTIMATE_DISTANCE *********************************/
/* **********************************************************************************/
/*
* estimate_distance: estimate the distances between ref patch and moving patches (prev and after)
* patches are of fixed size (2*SIM_HAFTSIZE+1) x (2*SIM_HAFTSIZE+1)
* reference patch are centered at [center_ref_idy, center_ref_idz]
* moving patches are centered at [center_moving_idy, center_moving_idz]
* dist_all contain 2 elements: distances to moving patches in the prev and after plane
* x_ref: reference plane
* x_prev: previous plane
* x_after: plane after
* ref_ids_y(z): indices of points in reference patch
* moving_ids_y(z): indices of points in moving patch
*/
void generate_grids(int *gridpatches_y, int *gridpatches_z, int * acc_ids)
{
int neighbor_id, sim_id;
int gridyoffset_neighbor[NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE], gridzoffset_neighbor[NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE];
for (int m = 0; m < NEIGHBOR_FULLSIZE; m++)
{
for (int n = 0; n < NEIGHBOR_FULLSIZE; n++)
{
gridyoffset_neighbor[m * NEIGHBOR_FULLSIZE + n] = m - NEIGHBOR_HAFTSIZE;
gridzoffset_neighbor[m * NEIGHBOR_FULLSIZE + n] = n - NEIGHBOR_HAFTSIZE;
}
}
int gridyoffset_sim[SIM_FULLSIZE * SIM_FULLSIZE], gridzoffset_sim[SIM_FULLSIZE * SIM_FULLSIZE];
for (int p = 0; p < SIM_FULLSIZE; p++)
{
for (int q = 0; q < SIM_FULLSIZE; q++)
{
gridyoffset_sim[p * SIM_FULLSIZE + q] = p - SIM_HAFTSIZE;
gridzoffset_sim[p * SIM_FULLSIZE + q] = q - SIM_HAFTSIZE;
}
}
int grid_sim[SIM_FULLSIZE][SIM_FULLSIZE];
for (int p = 0; p < SIM_FULLSIZE; p++)
for (int q = 0; q < SIM_FULLSIZE; q++)
grid_sim[p][q] = p * SIM_FULLSIZE + q;
for (int p = 0; p < ACC_FULLSIZE; p++)
for (int q = 0; q < ACC_FULLSIZE; q++)
acc_ids[p * ACC_FULLSIZE + q] = grid_sim[SIM_HAFTSIZE - ACC_HAFTSIZE + p][SIM_HAFTSIZE - ACC_HAFTSIZE + q];
int valy, valz;
long int grid_id;
for (int i = 0; i < N_HR; i++)
{
for (int j = 0; j < N_HR; j++)
{
for (int neighbor_id = 0; neighbor_id < NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE; neighbor_id++)
{
for (int sim_id = 0; sim_id < SIM_FULLSIZE * SIM_FULLSIZE; sim_id++)
{
grid_id = i * N_HR * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE
+ j * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE
+ neighbor_id * SIM_FULLSIZE * SIM_FULLSIZE + sim_id;
valy = i + gridyoffset_neighbor[neighbor_id] + gridyoffset_sim[sim_id];
valz = j + gridzoffset_neighbor[neighbor_id] + gridzoffset_sim[sim_id];
if (valy < 0)
gridpatches_y[grid_id] = (N_HR - 1) + valy;
else if (valy > (N_HR - 1))
gridpatches_y[grid_id] = valy - (N_HR - 1);
else
gridpatches_y[grid_id] = valy;
if (valz < 0)
gridpatches_z[grid_id] = (N_HR - 1) + valz;
else if (valz > (N_HR - 1))
gridpatches_z[grid_id] = valz - (N_HR - 1);
else
gridpatches_z[grid_id] = valz;
}
}
}
}
//printf("\n gridpatches_z: %i \n", gridpatches_y[0]);
}
/* **********************************************************************************/
/* ****************************** NLMEAN *********************************/
/* **********************************************************************************/
/*
* estimate_distance: estimate the distances between ref patch and moving patches (prev and after)
* patches are of fixed size (2*SIM_HAFTSIZE+1) x (2*SIM_HAFTSIZE+1)
* reference patch are centered at [center_ref_idy, center_ref_idz]
* moving patches are centered at [center_moving_idy, center_moving_idz]
* dist_all contain 2 elements: distances to moving patches in the prev and after plane
* x_ref: reference plane
* x_prev: previous plane
* x_after: plane after
* ref_ids_y(z): indices of points in reference patch
* moving_ids_y(z): indices of points in moving patch
*/
/*void fusion(double *x_NLM, double *weight_NLM, double *x_ref, double *x_moving, double *x_fusion,
int gridpatches_y[N_HR][N_HR][NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE][SIM_FULLSIZE * SIM_FULLSIZE],
int gridpatches_z[N_HR][N_HR][NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE][SIM_FULLSIZE * SIM_FULLSIZE],
int acc_ids[NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE], int est_idy, int est_idz)*/
void NLmean(double *x_NLM, double *weight_NLM, double *x_ref, double *x_moving, double *x_fusion, int *gridy, int *gridz, int *accids)
{
double norm_fact = 1.0/((double) (SIM_FULLSIZE * SIM_FULLSIZE));
int ri = NEIGHBOR_HAFTSIZE * NEIGHBOR_FULLSIZE + NEIGHBOR_HAFTSIZE;
int est_idy;
#pragma omp parallel for private (est_idy)
for (est_idy = 0; est_idy < N_HR; est_idy++)
for (int est_idz = 0; est_idz < N_HR; est_idz++)
for (int ni = 0; ni < NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE; ni++)
{
int ref_idy, ref_idz, moving_idy, moving_idz;
double du;
double d = 0.0;
long int grid_rid, grid_nid;
for (int si = 0; si < SIM_FULLSIZE * SIM_FULLSIZE; si++)
{
grid_rid = est_idy * N_HR * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE
+ est_idz * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE + ri * SIM_FULLSIZE * SIM_FULLSIZE + si ;
grid_nid = est_idy * N_HR * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE
+ est_idz * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE + ni * SIM_FULLSIZE * SIM_FULLSIZE + si;
ref_idy = gridy[grid_rid];
moving_idy = gridy[grid_nid];
ref_idz = gridz[grid_rid];
moving_idz = gridz[grid_nid];
//compute distance btw reference patch and fusion patch
du = x_ref[ref_idy * N_HR + ref_idz] - x_moving[moving_idy * N_HR + moving_idz];
d = d + norm_fact*du*du;
}
double w = exp(-d/(2.0*TAU*TAU));
for(int k = 0; k < ACC_FULLSIZE * ACC_FULLSIZE; k++)
{
int ai = accids[k];
grid_rid = est_idy * N_HR * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE
+ est_idz * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE + ri * SIM_FULLSIZE * SIM_FULLSIZE + ai ;
grid_nid = est_idy * N_HR * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE
+ est_idz * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE + ni * SIM_FULLSIZE * SIM_FULLSIZE + ai;
ref_idy = gridy[grid_rid];
moving_idy = gridy[grid_nid];
ref_idz = gridz[grid_rid];
moving_idz = gridz[grid_nid];
x_NLM[ref_idy * N_HR + ref_idz] = x_NLM[ref_idy * N_HR + ref_idz] + w*x_fusion[moving_idy * N_HR + moving_idz];
weight_NLM[ref_idy * N_HR + ref_idz] = weight_NLM[ref_idy * N_HR + ref_idz] + w;
}
//printf("\n w=%f\n ",w);
}
}
void propag_forward(double *Xrec, double *Xlf, int *gridy, int *gridz, int *accids, int t_first, int t_bound1, int t_offset)
{
for (int t_est = t_first + 1; t_est <= t_bound1; t_est++)
{
int t_prev = t_est - 1;
double xref_lf[N_HR * N_HR], xref_hf[N_HR * N_HR], xmov_lf[N_HR * N_HR], xmov_hf[N_HR * N_HR], w[N_HR * N_HR];
get_onesnap(Xlf, xref_lf, t_offset + t_est * N_HR * N_HR, t_offset + (t_est + 1) * N_HR * N_HR - 1);
get_onesnap(Xlf, xmov_lf, t_offset + t_prev * N_HR * N_HR, t_offset + (t_prev + 1) * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + t_prev * N_HR * N_HR, t_offset + (t_prev + 1) * N_HR * N_HR - 1);
//Initialize with zeros
initialize(N_HR * N_HR, xref_hf, 0.0);
initialize(N_HR * N_HR, w, 0.0);
// Propagation from previous planes
NLmean(xref_hf, w, xref_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
// Normalize and put back
norm_by_weight(N_HR*N_HR, xref_hf, w);
put_onesnap(Xrec, xref_hf, t_offset + t_est * N_HR * N_HR, t_offset + (t_est + 1) * N_HR * N_HR - 1);
}
}
void propag_backward(double *Xrec, double *Xlf, int *gridy, int *gridz, int *accids, int t_last, int t_bound2, int t_offset)
{
for (int t_est = t_last - 1; t_est >= t_bound2; --t_est)
{
int t_prev = t_est + 1;
double xref_lf[N_HR * N_HR], xref_hf[N_HR * N_HR], xmov_lf[N_HR * N_HR], xmov_hf[N_HR * N_HR], w[N_HR * N_HR];
get_onesnap(Xlf, xref_lf, t_offset + t_est * N_HR * N_HR, t_offset + (t_est + 1) * N_HR * N_HR - 1);
get_onesnap(Xlf, xmov_lf, t_offset + t_prev * N_HR * N_HR, t_offset + (t_prev + 1) * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + t_prev * N_HR * N_HR, t_offset + (t_prev + 1) * N_HR * N_HR - 1);
//Initialize with zeros
initialize(N_HR * N_HR, xref_hf, 0.0);
initialize(N_HR * N_HR, w, 0.0);
// Propagation from previous planes
NLmean(xref_hf, w, xref_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
// Normalize and put back
norm_by_weight(N_HR*N_HR, xref_hf, w);
put_onesnap(Xrec, xref_hf, t_offset + t_est * N_HR * N_HR, t_offset + (t_est + 1) * N_HR * N_HR - 1);
}
}
void propag_2planes(double *Xrec, double *Xlf, int *gridy, int *gridz, int *accids, int t_mid, int t_offset)
{
double xref_lf[N_HR * N_HR], xref_hf[N_HR * N_HR], xmov_lf[N_HR * N_HR], xmov_hf[N_HR * N_HR], w[N_HR * N_HR];
int t_prev = t_mid - 1;
int t_after = t_mid + 1;
//Initialize with zeros
initialize(N_HR * N_HR, xref_hf, 0.0);
initialize(N_HR * N_HR, w, 0.0);
get_onesnap(Xlf, xref_lf, t_offset + t_mid * N_HR * N_HR, t_offset + (t_mid + 1) * N_HR * N_HR - 1);
get_onesnap(Xlf, xmov_lf, t_offset + t_prev * N_HR * N_HR, t_offset + (t_prev + 1) * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + t_prev * N_HR * N_HR, t_offset + (t_prev + 1) * N_HR * N_HR - 1);
NLmean(xref_hf, w, xref_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
get_onesnap(Xlf, xmov_lf, t_offset + t_after * N_HR * N_HR, t_offset + (t_after + 1) * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + t_after * N_HR * N_HR, t_offset + (t_after + 1) * N_HR * N_HR - 1);
NLmean(xref_hf, w, xref_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
// Normalize and put back
norm_by_weight(N_HR*N_HR, xref_hf, w);
put_onesnap(Xrec, xref_hf, t_offset + t_mid * N_HR * N_HR, t_offset + (t_mid + 1) * N_HR * N_HR - 1);
}
void propag_towardcenter(double *Xrec, double *Xlf, int *gridy, int *gridz, int *accids, int t_first, int t_offset)
{
double xref1_lf[N_HR * N_HR], xref2_lf[N_HR * N_HR], xmov_lf[N_HR * N_HR], xmov_hf[N_HR * N_HR];
double xref1_hf[N_HR * N_HR], w1[N_HR * N_HR], xref2_hf[N_HR * N_HR], w2[N_HR * N_HR];
int tc = (int)SCALE_FACTOR_TIME/2;
if (SCALE_FACTOR_TIME % 2) { tc = (int)SCALE_FACTOR_TIME/2 + 1; }
for (int td = 1; td < tc; td++)
{
int t1 = t_first + td; // bound on left side
int t2 = t_first + SCALE_FACTOR_TIME - td; // bound on right side
// Initialize with zeros
initialize(N_HR * N_HR, xref1_hf, 0.0);
initialize(N_HR * N_HR, w1, 0.0);
initialize(N_HR * N_HR, xref2_hf, 0.0);
initialize(N_HR * N_HR, w2, 0.0);
get_onesnap(Xlf, xref1_lf, t_offset + t1 * N_HR * N_HR, t_offset + (t1 + 1) * N_HR * N_HR - 1);
get_onesnap(Xlf, xref2_lf, t_offset + t2 * N_HR * N_HR, t_offset + (t2 + 1) * N_HR * N_HR - 1);
//Propagate from left bound
get_onesnap(Xlf, xmov_lf, t_offset + (t1 - 1) * N_HR * N_HR, t_offset + t1 * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + (t1 - 1) * N_HR * N_HR, t_offset + t1 * N_HR * N_HR - 1);
NLmean(xref1_hf, w1, xref1_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
NLmean(xref2_hf, w2, xref2_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
//Propagate from right bound
get_onesnap(Xlf, xmov_lf, t_offset + (t2 + 1) * N_HR * N_HR, t_offset + (t2 + 2) * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + (t2 + 1) * N_HR * N_HR, t_offset + (t2 + 2) * N_HR * N_HR - 1);
NLmean(xref1_hf, w1, xref1_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
NLmean(xref2_hf, w2, xref2_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
// Normalize and put back
norm_by_weight(N_HR*N_HR, xref1_hf, w1);
put_onesnap(Xrec, xref1_hf, t_offset + t1 * N_HR * N_HR, t_offset + (t1 + 1) * N_HR * N_HR - 1);
norm_by_weight(N_HR*N_HR, xref2_hf, w2);
put_onesnap(Xrec, xref2_hf, t_offset + t2 * N_HR * N_HR, t_offset + (t2 + 1) * N_HR * N_HR - 1);
}
// Last plane in the center
if (SCALE_FACTOR_TIME % 2 == 0)
{
initialize(N_HR * N_HR, xref1_hf, 0.0);
initialize(N_HR * N_HR, w1, 0.0);
get_onesnap(Xlf, xref1_lf, t_offset + (t_first + tc) * N_HR * N_HR, t_offset + (t_first + tc + 1) * N_HR * N_HR - 1);
get_onesnap(Xlf, xmov_lf, t_offset + (t_first + tc - 1) * N_HR * N_HR, t_offset + (t_first + tc) * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + (t_first + tc - 1) * N_HR * N_HR, t_offset + (t_first + tc) * N_HR * N_HR - 1);
NLmean(xref1_hf, w1, xref1_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
get_onesnap(Xlf, xmov_lf, t_offset + (t_first + tc + 1) * N_HR * N_HR, t_offset + (t_first + tc + 2) * N_HR * N_HR - 1);
get_onesnap(Xrec, xmov_hf, t_offset + (t_first + tc + 1) * N_HR * N_HR, t_offset + (t_first + tc + 2) * N_HR * N_HR - 1);
NLmean(xref1_hf, w1, xref1_lf, xmov_lf, xmov_hf, gridy, gridz, accids);
norm_by_weight(N_HR*N_HR, xref1_hf, w1);
put_onesnap(Xrec, xref1_hf, t_offset + (t_first + tc) * N_HR * N_HR, t_offset + (t_first + tc + 1) * N_HR * N_HR - 1);
}
}
/* **********************************************************************************/
/* ********************************** MAIN FUNCTION *********************************/
/* **********************************************************************************/
int main()
{
/* Creat the file to save results */
char *varnames[NUM_VARS] = {"x_rec_all"};
create_netcdf(FILENAME_WR, NUM_VARS, varnames);
/* Allocate memory */
double *x_fusion_lf_all = (double*)malloc(NUM_3DSNAPS * NUM_2DSNAPS * N_HR * N_HR * sizeof(double));
double *x_fusion_hf_all = (double*)malloc(NUM_3DSNAPS * NUM_2DSNAPS * N_HR * N_HR * sizeof(double));
double *x_rec_all = (double*)malloc(NUM_3DSNAPS * NUM_2DSNAPS * N_HR * N_HR * sizeof(double));
/* read all snapshots */
size_t start_ids[4] = {0, 0, 0, 0};
size_t count_ids[4] = {NUM_3DSNAPS, NUM_2DSNAPS, N_HR, N_HR };
read_netcdf(FILENAME_RD, "Uinterp_all", start_ids, count_ids, x_fusion_lf_all);
read_netcdf(FILENAME_RD, "Udiff_all", start_ids, count_ids, x_fusion_hf_all);
double time_all_start = omp_get_wtime();
double *x_current_lf = (double*)malloc(N_HR * N_HR * sizeof(double));
double *x_current_hf = (double*)malloc(N_HR * N_HR * sizeof(double));
double *x_rec = (double*)malloc(N_HR * N_HR * sizeof(double));
long int grid_size = N_HR * N_HR * NEIGHBOR_FULLSIZE * NEIGHBOR_FULLSIZE * SIM_FULLSIZE * SIM_FULLSIZE;
int *gridpatches_y = (int*)malloc(grid_size * sizeof(int));
int *gridpatches_z = (int*)malloc(grid_size * sizeof(int));
int *acc_ids = (int*)malloc(ACC_FULLSIZE * ACC_FULLSIZE * sizeof(int));
generate_grids(gridpatches_y, gridpatches_z, acc_ids);
for(int snap3d_id = 0; snap3d_id < NUM_3DSNAPS; snap3d_id++)
{
int t_offset = snap3d_id * NUM_2DSNAPS * N_HR*N_HR;
// put first PIV
get_onesnap(x_fusion_hf_all, x_current_hf, t_offset + 0 * N_HR * N_HR, t_offset + 1 * N_HR * N_HR - 1);
put_onesnap(x_rec_all, x_current_hf, t_offset + 0 * N_HR * N_HR, t_offset + 1 * N_HR * N_HR - 1);
int block_id;
for(block_id = 0; block_id < NUM_BLOCKS; block_id++)
{
double time_start = omp_get_wtime();
int t_first = SCALE_FACTOR_TIME*block_id;
int t_last = SCALE_FACTOR_TIME*(block_id+1);
// Put last PIV of the block
get_onesnap(x_fusion_hf_all, x_current_hf, t_offset + t_last * N_HR * N_HR, t_offset + (t_last + 1) * N_HR * N_HR - 1);
put_onesnap(x_rec_all, x_current_hf, t_offset + t_last * N_HR * N_HR, t_offset + (t_last + 1) * N_HR * N_HR - 1);
if (SCALE_FACTOR_TIME % 2)
{
int t_bound1 = t_first + (int)SCALE_FACTOR_TIME/2;
int t_bound2 = t_bound1 + 1;
propag_forward(x_rec_all, x_fusion_lf_all, gridpatches_y, gridpatches_z, acc_ids, t_first, t_bound1, t_offset);
propag_backward(x_rec_all, x_fusion_lf_all, gridpatches_y, gridpatches_z, acc_ids, t_last, t_bound2, t_offset);
}
else
{
int t_mid = t_first + (int)SCALE_FACTOR_TIME/2;
int t_bound1 = t_mid - 1;
int t_bound2 = t_mid + 1;
propag_forward(x_rec_all, x_fusion_lf_all, gridpatches_y, gridpatches_z, acc_ids, t_first, t_bound1, t_offset);
propag_backward(x_rec_all, x_fusion_lf_all, gridpatches_y, gridpatches_z, acc_ids, t_last, t_bound2, t_offset);
propag_2planes(x_rec_all, x_fusion_lf_all, gridpatches_y, gridpatches_z, acc_ids, t_mid, t_offset);
printf("\n Estimated block %i (total 23) in 3D snapshot %i (total 37) in %f seconds \n", block_id, snap3d_id, (double)omp_get_wtime() - time_start);
}
}
}
// Write to file
write_netcdf(FILENAME_WR, "x_rec_all", start_ids, count_ids, x_rec_all);
/* free memory */
free(x_rec); free(x_current_lf); free(x_current_hf);
free(x_rec_all); free(x_fusion_lf_all); free(x_fusion_hf_all);
free(gridpatches_y); free(gridpatches_z); free(acc_ids);
printf("\n FINISH ALL COMPUTATION IN %f SECONDS \n", (double)omp_get_wtime() - time_all_start);
return 1;
}
|
lastpass_sniffed_fmt_plug.c | /* LastPass sniffed session cracker patch for JtR. Hacked together during
* November of 2012 by Dhiru Kholia <dhiru at openwall.com>.
*
* Burp Suite is awesome. Open-source it!
*
* This software is Copyright (c) 2012 Dhiru Kholia <dhiru at openwall.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* Jan, 2015, JimF. Fixed salt-dupe problem. Now salt ONLY depends upon
* unencrypted user name, so we have real salt-dupe removal.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_sniffed_lastpass;
#elif FMT_REGISTERS_H
john_register_one(&fmt_sniffed_lastpass);
#else
#include <string.h>
#include <errno.h>
#include "arch.h"
#include "johnswap.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "base64_convert.h"
#include "aes.h"
#include "pbkdf2_hmac_sha256.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 64
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "LastPass"
#define FORMAT_NAME "sniffed sessions"
#define FORMAT_TAG "$lastpass$"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#ifdef SIMD_COEF_32
#define ALGORITHM_NAME "PBKDF2-SHA256 AES " SHA256_ALGORITHM_NAME
#else
#define ALGORITHM_NAME "PBKDF2-SHA256 AES 32/" ARCH_BITS_STR
#endif
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 55
#define BINARY_SIZE 16
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 4
#define SALT_ALIGN sizeof(int)
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
/* sentms=1352643586902&xml=2&username=hackme%40mailinator.com&method=cr&hash=4c11d8717015d92db74c42bc1a2570abea3fa18ab17e58a51ce885ee217ccc3f&version=2.0.15&encrypted_username=i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D&uuid=aHnPh8%40NdhSTWZ%40GJ2fEZe%24cF%40kdzdYh&lang=en-US&iterations=500&sessonly=0&otp=&sesameotp=&multifactorresponse=&lostpwotphash=07a286341be484fc3b96c176e611b10f4d74f230c516f944a008f960f4ec8870&requesthash=i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D&requestsrc=cr&encuser=i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D&hasplugin=2.0.15
* decodeURIComponent("hackme%40mailinator.com")
* decodeURIComponent("i%2BhJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk%3D") */
/* C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Extensions\hdokiejnpimakedhajhdlcegeplioahd\2.0.15_0
* lpfulllib.js and server.js are main files involved */
static struct fmt_tests lastpass_tests[] = {
{"$lastpass$hackme@mailinator.com$500$i+hJCwPOj5eQN4tvHcMguoejx4VEmiqzOXOdWIsZKlk=", "openwall"},
{"$lastpass$pass_gen@generated.com$500$vgC0g8BxOi4MerkKfZYFFSAJi8riD7k0ROLpBEA3VJk=", "password"},
// get one with salt under 16 bytes.
{"$lastpass$1@short.com$500$2W/GA8d2N+Z4HGvRYs2R7w==", "password"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static ARCH_WORD_32 (*crypt_key)[4];
static struct custom_salt {
unsigned int iterations;
unsigned int length;
char username[129];
} *cur_salt;
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
int omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_key));
}
static void done(void)
{
MEM_FREE(crypt_key);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr, *p;
if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0)
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += FORMAT_TAG_LEN;
if ((p = strtokm(ctcopy, "$")) == NULL) /* username */
goto err;
if (strlen(p) > 128)
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* iterations */
goto err;
if (!isdec(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* data */
goto err;
if (strlen(p) > 50) /* not exact! */
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;
int i;
char *p;
static struct custom_salt cs;
memset(&cs, 0, sizeof(cs));
ctcopy += FORMAT_TAG_LEN; /* skip over "$lastpass$" */
p = strtokm(ctcopy, "$");
i = strlen(p);
if (i > 16)
i = 16;
cs.length = i; /* truncated length */
strncpy(cs.username, p, 128);
p = strtokm(NULL, "$");
cs.iterations = atoi(p);
MEM_FREE(keeptr);
return (void *)&cs;
}
static void *get_binary(char *ciphertext)
{
static unsigned int out[4];
char Tmp[48];
char *p;
ciphertext += FORMAT_TAG_LEN;
p = strchr(ciphertext, '$')+1;
p = strchr(p, '$')+1;
base64_convert(p, e_b64_mime, strlen(p), Tmp, e_b64_raw, sizeof(Tmp), 0, 0);
memcpy(out, Tmp, 16);
return out;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT)
#endif
{
ARCH_WORD_32 key[MAX_KEYS_PER_CRYPT][8];
unsigned i;
#ifdef SIMD_COEF_32
int lens[MAX_KEYS_PER_CRYPT];
unsigned char *pin[MAX_KEYS_PER_CRYPT];
union {
ARCH_WORD_32 *pout[MAX_KEYS_PER_CRYPT];
unsigned char *poutc;
} x;
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
lens[i] = strlen(saved_key[i+index]);
pin[i] = (unsigned char*)saved_key[i+index];
x.pout[i] = key[i];
}
pbkdf2_sha256_sse((const unsigned char **)pin, lens, (unsigned char*)cur_salt->username, strlen(cur_salt->username), cur_salt->iterations, &(x.poutc), 32, 0);
#else
pbkdf2_sha256((unsigned char*)saved_key[index], strlen(saved_key[index]), (unsigned char*)cur_salt->username, strlen(cur_salt->username), cur_salt->iterations, (unsigned char*)(&key[0]),32,0);
#endif
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
unsigned char *Key = (unsigned char*)key[i];
AES_KEY akey;
unsigned char iv[16];
unsigned char out[32];
if(AES_set_encrypt_key(Key, 256, &akey) < 0) {
fprintf(stderr, "AES_set_encrypt_key failed in crypt!\n");
}
memset(iv, 0, sizeof(iv));
AES_cbc_encrypt((const unsigned char*)cur_salt->username, out, 32, &akey, iv, AES_ENCRYPT);
memcpy(crypt_key[index+i], out, 16);
}
}
return count;
}
static int get_hash_0(int index) { return crypt_key[index][0] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_key[index][0] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_key[index][0] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_key[index][0] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_key[index][0] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_key[index][0] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_key[index][0] & PH_MASK_6; }
static int cmp_all(void *binary, int count) {
int index;
for (index = 0; index < count; index++)
if ( ((ARCH_WORD_32*)binary)[0] == crypt_key[index][0] )
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_key[index], BINARY_SIZE);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void lastpass_set_key(char *key, int index)
{
int saved_len = strlen(key);
if (saved_len > PLAINTEXT_LENGTH)
saved_len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_len);
saved_key[index][saved_len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
static unsigned int iteration_count(void *salt)
{
struct custom_salt *my_salt;
my_salt = salt;
return (unsigned int) my_salt->iterations;
}
struct fmt_main fmt_sniffed_lastpass = {
{
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,
{
"iteration count",
},
{ FORMAT_TAG },
lastpass_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
{
iteration_count,
},
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
set_salt,
lastpass_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 */
|
morn_image.c | /*
Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>
Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#include "morn_image.h"
struct HandleImageCreate
{
MImage *img;
MChain *property;
int64_t reserve[8];
int writeable;
int cn;
int height;
int width;
unsigned char **index;
MMemory *memory;
unsigned char **backup_index;
MMemory *backup_memory;
unsigned char **backup_data[MORN_MAX_IMAGE_CN];
int image_type;
int border_type;
};
void endImageCreate(struct HandleImageCreate *handle)
{
mException((handle->img == NULL),EXIT,"invalid image");
if(handle->property!=NULL) mChainRelease(handle->property);
if(handle->index !=NULL) mFree(handle->index);
if(handle->memory !=NULL) mMemoryRelease(handle->memory);
if(handle->backup_index !=NULL) mFree(handle->backup_index);
if(handle->backup_memory!=NULL) mMemoryRelease(handle->backup_memory);
memset(handle->img,0,sizeof(MImage));
// mFree(((MList **)(handle->img))-1);
}
#define HASH_ImageCreate 0xccb34f86
MImage *ImageCreate(int cn,int height,int width,unsigned char **data[])
{
if(cn <0) {cn = 0;} if(height <0) {height = 0;} if(width <0) {width = 0;}
mException((cn>MORN_MAX_IMAGE_CN),EXIT,"invalid input");
MImage *img = (MImage *)ObjectAlloc(sizeof(MImage));
img->height = height;img->width = width;img->channel = cn;
MHandle *hdl=mHandle(img,ImageCreate);
struct HandleImageCreate *handle = (struct HandleImageCreate *)(hdl->handle);
handle->img = img;
mPropertyVariate(img,"image_type",&(handle->image_type));
if(cn==1) handle->image_type=MORN_IMAGE_GRAY;
else if(cn==3) handle->image_type=MORN_IMAGE_RGB ;
else if(cn==4) handle->image_type=MORN_IMAGE_RGBA;
else handle->image_type=DFLT;
mPropertyVariate(img,"border_type",&(handle->border_type));
handle->border_type=DFLT;
if((cn==0)||(height == 0))
{
mException((!INVALID_POINTER(data)),EXIT,"invalid input");
return img;
}
if(!INVALID_POINTER(data))
{
memcpy(img->data,data,cn*sizeof(unsigned char **));
handle->border_type = MORN_BORDER_INVALID;
return img;
}
int col = width + 32;
int row = height+ 16;
handle->index = (unsigned char **)mMalloc(row*cn*sizeof(unsigned char *));
handle->height = height;
handle->cn = cn;
if(width==0)
{
mException(!INVALID_POINTER(data),EXIT,"invalid input");
memset(handle->index,0,row*cn*sizeof(unsigned char *));
handle->border_type = MORN_BORDER_INVALID;
return img;
}
if(handle->memory == NULL) handle->memory = mMemoryCreate(1,cn*row*col*sizeof(unsigned char),MORN_HOST);
mException(handle->memory->num!=1,EXIT,"invalid image memory");
mMemoryIndex(handle->memory,cn*row,col*sizeof(unsigned char),(void ***)(&(handle->index)),1);
handle->width = width;
mPropertyFunction(img,"device",mornMemoryDevice,handle->memory);
for(int i=0;i<cn*row;i++) handle->index[i] = &(handle->index[i][16]);
for(int k=0;k<cn;k++) img->data[k] = handle->index + k*row+8;
handle->border_type = MORN_BORDER_UNDEFINED;
return img;
}
void ImageRedefine(MImage *img,int cn,int height,int width,unsigned char **data[])
{
mException((INVALID_POINTER(img)),EXIT,"invalid input");
if(cn<=0) cn =img->channel;
if(height <= 0) height=img->height;
if(width<=0) width =img->width;
if((cn!=img->channel)||(height!=img->height)||(width!=img->width)) mHandleReset(img);
int same_size = ((cn<=img->channel)&&(height<=img->height)&&(width<=img->width));
int reuse = (data==img->data);
int flag = (img->channel&&img->height&&img->width);
mException((cn>MORN_MAX_IMAGE_CN),EXIT,"invalid input channel");
img->channel = cn;
img->height = height;
img->width = width;
if(same_size&&reuse) return;
struct HandleImageCreate *handle = (struct HandleImageCreate *)(ObjHandle(img,0)->handle);
if(cn!= img->channel)
{
if(cn==1) handle->image_type=MORN_IMAGE_GRAY;
else if(cn==3) handle->image_type=MORN_IMAGE_RGB ;
else if(cn==4) handle->image_type=MORN_IMAGE_RGBA;
}
if(same_size&&INVALID_POINTER(data)&&(handle->width >0)) return;
//
mException(reuse&&flag&&(handle->width==0),EXIT,"invalid redefine");
handle->width = 0;
img->border = NULL;
handle->border_type = MORN_BORDER_UNDEFINED;
if((height<=0)||(cn<=0)||(width<=0))
{
mException((!INVALID_POINTER(data))&&(!reuse),EXIT,"invalid input");
memset(img->data,0,MORN_MAX_IMAGE_CN*sizeof(unsigned char*));
return;
}
if(reuse) data=NULL;
int col = width + 32;
int row = height+ 16;
if(height*cn>handle->height*handle->cn)
{
if(handle->index!=NULL) mFree(handle->index);
handle->index = NULL;
}
if(handle->index == NULL)
{
handle->index = (unsigned char **)mMalloc(row*cn*sizeof(unsigned char *));
handle->cn = cn;
handle->height = height;
}
if(!INVALID_POINTER(data))
{
memcpy(img->data,data,cn*sizeof(unsigned char **));
if(data == handle->backup_data)
{
if(!INVALID_POINTER(handle->backup_index )) mFree(handle->backup_index);
if(!INVALID_POINTER(handle->backup_memory)) mMemoryRelease(handle->backup_memory);
handle->backup_index=NULL;
handle->backup_memory=NULL;
}
else handle->border_type = MORN_BORDER_INVALID;
return;
}
if(handle->memory == NULL)
{
handle->memory = mMemoryCreate(1,cn*row*col*sizeof(unsigned char),MORN_HOST);
mPropertyFunction(img,"device",mornMemoryDevice,handle->memory);
}
else mMemoryRedefine(handle->memory,1,cn*row*col*sizeof(unsigned char),DFLT);
mException(handle->memory->num!=1,EXIT,"invalid image memory");
mMemoryIndex(handle->memory,cn*row,col*sizeof(unsigned char),(void ***)(&(handle->index)),1);
for(int i=0;i<cn*row;i++) handle->index[i] = &(handle->index[i][16]);
handle->width = width;
for(int k=0;k<cn;k++) img->data[k] = handle->index + k*row+8;
}
void mImageRelease(MImage *img)
{
ObjectFree(img);
}
unsigned char ***mImageBackup(MImage *img,int cn,int height,int width)
{
if(cn <=0) cn =img->channel;
if(height<=0) height=img->height;
if(width <=0) width =img->width;
int col = width + 32;
int row = height+ 16;
struct HandleImageCreate *handle = (struct HandleImageCreate *)(ObjHandle(img,0)->handle);
if(handle->backup_index!=NULL) mFree(handle->backup_index);
handle->backup_index = (unsigned char **)mMalloc(cn*row*sizeof(unsigned char *));
if(handle->backup_memory == NULL) handle->backup_memory = mMemoryCreate(1,cn*row*col*sizeof(unsigned char),MORN_HOST);
else mMemoryRedefine(handle->backup_memory,1,cn*row*col*sizeof(unsigned char),DFLT);
mException(handle->backup_memory->num!=1,EXIT,"invalid image backup memory");
mMemoryIndex(handle->backup_memory,cn*row,col*sizeof(unsigned char),(void ***)(&(handle->backup_index)),1);
for(int i=0;i<cn*row;i++) handle->backup_index[i] = &(handle->backup_index[i][16]);
for(int k=0;k<cn;k++) handle->backup_data[k] = handle->backup_index + k*row+8;
return (handle->backup_data);
}
void mImageExpand(MImage *img,int r,int border_type)
{
mException((r>8)||(border_type < MORN_BORDER_BLACK)||(border_type > MORN_BORDER_REFLECT),EXIT,"invalid border type");
int *img_border_type = (int *)mPropertyRead(img,"border_type");
mException((*img_border_type == MORN_BORDER_INVALID),EXIT,"image expand is invalid");
#define EXPEND_LEFT(Y,X1) {\
if(border_type == MORN_BORDER_BLACK)\
memset(img->data[cn][Y]+X1-r,0,r*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_WHITE)\
memset(img->data[cn][Y]+X1-r,255,r*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REPLICATE)\
memset(img->data[cn][Y]+X1-r,img->data[cn][Y][X1],r*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REFLECT)\
for(int i=1;i<=r;i++) img->data[cn][Y][X1-i]=img->data[cn][Y][X1+i];\
}
#define EXPEND_RIGHT(Y,X2) {\
if(border_type == MORN_BORDER_BLACK)\
memset(img->data[cn][Y]+X2+1,0,r*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_WHITE)\
memset(img->data[cn][Y]+X2+1,255,r*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REPLICATE)\
memset(img->data[cn][Y]+X2+1,img->data[cn][Y][X2],r*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REFLECT)\
for(int i=1;i<=r;i++) img->data[cn][Y][X2+i]=img->data[cn][Y][X2-i];\
}
#define EXPEND_TOP(Y,Y1,X1,X2) {\
if(border_type == MORN_BORDER_BLACK)\
memset(img->data[cn][Y]+X1-r,0,(X2-X1+r+r)*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_WHITE)\
memset(img->data[cn][Y]+X1-r,255,(X2-X1+r+r)*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REPLICATE)\
memcpy(img->data[cn][Y]+X1-r,img->data[cn][Y1]+X1-r,(X2-X1+r+r)*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REFLECT)\
memcpy(img->data[cn][Y]+X1-r,img->data[cn][Y1+Y1-Y]+X1-r,(X2-X1+r+r)*sizeof(unsigned char));\
}
#define EXPEND_BUTTOM(Y,Y2,X1,X2) {\
if(border_type == MORN_BORDER_BLACK)\
memset(img->data[cn][Y]+X1-r,0,(X2-X1+r+r)*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_WHITE)\
memset(img->data[cn][Y]+X1-r,255,(X2-X1+r+r)*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REPLICATE)\
memcpy(img->data[cn][Y]+X1-r,img->data[cn][Y2]+X1-r,(X2-X1+r+r)*sizeof(unsigned char));\
else if(border_type == MORN_BORDER_REFLECT)\
memcpy(img->data[cn][Y]+X1-r,img->data[cn][Y2+Y2-Y]+X1-r,(X2-X1+r+r)*sizeof(unsigned char));\
}
int height = img->height;
int width = img->width;
int y1 = ImageY1(img);
int y2 = ImageY2(img)-1;
if(*img_border_type == MORN_BORDER_IMAGE)
{
for(int cn=0;cn<img->channel;cn++)
{
int j;
for(j=MAX(y1-r,0);j<y1;j++) {int x1 = ImageX1(img,y1); if(x1<r) EXPEND_LEFT(j,0); int x2 =ImageX2(img,y1); if(x2>width-r) EXPEND_RIGHT(j,width);}
#pragma omp parallel for
for(j=y1;j<=y2;j++) {int x1 = ImageX1(img,j ); if(x1<r) EXPEND_LEFT(j,0); int x2 =ImageX2(img,j ); if(x2>width-r) EXPEND_RIGHT(j,width);}
for(j=y2+1;j<MIN(y2+r,height);j++) {int x1 = ImageX1(img,y2); if(x1<r) EXPEND_LEFT(j,0); int x2 =ImageX2(img,y2); if(x2>width-r) EXPEND_RIGHT(j,width);}
int x1,x2;
x1 = ImageX1(img,y1); x2 = ImageX2(img,y1); for(j=y1-r;j<0;j++) EXPEND_TOP(j, 0,x1,x2);
x1 = ImageX1(img,y2); x2 = ImageX2(img,y2); for(j=height;j<=y2+r;j++) EXPEND_BUTTOM(j,(height-1),x1,x2);
}
return;
}
for(int cn=0;cn<img->channel;cn++)
{
int j;
#pragma omp parallel for
for(j=y1;j<=y2;j++)
{
int x1 = ImageX1(img,j);
int x2 = ImageX2(img,j)-1;
EXPEND_LEFT(j,x1);
EXPEND_RIGHT(j,x2);
}
int x1,x2;
x1 = ImageX1(img,y1);
x2 = ImageX2(img,y1)-1;
for(j=y1-r;j<y1;j++)
EXPEND_TOP(j,y1,x1,x2);
x1 = ImageX1(img,y2);
x2 = ImageX2(img,y2)-1;
for(j=y2+1;j<=y2+r;j++)
EXPEND_BUTTOM(j,y2,x1,x2);
}
mPropertyWrite(img,"border_type",&border_type,sizeof(int));
}
void m_ImageCut(MImage *img,MImage *dst,MImageRect *rect,MImagePoint *locate)
{
mException(INVALID_IMAGE(img)||INVALID_POINTER(rect),EXIT,"invalid input");
int x1=rect->x1;int x2=rect->x2;int y1=rect->y1;int y2=rect->y2;
int lx,ly;if(INVALID_POINTER(locate)) {lx=0,ly=0;}else {lx=locate->x;ly=locate->y;}
int height = ABS(y1-y2);int width = ABS(x1-x2);
mException((height==0)||(width<=0),EXIT,"invalid input");
if(lx<0) {x1=(x1<x2)?(x1-lx):(x1+lx); lx=0;} else if(lx>0) {x2=(x1<x2)?(x2-lx):(x2+lx);}
if(ly<0) {y1=(y1<y2)?(y1-ly):(y1+ly); ly=0;} else if(ly>0) {y2=(y1<y2)?(y2-ly):(y2+ly);}
if((y1<0)&&(y2<0)) {return;} if((y1>=img->height)&&(y2>=img->height)) {return;}
if((x1<0)&&(x2<0)) {return;} if((x1>=img->width )&&(x2>=img->width )) {return;}
if(y1<0) {ly=ly-y1; y1=0;} else if(y2<0) {ly=ly-y2; y2=0;}
if(x1<0) {lx=lx-x1; x1=0;} else if(x2<0) {lx=lx-x2; x2=0;}
y1=MIN(y1,img->height);y2=MIN(y2,img->height);
x1=MIN(x1,img->width );x2=MIN(x2,img->width );
int h = ABS(y1-y2);int w = ABS(x1-x2);
if((h==0)||(w==0)) return;
// printf("x1=%d,x2=%d,width=%d,w=%d\n",x1,x2,width,w);
if(INVALID_POINTER(dst)) dst=img;
unsigned char ***dst_data;
if(dst!=img)
{
mImageRedefine(dst,img->channel,height,width);
dst_data=dst->data;
}
else
{
if(( ly *img->width+lx <= y1*img->width+x1)&&( ly *img->width+lx+w <= y1*img->width+x2)
&&((ly+h)*img->width+lx <= y2*img->width+x1)&&((ly+h)*img->width+lx+w <= y1*img->width+x2))
dst_data=img->data;
else
dst_data=mImageBackup(img,DFLT,height,width);
}
printf("x1 is %d,x2 is %d,y1 is %d,y2 is %d,lx=%d,ly=%d,height=%d,width=%d,h=%d,w=%d\n",x1,x2,y1,y2,lx,ly,height,width,h,w);
if(x1<x2)
{
for(int c=0;c<img->channel;c++)
for(int j=ly,y=y1;j<ly+h;j++,y+=((y2>y1)?1:-1))
memcpy(dst->data[c][j]+lx,img->data[c][y]+x1,w*sizeof(unsigned char));
}
else
{
for(int c=0;c<img->channel;c++)
for(int j=ly,y=y1;j<ly+h;j++,y+=((y2>y1)?1:-1))
for(int i=lx,x=x1;i<lx+w;i++,x--)
dst->data[c][j][i]=img->data[c][y][x];
}
if(img==dst) mImageRedefine(dst,DFLT,height,width,dst_data);
}
// void mImageCut(MImage *img,MImage *ROI,int x1,int x2,int y1,int y2,int lx,int ly)
// {
// mException(INVALID_IMAGE(img),EXIT,"invalid input");
// int flag = (x1<0)||(x2>=img->width)||(x1>=x2)||(y1<0)||(y2>=img->height)||(y1>=y2)||((img==ROI)&&(ly<y1));
// if(flag){ImageCut(img,ROI,x1,x2,y1,y2,lx,ly);return;}
// int height=y2-y1;int width =x2-x1;
// if(INVALID_POINTER(ROI)) ROI=img;
// else mImageRedefine(ROI,img->channel,height,width);
// if(lx<0) {x1=x1-lx;lx=0;} else if(lx>0) {x2=x2-lx;}
// if(ly<0) {y1=y1-ly;ly=0;} else if(ly>0) {y2=y2-ly;}
// // printf("x1 is %d,x2 is %d,y1 is %d,y2 is %d\n",x1,x2,y1,y2);
// for(int j=y1;j<y2;j++)for(int cn=0;cn<ROI->channel;cn++)
// memmove(ROI->data[cn][ly+j-y1]+lx,img->data[cn][j]+x1,MIN((ROI->width-lx),(x2-x1))*sizeof(unsigned char));
// }
void mImageCopy(MImage *src,MImage *dst)
{
int i;
if(src==dst) return;
mException((INVALID_IMAGE(src)||INVALID_POINTER(dst)),EXIT,"invalid input");
mImageRedefine(dst,src->channel,src->height,src->width,dst->data);
dst->border = src->border;
// dst->info = src->info;
for(int cn=0;cn<src->channel;cn++)
{
#pragma omp parallel for
for(i=0;i<src->height;i++)
memcpy(dst->data[cn][i],src->data[cn][i],src->width*sizeof(unsigned char));
}
}
// void m_ImageWipe(MImage *img,int channel)
// {
// char f[MORN_MAX_IMAGE_CN];
// if(channel<0) {memset(f,1,MORN_MAX_IMAGE_CN*sizeof(char));}
// else {mException(channel>=img->channel,EXIT,"invalid input");memset(f,0,MORN_MAX_IMAGE_CN*sizeof(char));f[channel]=1;}
// for(int c=0;c<img->channel;c++)
// {
// if(f[c]==0) continue;
// for(int j=0;j<img->height;j++)
// memset(img->data[c][j],0,img->width*sizeof(unsigned char));
// }
// }
void m_ImageWipe(MImage *img,int channel,MImageRect *rect)
{
char f[MORN_MAX_IMAGE_CN];
if(channel<0) {memset(f,1,MORN_MAX_IMAGE_CN*sizeof(char));}
else {mException(channel>=img->channel,EXIT,"invalid input");memset(f,0,MORN_MAX_IMAGE_CN*sizeof(char));f[channel]=1;}
int x,y,width,height;
if(rect==NULL) {x=0;y=0;width=img->width;height=img->height;}
else
{
x=MIN(rect->x1,rect->x2);y=MIN(rect->y1,rect->y2);width=ABS(rect->x2-rect->x1);height=ABS(rect->y2-rect->y1);
if(x>=img->width ) {return;} if(x<0) {width =width +x;x=0;}
if(y>=img->height) {return;} if(y<0) {height=height+y;y=0;}
if(width >=img->width ) width =img->width -x;
if(height>=img->height) height=img->height-y;
}
for(int c=0;c<img->channel;c++)
{
if(f[c]==0) continue;
for(int j=y;j<y+height;j++)
memset(img->data[c][j]+x,0,width*sizeof(unsigned char));
}
}
void mImageDiff(MImage *src1,MImage *src2,MImage *diff)
{
mException((INVALID_IMAGE(src1)||INVALID_IMAGE(src2)),EXIT,"invalid input");
mException(((src1->channel!=src2->channel)||(src1->height != src2->height)||(src1->width != src2->width)),EXIT,"invalid input");
if(INVALID_POINTER(diff)) diff = src1;
else mImageRedefine(diff,src1->channel,src1->height,src1->width,diff->data);
if(!INVALID_POINTER(src1->border)) diff->border = src1->border;
else if(!INVALID_POINTER(src2->border)) diff->border = src2->border;
for(int k=0;k<diff->channel;k++)
{
int j;
#pragma omp parallel for
for(j=ImageY1(diff);j<ImageY2(diff);j++)
for(int i=ImageX1(diff,j);i<ImageX2(diff,j);i++)
diff->data[k][j][i] = ABS(src1->data[k][j][i]-src2->data[k][j][i]);
}
}
void mImageThreshold(MImage *src,MImage *dst,int *thresh,int value1,int value2)
{
mException((INVALID_IMAGE(src)),EXIT,"invalid input");
if(INVALID_POINTER(dst)) dst=src;
if(value1<0) value1=0;
if(value2<0) value2=255;
for(int j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
{
int c;for(c=0;c<src->channel;c++) if(src->data[c][j][i]<thresh[c]) break;
dst->data[0][j][i]=(c==src->channel)?value2:value1;
}
dst->channel = 1;
}
void mImageDiffThreshold(MImage *src1,MImage *src2,MImage *diff,int thresh)
{
mException((INVALID_IMAGE(src1)||INVALID_IMAGE(src2)),EXIT,"invalid input");
mException(((src1->channel!=src2->channel)||(src1->height != src2->height)||(src1->width != src2->width)),EXIT,"invalid input");
if(INVALID_POINTER(diff)) diff = src1;
else mImageRedefine(diff,1,src1->height,src1->width,diff->data);
if(!INVALID_POINTER(src1->border)) diff->border = src1->border;
else if(!INVALID_POINTER(src2->border)) diff->border = src2->border;
int j;
#pragma omp parallel for
for(j=ImageY1(diff);j<ImageY2(diff);j++)
for(int i=ImageX1(diff,j);i<ImageX2(diff,j);i++)
{
diff->data[0][j][i] = 0;
for(int k=0;k<src1->channel;k++)
{
if(ABS(src1->data[k][j][i]-src2->data[k][j][i])>thresh)
{
diff->data[0][j][i] = 255;
break;
}
}
}
diff->channel = 1;
}
void mImageDataAdd(MImage *src1,MImage *src2,MImage *dst)
{
mException((INVALID_IMAGE(src1)||INVALID_IMAGE(src2)),EXIT,"invalid input");
mException(((src1->height != src2->height)||(src1->width != src2->width)),EXIT,"invalid input");
mException((src2->channel!=src1->channel)&&(src2->channel!=1),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src1;}
else {mImageRedefine(dst,src1->channel,src1->height,src1->width,dst->data);}
if(!INVALID_POINTER(src1->border)) dst->border = src1->border;
else if(!INVALID_POINTER(src2->border)) dst->border = src2->border;
unsigned char **data1,**data2;
for(int k=0;k<dst->channel;k++)
{
data1 = src1->data[k];
data2 = (k>=src2->channel)?src2->data[0]:src2->data[k];
int j;
#pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
{
register int data = data1[j][i]+data2[j][i];
dst->data[k][j][i] = (data>255)?255:data;
}
}
}
void mImageDataWeightAdd(MImage *src1,MImage *src2,MImage *dst,float w1,float w2)
{
mException((INVALID_IMAGE(src1)||INVALID_IMAGE(src2)),EXIT,"invalid input");
mException(((src1->height != src2->height)||(src1->width != src2->width)),EXIT,"invalid input");
mException((src2->channel!=src1->channel)&&(src2->channel!=1),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src1;}
else {mImageRedefine(dst,src1->channel,src1->height,src1->width,dst->data);}
if(!INVALID_POINTER(src1->border)) dst->border = src1->border;
else if(!INVALID_POINTER(src2->border)) dst->border = src2->border;
int v1[256];int v2[256];
for(int i=0;i<256;i++){v1[i]=(int)((float)i*w1); v2[i]=(int)((float)i*w2);}
unsigned char **data1,**data2;
for(int k=0;k<dst->channel;k++)
{
data1 = src1->data[k];
data2 = (k>=src2->channel)?src2->data[0]:src2->data[k];
int j;
#pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
{
register int data = v1[data1[j][i]]+v2[data2[j][i]];
dst->data[k][j][i] = (data>255)?255:((data<0)?0:data);
}
}
}
void mImageDataSub(MImage *src1,MImage *src2,MImage *dst)
{
mException((INVALID_IMAGE(src1)||INVALID_IMAGE(src2)),EXIT,"invalid input");
mException(((src1->height != src2->height)||(src1->width != src2->width)),EXIT,"invalid input");
mException((src2->channel!=src1->channel)&&(src2->channel!=1),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src1;}
else {mImageRedefine(dst,src1->channel,src1->height,src1->width,dst->data);}
if(!INVALID_POINTER(src1->border)) dst->border = src1->border;
else if(!INVALID_POINTER(src2->border)) dst->border = src2->border;
unsigned char **data1,**data2;
for(int k=0;k<dst->channel;k++)
{
data1 = src1->data[k];
data2 = (k>=src2->channel)?src2->data[0]:src2->data[k];
int j;
#pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
{
register int data = data1[j][i]-data2[j][i];
dst->data[k][j][i] = (data<0)?0:data;
}
}
}
void mImageDataAnd(MImage *src1,MImage *src2,MImage *dst)
{
mException((INVALID_IMAGE(src1)||INVALID_IMAGE(src2)),EXIT,"invalid input");
mException(((src1->height != src2->height)||(src1->width != src2->width)),EXIT,"invalid input");
mException((src2->channel!=src1->channel)&&(src2->channel!=1),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src1;}
if(dst!=src1) {mImageRedefine(dst,src1->channel,src1->height,src1->width,dst->data);}
if(!INVALID_POINTER(src1->border)) dst->border = src1->border;
else if(!INVALID_POINTER(src2->border)) dst->border = src2->border;
unsigned char **data1,**data2;
for(int k=0;k<dst->channel;k++)
{
data1 = src1->data[k];
data2 = (k>=src2->channel)?src2->data[0]:src2->data[k];
int j;
#pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
dst->data[k][j][i] = data1[j][i]&data2[j][i];
}
}
void mImageDataOr(MImage *src1,MImage *src2,MImage *dst)
{
mException((INVALID_IMAGE(src1)||INVALID_IMAGE(src2)),EXIT,"invalid input");
mException(((src1->height != src2->height)||(src1->width != src2->width)),EXIT,"invalid input");
mException((src2->channel!=src1->channel)&&(src2->channel!=1),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src1;}
else {mImageRedefine(dst,src1->channel,src1->height,src1->width,dst->data);}
if(!INVALID_POINTER(src1->border)) dst->border = src1->border;
else if(!INVALID_POINTER(src2->border)) dst->border = src2->border;
unsigned char **data1,**data2;
for(int k=0;k<dst->channel;k++)
{
data1 = src1->data[k];
data2 = (k>=src2->channel)?src2->data[0]:src2->data[k];
int j;
#pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
dst->data[k][j][i] = data1[j][i]|data2[j][i];
}
}
void mImageInvert(MImage *src,MImage *dst)
{
mException((INVALID_IMAGE(src)),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src;}
else {mImageRedefine(dst,src->channel,src->height,src->width,dst->data);}
if(!INVALID_POINTER(src->border)) dst->border = src->border;
for(int k=0;k<dst->channel;k++)
{
int j;
#pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
dst->data[k][j][i] = 255-src->data[k][j][i];
}
dst->border = src->border;
}
void mImageLinearMap(MImage *src,MImage *dst,float k,float b)
{
mException((INVALID_IMAGE(src)),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src;}
else {mImageRedefine(dst,src->channel,src->height,src->width,dst->data);}
if(!INVALID_POINTER(src->border)) dst->border = src->border;
unsigned char data[256];
for(int i=0;i<256;i++)
{
float rst = ((float)i)*k+b;
if(rst>255.0f) data[i] = 255;
else if(rst<0.0f) data[i] = 0;
else data[i] = (unsigned char)(rst+0.5f);
}
for(int cn=0;cn<dst->channel;cn++)
{
int j;
#pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)
for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
dst->data[cn][j][i] = data[src->data[cn][j][i]];
}
dst->border = src->border;
}
void mImageOperate(MImage *src,MImage *dst,void (*func)(unsigned char *,unsigned char *,void *),void *para)
{
mException((INVALID_IMAGE(src)),EXIT,"invalid input");
if(INVALID_POINTER(dst)) {dst = src;}
else
{
mException((dst->channel<=0),EXIT,"invalid input dst channel");
mImageRedefine(dst,dst->channel,src->height,src->width,dst->data);
}
if(!INVALID_POINTER(src->border)) dst->border = src->border;
unsigned char idata[MORN_MAX_IMAGE_CN];
unsigned char odata[MORN_MAX_IMAGE_CN];
int j;
// #pragma omp parallel for
for(j=ImageY1(dst);j<ImageY2(dst);j++)for(int i=ImageX1(dst,j);i<ImageX2(dst,j);i++)
{
for(int cn=0;cn<src->channel;cn++) idata[cn]=src->data[cn][j][i];
func(idata,odata,para);
for(int cn=0;cn<dst->channel;cn++) dst->data[cn][j][i]=odata[cn];
}
dst->border = src->border;
}
struct HandleImageChannelSplit
{
int flag[64];
MImage *img[64];
int n;
};
void endImageChannelSplit(struct HandleImageChannelSplit *handle)
{
for(int i=0;i<64;i++)
{
if(handle->img[i]!=NULL)
mImageRelease(handle->img[i]);
}
}
#define HASH_ImageChannelSplit 0x41e09e5b
MImage *mImageChannelSplit(MImage *src,int num,...)
{
mException(INVALID_IMAGE(src),EXIT,"invalid input image");
mException((num>=4),EXIT,"invalid input");
MHandle *hdl=mHandle(src,ImageChannelSplit);
struct HandleImageChannelSplit *handle = (struct HandleImageChannelSplit *)(hdl->handle);
hdl->valid = 1;
int cn[4]={0,0,0,0}; unsigned char **data[4];
va_list para;
va_start(para,num);
for(int i=0;i<num;i++) {cn[i]=va_arg(para,int);mException((cn[i]>=4),EXIT,"invalid input channel");}
va_end(para);
int flag = ((cn[0]+1)<<24)+((cn[1]+1)<<16)+((cn[2]+1)<<8)+(cn[3]+1);
for(int i=0;i<handle->n;i++) if(flag==handle->flag[i]) return handle->img[i];
int n=handle->n;
handle->img [n]=mImageCreate(num,src->height,src->width,data);
handle->flag[n]=flag;
handle->n=n+1;
return handle->img[n];
}
|
util.h | /*
Copyright (c) 2013, Taiga Nomi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> 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.
*/
#pragma once
#include <vector>
#include <functional>
#include <random>
#include <type_traits>
#include <limits>
#include <cassert>
#include <cstdio>
#include <cstdarg>
#include <string>
#include "aligned_allocator.h"
#include "nn_error.h"
#include "tiny_cnn/config.h"
#ifdef CNN_USE_TBB
#ifndef NOMINMAX
#define NOMINMAX // tbb includes windows.h in tbb/machine/windows_api.h
#endif
#include <tbb/tbb.h>
#include <tbb/task_group.h>
#endif
#ifndef CNN_USE_OMP
#include <thread>
#include <future>
#endif
#define CNN_UNREFERENCED_PARAMETER(x) (void)(x)
namespace tiny_cnn {
///< output label(class-index) for classification
///< must be equal to cnn_size_t, because size of last layer is equal to num. of classes
typedef cnn_size_t label_t;
typedef cnn_size_t layer_size_t; // for backward compatibility
typedef std::vector<float_t, aligned_allocator<float_t, 64>> vec_t;
enum class net_phase {
train,
test
};
template<typename T> inline
typename std::enable_if<std::is_integral<T>::value, T>::type
uniform_rand(T min, T max) {
// avoid gen(0) for MSVC known issue
// https://connect.microsoft.com/VisualStudio/feedback/details/776456
static std::mt19937 gen(1);
std::uniform_int_distribution<T> dst(min, max);
return dst(gen);
}
template<typename T> inline
typename std::enable_if<std::is_floating_point<T>::value, T>::type
uniform_rand(T min, T max) {
static std::mt19937 gen(1);
std::uniform_real_distribution<T> dst(min, max);
return dst(gen);
}
template<typename T> inline
typename std::enable_if<std::is_floating_point<T>::value, T>::type
gaussian_rand(T mean, T sigma) {
static std::mt19937 gen(1);
std::normal_distribution<T> dst(mean, sigma);
return dst(gen);
}
template<typename Container>
inline int uniform_idx(const Container& t) {
return uniform_rand(0, int(t.size() - 1));
}
inline bool bernoulli(float_t p) {
return uniform_rand(float_t(0), float_t(1)) <= p;
}
template<typename Iter>
void uniform_rand(Iter begin, Iter end, float_t min, float_t max) {
for (Iter it = begin; it != end; ++it)
*it = uniform_rand(min, max);
}
template<typename Iter>
void gaussian_rand(Iter begin, Iter end, float_t mean, float_t sigma) {
for (Iter it = begin; it != end; ++it)
*it = gaussian_rand(mean, sigma);
}
template<typename T>
T* reverse_endian(T* p) {
std::reverse(reinterpret_cast<char*>(p), reinterpret_cast<char*>(p) + sizeof(T));
return p;
}
inline bool is_little_endian() {
int x = 1;
return *(char*) &x != 0;
}
template<typename T>
size_t max_index(const T& vec) {
auto begin_iterator = std::begin(vec);
return std::max_element(begin_iterator, std::end(vec)) - begin_iterator;
}
template<typename T, typename U>
U rescale(T x, T src_min, T src_max, U dst_min, U dst_max) {
U value = static_cast<U>(((x - src_min) * (dst_max - dst_min)) / (src_max - src_min) + dst_min);
return std::min(dst_max, std::max(value, dst_min));
}
inline void nop()
{
// do nothing
}
#ifdef CNN_USE_TBB
static tbb::task_scheduler_init tbbScheduler(tbb::task_scheduler_init::automatic);//tbb::task_scheduler_init::deferred);
typedef tbb::blocked_range<int> blocked_range;
template<typename Func>
void parallel_for(int begin, int end, const Func& f, int grainsize) {
tbb::parallel_for(blocked_range(begin, end, end - begin > grainsize ? grainsize : 1), f);
}
template<typename Func>
void xparallel_for(int begin, int end, const Func& f) {
f(blocked_range(begin, end, 100));
}
#else
struct blocked_range {
typedef int const_iterator;
blocked_range(int begin, int end) : begin_(begin), end_(end) {}
blocked_range(size_t begin, size_t end) : begin_(static_cast<int>(begin)), end_(static_cast<int>(end)) {}
const_iterator begin() const { return begin_; }
const_iterator end() const { return end_; }
private:
int begin_;
int end_;
};
template<typename Func>
void xparallel_for(size_t begin, size_t end, const Func& f) {
blocked_range r(begin, end);
f(r);
}
#ifdef CNN_USE_OMP
template<typename Func>
void parallel_for(int begin, int end, const Func& f, int /*grainsize*/) {
#pragma omp parallel for
for (int i=begin; i<end; ++i)
f(blocked_range(i,i+1));
}
#else
template<typename Func>
void parallel_for(int start, int end, const Func &f, int /*grainsize*/) {
int nthreads = std::thread::hardware_concurrency();
int blockSize = (end - start) / nthreads;
if (blockSize*nthreads < end - start)
blockSize++;
std::vector<std::future<void>> futures;
int blockStart = start;
int blockEnd = blockStart + blockSize;
if (blockEnd > end) blockEnd = end;
for (int i = 0; i < nthreads; i++) {
futures.push_back(std::move(std::async(std::launch::async, [blockStart, blockEnd, &f] {
f(blocked_range(blockStart, blockEnd));
})));
blockStart += blockSize;
blockEnd = blockStart + blockSize;
if (blockStart >= end) break;
if (blockEnd > end) blockEnd = end;
}
for (auto &future : futures)
future.wait();
}
#endif
#endif // CNN_USE_TBB
template<typename T, typename U>
bool value_representation(U const &value) {
return static_cast<U>(static_cast<T>(value)) == value;
}
template<typename T, typename Func>
inline
void for_(std::true_type, bool parallelize, int begin, T end, Func f, int grainsize = 100){
parallelize = parallelize && value_representation<int>(end);
parallelize ? parallel_for(begin, static_cast<int>(end), f, grainsize) :
xparallel_for(begin, static_cast<int>(end), f);
}
template<typename T, typename Func>
inline
void for_(std::false_type, bool parallelize, int begin, T end, Func f, int grainsize = 100){
parallelize ? parallel_for(begin, static_cast<int>(end), f, grainsize) : xparallel_for(begin, end, f);
}
template<typename T, typename Func>
inline
void for_(bool parallelize, int begin, T end, Func f, int grainsize = 100) {
static_assert(std::is_integral<T>::value, "end must be integral type");
for_(typename std::is_unsigned<T>::type(), parallelize, begin, end, f, grainsize);
}
template <typename T, typename Func>
void for_i(bool parallelize, T size, Func f, int grainsize = 100)
{
for_(parallelize, 0, size, [&](const blocked_range& r) {
#ifdef CNN_USE_OMP
#pragma omp parallel for
#endif
for (int i = r.begin(); i < r.end(); i++)
f(i);
}, grainsize);
}
template <typename T, typename Func>
void for_i(T size, Func f, int grainsize = 100) {
for_i(true, size, f, grainsize);
}
template <typename T> inline T sqr(T value) { return value*value; }
inline bool isfinite(float_t x) {
return x == x;
}
template <typename Container> inline bool has_infinite(const Container& c) {
for (auto v : c)
if (!isfinite(v)) return true;
return false;
}
template <typename Container>
size_t max_size(const Container& c) {
typedef typename Container::value_type value_t;
return std::max_element(c.begin(), c.end(),
[](const value_t& left, const value_t& right) { return left.size() < right.size(); })->size();
}
inline std::string format_str(const char *fmt, ...) {
static char buf[2048];
#ifdef _MSC_VER
#pragma warning(disable:4996)
#endif
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
#ifdef _MSC_VER
#pragma warning(default:4996)
#endif
return std::string(buf);
}
template <typename T>
struct index3d {
index3d(T width, T height, T depth) {
reshape(width, height, depth);
}
index3d() : width_(0), height_(0), depth_(0) {}
void reshape(T width, T height, T depth) {
width_ = width;
height_ = height;
depth_ = depth;
if ((long long) width * height * depth > std::numeric_limits<T>::max())
throw nn_error(
format_str("error while constructing layer: layer size too large for tiny-cnn\nWidthxHeightxChannels=%dx%dx%d >= max size of [%s](=%d)",
width, height, depth, typeid(T).name(), std::numeric_limits<T>::max()));
}
T get_index(T x, T y, T channel) const {
assert(x >= 0 && x < width_);
assert(y >= 0 && y < height_);
assert(channel >= 0 && channel < depth_);
return (height_ * channel + y) * width_ + x;
}
T area() const {
return width_ * height_;
}
T size() const {
return width_ * height_ * depth_;
}
T width_;
T height_;
T depth_;
};
template <typename T>
bool operator == (const index3d<T>& lhs, const index3d<T>& rhs) {
return (lhs.width_ == rhs.width_) && (lhs.height_ == rhs.height_) && (lhs.depth_ == rhs.depth_);
}
template <typename T>
bool operator != (const index3d<T>& lhs, const index3d<T>& rhs) {
return !(lhs == rhs);
}
typedef index3d<cnn_size_t> layer_shape_t;
template <typename Stream, typename T>
Stream& operator << (Stream& s, const index3d<T>& d) {
s << d.width_ << "x" << d.height_ << "x" << d.depth_;
return s;
}
// boilerplate to resolve dependent name
#define CNN_USE_LAYER_MEMBERS using layer_base::in_size_;\
using layer_base::out_size_; \
using layer_base::parallelize_; \
using layer_base::next_; \
using layer_base::prev_; \
using layer_base::a_; \
using layer_base::output_; \
using layer_base::prev_delta_; \
using layer_base::W_; \
using layer_base::b_; \
using layer_base::dW_; \
using layer_base::db_; \
using layer_base::Whessian_; \
using layer_base::bhessian_; \
using layer_base::prev_delta2_; \
using layer<Activation>::h_
void CNN_LOG_VECTOR(const vec_t& vec, const std::string& name);
} // namespace tiny_cnn
#if defined(_MSC_VER) && (_MSC_VER <= 1800)
#define CNN_DEFAULT_MOVE_CONSTRUCTOR_UNAVAILABLE
#define CNN_DEFAULT_ASSIGNMENT_OPERATOR_UNAVAILABLE
#endif
|
util.h | #pragma once
#include<vector>
#include<iostream>
#include<sstream>
#include<exception>
#include<cmath>
#include<fstream>
#include<cstring>
#include<unordered_set>
#include<unordered_map>
#include<limits>
using std::vector;
using std::cerr;
using std::endl;
using std::stringstream;
using std::exception;
using std::string;
using std::fstream;
using std::ios;
using std::strcmp;
using std::unordered_map;
using std::unordered_set;
using std::pair;
using std::numeric_limits;
using std::ostream;
using std::tuple;
#define EPS 0.000000000001
class vectorLengthNotEqual: public exception {};
float distL2(const vector<float>& ptA, const vector<float>& ptB){
if(ptA.size() != ptB.size()){
cerr << ptA.size() << " != " << ptB.size() << endl;
throw vectorLengthNotEqual();
}
float res = 0;
for(unsigned int i = 0; i < ptA.size(); ++i){
res += pow(ptA[i]-ptB[i], 2);
}
return sqrt(res);
}
float cosSim(const vector<float>& ptA, const vector<float>& ptB){
if(ptA.size() != ptB.size()){
cerr << ptA.size() << " != " << ptB.size() << endl;
throw vectorLengthNotEqual();
}
float aDotB = 0, normA = 0, normB = 0;
for(unsigned int i = 0; i < ptA.size(); ++i){
float a = ptA[i], b = ptB[i];
aDotB += a * b;
normA += a * a;
normB += b * b;
}
return aDotB / (sqrt(normA) * sqrt(normB));
}
union charBuff{
unsigned int i;
float f;
char buff[4];
};
void operator+= (vector<float>& a, const vector<float>& b){
if(a.size() != b.size())
throw vectorLengthNotEqual();
for(unsigned int i = 0; i < a.size(); ++i){
a[i] += b[i];
}
}
vector<float> operator+ (const vector<float>& a, const vector<float>& b){
if(a.size() != b.size())
throw vectorLengthNotEqual();
vector<float> res(a.size(), 0);
for(unsigned int i = 0; i < a.size(); ++i){
res[i] = a[i] + b[i];
}
return res;
}
vector<float> operator- (const vector<float>& a, const vector<float>& b){
if(a.size() != b.size())
throw vectorLengthNotEqual();
vector<float> res(a.size(), 0);
for(unsigned int i = 0; i < a.size(); ++i){
res[i] = a[i] - b[i];
}
return res;
}
void operator/= (vector<float>& a, float b){
for(unsigned int i = 0; i < a.size(); ++i){
a[i] /= b;
}
}
void operator*= (vector<float>& a, float b){
for(unsigned int i = 0; i < a.size(); ++i){
a[i] *= b;
}
}
vector<float> operator* (const vector<float>& a, float b){
vector<float> res(a.size());
for(unsigned int i = 0; i < a.size(); ++i){
res[i] = a[i] * b;
}
return res;
}
float magnitude(const vector<float>& a){
float sumsqrd = 0;
for(float f : a){
sumsqrd += f * f;
}
return sqrt(sumsqrd);
}
ostream& operator<<(ostream& out, const vector<float>&a){
bool first = true;
for(float f : a){
if(!first)
out << " ";
out << f;
first = false;
}
return out;
}
class getVectorException: public exception {};
class neverGaveMeAnyDamnFilesException: public exception {};
class GetVector{
public:
GetVector(string ngramPath, string pmidPath = "", string umlsPath = ""):ngramPath(ngramPath), pmidPath(pmidPath), umlsPath(umlsPath){};
unordered_map<string, vector<float>> operator() (const unordered_set<string>& labels) const {
unordered_map<string, vector<float>> res;
unordered_set<string> paths;
for(const string& label : labels){
if(label[0] == 'C')
paths.insert(umlsPath);
else if (label[0] == 'P')
paths.insert(pmidPath);
else
paths.insert(ngramPath);
}
unsigned int vSize = getVecSize();
for(const string& path : paths){
fstream fin(path, ios::in);
string line;
#pragma omp parallel
{
#pragma omp single
{
while(getline(fin, line)){
#pragma omp task firstprivate(line)
{
string token;
stringstream ss(line);
ss >> token;
if(labels.find(token) != labels.end()){
vector<float> vec(vSize);
string crap;
float temp;
unsigned int count = 0;
stringstream ss(line);
ss >> crap;
while(ss >> temp){ vec[count] = temp; ++count; }
#pragma omp critical(res)
res[token] = vec;
}
}
}
}
}
}
//if(labels.size() > 0)
//cerr << "warning, did not find all items" << endl;
return res;
}
vector<float> operator() (const string & label) const {
string targetFile = ngramPath;
if(label[0] == 'C')
targetFile = umlsPath;
if(label[0] == 'P')
targetFile = pmidPath;
fstream fin(targetFile, ios::in);
string line, token;
vector<float> res(getVecSize());
while(getline(fin, line)){
// line starts with label, not sufficient, but good filter
if(strncmp(line.c_str(), label.c_str(), label.length()) == 0){
stringstream ss(line);
ss >> token;
if(token == label){
string crap;
float temp;
unsigned int count = 0;
stringstream ss(line);
ss >> crap;
while(ss >> temp){ res[count] = temp; ++count; }
return res;
}
}
}
cerr << "Failed to find " << label << " in " << targetFile << endl;
throw getVectorException();
}
unsigned int getVecSize() const {
static unsigned int vecSize = 0;
static bool init = false;
if(! init){
string p = ngramPath;
if(p == "")
p = pmidPath;
if(p == "")
p = umlsPath;
if(p == "")
throw neverGaveMeAnyDamnFilesException();
fstream fin(p, ios::in);
string line, label;
getline(fin, line);
getline(fin, line);
unsigned int size = 0;
stringstream ss(line);
string token;
while(ss >> token){ ++size; }
vecSize = size - 1; // -1 becuase label was counted
}
return vecSize;
}
private:
string ngramPath, pmidPath, umlsPath;
};
template<class T, class K>
bool cmpPairRev(const pair<T,K>& a, const pair<T,K>& b){
return a.first > b.first;
}
template<class T, class K>
bool cmpPair(const pair<T,K>& a, const pair<T,K>& b){
return a.first < b.first;
}
const unsigned int NUM_BYTE_PER_EDGE = 12;
typedef unsigned int nodeIdx;
const nodeIdx UNDEFINED = numeric_limits<nodeIdx>::max();
struct edge{
edge(): a(UNDEFINED), b(UNDEFINED), weight(0) {}
edge(nodeIdx a, nodeIdx b, float w): a(a), b(b), weight(w) {}
nodeIdx a, b;
float weight;
};
ostream& operator<<(ostream& out, const edge& e){
out << e.a << " " << e.b << " " << e.weight;
return out;
}
typedef tuple<string, string, float> rawEdge;
void string2vec(const string& line, string& label, vector<float>& vec){
stringstream ss(line);
ss >> label;
float temp;
while(ss >> temp){ vec.push_back(temp);}
}
pair<string, vector<float>> line2vec(const string& line){
pair<string, vector<float>> res;
string2vec(line, res.first, res.second);
return res;
}
|
dpado.202001231600.no_bp_and_limit_batches.h | //
// Created by Zhen Peng on 1/6/20.
//
#ifndef PADO_DPADO_H
#define PADO_DPADO_H
#include <vector>
//#include <unordered_map>
#include <map>
#include <algorithm>
#include <iostream>
#include <limits.h>
//#include <xmmintrin.h>
#include <immintrin.h>
#include <bitset>
#include <math.h>
#include <fstream>
#include <omp.h>
#include "globals.h"
#include "dglobals.h"
#include "dgraph.h"
namespace PADO {
template <VertexID BATCH_SIZE = 1024>
class DistBVCPLL {
private:
static const VertexID BITPARALLEL_SIZE = 50;
const inti THRESHOLD_PARALLEL = 80;
// Structure for the type of label
struct IndexType {
// struct Batch {
// VertexID batch_id; // Batch ID
// VertexID start_index; // Index to the array distances where the batch starts
// VertexID size; // Number of distances element in this batch
//
// Batch() = default;
// Batch(VertexID batch_id_, VertexID start_index_, VertexID size_):
// batch_id(batch_id_), start_index(start_index_), size(size_)
// { }
// };
struct DistanceIndexType {
VertexID start_index; // Index to the array vertices where the same-distance vertices start
VertexID size; // Number of the same-distance vertices
UnweightedDist dist; // The real distance
DistanceIndexType() = default;
DistanceIndexType(VertexID start_index_, VertexID size_, UnweightedDist dist_):
start_index(start_index_), size(size_), dist(dist_)
{ }
};
// Bit-parallel Labels
UnweightedDist bp_dist[BITPARALLEL_SIZE];
uint64_t bp_sets[BITPARALLEL_SIZE][2]; // [0]: S^{-1}, [1]: S^{0}
// std::vector<Batch> batches; // Batch info
std::vector<DistanceIndexType> distances; // Distance info
std::vector<VertexID> vertices; // Vertices in the label, presented as temporary ID
size_t get_size_in_bytes() const
{
return sizeof(bp_dist) +
sizeof(bp_sets) +
// batches.size() * sizeof(Batch) +
distances.size() * sizeof(DistanceIndexType) +
vertices.size() * sizeof(VertexID);
}
void clean_all_indices()
{
std::vector<DistanceIndexType>().swap(distances);
std::vector<VertexID>().swap(vertices);
}
}; //__attribute__((aligned(64)));
struct ShortIndex {
// I use BATCH_SIZE + 1 bit for indicator bit array.
// The v.indicator[BATCH_SIZE] is set if in current batch v has got any new labels already.
// In this way, it helps update_label_indices() and can be reset along with other indicator elements.
// std::bitset<BATCH_SIZE + 1> indicator; // Global indicator, indicator[r] (0 <= r < BATCH_SIZE) is set means root r once selected as candidate already
// If the Batch structure is not used, the indicator could just be BATCH_SIZE long.
std::vector<uint8_t> indicator = std::vector<uint8_t>(BATCH_SIZE, 0);
// std::vector<uint8_t> indicator = std::vector<uint8_t>(BATCH_SIZE + 1, 0);
// Use a queue to store candidates
std::vector<VertexID> candidates_que = std::vector<VertexID>(BATCH_SIZE);
VertexID end_candidates_que = 0;
std::vector<uint8_t> is_candidate = std::vector<uint8_t>(BATCH_SIZE, 0);
void indicator_reset()
{
std::fill(indicator.begin(), indicator.end(), 0);
}
}; //__attribute__((aligned(64)));
// Type of Bit-Parallel Label
struct BPLabelType {
UnweightedDist bp_dist[BITPARALLEL_SIZE] = { 0 };
uint64_t bp_sets[BITPARALLEL_SIZE][2] = { {0} }; // [0]: S^{-1}, [1]: S^{0}
};
// Type of Label Message Unit, for initializing distance table
struct LabelTableUnit {
VertexID root_id;
VertexID label_global_id;
UnweightedDist dist;
LabelTableUnit() = default;
LabelTableUnit(VertexID r, VertexID l, UnweightedDist d) :
root_id(r), label_global_id(l), dist(d) {}
};
// Type of BitParallel Label Message Unit for initializing bit-parallel labels
struct MsgBPLabel {
VertexID r_root_id;
UnweightedDist bp_dist[BITPARALLEL_SIZE];
uint64_t bp_sets[BITPARALLEL_SIZE][2];
MsgBPLabel() = default;
MsgBPLabel(VertexID r, const UnweightedDist dist[], const uint64_t sets[][2])
: r_root_id(r)
{
memcpy(bp_dist, dist, sizeof(bp_dist));
memcpy(bp_sets, sets, sizeof(bp_sets));
}
};
VertexID num_v = 0;
VertexID num_masters = 0;
// VertexID BATCH_SIZE = 0;
int host_id = 0;
int num_hosts = 0;
MPI_Datatype V_ID_Type;
std::vector<IndexType> L;
inline void bit_parallel_push_labels(
const DistGraph &G,
VertexID v_global,
// std::vector<VertexID> &tmp_que,
// VertexID &end_tmp_que,
// std::vector< std::pair<VertexID, VertexID> > &sibling_es,
// VertexID &num_sibling_es,
// std::vector< std::pair<VertexID, VertexID> > &child_es,
// VertexID &num_child_es,
std::vector<VertexID> &tmp_q,
VertexID &size_tmp_q,
std::vector< std::pair<VertexID, VertexID> > &tmp_sibling_es,
VertexID &size_tmp_sibling_es,
std::vector< std::pair<VertexID, VertexID> > &tmp_child_es,
VertexID &size_tmp_child_es,
const VertexID &offset_tmp_q,
std::vector<UnweightedDist> &dists,
UnweightedDist iter);
inline void bit_parallel_labeling(
const DistGraph &G,
std::vector<uint8_t> &used_bp_roots);
// inline void bit_parallel_push_labels(
// const DistGraph &G,
// VertexID v_global,
// std::vector<VertexID> &tmp_que,
// VertexID &end_tmp_que,
// std::vector< std::pair<VertexID, VertexID> > &sibling_es,
// VertexID &num_sibling_es,
// std::vector< std::pair<VertexID, VertexID> > &child_es,
// VertexID &num_child_es,
// std::vector<UnweightedDist> &dists,
// UnweightedDist iter);
// inline void bit_parallel_labeling(
// const DistGraph &G,
//// std::vector<IndexType> &L,
// std::vector<uint8_t> &used_bp_roots);
inline void batch_process(
const DistGraph &G,
// const VertexID b_id,
const VertexID roots_start,
const VertexID roots_size,
const std::vector<uint8_t> &used_bp_roots,
std::vector<VertexID> &active_queue,
VertexID &end_active_queue,
std::vector<VertexID> &got_candidates_queue,
VertexID &end_got_candidates_queue,
std::vector<ShortIndex> &short_index,
std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::vector<VertexID> > &recved_dist_table,
std::vector<BPLabelType> &bp_labels_table,
std::vector<uint8_t> &got_candidates,
// std::vector<bool> &got_candidates,
std::vector<uint8_t> &is_active,
// std::vector<bool> &is_active,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated);
// std::vector<bool> &once_candidated);
inline VertexID initialization(
const DistGraph &G,
std::vector<ShortIndex> &short_index,
std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::vector<VertexID> > &recved_dist_table,
std::vector<BPLabelType> &bp_labels_table,
std::vector<VertexID> &active_queue,
VertexID &end_active_queue,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
// std::vector<bool> &once_candidated,
// VertexID b_id,
VertexID roots_start,
VertexID roots_size,
// std::vector<VertexID> &roots_master_local,
const std::vector<uint8_t> &used_bp_roots);
// inline void push_single_label(
// VertexID v_head_global,
// VertexID label_root_id,
// VertexID roots_start,
// const DistGraph &G,
// std::vector<ShortIndex> &short_index,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
// std::vector<bool> &got_candidates,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
// std::vector<bool> &once_candidated,
// const std::vector<BPLabelType> &bp_labels_table,
// const std::vector<uint8_t> &used_bp_roots,
// UnweightedDist iter);
inline void schedule_label_pushing_para(
const DistGraph &G,
const VertexID roots_start,
const std::vector<uint8_t> &used_bp_roots,
const std::vector<VertexID> &active_queue,
const VertexID global_start,
const VertexID global_size,
const VertexID local_size,
// const VertexID start_active_queue,
// const VertexID size_active_queue,
std::vector<VertexID> &got_candidates_queue,
VertexID &end_got_candidates_queue,
std::vector<ShortIndex> &short_index,
const std::vector<BPLabelType> &bp_labels_table,
std::vector<uint8_t> &got_candidates,
std::vector<uint8_t> &is_active,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
const UnweightedDist iter);
inline void local_push_labels_seq(
VertexID v_head_global,
EdgeID start_index,
EdgeID bound_index,
VertexID roots_start,
const std::vector<VertexID> &labels_buffer,
const DistGraph &G,
std::vector<ShortIndex> &short_index,
std::vector<VertexID> &got_candidates_queue,
VertexID &end_got_candidates_queue,
std::vector<uint8_t> &got_candidates,
// std::vector<bool> &got_candidates,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
// std::vector<bool> &once_candidated,
const std::vector<BPLabelType> &bp_labels_table,
const std::vector<uint8_t> &used_bp_roots,
const UnweightedDist iter);
inline void local_push_labels_para(
const VertexID v_head_global,
const EdgeID start_index,
const EdgeID bound_index,
const VertexID roots_start,
const std::vector<VertexID> &labels_buffer,
const DistGraph &G,
std::vector<ShortIndex> &short_index,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
std::vector<VertexID> &tmp_got_candidates_queue,
VertexID &size_tmp_got_candidates_queue,
const VertexID offset_tmp_queue,
std::vector<uint8_t> &got_candidates,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
std::vector<VertexID> &tmp_once_candidated_queue,
VertexID &size_tmp_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
const std::vector<BPLabelType> &bp_labels_table,
const std::vector<uint8_t> &used_bp_roots,
const UnweightedDist iter);
// inline void local_push_labels(
// VertexID v_head_local,
// VertexID roots_start,
// const DistGraph &G,
// std::vector<ShortIndex> &short_index,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
// std::vector<bool> &got_candidates,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
// std::vector<bool> &once_candidated,
// const std::vector<BPLabelType> &bp_labels_table,
// const std::vector<uint8_t> &used_bp_roots,
// UnweightedDist iter);
inline void schedule_label_inserting_para(
const DistGraph &G,
const VertexID roots_start,
const VertexID roots_size,
std::vector<ShortIndex> &short_index,
const std::vector< std::vector<UnweightedDist> > &dist_table,
const std::vector<VertexID> &got_candidates_queue,
const VertexID start_got_candidates_queue,
const VertexID size_got_candidates_queue,
std::vector<uint8_t> &got_candidates,
std::vector<VertexID> &active_queue,
VertexID &end_active_queue,
std::vector<uint8_t> &is_active,
std::vector< std::pair<VertexID, VertexID> > &buffer_send,
const VertexID iter);
inline bool distance_query(
VertexID cand_root_id,
VertexID v_id,
VertexID roots_start,
// const std::vector<IndexType> &L,
const std::vector< std::vector<UnweightedDist> > &dist_table,
UnweightedDist iter);
inline void insert_label_only_seq(
VertexID cand_root_id,
// VertexID cand_root_id,
VertexID v_id_local,
VertexID roots_start,
VertexID roots_size,
const DistGraph &G,
// std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::pair<VertexID, VertexID> > &buffer_send);
// UnweightedDist iter);
inline void insert_label_only_para(
VertexID cand_root_id,
VertexID v_id_local,
VertexID roots_start,
VertexID roots_size,
const DistGraph &G,
// std::vector< std::pair<VertexID, VertexID> > &buffer_send)
std::vector< std::pair<VertexID, VertexID> > &tmp_buffer_send,
EdgeID &size_tmp_buffer_send,
const EdgeID offset_tmp_buffer_send);
inline void update_label_indices(
const VertexID v_id,
const VertexID inserted_count,
// std::vector<IndexType> &L,
// std::vector<ShortIndex> &short_index,
// VertexID b_id,
const UnweightedDist iter);
inline void reset_at_end(
const DistGraph &G,
// VertexID roots_start,
// const std::vector<VertexID> &roots_master_local,
std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::vector<VertexID> > &recved_dist_table,
std::vector<BPLabelType> &bp_labels_table,
const std::vector<VertexID> &once_candidated_queue,
const VertexID end_once_candidated_queue);
// template <typename E_T, typename F>
// inline void every_host_bcasts_buffer_and_proc(
// std::vector<E_T> &buffer_send,
// F &fun);
template <typename E_T>
inline void one_host_bcasts_buffer_to_buffer(
int root,
std::vector<E_T> &buffer_send,
std::vector<E_T> &buffer_recv);
// // Function: get the destination host id which is i hop from this host.
// // For example, 1 hop from host 2 is host 0 (assume total 3 hosts);
// // -1 hop from host 0 is host 2.
// int hop_2_me_host_id(int hop) const
// {
// assert(hop >= -(num_hosts - 1) && hop < num_hosts && hop != 0);
// return (host_id + hop + num_hosts) % num_hosts;
// }
// // Function: get the destination host id which is i hop from the root.
// // For example, 1 hop from host 2 is host 0 (assume total 3 hosts);
// // -1 hop from host 0 is host 2.
// int hop_2_root_host_id(int hop, int root) const
// {
// assert(hop >= -(num_hosts - 1) && hop < num_hosts && hop != 0);
// assert(root >= 0 && root < num_hosts);
// return (root + hop + num_hosts) % num_hosts;
// }
size_t get_index_size()
{
size_t bytes = 0;
for (VertexID v_i = 0; v_i < num_masters; ++v_i) {
bytes += L[v_i].get_size_in_bytes();
}
return bytes;
}
// Test only
// uint64_t normal_hit_count = 0;
// uint64_t bp_hit_count = 0;
// uint64_t total_check_count = 0;
// uint64_t normal_check_count = 0;
// uint64_t total_candidates_num = 0;
// uint64_t set_candidates_num = 0;
// double initializing_time = 0;
// double candidating_time = 0;
// double adding_time = 0;
// double distance_query_time = 0;
// double init_index_time = 0;
// double init_dist_matrix_time = 0;
// double init_start_reset_time = 0;
// double init_indicators_time = 0;
//L2CacheMissRate cache_miss;
// double message_time = 0;
// double bp_labeling_time = 0;
// double initializing_time = 0;
// double scatter_time = 0;
// double gather_time = 0;
// double clearup_time = 0;
// TotalInstructsExe candidating_ins_count;
// TotalInstructsExe adding_ins_count;
// TotalInstructsExe bp_labeling_ins_count;
// TotalInstructsExe bp_checking_ins_count;
// TotalInstructsExe dist_query_ins_count;
// End test
public:
// std::pair<uint64_t, uint64_t> length_larger_than_16 = std::make_pair(0, 0);
DistBVCPLL() = default;
explicit DistBVCPLL(
const DistGraph &G);
// UnweightedDist dist_distance_query_pair(
// VertexID a_global,
// VertexID b_global,
// const DistGraph &G);
}; // class DistBVCPLL
template <VertexID BATCH_SIZE>
DistBVCPLL<BATCH_SIZE>::
DistBVCPLL(
const DistGraph &G)
{
num_v = G.num_v;
assert(num_v >= BATCH_SIZE);
num_masters = G.num_masters;
host_id = G.host_id;
// {
// if (1 == host_id) {
// volatile int i = 0;
// while (i == 0) {
// sleep(5);
// }
// }
// }
num_hosts = G.num_hosts;
V_ID_Type = G.V_ID_Type;
// L.resize(num_v);
L.resize(num_masters);
VertexID remainer = num_v % BATCH_SIZE;
VertexID b_i_bound = num_v / BATCH_SIZE;
std::vector<uint8_t> used_bp_roots(num_v, 0);
//cache_miss.measure_start();
double time_labeling = -WallTimer::get_time_mark();
// bp_labeling_time -= WallTimer::get_time_mark();
bit_parallel_labeling(G,
used_bp_roots);
// bp_labeling_time += WallTimer::get_time_mark();
{//test
//#ifdef DEBUG_MESSAGES_ON
if (0 == host_id) {
printf("host_id: %u bp_labeling_finished.\n", host_id);
}
//#endif
}
std::vector<VertexID> active_queue(num_masters); // Any vertex v who is active should be put into this queue.
VertexID end_active_queue = 0;
std::vector<uint8_t> is_active(num_masters, false);// is_active[v] is true means vertex v is in the active queue.
// std::vector<bool> is_active(num_masters, false);// is_active[v] is true means vertex v is in the active queue.
std::vector<VertexID> got_candidates_queue(num_masters); // Any vertex v who got candidates should be put into this queue.
VertexID end_got_candidates_queue = 0;
std::vector<uint8_t> got_candidates(num_masters, false); // got_candidates[v] is true means vertex v is in the queue got_candidates_queue
// std::vector<bool> got_candidates(num_masters, false); // got_candidates[v] is true means vertex v is in the queue got_candidates_queue
std::vector<ShortIndex> short_index(num_masters);
std::vector< std::vector<UnweightedDist> > dist_table(BATCH_SIZE, std::vector<UnweightedDist>(num_v, MAX_UNWEIGHTED_DIST));
std::vector<VertexID> once_candidated_queue(num_masters); // if short_index[v].indicator.any() is true, v is in the queue.
// Used mainly for resetting short_index[v].indicator.
VertexID end_once_candidated_queue = 0;
std::vector<uint8_t> once_candidated(num_masters, false);
// std::vector<bool> once_candidated(num_masters, false);
std::vector< std::vector<VertexID> > recved_dist_table(BATCH_SIZE); // Some distances are from other hosts. This is used to reset the dist_table.
std::vector<BPLabelType> bp_labels_table(BATCH_SIZE); // All roots' bit-parallel labels
//printf("b_i_bound: %u\n", b_i_bound);//test
for (VertexID b_i = 0; b_i < b_i_bound; ++b_i) {
{// Batch number limit
if (64 == b_i) {
remainer = 0;
break;
}
}
{
//#ifdef DEBUG_MESSAGES_ON
if (0 == host_id) {
printf("b_i: %u\n", b_i);//test
}
//#endif
}
batch_process(
G,
// b_i,
b_i * BATCH_SIZE,
BATCH_SIZE,
// L,
used_bp_roots,
active_queue,
end_active_queue,
got_candidates_queue,
end_got_candidates_queue,
short_index,
dist_table,
recved_dist_table,
bp_labels_table,
got_candidates,
is_active,
once_candidated_queue,
end_once_candidated_queue,
once_candidated);
// exit(EXIT_SUCCESS); //test
}
if (remainer != 0) {
{
//#ifdef DEBUG_MESSAGES_ON
if (0 == host_id) {
printf("b_i: %u\n", b_i_bound);//test
}
//#endif
}
batch_process(
G,
// b_i_bound,
b_i_bound * BATCH_SIZE,
remainer,
// L,
used_bp_roots,
active_queue,
end_active_queue,
got_candidates_queue,
end_got_candidates_queue,
short_index,
dist_table,
recved_dist_table,
bp_labels_table,
got_candidates,
is_active,
once_candidated_queue,
end_once_candidated_queue,
once_candidated);
}
time_labeling += WallTimer::get_time_mark();
//cache_miss.measure_stop();
// Test
setlocale(LC_NUMERIC, "");
if (0 == host_id) {
printf("BATCH_SIZE: %u\n", BATCH_SIZE);
printf("BP_Size: %u\n", BITPARALLEL_SIZE);
}
{// Total Number of Labels
EdgeID local_num_labels = 0;
for (VertexID v_global = 0; v_global < num_v; ++v_global) {
if (G.get_master_host_id(v_global) != host_id) {
continue;
}
local_num_labels += L[G.get_local_vertex_id(v_global)].vertices.size();
}
EdgeID global_num_labels;
MPI_Allreduce(&local_num_labels,
&global_num_labels,
1,
MPI_Instance::get_mpi_datatype<EdgeID>(),
MPI_SUM,
MPI_COMM_WORLD);
// printf("host_id: %u local_num_labels: %lu %.2f%%\n", host_id, local_num_labels, 100.0 * local_num_labels / global_num_labels);
MPI_Barrier(MPI_COMM_WORLD);
if (0 == host_id) {
printf("Global_num_labels: %lu average: %f\n", global_num_labels, 1.0 * global_num_labels / num_v);
}
// VertexID local_num_batches = 0;
// VertexID local_num_distances = 0;
//// double local_avg_distances_per_batches = 0;
// for (VertexID v_global = 0; v_global < num_v; ++v_global) {
// if (G.get_master_host_id(v_global) != host_id) {
// continue;
// }
// VertexID v_local = G.get_local_vertex_id(v_global);
// local_num_batches += L[v_local].batches.size();
// local_num_distances += L[v_local].distances.size();
//// double avg_d_p_b = 0;
//// for (VertexID i_b = 0; i_b < L[v_local].batches.size(); ++i_b) {
//// avg_d_p_b += L[v_local].batches[i_b].size;
//// }
//// avg_d_p_b /= L[v_local].batches.size();
//// local_avg_distances_per_batches += avg_d_p_b;
// }
//// local_avg_distances_per_batches /= num_masters;
//// double local_avg_batches = local_num_batches * 1.0 / num_masters;
//// double local_avg_distances = local_num_distances * 1.0 / num_masters;
// uint64_t global_num_batches = 0;
// uint64_t global_num_distances = 0;
// MPI_Allreduce(
// &local_num_batches,
// &global_num_batches,
// 1,
// MPI_UINT64_T,
// MPI_SUM,
// MPI_COMM_WORLD);
//// global_avg_batches /= num_hosts;
// MPI_Allreduce(
// &local_num_distances,
// &global_num_distances,
// 1,
// MPI_UINT64_T,
// MPI_SUM,
// MPI_COMM_WORLD);
//// global_avg_distances /= num_hosts;
// double global_avg_d_p_b = global_num_distances * 1.0 / global_num_batches;
// double global_avg_l_p_d = global_num_labels * 1.0 / global_num_distances;
// double global_avg_batches = global_num_batches / num_v;
// double global_avg_distances = global_num_distances / num_v;
//// MPI_Allreduce(
//// &local_avg_distances_per_batches,
//// &global_avg_d_p_b,
//// 1,
//// MPI_DOUBLE,
//// MPI_SUM,
//// MPI_COMM_WORLD);
//// global_avg_d_p_b /= num_hosts;
// MPI_Barrier(MPI_COMM_WORLD);
// if (0 == host_id) {
// printf("global_avg_batches: %f "
// "global_avg_distances: %f "
// "global_avg_distances_per_batch: %f "
// "global_avg_labels_per_distance: %f\n",
// global_avg_batches,
// global_avg_distances,
// global_avg_d_p_b,
// global_avg_l_p_d);
// }
}
// printf("BP_labeling: %f %.2f%%\n", bp_labeling_time, bp_labeling_time / time_labeling * 100);
// printf("Initializing: %f %.2f%%\n", initializing_time, initializing_time / time_labeling * 100);
// printf("\tinit_start_reset_time: %f (%f%%)\n", init_start_reset_time, init_start_reset_time / initializing_time * 100);
// printf("\tinit_index_time: %f (%f%%)\n", init_index_time, init_index_time / initializing_time * 100);
// printf("\t\tinit_indicators_time: %f (%f%%)\n", init_indicators_time, init_indicators_time / init_index_time * 100);
// printf("\tinit_dist_matrix_time: %f (%f%%)\n", init_dist_matrix_time, init_dist_matrix_time / initializing_time * 100);
// printf("Candidating: %f %.2f%%\n", candidating_time, candidating_time / time_labeling * 100);
// printf("Adding: %f %.2f%%\n", adding_time, adding_time / time_labeling * 100);
// printf("distance_query_time: %f %.2f%%\n", distance_query_time, distance_query_time / time_labeling * 100);
// uint64_t total_check_count = bp_hit_count + normal_check_count;
// printf("total_check_count: %'llu\n", total_check_count);
// printf("bp_hit_count: %'llu %.2f%%\n",
// bp_hit_count,
// bp_hit_count * 100.0 / total_check_count);
// printf("normal_check_count: %'llu %.2f%%\n", normal_check_count, normal_check_count * 100.0 / total_check_count);
// printf("total_candidates_num: %'llu set_candidates_num: %'llu %.2f%%\n",
// total_candidates_num,
// set_candidates_num,
// set_candidates_num * 100.0 / total_candidates_num);
// printf("\tnormal_hit_count (to total_check, to normal_check): %llu (%f%%, %f%%)\n",
// normal_hit_count,
// normal_hit_count * 100.0 / total_check_count,
// normal_hit_count * 100.0 / (total_check_count - bp_hit_count));
//cache_miss.print();
// printf("Candidating: "); candidating_ins_count.print();
// printf("Adding: "); adding_ins_count.print();
// printf("BP_Labeling: "); bp_labeling_ins_count.print();
// printf("BP_Checking: "); bp_checking_ins_count.print();
// printf("distance_query: "); dist_query_ins_count.print();
// printf("num_hosts: %u host_id: %u\n"
// "Local_labeling_time: %.2f seconds\n"
// "bp_labeling_time: %.2f %.2f%%\n"
// "initializing_time: %.2f %.2f%%\n"
// "scatter_time: %.2f %.2f%%\n"
// "gather_time: %.2f %.2f%%\n"
// "clearup_time: %.2f %.2f%%\n"
// "message_time: %.2f %.2f%%\n",
// num_hosts, host_id,
// time_labeling,
// bp_labeling_time, 100.0 * bp_labeling_time / time_labeling,
// initializing_time, 100.0 * initializing_time / time_labeling,
// scatter_time, 100.0 * scatter_time / time_labeling,
// gather_time, 100.0 * gather_time / time_labeling,
// clearup_time, 100.0 * clearup_time / time_labeling,
// message_time, 100.0 * message_time / time_labeling);
double global_time_labeling;
MPI_Allreduce(&time_labeling,
&global_time_labeling,
1,
MPI_DOUBLE,
MPI_MAX,
MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
if (0 == host_id) {
printf("num_hosts: %d "
"Global_labeling_time: %.2f seconds\n",
num_hosts,
global_time_labeling);
}
// End test
}
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::bit_parallel_labeling(
// const DistGraph &G,
// std::vector<uint8_t> &used_bp_roots)
//{
//// VertexID num_v = G.num_v;
// EdgeID num_e = G.num_e;
//
// std::vector<UnweightedDist> tmp_d(num_v); // distances from the root to every v
// std::vector<std::pair<uint64_t, uint64_t> > tmp_s(num_v); // first is S_r^{-1}, second is S_r^{0}
// std::vector<VertexID> que(num_v); // active queue
// std::vector<std::pair<VertexID, VertexID> > sibling_es(num_e); // siblings, their distances to the root are equal (have difference of 0)
// std::vector<std::pair<VertexID, VertexID> > child_es(num_e); // child and father, their distances to the root have difference of 1.
//
// VertexID r = 0; // root r
// for (VertexID i_bpspt = 0; i_bpspt < BITPARALLEL_SIZE; ++i_bpspt) {
// while (r < num_v && used_bp_roots[r]) {
// ++r;
// }
// if (r == num_v) {
// for (VertexID v = 0; v < num_v; ++v) {
// L[v].bp_dist[i_bpspt] = MAX_UNWEIGHTED_DIST;
// }
// continue;
// }
// used_bp_roots[r] = true;
//
// fill(tmp_d.begin(), tmp_d.end(), MAX_UNWEIGHTED_DIST);
// fill(tmp_s.begin(), tmp_s.end(), std::make_pair(0, 0));
//
// VertexID que_t0 = 0, que_t1 = 0, que_h = 0;
// que[que_h++] = r;
// tmp_d[r] = 0;
// que_t1 = que_h;
//
// int ns = 0; // number of selected neighbor, default 64
// // the edge of one vertex in G is ordered decreasingly to rank, lower rank first, so here need to traverse edges backward
// // There was a bug cost countless time: the unsigned iterator i might decrease to zero and then flip to the INF.
//// VertexID i_bound = G.vertices[r] - 1;
//// VertexID i_start = i_bound + G.out_degrees[r];
//// for (VertexID i = i_start; i > i_bound; --i) {
// //int i_bound = G.vertices[r];
// //int i_start = i_bound + G.out_degrees[r] - 1;
// //for (int i = i_start; i >= i_bound; --i) {
// VertexID d_i_bound = G.local_out_degrees[r];
// EdgeID i_start = G.vertices_idx[r] + d_i_bound - 1;
// for (VertexID d_i = 0; d_i < d_i_bound; ++d_i) {
// EdgeID i = i_start - d_i;
// VertexID v = G.out_edges[i];
// if (!used_bp_roots[v]) {
// used_bp_roots[v] = true;
// // Algo3:line4: for every v in S_r, (dist[v], S_r^{-1}[v], S_r^{0}[v]) <- (1, {v}, empty_set)
// que[que_h++] = v;
// tmp_d[v] = 1;
// tmp_s[v].first = 1ULL << ns;
// if (++ns == 64) break;
// }
// }
// //}
//// }
//
// for (UnweightedDist d = 0; que_t0 < que_h; ++d) {
// VertexID num_sibling_es = 0, num_child_es = 0;
//
// for (VertexID que_i = que_t0; que_i < que_t1; ++que_i) {
// VertexID v = que[que_i];
//// bit_parallel_push_labels(G,
//// v,
//// que,
//// que_h,
//// sibling_es,
//// num_sibling_es,
//// child_es,
//// num_child_es,
//// tmp_d,
//// d);
// EdgeID i_start = G.vertices_idx[v];
// EdgeID i_bound = i_start + G.local_out_degrees[v];
// for (EdgeID i = i_start; i < i_bound; ++i) {
// VertexID tv = G.out_edges[i];
// UnweightedDist td = d + 1;
//
// if (d > tmp_d[tv]) {
// ;
// }
// else if (d == tmp_d[tv]) {
// if (v < tv) { // ??? Why need v < tv !!! Because it's a undirected graph.
// sibling_es[num_sibling_es].first = v;
// sibling_es[num_sibling_es].second = tv;
// ++num_sibling_es;
// }
// } else { // d < tmp_d[tv]
// if (tmp_d[tv] == MAX_UNWEIGHTED_DIST) {
// que[que_h++] = tv;
// tmp_d[tv] = td;
// }
// child_es[num_child_es].first = v;
// child_es[num_child_es].second = tv;
// ++num_child_es;
// }
// }
// }
//
// for (VertexID i = 0; i < num_sibling_es; ++i) {
// VertexID v = sibling_es[i].first, w = sibling_es[i].second;
// tmp_s[v].second |= tmp_s[w].first;
// tmp_s[w].second |= tmp_s[v].first;
// }
// for (VertexID i = 0; i < num_child_es; ++i) {
// VertexID v = child_es[i].first, c = child_es[i].second;
// tmp_s[c].first |= tmp_s[v].first;
// tmp_s[c].second |= tmp_s[v].second;
// }
//
// {// test
// printf("iter %u @%u host_id: %u num_sibling_es: %u num_child_es: %u\n", d, __LINE__, host_id, num_sibling_es, num_child_es);
//// if (4 == d) {
//// exit(EXIT_SUCCESS);
//// }
// }
//
// que_t0 = que_t1;
// que_t1 = que_h;
// }
//
// for (VertexID v = 0; v < num_v; ++v) {
// L[v].bp_dist[i_bpspt] = tmp_d[v];
// L[v].bp_sets[i_bpspt][0] = tmp_s[v].first; // S_r^{-1}
// L[v].bp_sets[i_bpspt][1] = tmp_s[v].second & ~tmp_s[v].first; // Only need those r's neighbors who are not already in S_r^{-1}
// }
// }
//
//}
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
bit_parallel_push_labels(
const DistGraph &G,
const VertexID v_global,
// std::vector<VertexID> &tmp_que,
// VertexID &end_tmp_que,
// std::vector< std::pair<VertexID, VertexID> > &sibling_es,
// VertexID &num_sibling_es,
// std::vector< std::pair<VertexID, VertexID> > &child_es,
// VertexID &num_child_es,
std::vector<VertexID> &tmp_q,
VertexID &size_tmp_q,
std::vector< std::pair<VertexID, VertexID> > &tmp_sibling_es,
VertexID &size_tmp_sibling_es,
std::vector< std::pair<VertexID, VertexID> > &tmp_child_es,
VertexID &size_tmp_child_es,
const VertexID &offset_tmp_q,
std::vector<UnweightedDist> &dists,
const UnweightedDist iter)
{
EdgeID i_start = G.vertices_idx[v_global];
EdgeID i_bound = i_start + G.local_out_degrees[v_global];
// {//test
// printf("host_id: %u local_out_degrees[%u]: %u\n", host_id, v_global, G.local_out_degrees[v_global]);
// }
for (EdgeID i = i_start; i < i_bound; ++i) {
VertexID tv_global = G.out_edges[i];
VertexID tv_local = G.get_local_vertex_id(tv_global);
UnweightedDist td = iter + 1;
if (iter > dists[tv_local]) {
;
} else if (iter == dists[tv_local]) {
if (v_global < tv_global) { // ??? Why need v < tv !!! Because it's a undirected graph.
tmp_sibling_es[offset_tmp_q + size_tmp_sibling_es].first = v_global;
tmp_sibling_es[offset_tmp_q + size_tmp_sibling_es].second = tv_global;
++size_tmp_sibling_es;
// sibling_es[num_sibling_es].first = v_global;
// sibling_es[num_sibling_es].second = tv_global;
// ++num_sibling_es;
}
} else { // iter < dists[tv]
if (dists[tv_local] == MAX_UNWEIGHTED_DIST) {
if (CAS(dists.data() + tv_local, MAX_UNWEIGHTED_DIST, td)) {
tmp_q[offset_tmp_q + size_tmp_q++] = tv_global;
}
}
// if (dists[tv_local] == MAX_UNWEIGHTED_DIST) {
// tmp_que[end_tmp_que++] = tv_global;
// dists[tv_local] = td;
// }
tmp_child_es[offset_tmp_q + size_tmp_child_es].first = v_global;
tmp_child_es[offset_tmp_q + size_tmp_child_es].second = tv_global;
++size_tmp_child_es;
// child_es[num_child_es].first = v_global;
// child_es[num_child_es].second = tv_global;
// ++num_child_es;
}
}
}
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
bit_parallel_labeling(
const DistGraph &G,
// std::vector<IndexType> &L,
std::vector<uint8_t> &used_bp_roots)
{
// Class type of Bit-Parallel label message unit.
struct MsgUnitBP {
VertexID v_global;
uint64_t S_n1;
uint64_t S_0;
MsgUnitBP() = default;
// MsgUnitBP(MsgUnitBP&& other) = default;
// MsgUnitBP(MsgUnitBP& other) = default;
// MsgUnitBP& operator=(const MsgUnitBP& other) = default;
// MsgUnitBP& operator=(MsgUnitBP&& other) = default;
MsgUnitBP(VertexID v, uint64_t sn1, uint64_t s0)
: v_global(v), S_n1(sn1), S_0(s0) { }
};
// VertexID num_v = G.num_v;
// EdgeID num_e = G.num_e;
EdgeID local_num_edges = G.num_edges_local;
std::vector<UnweightedDist> tmp_d(num_masters); // distances from the root to every v
std::vector<std::pair<uint64_t, uint64_t> > tmp_s(num_v); // first is S_r^{-1}, second is S_r^{0}
std::vector<VertexID> que(num_masters); // active queue
VertexID end_que = 0;
std::vector<VertexID> tmp_que(num_masters); // temporary queue, to be swapped with que
VertexID end_tmp_que = 0;
std::vector<std::pair<VertexID, VertexID> > sibling_es(local_num_edges); // siblings, their distances to the root are equal (have difference of 0)
std::vector<std::pair<VertexID, VertexID> > child_es(local_num_edges); // child and father, their distances to the root have difference of 1.
VertexID r_global = 0; // root r
for (VertexID i_bpspt = 0; i_bpspt < BITPARALLEL_SIZE; ++i_bpspt) {
// {// test
// if (0 == host_id) {
// printf("i_bpsp: %u\n", i_bpspt);
// }
// }
// Select the root r_global
if (0 == host_id) {
while (r_global < num_v && used_bp_roots[r_global]) {
++r_global;
}
if (r_global == num_v) {
for (VertexID v = 0; v < num_v; ++v) {
L[v].bp_dist[i_bpspt] = MAX_UNWEIGHTED_DIST;
}
continue;
}
}
// Broadcast the r here.
// message_time -= WallTimer::get_time_mark();
MPI_Bcast(&r_global,
1,
V_ID_Type,
0,
MPI_COMM_WORLD);
// message_time += WallTimer::get_time_mark();
used_bp_roots[r_global] = 1;
//#ifdef DEBUG_MESSAGES_ON
// {//test
// if (0 == host_id) {
// printf("r_global: %u i_bpspt: %u\n", r_global, i_bpspt);
// }
// }
//#endif
// VertexID que_t0 = 0, que_t1 = 0, que_h = 0;
fill(tmp_d.begin(), tmp_d.end(), MAX_UNWEIGHTED_DIST);
fill(tmp_s.begin(), tmp_s.end(), std::make_pair(0, 0));
// Mark the r_global
if (G.get_master_host_id(r_global) == host_id) {
tmp_d[G.get_local_vertex_id(r_global)] = 0;
que[end_que++] = r_global;
}
// Select the r_global's 64 neighbors
{
// Get r_global's neighbors into buffer_send, rank from high to low.
VertexID local_degree = G.local_out_degrees[r_global];
std::vector<VertexID> buffer_send(local_degree);
if (local_degree) {
EdgeID e_i_start = G.vertices_idx[r_global] + local_degree - 1;
for (VertexID d_i = 0; d_i < local_degree; ++d_i) {
EdgeID e_i = e_i_start - d_i;
buffer_send[d_i] = G.out_edges[e_i];
}
}
// Get selected neighbors (up to 64)
std::vector<VertexID> selected_nbrs;
if (0 != host_id) {
// Every host other than 0 sends neighbors to host 0
// message_time -= WallTimer::get_time_mark();
MPI_Instance::send_buffer_2_dst(buffer_send,
0,
SENDING_ROOT_NEIGHBORS,
SENDING_SIZE_ROOT_NEIGHBORS);
// Receive selected neighbors from host 0
MPI_Instance::recv_buffer_from_src(selected_nbrs,
0,
SENDING_SELECTED_NEIGHBORS,
SENDING_SIZE_SELETED_NEIGHBORS);
// message_time += WallTimer::get_time_mark();
} else {
// Host 0
// Host 0 receives neighbors from others
std::vector<VertexID> all_nbrs(buffer_send);
std::vector<VertexID > buffer_recv;
for (int loc = 0; loc < num_hosts - 1; ++loc) {
// message_time -= WallTimer::get_time_mark();
MPI_Instance::recv_buffer_from_any(buffer_recv,
SENDING_ROOT_NEIGHBORS,
SENDING_SIZE_ROOT_NEIGHBORS);
// message_time += WallTimer::get_time_mark();
if (buffer_recv.empty()) {
continue;
}
buffer_send.resize(buffer_send.size() + buffer_recv.size());
std::merge(buffer_recv.begin(), buffer_recv.end(), all_nbrs.begin(), all_nbrs.end(), buffer_send.begin());
all_nbrs.resize(buffer_send.size());
all_nbrs.assign(buffer_send.begin(), buffer_send.end());
}
assert(all_nbrs.size() == G.get_global_out_degree(r_global));
// Select 64 (or less) neighbors
VertexID ns = 0; // number of selected neighbor, default 64
for (VertexID v_global : all_nbrs) {
if (used_bp_roots[v_global]) {
continue;
}
used_bp_roots[v_global] = 1;
selected_nbrs.push_back(v_global);
if (++ns == 64) {
break;
}
}
// Send selected neighbors to other hosts
// message_time -= WallTimer::get_time_mark();
for (int dest = 1; dest < num_hosts; ++dest) {
MPI_Instance::send_buffer_2_dst(selected_nbrs,
dest,
SENDING_SELECTED_NEIGHBORS,
SENDING_SIZE_SELETED_NEIGHBORS);
}
// message_time += WallTimer::get_time_mark();
}
// {//test
// printf("host_id: %u selected_nbrs.size(): %lu\n", host_id, selected_nbrs.size());
// }
// Synchronize the used_bp_roots.
for (VertexID v_global : selected_nbrs) {
used_bp_roots[v_global] = 1;
}
// Mark selected neighbors
for (VertexID v_i = 0; v_i < selected_nbrs.size(); ++v_i) {
VertexID v_global = selected_nbrs[v_i];
if (host_id != G.get_master_host_id(v_global)) {
continue;
}
tmp_que[end_tmp_que++] = v_global;
tmp_d[G.get_local_vertex_id(v_global)] = 1;
tmp_s[v_global].first = 1ULL << v_i;
}
}
// Reduce the global number of active vertices
VertexID global_num_actives = 1;
UnweightedDist d = 0;
while (global_num_actives) {
//#ifdef DEBUG_MESSAGES_ON
// {//test
// if (0 == host_id) {
// printf("d: %u que_size: %u\n", d, global_num_actives);
// }
// }
//#endif
// for (UnweightedDist d = 0; que_t0 < que_h; ++d) {
VertexID num_sibling_es = 0, num_child_es = 0;
// Send active masters to mirrors
{
std::vector<MsgUnitBP> buffer_send(end_que);
for (VertexID que_i = 0; que_i < end_que; ++que_i) {
VertexID v_global = que[que_i];
buffer_send[que_i] = MsgUnitBP(v_global, tmp_s[v_global].first, tmp_s[v_global].second);
}
// {// test
// printf("host_id: %u buffer_send.size(): %lu\n", host_id, buffer_send.size());
// }
for (int root = 0; root < num_hosts; ++root) {
std::vector<MsgUnitBP> buffer_recv;
one_host_bcasts_buffer_to_buffer(root,
buffer_send,
buffer_recv);
if (buffer_recv.empty()) {
continue;
}
// For parallel adding to queue
VertexID size_buffer_recv = buffer_recv.size();
std::vector<VertexID> offsets_tmp_q(size_buffer_recv);
#pragma omp parallel for
for (VertexID i_q = 0; i_q < size_buffer_recv; ++i_q) {
offsets_tmp_q[i_q] = G.local_out_degrees[buffer_recv[i_q].v_global];
}
VertexID num_neighbors = PADO::prefix_sum_for_offsets(offsets_tmp_q);
std::vector<VertexID> tmp_q(num_neighbors);
std::vector<VertexID> sizes_tmp_q(size_buffer_recv, 0);
// For parallel adding to sibling_es
std::vector< std::pair<VertexID, VertexID> > tmp_sibling_es(num_neighbors);
std::vector<VertexID> sizes_tmp_sibling_es(size_buffer_recv, 0);
// For parallel adding to child_es
std::vector< std::pair<VertexID, VertexID> > tmp_child_es(num_neighbors);
std::vector<VertexID> sizes_tmp_child_es(size_buffer_recv, 0);
#pragma omp parallel for
// for (const MsgUnitBP &m : buffer_recv) {
for (VertexID i_m = 0; i_m < size_buffer_recv; ++i_m) {
const MsgUnitBP &m = buffer_recv[i_m];
VertexID v_global = m.v_global;
if (!G.local_out_degrees[v_global]) {
continue;
}
tmp_s[v_global].first = m.S_n1;
tmp_s[v_global].second = m.S_0;
// Push labels
bit_parallel_push_labels(
G,
v_global,
tmp_q,
sizes_tmp_q[i_m],
tmp_sibling_es,
sizes_tmp_sibling_es[i_m],
tmp_child_es,
sizes_tmp_child_es[i_m],
offsets_tmp_q[i_m],
// tmp_que,
// end_tmp_que,
// sibling_es,
// num_sibling_es,
// child_es,
// num_child_es,
tmp_d,
d);
}
{// From tmp_sibling_es to sibling_es
idi total_size_tmp = PADO::prefix_sum_for_offsets(sizes_tmp_sibling_es);
PADO::collect_into_queue(
tmp_sibling_es,
offsets_tmp_q,
sizes_tmp_sibling_es,
total_size_tmp,
sibling_es,
num_sibling_es);
}
{// From tmp_child_es to child_es
idi total_size_tmp = PADO::prefix_sum_for_offsets(sizes_tmp_child_es);
PADO::collect_into_queue(
tmp_child_es,
offsets_tmp_q,
sizes_tmp_child_es,
total_size_tmp,
child_es,
num_child_es);
}
{// From tmp_q to tmp_que
idi total_size_tmp = PADO::prefix_sum_for_offsets(sizes_tmp_q);
PADO::collect_into_queue(
tmp_q,
offsets_tmp_q,
sizes_tmp_q,
total_size_tmp,
tmp_que,
end_tmp_que);
}
// {// test
// printf("host_id: %u root: %u done push.\n", host_id, root);
// }
}
}
// Update the sets in tmp_s
{
#pragma omp parallel for
for (VertexID i = 0; i < num_sibling_es; ++i) {
VertexID v = sibling_es[i].first, w = sibling_es[i].second;
__atomic_or_fetch(&tmp_s[v].second, tmp_s[w].first, __ATOMIC_SEQ_CST);
__atomic_or_fetch(&tmp_s[w].second, tmp_s[v].first, __ATOMIC_SEQ_CST);
// tmp_s[v].second |= tmp_s[w].first; // !!! Need to send back!!!
// tmp_s[w].second |= tmp_s[v].first;
}
// Put into the buffer sending to others
std::vector< std::pair<VertexID, uint64_t> > buffer_send(2 * num_sibling_es);
#pragma omp parallel for
for (VertexID i = 0; i < num_sibling_es; ++i) {
VertexID v = sibling_es[i].first;
VertexID w = sibling_es[i].second;
buffer_send[2 * i] = std::make_pair(v, tmp_s[v].second);
buffer_send[2 * i + 1] = std::make_pair(w, tmp_s[w].second);
}
// Send the messages
for (int root = 0; root < num_hosts; ++root) {
std::vector< std::pair<VertexID, uint64_t> > buffer_recv;
one_host_bcasts_buffer_to_buffer(root,
buffer_send,
buffer_recv);
if (buffer_recv.empty()) {
continue;
}
size_t i_m_bound = buffer_recv.size();
#pragma omp parallel for
for (size_t i_m = 0; i_m < i_m_bound; ++i_m) {
const auto &m = buffer_recv[i_m];
__atomic_or_fetch(&tmp_s[m.first].second, m.second, __ATOMIC_SEQ_CST);
}
// for (const std::pair<VertexID, uint64_t> &m : buffer_recv) {
// tmp_s[m.first].second |= m.second;
// }
}
#pragma omp parallel for
for (VertexID i = 0; i < num_child_es; ++i) {
VertexID v = child_es[i].first, c = child_es[i].second;
__atomic_or_fetch(&tmp_s[c].first, tmp_s[v].first, __ATOMIC_SEQ_CST);
__atomic_or_fetch(&tmp_s[c].second, tmp_s[v].second, __ATOMIC_SEQ_CST);
// tmp_s[c].first |= tmp_s[v].first;
// tmp_s[c].second |= tmp_s[v].second;
}
}
//#ifdef DEBUG_MESSAGES_ON
// {// test
// VertexID global_num_sibling_es;
// VertexID global_num_child_es;
// MPI_Allreduce(&num_sibling_es,
// &global_num_sibling_es,
// 1,
// V_ID_Type,
// MPI_SUM,
// MPI_COMM_WORLD);
// MPI_Allreduce(&num_child_es,
// &global_num_child_es,
// 1,
// V_ID_Type,
// MPI_SUM,
// MPI_COMM_WORLD);
// if (0 == host_id) {
// printf("iter: %u num_sibling_es: %u num_child_es: %u\n", d, global_num_sibling_es, global_num_child_es);
// }
//
//// printf("iter %u @%u host_id: %u num_sibling_es: %u num_child_es: %u\n", d, __LINE__, host_id, num_sibling_es, num_child_es);
//// if (0 == d) {
//// exit(EXIT_SUCCESS);
//// }
// }
//#endif
// Swap que and tmp_que
tmp_que.swap(que);
end_que = end_tmp_que;
end_tmp_que = 0;
MPI_Allreduce(&end_que,
&global_num_actives,
1,
V_ID_Type,
MPI_MAX,
MPI_COMM_WORLD);
// }
++d;
}
#pragma omp parallel for
for (VertexID v_local = 0; v_local < num_masters; ++v_local) {
VertexID v_global = G.get_global_vertex_id(v_local);
L[v_local].bp_dist[i_bpspt] = tmp_d[v_local];
L[v_local].bp_sets[i_bpspt][0] = tmp_s[v_global].first; // S_r^{-1}
L[v_local].bp_sets[i_bpspt][1] = tmp_s[v_global].second & ~tmp_s[v_global].first; // Only need those r's neighbors who are not already in S_r^{-1}
}
}
}
//template <VertexID BATCH_SIZE>
//inline void DistBVCPLL<BATCH_SIZE>::
//bit_parallel_push_labels(
// const DistGraph &G,
// const VertexID v_global,
// std::vector<VertexID> &tmp_que,
// VertexID &end_tmp_que,
// std::vector< std::pair<VertexID, VertexID> > &sibling_es,
// VertexID &num_sibling_es,
// std::vector< std::pair<VertexID, VertexID> > &child_es,
// VertexID &num_child_es,
// std::vector<UnweightedDist> &dists,
// const UnweightedDist iter)
//{
// EdgeID i_start = G.vertices_idx[v_global];
// EdgeID i_bound = i_start + G.local_out_degrees[v_global];
//// {//test
//// printf("host_id: %u local_out_degrees[%u]: %u\n", host_id, v_global, G.local_out_degrees[v_global]);
//// }
// for (EdgeID i = i_start; i < i_bound; ++i) {
// VertexID tv_global = G.out_edges[i];
// VertexID tv_local = G.get_local_vertex_id(tv_global);
// UnweightedDist td = iter + 1;
//
// if (iter > dists[tv_local]) {
// ;
// } else if (iter == dists[tv_local]) {
// if (v_global < tv_global) { // ??? Why need v < tv !!! Because it's a undirected graph.
// sibling_es[num_sibling_es].first = v_global;
// sibling_es[num_sibling_es].second = tv_global;
// ++num_sibling_es;
// }
// } else { // iter < dists[tv]
// if (dists[tv_local] == MAX_UNWEIGHTED_DIST) {
// tmp_que[end_tmp_que++] = tv_global;
// dists[tv_local] = td;
// }
// child_es[num_child_es].first = v_global;
// child_es[num_child_es].second = tv_global;
// ++num_child_es;
//// {
//// printf("host_id: %u num_child_es: %u v_global: %u tv_global: %u\n", host_id, num_child_es, v_global, tv_global);//test
//// }
// }
// }
//
//}
//
//template <VertexID BATCH_SIZE>
//inline void DistBVCPLL<BATCH_SIZE>::
//bit_parallel_labeling(
// const DistGraph &G,
//// std::vector<IndexType> &L,
// std::vector<uint8_t> &used_bp_roots)
//{
// // Class type of Bit-Parallel label message unit.
// struct MsgUnitBP {
// VertexID v_global;
// uint64_t S_n1;
// uint64_t S_0;
//
// MsgUnitBP() = default;
//// MsgUnitBP(MsgUnitBP&& other) = default;
//// MsgUnitBP(MsgUnitBP& other) = default;
//// MsgUnitBP& operator=(const MsgUnitBP& other) = default;
//// MsgUnitBP& operator=(MsgUnitBP&& other) = default;
// MsgUnitBP(VertexID v, uint64_t sn1, uint64_t s0)
// : v_global(v), S_n1(sn1), S_0(s0) { }
// };
//// VertexID num_v = G.num_v;
//// EdgeID num_e = G.num_e;
// EdgeID local_num_edges = G.num_edges_local;
//
// std::vector<UnweightedDist> tmp_d(num_masters); // distances from the root to every v
// std::vector<std::pair<uint64_t, uint64_t> > tmp_s(num_v); // first is S_r^{-1}, second is S_r^{0}
// std::vector<VertexID> que(num_masters); // active queue
// VertexID end_que = 0;
// std::vector<VertexID> tmp_que(num_masters); // temporary queue, to be swapped with que
// VertexID end_tmp_que = 0;
// std::vector<std::pair<VertexID, VertexID> > sibling_es(local_num_edges); // siblings, their distances to the root are equal (have difference of 0)
// std::vector<std::pair<VertexID, VertexID> > child_es(local_num_edges); // child and father, their distances to the root have difference of 1.
//
//// std::vector<UnweightedDist> tmp_d(num_v); // distances from the root to every v
//// std::vector<std::pair<uint64_t, uint64_t> > tmp_s(num_v); // first is S_r^{-1}, second is S_r^{0}
//// std::vector<VertexID> que(num_v); // active queue
//// std::vector<std::pair<VertexID, VertexID> > sibling_es(num_e); // siblings, their distances to the root are equal (have difference of 0)
//// std::vector<std::pair<VertexID, VertexID> > child_es(num_e); // child and father, their distances to the root have difference of 1.
//
// VertexID r_global = 0; // root r
// for (VertexID i_bpspt = 0; i_bpspt < BITPARALLEL_SIZE; ++i_bpspt) {
// // Select the root r_global
// if (0 == host_id) {
// while (r_global < num_v && used_bp_roots[r_global]) {
// ++r_global;
// }
// if (r_global == num_v) {
// for (VertexID v = 0; v < num_v; ++v) {
// L[v].bp_dist[i_bpspt] = MAX_UNWEIGHTED_DIST;
// }
// continue;
// }
// }
// // Broadcast the r here.
// message_time -= WallTimer::get_time_mark();
// MPI_Bcast(&r_global,
// 1,
// V_ID_Type,
// 0,
// MPI_COMM_WORLD);
// message_time += WallTimer::get_time_mark();
// used_bp_roots[r_global] = 1;
//#ifdef DEBUG_MESSAGES_ON
// {//test
// if (0 == host_id) {
// printf("r_global: %u i_bpspt: %u\n", r_global, i_bpspt);
// }
// }
//#endif
//
//// VertexID que_t0 = 0, que_t1 = 0, que_h = 0;
// fill(tmp_d.begin(), tmp_d.end(), MAX_UNWEIGHTED_DIST);
// fill(tmp_s.begin(), tmp_s.end(), std::make_pair(0, 0));
//
// // Mark the r_global
// if (G.get_master_host_id(r_global) == host_id) {
// tmp_d[G.get_local_vertex_id(r_global)] = 0;
// que[end_que++] = r_global;
// }
// // Select the r_global's 64 neighbors
// {
// // Get r_global's neighbors into buffer_send, rank from low to high.
// VertexID local_degree = G.local_out_degrees[r_global];
// std::vector<VertexID> buffer_send(local_degree);
// if (local_degree) {
// EdgeID e_i_start = G.vertices_idx[r_global] + local_degree - 1;
// for (VertexID d_i = 0; d_i < local_degree; ++d_i) {
// EdgeID e_i = e_i_start - d_i;
// buffer_send[d_i] = G.out_edges[e_i];
// }
// }
//
// // Get selected neighbors (up to 64)
// std::vector<VertexID> selected_nbrs;
// if (0 != host_id) {
// // Every host other than 0 sends neighbors to host 0
// message_time -= WallTimer::get_time_mark();
// MPI_Instance::send_buffer_2_dst(buffer_send,
// 0,
// SENDING_ROOT_NEIGHBORS,
// SENDING_SIZE_ROOT_NEIGHBORS);
// // Receive selected neighbors from host 0
// MPI_Instance::recv_buffer_from_src(selected_nbrs,
// 0,
// SENDING_SELECTED_NEIGHBORS,
// SENDING_SIZE_SELETED_NEIGHBORS);
// message_time += WallTimer::get_time_mark();
// } else {
// // Host 0
// // Host 0 receives neighbors from others
// std::vector<VertexID> all_nbrs(buffer_send);
// std::vector<VertexID > buffer_recv;
// for (int loc = 0; loc < num_hosts - 1; ++loc) {
// message_time -= WallTimer::get_time_mark();
// MPI_Instance::recv_buffer_from_any(buffer_recv,
// SENDING_ROOT_NEIGHBORS,
// SENDING_SIZE_ROOT_NEIGHBORS);
//// MPI_Instance::receive_dynamic_buffer_from_any(buffer_recv,
//// num_hosts,
//// SENDING_ROOT_NEIGHBORS);
// message_time += WallTimer::get_time_mark();
// if (buffer_recv.empty()) {
// continue;
// }
//
// buffer_send.resize(buffer_send.size() + buffer_recv.size());
// std::merge(buffer_recv.begin(), buffer_recv.end(), all_nbrs.begin(), all_nbrs.end(), buffer_send.begin());
// all_nbrs.resize(buffer_send.size());
// all_nbrs.assign(buffer_send.begin(), buffer_send.end());
// }
// assert(all_nbrs.size() == G.get_global_out_degree(r_global));
// // Select 64 (or less) neighbors
// VertexID ns = 0; // number of selected neighbor, default 64
// for (VertexID v_global : all_nbrs) {
// if (used_bp_roots[v_global]) {
// continue;
// }
// used_bp_roots[v_global] = 1;
// selected_nbrs.push_back(v_global);
// if (++ns == 64) {
// break;
// }
// }
// // Send selected neighbors to other hosts
// message_time -= WallTimer::get_time_mark();
// for (int dest = 1; dest < num_hosts; ++dest) {
// MPI_Instance::send_buffer_2_dst(selected_nbrs,
// dest,
// SENDING_SELECTED_NEIGHBORS,
// SENDING_SIZE_SELETED_NEIGHBORS);
// }
// message_time += WallTimer::get_time_mark();
// }
//// {//test
//// printf("host_id: %u selected_nbrs.size(): %lu\n", host_id, selected_nbrs.size());
//// }
//
// // Synchronize the used_bp_roots.
// for (VertexID v_global : selected_nbrs) {
// used_bp_roots[v_global] = 1;
// }
//
// // Mark selected neighbors
// for (VertexID v_i = 0; v_i < selected_nbrs.size(); ++v_i) {
// VertexID v_global = selected_nbrs[v_i];
// if (host_id != G.get_master_host_id(v_global)) {
// continue;
// }
// tmp_que[end_tmp_que++] = v_global;
// tmp_d[G.get_local_vertex_id(v_global)] = 1;
// tmp_s[v_global].first = 1ULL << v_i;
// }
// }
//
// // Reduce the global number of active vertices
// VertexID global_num_actives = 1;
// UnweightedDist d = 0;
// while (global_num_actives) {
//// for (UnweightedDist d = 0; que_t0 < que_h; ++d) {
// VertexID num_sibling_es = 0, num_child_es = 0;
//
//
// // Send active masters to mirrors
// {
// std::vector<MsgUnitBP> buffer_send(end_que);
// for (VertexID que_i = 0; que_i < end_que; ++que_i) {
// VertexID v_global = que[que_i];
// buffer_send[que_i] = MsgUnitBP(v_global, tmp_s[v_global].first, tmp_s[v_global].second);
// }
//// {// test
//// printf("host_id: %u buffer_send.size(): %lu\n", host_id, buffer_send.size());
//// }
//
// for (int root = 0; root < num_hosts; ++root) {
// std::vector<MsgUnitBP> buffer_recv;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send,
// buffer_recv);
// if (buffer_recv.empty()) {
// continue;
// }
// for (const MsgUnitBP &m : buffer_recv) {
// VertexID v_global = m.v_global;
// if (!G.local_out_degrees[v_global]) {
// continue;
// }
// tmp_s[v_global].first = m.S_n1;
// tmp_s[v_global].second = m.S_0;
// // Push labels
// bit_parallel_push_labels(G,
// v_global,
// tmp_que,
// end_tmp_que,
// sibling_es,
// num_sibling_es,
// child_es,
// num_child_es,
// tmp_d,
// d);
// }
//// {// test
//// printf("host_id: %u root: %u done push.\n", host_id, root);
//// }
// }
// }
//
// // Update the sets in tmp_s
// {
//
// for (VertexID i = 0; i < num_sibling_es; ++i) {
// VertexID v = sibling_es[i].first, w = sibling_es[i].second;
// tmp_s[v].second |= tmp_s[w].first; // !!! Need to send back!!!
// tmp_s[w].second |= tmp_s[v].first;
//
// }
// // Put into the buffer sending to others
// std::vector< std::pair<VertexID, uint64_t> > buffer_send(2 * num_sibling_es);
//// std::vector< std::vector<MPI_Request> > requests_list(num_hosts - 1);
// for (VertexID i = 0; i < num_sibling_es; ++i) {
// VertexID v = sibling_es[i].first;
// VertexID w = sibling_es[i].second;
//// buffer_send.emplace_back(v, tmp_s[v].second);
//// buffer_send.emplace_back(w, tmp_s[w].second);
// buffer_send[2 * i] = std::make_pair(v, tmp_s[v].second);
// buffer_send[2 * i + 1] = std::make_pair(w, tmp_s[w].second);
// }
// // Send the messages
// for (int root = 0; root < num_hosts; ++root) {
// std::vector< std::pair<VertexID, uint64_t> > buffer_recv;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send,
// buffer_recv);
// if (buffer_recv.empty()) {
// continue;
// }
// for (const std::pair<VertexID, uint64_t> &m : buffer_recv) {
// tmp_s[m.first].second |= m.second;
// }
// }
// for (VertexID i = 0; i < num_child_es; ++i) {
// VertexID v = child_es[i].first, c = child_es[i].second;
// tmp_s[c].first |= tmp_s[v].first;
// tmp_s[c].second |= tmp_s[v].second;
// }
// }
////#ifdef DEBUG_MESSAGES_ON
// {// test
// VertexID global_num_sibling_es;
// VertexID global_num_child_es;
// MPI_Allreduce(&num_sibling_es,
// &global_num_sibling_es,
// 1,
// V_ID_Type,
// MPI_SUM,
// MPI_COMM_WORLD);
// MPI_Allreduce(&num_child_es,
// &global_num_child_es,
// 1,
// V_ID_Type,
// MPI_SUM,
// MPI_COMM_WORLD);
// if (0 == host_id) {
// printf("iter: %u num_sibling_es: %u num_child_es: %u\n", d, global_num_sibling_es, global_num_child_es);
// }
// }
////#endif
//
// // Swap que and tmp_que
// tmp_que.swap(que);
// end_que = end_tmp_que;
// end_tmp_que = 0;
// MPI_Allreduce(&end_que,
// &global_num_actives,
// 1,
// V_ID_Type,
// MPI_SUM,
// MPI_COMM_WORLD);
//
//// }
// ++d;
// }
//
// for (VertexID v_local = 0; v_local < num_masters; ++v_local) {
// VertexID v_global = G.get_global_vertex_id(v_local);
// L[v_local].bp_dist[i_bpspt] = tmp_d[v_local];
// L[v_local].bp_sets[i_bpspt][0] = tmp_s[v_global].first; // S_r^{-1}
// L[v_local].bp_sets[i_bpspt][1] = tmp_s[v_global].second & ~tmp_s[v_global].first; // Only need those r's neighbors who are not already in S_r^{-1}
// }
// }
//}
//// Function bit parallel checking:
//// return false if shortest distance exits in bp labels, return true if bp labels cannot cover the distance
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//inline bool DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::bit_parallel_checking(
// VertexID v_id,
// VertexID w_id,
// const std::vector<IndexType> &L,
// UnweightedDist iter)
//{
// // Bit Parallel Checking: if label_real_id to v_tail has shorter distance already
// const IndexType &Lv = L[v_id];
// const IndexType &Lw = L[w_id];
//
// _mm_prefetch(&Lv.bp_dist[0], _MM_HINT_T0);
// _mm_prefetch(&Lv.bp_sets[0][0], _MM_HINT_T0);
// _mm_prefetch(&Lw.bp_dist[0], _MM_HINT_T0);
// _mm_prefetch(&Lw.bp_sets[0][0], _MM_HINT_T0);
// for (VertexID i = 0; i < BITPARALLEL_SIZE; ++i) {
// VertexID td = Lv.bp_dist[i] + Lw.bp_dist[i]; // Use type VertexID in case of addition of two INF.
// if (td - 2 <= iter) {
// td +=
// (Lv.bp_sets[i][0] & Lw.bp_sets[i][0]) ? -2 :
// ((Lv.bp_sets[i][0] & Lw.bp_sets[i][1]) |
// (Lv.bp_sets[i][1] & Lw.bp_sets[i][0]))
// ? -1 : 0;
// if (td <= iter) {
//// ++bp_hit_count;
// return false;
// }
// }
// }
// return true;
//}
// Function for initializing at the begin of a batch
// For a batch, initialize the temporary labels and real labels of roots;
// traverse roots' labels to initialize distance buffer;
// unset flag arrays is_active and got_labels
template <VertexID BATCH_SIZE>
inline VertexID DistBVCPLL<BATCH_SIZE>::
initialization(
const DistGraph &G,
std::vector<ShortIndex> &short_index,
std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::vector<VertexID> > &recved_dist_table,
std::vector<BPLabelType> &bp_labels_table,
std::vector<VertexID> &active_queue,
VertexID &end_active_queue,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
// VertexID b_id,
VertexID roots_start,
VertexID roots_size,
// std::vector<VertexID> &roots_master_local,
const std::vector<uint8_t> &used_bp_roots)
{
// Get the roots_master_local, containing all local roots.
std::vector<VertexID> roots_master_local;
VertexID size_roots_master_local;
VertexID roots_bound = roots_start + roots_size;
try {
for (VertexID r_global = roots_start; r_global < roots_bound; ++r_global) {
if (G.get_master_host_id(r_global) == host_id && !used_bp_roots[r_global]) {
roots_master_local.push_back(G.get_local_vertex_id(r_global));
}
}
size_roots_master_local = roots_master_local.size();
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("initialization_roots_master_local: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
// Short_index
{
if (end_once_candidated_queue >= THRESHOLD_PARALLEL) {
#pragma omp parallel for
for (VertexID v_i = 0; v_i < end_once_candidated_queue; ++v_i) {
VertexID v_local = once_candidated_queue[v_i];
short_index[v_local].indicator_reset();
once_candidated[v_local] = 0;
}
} else {
for (VertexID v_i = 0; v_i < end_once_candidated_queue; ++v_i) {
VertexID v_local = once_candidated_queue[v_i];
short_index[v_local].indicator_reset();
once_candidated[v_local] = 0;
}
}
end_once_candidated_queue = 0;
if (size_roots_master_local >= THRESHOLD_PARALLEL) {
#pragma omp parallel for
for (VertexID i_r = 0; i_r < size_roots_master_local; ++i_r) {
VertexID r_local = roots_master_local[i_r];
short_index[r_local].indicator[G.get_global_vertex_id(r_local) - roots_start] = 1; // v itself
// short_index[r_local].indicator[BATCH_SIZE] = 1; // v got labels
}
} else {
for (VertexID r_local : roots_master_local) {
short_index[r_local].indicator[G.get_global_vertex_id(r_local) - roots_start] = 1; // v itself
// short_index[r_local].indicator[BATCH_SIZE] = 1; // v got labels
}
}
}
//
// Real Index
try
{
if (size_roots_master_local >= THRESHOLD_PARALLEL) {
#pragma omp parallel for
for (VertexID i_r = 0; i_r < size_roots_master_local; ++i_r) {
VertexID r_local = roots_master_local[i_r];
IndexType &Lr = L[r_local];
// Lr.batches.emplace_back(
// b_id, // Batch ID
// Lr.distances.size(), // start_index
// 1); // size
Lr.distances.emplace_back(
Lr.vertices.size(), // start_index
1, // size
0); // dist
Lr.vertices.push_back(G.get_global_vertex_id(r_local));
// Lr.vertices.push_back(G.get_global_vertex_id(r_local) - roots_start);
}
} else {
for (VertexID r_local : roots_master_local) {
IndexType &Lr = L[r_local];
// Lr.batches.emplace_back(
// b_id, // Batch ID
// Lr.distances.size(), // start_index
// 1); // size
Lr.distances.emplace_back(
Lr.vertices.size(), // start_index
1, // size
0); // dist
Lr.vertices.push_back(G.get_global_vertex_id(r_local));
// Lr.vertices.push_back(G.get_global_vertex_id(r_local) - roots_start);
}
}
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("initialization_real_index: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
// Dist Table
try
{
// struct LabelTableUnit {
// VertexID root_id;
// VertexID label_global_id;
// UnweightedDist dist;
//
// LabelTableUnit() = default;
//
// LabelTableUnit(VertexID r, VertexID l, UnweightedDist d) :
// root_id(r), label_global_id(l), dist(d) {}
// };
std::vector<LabelTableUnit> buffer_send; // buffer for sending
// Dist_matrix
{
// Deprecated Old method: unpack the IndexType structure before sending.
// Okay, it's back.
if (size_roots_master_local >= THRESHOLD_PARALLEL) {
// Offsets for adding labels to buffer_send in parallel
std::vector<VertexID> offsets_beffer_send(size_roots_master_local);
#pragma omp parallel for
for (VertexID i_r = 0; i_r < size_roots_master_local; ++i_r) {
VertexID r_local = roots_master_local[i_r];
offsets_beffer_send[i_r] = L[r_local].vertices.size();
}
EdgeID size_labels = PADO::prefix_sum_for_offsets(offsets_beffer_send);
buffer_send.resize(size_labels);
#pragma omp parallel for
for (VertexID i_r = 0; i_r < size_roots_master_local; ++i_r) {
VertexID r_local = roots_master_local[i_r];
VertexID top_location = 0;
IndexType &Lr = L[r_local];
VertexID r_root_id = G.get_global_vertex_id(r_local) - roots_start;
// VertexID b_i_bound = Lr.batches.size();
// _mm_prefetch(&Lr.batches[0], _MM_HINT_T0);
_mm_prefetch(&Lr.distances[0], _MM_HINT_T0);
_mm_prefetch(&Lr.vertices[0], _MM_HINT_T0);
// Traverse batches array
// for (VertexID b_i = 0; b_i < b_i_bound; ++b_i) {
// VertexID id_offset = Lr.batches[b_i].batch_id * BATCH_SIZE;
// VertexID dist_start_index = Lr.batches[b_i].start_index;
// VertexID dist_bound_index = dist_start_index + Lr.batches[b_i].size;
// Traverse distances array
// for (VertexID dist_i = dist_start_index; dist_i < dist_bound_index; ++dist_i) {
VertexID dist_bound_index = Lr.distances.size();
for (VertexID dist_i = 0; dist_i < dist_bound_index; ++dist_i) {
VertexID v_start_index = Lr.distances[dist_i].start_index;
VertexID v_bound_index = v_start_index + Lr.distances[dist_i].size;
UnweightedDist dist = Lr.distances[dist_i].dist;
// Traverse vertices array
for (VertexID v_i = v_start_index; v_i < v_bound_index; ++v_i) {
// Write into the dist_table
// buffer_send[offsets_beffer_send[i_r] + top_location++] =
// LabelTableUnit(r_root_id, Lr.vertices[v_i] + id_offset, dist);
buffer_send[offsets_beffer_send[i_r] + top_location++] =
LabelTableUnit(r_root_id, Lr.vertices[v_i], dist);
}
}
// }
}
} else {
for (VertexID r_local : roots_master_local) {
// The distance table.
IndexType &Lr = L[r_local];
VertexID r_root_id = G.get_global_vertex_id(r_local) - roots_start;
// VertexID b_i_bound = Lr.batches.size();
// _mm_prefetch(&Lr.batches[0], _MM_HINT_T0);
_mm_prefetch(&Lr.distances[0], _MM_HINT_T0);
_mm_prefetch(&Lr.vertices[0], _MM_HINT_T0);
// Traverse batches array
// for (VertexID b_i = 0; b_i < b_i_bound; ++b_i) {
// VertexID id_offset = Lr.batches[b_i].batch_id * BATCH_SIZE;
// VertexID dist_start_index = Lr.batches[b_i].start_index;
// VertexID dist_bound_index = dist_start_index + Lr.batches[b_i].size;
// Traverse distances array
// for (VertexID dist_i = dist_start_index; dist_i < dist_bound_index; ++dist_i) {
VertexID dist_bound_index = Lr.distances.size();
for (VertexID dist_i = 0; dist_i < dist_bound_index; ++dist_i) {
VertexID v_start_index = Lr.distances[dist_i].start_index;
VertexID v_bound_index = v_start_index + Lr.distances[dist_i].size;
UnweightedDist dist = Lr.distances[dist_i].dist;
// Traverse vertices array
for (VertexID v_i = v_start_index; v_i < v_bound_index; ++v_i) {
// Write into the dist_table
buffer_send.emplace_back(r_root_id, Lr.vertices[v_i],
dist); // buffer for sending
// buffer_send.emplace_back(r_root_id, Lr.vertices[v_i] + id_offset,
// dist); // buffer for sending
}
}
// }
}
}
}
// Broadcast local roots labels
for (int root = 0; root < num_hosts; ++root) {
std::vector<LabelTableUnit> buffer_recv;
one_host_bcasts_buffer_to_buffer(root,
buffer_send,
buffer_recv);
if (buffer_recv.empty()) {
continue;
}
EdgeID size_buffer_recv = buffer_recv.size();
if (size_buffer_recv >= THRESHOLD_PARALLEL) {
std::vector<VertexID> sizes_recved_root_labels(roots_size, 0);
#pragma omp parallel for
for (EdgeID i_l = 0; i_l < size_buffer_recv; ++i_l) {
const LabelTableUnit &l = buffer_recv[i_l];
VertexID root_id = l.root_id;
VertexID label_global_id = l.label_global_id;
UnweightedDist dist = l.dist;
dist_table[root_id][label_global_id] = dist;
// Record root_id's number of its received label, for later adding to recved_dist_table
__atomic_add_fetch(sizes_recved_root_labels.data() + root_id, 1, __ATOMIC_SEQ_CST);
// recved_dist_table[root_id].push_back(label_global_id);
}
// Record the received label in recved_dist_table, for later reset
#pragma omp parallel for
for (VertexID root_id = 0; root_id < roots_size; ++root_id) {
VertexID &size = sizes_recved_root_labels[root_id];
if (size) {
recved_dist_table[root_id].resize(size);
size = 0;
}
}
#pragma omp parallel for
for (EdgeID i_l = 0; i_l < size_buffer_recv; ++i_l) {
const LabelTableUnit &l = buffer_recv[i_l];
VertexID root_id = l.root_id;
VertexID label_global_id = l.label_global_id;
PADO::TS_enqueue(recved_dist_table[root_id], sizes_recved_root_labels[root_id], label_global_id);
}
} else {
for (const LabelTableUnit &l : buffer_recv) {
VertexID root_id = l.root_id;
VertexID label_global_id = l.label_global_id;
UnweightedDist dist = l.dist;
dist_table[root_id][label_global_id] = dist;
// Record the received label in recved_dist_table, for later reset
recved_dist_table[root_id].push_back(label_global_id);
}
}
}
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("initialization_dist_table: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
// Build the Bit-Parallel Labels Table
try
{
// struct MsgBPLabel {
// VertexID r_root_id;
// UnweightedDist bp_dist[BITPARALLEL_SIZE];
// uint64_t bp_sets[BITPARALLEL_SIZE][2];
//
// MsgBPLabel() = default;
// MsgBPLabel(VertexID r, const UnweightedDist dist[], const uint64_t sets[][2])
// : r_root_id(r)
// {
// memcpy(bp_dist, dist, sizeof(bp_dist));
// memcpy(bp_sets, sets, sizeof(bp_sets));
// }
// };
// std::vector<MPI_Request> requests_send(num_hosts - 1);
std::vector<MsgBPLabel> buffer_send;
std::vector<VertexID> roots_queue;
for (VertexID r_global = roots_start; r_global < roots_bound; ++r_global) {
if (G.get_master_host_id(r_global) != host_id) {
continue;
}
roots_queue.push_back(r_global);
}
VertexID size_roots_queue = roots_queue.size();
if (size_roots_queue >= THRESHOLD_PARALLEL) {
buffer_send.resize(size_roots_queue);
#pragma omp parallel for
for (VertexID i_r = 0; i_r < size_roots_queue; ++i_r) {
VertexID r_global = roots_queue[i_r];
VertexID r_local = G.get_local_vertex_id(r_global);
VertexID r_root = r_global - roots_start;
// Prepare for sending
// buffer_send.emplace_back(r_root, L[r_local].bp_dist, L[r_local].bp_sets);
buffer_send[i_r] = MsgBPLabel(r_root, L[r_local].bp_dist, L[r_local].bp_sets);
}
} else {
// for (VertexID r_global = roots_start; r_global < roots_bound; ++r_global) {
// if (G.get_master_host_id(r_global) != host_id) {
// continue;
// }
for (VertexID r_global : roots_queue) {
VertexID r_local = G.get_local_vertex_id(r_global);
VertexID r_root = r_global - roots_start;
// Local roots
// memcpy(bp_labels_table[r_root].bp_dist, L[r_local].bp_dist, sizeof(bp_labels_table[r_root].bp_dist));
// memcpy(bp_labels_table[r_root].bp_sets, L[r_local].bp_sets, sizeof(bp_labels_table[r_root].bp_sets));
// Prepare for sending
buffer_send.emplace_back(r_root, L[r_local].bp_dist, L[r_local].bp_sets);
}
}
for (int root = 0; root < num_hosts; ++root) {
std::vector<MsgBPLabel> buffer_recv;
one_host_bcasts_buffer_to_buffer(root,
buffer_send,
buffer_recv);
if (buffer_recv.empty()) {
continue;
}
VertexID size_buffer_recv = buffer_recv.size();
if (size_buffer_recv >= THRESHOLD_PARALLEL) {
#pragma omp parallel for
for (VertexID i_m = 0; i_m < size_buffer_recv; ++i_m) {
const MsgBPLabel &m = buffer_recv[i_m];
VertexID r_root = m.r_root_id;
memcpy(bp_labels_table[r_root].bp_dist, m.bp_dist, sizeof(bp_labels_table[r_root].bp_dist));
memcpy(bp_labels_table[r_root].bp_sets, m.bp_sets, sizeof(bp_labels_table[r_root].bp_sets));
}
} else {
for (const MsgBPLabel &m : buffer_recv) {
VertexID r_root = m.r_root_id;
memcpy(bp_labels_table[r_root].bp_dist, m.bp_dist, sizeof(bp_labels_table[r_root].bp_dist));
memcpy(bp_labels_table[r_root].bp_sets, m.bp_sets, sizeof(bp_labels_table[r_root].bp_sets));
}
}
}
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("initialization_bp_labels_table: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
// Active_queue
VertexID global_num_actives = 0; // global number of active vertices.
{
if (size_roots_master_local >= THRESHOLD_PARALLEL) {
#pragma omp parallel for
for (VertexID i_r = 0; i_r < size_roots_master_local; ++i_r) {
VertexID r_local = roots_master_local[i_r];
active_queue[i_r] = r_local;
}
end_active_queue = size_roots_master_local;
} else {
for (VertexID r_local : roots_master_local) {
active_queue[end_active_queue++] = r_local;
}
}
// Get the global number of active vertices;
// message_time -= WallTimer::get_time_mark();
MPI_Allreduce(&end_active_queue,
&global_num_actives,
1,
V_ID_Type,
// MPI_SUM,
MPI_MAX,
MPI_COMM_WORLD);
// message_time += WallTimer::get_time_mark();
}
return global_num_actives;
}
// Sequential Version
//// Function for initializing at the begin of a batch
//// For a batch, initialize the temporary labels and real labels of roots;
//// traverse roots' labels to initialize distance buffer;
//// unset flag arrays is_active and got_labels
//template <VertexID BATCH_SIZE>
//inline VertexID DistBVCPLL<BATCH_SIZE>::
//initialization(
// const DistGraph &G,
// std::vector<ShortIndex> &short_index,
// std::vector< std::vector<UnweightedDist> > &dist_table,
// std::vector< std::vector<VertexID> > &recved_dist_table,
// std::vector<BPLabelType> &bp_labels_table,
// std::vector<VertexID> &active_queue,
// VertexID &end_active_queue,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
// std::vector<uint8_t> &once_candidated,
// VertexID b_id,
// VertexID roots_start,
// VertexID roots_size,
//// std::vector<VertexID> &roots_master_local,
// const std::vector<uint8_t> &used_bp_roots)
//{
// // Get the roots_master_local, containing all local roots.
// std::vector<VertexID> roots_master_local;
// VertexID roots_bound = roots_start + roots_size;
// for (VertexID r_global = roots_start; r_global < roots_bound; ++r_global) {
// if (G.get_master_host_id(r_global) == host_id && !used_bp_roots[r_global]) {
// roots_master_local.push_back(G.get_local_vertex_id(r_global));
// }
// }
// // Short_index
// {
// for (VertexID v_i = 0; v_i < end_once_candidated_queue; ++v_i) {
// VertexID v_local = once_candidated_queue[v_i];
// short_index[v_local].indicator_reset();
// once_candidated[v_local] = 0;
// }
// end_once_candidated_queue = 0;
// for (VertexID r_local : roots_master_local) {
// short_index[r_local].indicator[G.get_global_vertex_id(r_local) - roots_start] = 1; // v itself
// short_index[r_local].indicator[BATCH_SIZE] = 1; // v got labels
//// short_index[r_local].indicator.set(G.get_global_vertex_id(r_local) - roots_start); // v itself
//// short_index[r_local].indicator.set(BATCH_SIZE); // v got labels
// }
// }
////
// // Real Index
// {
// for (VertexID r_local : roots_master_local) {
// IndexType &Lr = L[r_local];
// Lr.batches.emplace_back(
// b_id, // Batch ID
// Lr.distances.size(), // start_index
// 1); // size
// Lr.distances.emplace_back(
// Lr.vertices.size(), // start_index
// 1, // size
// 0); // dist
// Lr.vertices.push_back(G.get_global_vertex_id(r_local) - roots_start);
// }
// }
//
// // Dist Table
// {
//// struct LabelTableUnit {
//// VertexID root_id;
//// VertexID label_global_id;
//// UnweightedDist dist;
////
//// LabelTableUnit() = default;
////
//// LabelTableUnit(VertexID r, VertexID l, UnweightedDist d) :
//// root_id(r), label_global_id(l), dist(d) {}
//// };
// std::vector<LabelTableUnit> buffer_send; // buffer for sending
// // Dist_matrix
// {
// // Deprecated Old method: unpack the IndexType structure before sending.
// for (VertexID r_local : roots_master_local) {
// // The distance table.
// IndexType &Lr = L[r_local];
// VertexID r_root_id = G.get_global_vertex_id(r_local) - roots_start;
// VertexID b_i_bound = Lr.batches.size();
// _mm_prefetch(&Lr.batches[0], _MM_HINT_T0);
// _mm_prefetch(&Lr.distances[0], _MM_HINT_T0);
// _mm_prefetch(&Lr.vertices[0], _MM_HINT_T0);
// // Traverse batches array
// for (VertexID b_i = 0; b_i < b_i_bound; ++b_i) {
// VertexID id_offset = Lr.batches[b_i].batch_id * BATCH_SIZE;
// VertexID dist_start_index = Lr.batches[b_i].start_index;
// VertexID dist_bound_index = dist_start_index + Lr.batches[b_i].size;
// // Traverse distances array
// for (VertexID dist_i = dist_start_index; dist_i < dist_bound_index; ++dist_i) {
// VertexID v_start_index = Lr.distances[dist_i].start_index;
// VertexID v_bound_index = v_start_index + Lr.distances[dist_i].size;
// UnweightedDist dist = Lr.distances[dist_i].dist;
// // Traverse vertices array
// for (VertexID v_i = v_start_index; v_i < v_bound_index; ++v_i) {
// // Write into the dist_table
//// dist_table[r_root_id][Lr.vertices[v_i] + id_offset] = dist; // distance table
// buffer_send.emplace_back(r_root_id, Lr.vertices[v_i] + id_offset,
// dist); // buffer for sending
// }
// }
// }
// }
// }
// // Broadcast local roots labels
// for (int root = 0; root < num_hosts; ++root) {
// std::vector<LabelTableUnit> buffer_recv;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send,
// buffer_recv);
// if (buffer_recv.empty()) {
// continue;
// }
// for (const LabelTableUnit &l : buffer_recv) {
// VertexID root_id = l.root_id;
// VertexID label_global_id = l.label_global_id;
// UnweightedDist dist = l.dist;
// dist_table[root_id][label_global_id] = dist;
// // Record the received label in recved_dist_table, for later reset
// recved_dist_table[root_id].push_back(label_global_id);
// }
// }
// }
//
// // Build the Bit-Parallel Labels Table
// {
//// struct MsgBPLabel {
//// VertexID r_root_id;
//// UnweightedDist bp_dist[BITPARALLEL_SIZE];
//// uint64_t bp_sets[BITPARALLEL_SIZE][2];
////
//// MsgBPLabel() = default;
//// MsgBPLabel(VertexID r, const UnweightedDist dist[], const uint64_t sets[][2])
//// : r_root_id(r)
//// {
//// memcpy(bp_dist, dist, sizeof(bp_dist));
//// memcpy(bp_sets, sets, sizeof(bp_sets));
//// }
//// };
//// std::vector<MPI_Request> requests_send(num_hosts - 1);
// std::vector<MsgBPLabel> buffer_send;
// for (VertexID r_global = roots_start; r_global < roots_bound; ++r_global) {
// if (G.get_master_host_id(r_global) != host_id) {
// continue;
// }
// VertexID r_local = G.get_local_vertex_id(r_global);
// VertexID r_root = r_global - roots_start;
// // Local roots
//// memcpy(bp_labels_table[r_root].bp_dist, L[r_local].bp_dist, sizeof(bp_labels_table[r_root].bp_dist));
//// memcpy(bp_labels_table[r_root].bp_sets, L[r_local].bp_sets, sizeof(bp_labels_table[r_root].bp_sets));
// // Prepare for sending
// buffer_send.emplace_back(r_root, L[r_local].bp_dist, L[r_local].bp_sets);
// }
//
// for (int root = 0; root < num_hosts; ++root) {
// std::vector<MsgBPLabel> buffer_recv;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send,
// buffer_recv);
// if (buffer_recv.empty()) {
// continue;
// }
// for (const MsgBPLabel &m : buffer_recv) {
// VertexID r_root = m.r_root_id;
// memcpy(bp_labels_table[r_root].bp_dist, m.bp_dist, sizeof(bp_labels_table[r_root].bp_dist));
// memcpy(bp_labels_table[r_root].bp_sets, m.bp_sets, sizeof(bp_labels_table[r_root].bp_sets));
// }
// }
// }
//
// // TODO: parallel enqueue
// // Active_queue
// VertexID global_num_actives = 0; // global number of active vertices.
// {
// for (VertexID r_local : roots_master_local) {
// active_queue[end_active_queue++] = r_local;
// }
// // Get the global number of active vertices;
// message_time -= WallTimer::get_time_mark();
// MPI_Allreduce(&end_active_queue,
// &global_num_actives,
// 1,
// V_ID_Type,
// MPI_SUM,
// MPI_COMM_WORLD);
// message_time += WallTimer::get_time_mark();
// }
//
// return global_num_actives;
//}
//// Function: push v_head_global's newly added labels to its all neighbors.
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::
//push_single_label(
// VertexID v_head_global,
// VertexID label_root_id,
// VertexID roots_start,
// const DistGraph &G,
// std::vector<ShortIndex> &short_index,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
// std::vector<bool> &got_candidates,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
// std::vector<bool> &once_candidated,
// const std::vector<BPLabelType> &bp_labels_table,
// const std::vector<uint8_t> &used_bp_roots,
// UnweightedDist iter)
//{
// const BPLabelType &L_label = bp_labels_table[label_root_id];
// VertexID label_global_id = label_root_id + roots_start;
// EdgeID e_i_start = G.vertices_idx[v_head_global];
// EdgeID e_i_bound = e_i_start + G.local_out_degrees[v_head_global];
// for (EdgeID e_i = e_i_start; e_i < e_i_bound; ++e_i) {
// VertexID v_tail_global = G.out_edges[e_i];
// if (used_bp_roots[v_tail_global]) {
// continue;
// }
// if (v_tail_global < roots_start) { // all remaining v_tail_global has higher rank than any roots, then no roots can push new labels to it.
// return;
// }
//
// VertexID v_tail_local = G.get_local_vertex_id(v_tail_global);
// const IndexType &L_tail = L[v_tail_local];
// if (v_tail_global <= label_global_id) {
// // remaining v_tail_global has higher rank than the label
// return;
// }
// ShortIndex &SI_v_tail = short_index[v_tail_local];
// if (SI_v_tail.indicator[label_root_id]) {
// // The label is already selected before
// continue;
// }
// // Record label_root_id as once selected by v_tail_global
// SI_v_tail.indicator.set(label_root_id);
// // Add into once_candidated_queue
//
// if (!once_candidated[v_tail_local]) {
// // If v_tail_global is not in the once_candidated_queue yet, add it in
// once_candidated[v_tail_local] = true;
// once_candidated_queue[end_once_candidated_queue++] = v_tail_local;
// }
// // Bit Parallel Checking: if label_global_id to v_tail_global has shorter distance already
// // ++total_check_count;
//// const IndexType &L_label = L[label_global_id];
//// _mm_prefetch(&L_label.bp_dist[0], _MM_HINT_T0);
//// _mm_prefetch(&L_label.bp_sets[0][0], _MM_HINT_T0);
//// bp_checking_ins_count.measure_start();
// bool no_need_add = false;
// for (VertexID i = 0; i < BITPARALLEL_SIZE; ++i) {
// VertexID td = L_label.bp_dist[i] + L_tail.bp_dist[i];
// if (td - 2 <= iter) {
// td +=
// (L_label.bp_sets[i][0] & L_tail.bp_sets[i][0]) ? -2 :
// ((L_label.bp_sets[i][0] & L_tail.bp_sets[i][1]) |
// (L_label.bp_sets[i][1] & L_tail.bp_sets[i][0]))
// ? -1 : 0;
// if (td <= iter) {
// no_need_add = true;
//// ++bp_hit_count;
// break;
// }
// }
// }
// if (no_need_add) {
//// bp_checking_ins_count.measure_stop();
// continue;
// }
//// bp_checking_ins_count.measure_stop();
// if (SI_v_tail.is_candidate[label_root_id]) {
// continue;
// }
// SI_v_tail.is_candidate[label_root_id] = true;
// SI_v_tail.candidates_que[SI_v_tail.end_candidates_que++] = label_root_id;
//
// if (!got_candidates[v_tail_local]) {
// // If v_tail_global is not in got_candidates_queue, add it in (prevent duplicate)
// got_candidates[v_tail_local] = true;
// got_candidates_queue[end_got_candidates_queue++] = v_tail_local;
// }
// }
//// {// Just for the complain from the compiler
//// assert(iter >= iter);
//// }
//}
template<VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
schedule_label_pushing_para(
const DistGraph &G,
const VertexID roots_start,
const std::vector<uint8_t> &used_bp_roots,
const std::vector<VertexID> &active_queue,
const VertexID global_start,
const VertexID global_size,
const VertexID local_size,
// const VertexID start_active_queue,
// const VertexID size_active_queue,
std::vector<VertexID> &got_candidates_queue,
VertexID &end_got_candidates_queue,
std::vector<ShortIndex> &short_index,
const std::vector<BPLabelType> &bp_labels_table,
std::vector<uint8_t> &got_candidates,
std::vector<uint8_t> &is_active,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
const UnweightedDist iter)
{
std::vector<std::pair<VertexID, VertexID> > buffer_send_indices;
//.first: Vertex ID
//.second: size of labels
std::vector<VertexID> buffer_send_labels;
if (local_size) {
const VertexID start_active_queue = global_start;
const VertexID size_active_queue = global_size <= local_size ?
global_size :
local_size;
const VertexID bound_active_queue = start_active_queue + size_active_queue;
buffer_send_indices.resize(size_active_queue);
// Prepare offset for inserting
std::vector<VertexID> offsets_buffer_locs(size_active_queue);
#pragma omp parallel for
for (VertexID i_q = start_active_queue; i_q < bound_active_queue; ++i_q) {
VertexID v_head_local = active_queue[i_q];
is_active[v_head_local] = 0; // reset is_active
const IndexType &Lv = L[v_head_local];
offsets_buffer_locs[i_q - start_active_queue] = Lv.distances.rbegin()->size;
}
EdgeID size_buffer_send_labels = PADO::prefix_sum_for_offsets(offsets_buffer_locs);
try {
buffer_send_labels.resize(size_buffer_send_labels);
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("schedule_label_pushing_para.buffer_send_labels: bad_alloc "
"host_id: %d "
"size_buffer_send_labels: %lu "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
size_buffer_send_labels,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
// Build buffer_send_labels by parallel inserting
#pragma omp parallel for
for (VertexID i_q = start_active_queue; i_q < bound_active_queue; ++i_q) {
VertexID v_head_local = active_queue[i_q];
is_active[v_head_local] = 0; // reset is_active
VertexID v_head_global = G.get_global_vertex_id(v_head_local);
const IndexType &Lv = L[v_head_local];
// Prepare the buffer_send_indices
VertexID tmp_i_q = i_q - start_active_queue;
buffer_send_indices[tmp_i_q] = std::make_pair(v_head_global, Lv.distances.rbegin()->size);
// These 2 index are used for traversing v_head's last inserted labels
VertexID l_i_start = Lv.distances.rbegin()->start_index;
VertexID l_i_bound = l_i_start + Lv.distances.rbegin()->size;
VertexID top_labels = offsets_buffer_locs[tmp_i_q];
for (VertexID l_i = l_i_start; l_i < l_i_bound; ++l_i) {
VertexID label_root_id = Lv.vertices[l_i] - roots_start;
buffer_send_labels[top_labels++] = label_root_id;
// buffer_send_labels.push_back(label_root_id);
}
}
}
////////////////////////////////////////////////
////
// const VertexID bound_active_queue = start_active_queue + size_active_queue;
// std::vector<std::pair<VertexID, VertexID> > buffer_send_indices(size_active_queue);
// //.first: Vertex ID
// //.second: size of labels
// std::vector<VertexID> buffer_send_labels;
// // Prepare masters' newly added labels for sending
// // Parallel Version
// // Prepare offset for inserting
// std::vector<VertexID> offsets_buffer_locs(size_active_queue);
//#pragma omp parallel for
// for (VertexID i_q = start_active_queue; i_q < bound_active_queue; ++i_q) {
// VertexID v_head_local = active_queue[i_q];
// is_active[v_head_local] = 0; // reset is_active
// const IndexType &Lv = L[v_head_local];
// offsets_buffer_locs[i_q - start_active_queue] = Lv.distances.rbegin()->size;
// }
// EdgeID size_buffer_send_labels = PADO::prefix_sum_for_offsets(offsets_buffer_locs);
//// {// test
//// if (0 == host_id) {
//// double memtotal = 0;
//// double memfree = 0;
//// double bytes_buffer_send_labels = size_buffer_send_labels * sizeof(VertexID);
//// PADO::Utils::system_memory(memtotal, memfree);
//// printf("bytes_buffer_send_labels: %fGB memtotal: %fGB memfree: %fGB\n",
//// bytes_buffer_send_labels / (1 << 30), memtotal / 1024, memfree / 1024);
//// }
//// }
// buffer_send_labels.resize(size_buffer_send_labels);
//// {// test
//// if (0 == host_id) {
//// printf("buffer_send_labels created.\n");
//// }
//// }
//
// // Build buffer_send_labels by parallel inserting
//#pragma omp parallel for
// for (VertexID i_q = start_active_queue; i_q < bound_active_queue; ++i_q) {
// VertexID tmp_i_q = i_q - start_active_queue;
// VertexID v_head_local = active_queue[i_q];
// is_active[v_head_local] = 0; // reset is_active
// VertexID v_head_global = G.get_global_vertex_id(v_head_local);
// const IndexType &Lv = L[v_head_local];
// // Prepare the buffer_send_indices
// buffer_send_indices[tmp_i_q] = std::make_pair(v_head_global, Lv.distances.rbegin()->size);
// // These 2 index are used for traversing v_head's last inserted labels
// VertexID l_i_start = Lv.distances.rbegin()->start_index;
// VertexID l_i_bound = l_i_start + Lv.distances.rbegin()->size;
// VertexID top_labels = offsets_buffer_locs[tmp_i_q];
// for (VertexID l_i = l_i_start; l_i < l_i_bound; ++l_i) {
// VertexID label_root_id = Lv.vertices[l_i];
// buffer_send_labels[top_labels++] = label_root_id;
//// buffer_send_labels.push_back(label_root_id);
// }
// }
//// end_active_queue = 0;
////
////////////////////////////////////////////////
for (int root = 0; root < num_hosts; ++root) {
// Get the indices
std::vector<std::pair<VertexID, VertexID> > indices_buffer;
one_host_bcasts_buffer_to_buffer(root,
buffer_send_indices,
indices_buffer);
if (indices_buffer.empty()) {
continue;
}
// Get the labels
std::vector<VertexID> labels_buffer;
one_host_bcasts_buffer_to_buffer(root,
buffer_send_labels,
labels_buffer);
VertexID size_indices_buffer = indices_buffer.size();
// Prepare the offsets for reading indices_buffer
std::vector<EdgeID> starts_locs_index(size_indices_buffer);
#pragma omp parallel for
for (VertexID i_i = 0; i_i < size_indices_buffer; ++i_i) {
const std::pair<VertexID, VertexID> &e = indices_buffer[i_i];
starts_locs_index[i_i] = e.second;
}
EdgeID total_recved_labels = PADO::prefix_sum_for_offsets(starts_locs_index);
// Prepare the offsets for inserting v_tails into queue
std::vector<VertexID> offsets_tmp_queue(size_indices_buffer);
#pragma omp parallel for
for (VertexID i_i = 0; i_i < size_indices_buffer; ++i_i) {
const std::pair<VertexID, VertexID> &e = indices_buffer[i_i];
offsets_tmp_queue[i_i] = G.local_out_degrees[e.first];
}
EdgeID num_ngbrs = PADO::prefix_sum_for_offsets(offsets_tmp_queue);
std::vector<VertexID> tmp_got_candidates_queue;
std::vector<VertexID> sizes_tmp_got_candidates_queue;
std::vector<VertexID> tmp_once_candidated_queue;
std::vector<VertexID> sizes_tmp_once_candidated_queue;
try {
tmp_got_candidates_queue.resize(num_ngbrs);
sizes_tmp_got_candidates_queue.resize(size_indices_buffer, 0);
tmp_once_candidated_queue.resize(num_ngbrs);
sizes_tmp_once_candidated_queue.resize(size_indices_buffer, 0);
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("schedule_label_pushing_para.tmp_queues: bad_alloc "
"host_id: %d "
"num_ngbrs: %lu "
"size_indices_buffer: %u "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
num_ngbrs,
size_indices_buffer,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
#pragma omp parallel for
for (VertexID i_i = 0; i_i < size_indices_buffer; ++i_i) {
VertexID v_head_global = indices_buffer[i_i].first;
EdgeID start_index = starts_locs_index[i_i];
EdgeID bound_index = i_i != size_indices_buffer - 1 ?
starts_locs_index[i_i + 1] : total_recved_labels;
if (G.local_out_degrees[v_head_global]) {
local_push_labels_para(
v_head_global,
start_index,
bound_index,
roots_start,
labels_buffer,
G,
short_index,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
tmp_got_candidates_queue,
sizes_tmp_got_candidates_queue[i_i],
offsets_tmp_queue[i_i],
got_candidates,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
tmp_once_candidated_queue,
sizes_tmp_once_candidated_queue[i_i],
once_candidated,
bp_labels_table,
used_bp_roots,
iter);
}
}
{// Collect elements from tmp_got_candidates_queue to got_candidates_queue
VertexID total_new = PADO::prefix_sum_for_offsets(sizes_tmp_got_candidates_queue);
PADO::collect_into_queue(
tmp_got_candidates_queue,
offsets_tmp_queue, // the locations for reading tmp_got_candidate_queue
sizes_tmp_got_candidates_queue, // the locations for writing got_candidate_queue
total_new,
got_candidates_queue,
end_got_candidates_queue);
}
{// Collect elements from tmp_once_candidated_queue to once_candidated_queue
VertexID total_new = PADO::prefix_sum_for_offsets(sizes_tmp_once_candidated_queue);
PADO::collect_into_queue(
tmp_once_candidated_queue,
offsets_tmp_queue, // the locations for reading tmp_once_candidats_queue
sizes_tmp_once_candidated_queue, // the locations for writing once_candidated_queue
total_new,
once_candidated_queue,
end_once_candidated_queue);
}
}
}
// Function: pushes v_head's labels to v_head's every (master) neighbor
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
local_push_labels_para(
const VertexID v_head_global,
const EdgeID start_index,
const EdgeID bound_index,
const VertexID roots_start,
const std::vector<VertexID> &labels_buffer,
const DistGraph &G,
std::vector<ShortIndex> &short_index,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
std::vector<VertexID> &tmp_got_candidates_queue,
VertexID &size_tmp_got_candidates_queue,
const VertexID offset_tmp_queue,
std::vector<uint8_t> &got_candidates,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
std::vector<VertexID> &tmp_once_candidated_queue,
VertexID &size_tmp_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
const std::vector<BPLabelType> &bp_labels_table,
const std::vector<uint8_t> &used_bp_roots,
const UnweightedDist iter)
{
// Traverse v_head's every neighbor v_tail
EdgeID e_i_start = G.vertices_idx[v_head_global];
EdgeID e_i_bound = e_i_start + G.local_out_degrees[v_head_global];
for (EdgeID e_i = e_i_start; e_i < e_i_bound; ++e_i) {
VertexID v_tail_global = G.out_edges[e_i];
if (used_bp_roots[v_tail_global]) {
continue;
}
if (v_tail_global < roots_start) { // v_tail_global has higher rank than any roots, then no roots can push new labels to it.
return;
}
VertexID v_tail_local = G.get_local_vertex_id(v_tail_global);
const IndexType &L_tail = L[v_tail_local];
ShortIndex &SI_v_tail = short_index[v_tail_local];
// Traverse v_head's last inserted labels
for (VertexID l_i = start_index; l_i < bound_index; ++l_i) {
VertexID label_root_id = labels_buffer[l_i];
VertexID label_global_id = label_root_id + roots_start;
if (v_tail_global <= label_global_id) {
// v_tail_global has higher rank than the label
continue;
}
// if (SI_v_tail.indicator[label_root_id]) {
// // The label is already selected before
// continue;
// }
// // Record label_root_id as once selected by v_tail_global
// SI_v_tail.indicator[label_root_id] = 1;
{// Deal with race condition
if (!PADO::CAS(SI_v_tail.indicator.data() + label_root_id, static_cast<uint8_t>(0),
static_cast<uint8_t>(1))) {
// The label is already selected before
continue;
}
}
// Add into once_candidated_queue
if (!once_candidated[v_tail_local]) {
// If v_tail_global is not in the once_candidated_queue yet, add it in
if (PADO::CAS(once_candidated.data() + v_tail_local, static_cast<uint8_t>(0), static_cast<uint8_t>(1))) {
tmp_once_candidated_queue[offset_tmp_queue + size_tmp_once_candidated_queue++] = v_tail_local;
}
// once_candidated[v_tail_local] = 1;
// once_candidated_queue[end_once_candidated_queue++] = v_tail_local;
}
// Bit Parallel Checking: if label_global_id to v_tail_global has shorter distance already
// const IndexType &L_label = L[label_global_id];
// _mm_prefetch(&L_label.bp_dist[0], _MM_HINT_T0);
// _mm_prefetch(&L_label.bp_sets[0][0], _MM_HINT_T0);
const BPLabelType &L_label = bp_labels_table[label_root_id];
bool no_need_add = false;
for (VertexID i = 0; i < BITPARALLEL_SIZE; ++i) {
VertexID td = L_label.bp_dist[i] + L_tail.bp_dist[i];
if (td - 2 <= iter) {
td +=
(L_label.bp_sets[i][0] & L_tail.bp_sets[i][0]) ? -2 :
((L_label.bp_sets[i][0] & L_tail.bp_sets[i][1]) |
(L_label.bp_sets[i][1] & L_tail.bp_sets[i][0]))
? -1 : 0;
if (td <= iter) {
no_need_add = true;
break;
}
}
}
if (no_need_add) {
continue;
}
// if (SI_v_tail.is_candidate[label_root_id]) {
// continue;
// }
// SI_v_tail.is_candidate[label_root_id] = 1;
// SI_v_tail.candidates_que[SI_v_tail.end_candidates_que++] = label_root_id;
if (!SI_v_tail.is_candidate[label_root_id]) {
if (CAS(SI_v_tail.is_candidate.data() + label_root_id, static_cast<uint8_t>(0), static_cast<uint8_t>(1))) {
PADO::TS_enqueue(SI_v_tail.candidates_que, SI_v_tail.end_candidates_que, label_root_id);
}
}
// Add into got_candidates queue
// if (!got_candidates[v_tail_local]) {
// // If v_tail_global is not in got_candidates_queue, add it in (prevent duplicate)
// got_candidates[v_tail_local] = 1;
// got_candidates_queue[end_got_candidates_queue++] = v_tail_local;
// }
if (!got_candidates[v_tail_local]) {
if (CAS(got_candidates.data() + v_tail_local, static_cast<uint8_t>(0), static_cast<uint8_t>(1))) {
tmp_got_candidates_queue[offset_tmp_queue + size_tmp_got_candidates_queue++] = v_tail_local;
}
}
}
}
// {
// assert(iter >= iter);
// }
}
// Function: pushes v_head's labels to v_head's every (master) neighbor
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
local_push_labels_seq(
VertexID v_head_global,
EdgeID start_index,
EdgeID bound_index,
VertexID roots_start,
const std::vector<VertexID> &labels_buffer,
const DistGraph &G,
std::vector<ShortIndex> &short_index,
std::vector<VertexID> &got_candidates_queue,
VertexID &end_got_candidates_queue,
std::vector<uint8_t> &got_candidates,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated,
const std::vector<BPLabelType> &bp_labels_table,
const std::vector<uint8_t> &used_bp_roots,
const UnweightedDist iter)
{
// Traverse v_head's every neighbor v_tail
EdgeID e_i_start = G.vertices_idx[v_head_global];
EdgeID e_i_bound = e_i_start + G.local_out_degrees[v_head_global];
for (EdgeID e_i = e_i_start; e_i < e_i_bound; ++e_i) {
VertexID v_tail_global = G.out_edges[e_i];
if (used_bp_roots[v_tail_global]) {
continue;
}
if (v_tail_global < roots_start) { // v_tail_global has higher rank than any roots, then no roots can push new labels to it.
return;
}
// Traverse v_head's last inserted labels
for (VertexID l_i = start_index; l_i < bound_index; ++l_i) {
VertexID label_root_id = labels_buffer[l_i];
VertexID label_global_id = label_root_id + roots_start;
if (v_tail_global <= label_global_id) {
// v_tail_global has higher rank than the label
continue;
}
VertexID v_tail_local = G.get_local_vertex_id(v_tail_global);
const IndexType &L_tail = L[v_tail_local];
ShortIndex &SI_v_tail = short_index[v_tail_local];
if (SI_v_tail.indicator[label_root_id]) {
// The label is already selected before
continue;
}
// Record label_root_id as once selected by v_tail_global
SI_v_tail.indicator[label_root_id] = 1;
// SI_v_tail.indicator.set(label_root_id);
// Add into once_candidated_queue
if (!once_candidated[v_tail_local]) {
// If v_tail_global is not in the once_candidated_queue yet, add it in
once_candidated[v_tail_local] = 1;
once_candidated_queue[end_once_candidated_queue++] = v_tail_local;
}
// Bit Parallel Checking: if label_global_id to v_tail_global has shorter distance already
// const IndexType &L_label = L[label_global_id];
// _mm_prefetch(&L_label.bp_dist[0], _MM_HINT_T0);
// _mm_prefetch(&L_label.bp_sets[0][0], _MM_HINT_T0);
const BPLabelType &L_label = bp_labels_table[label_root_id];
bool no_need_add = false;
for (VertexID i = 0; i < BITPARALLEL_SIZE; ++i) {
VertexID td = L_label.bp_dist[i] + L_tail.bp_dist[i];
if (td - 2 <= iter) {
td +=
(L_label.bp_sets[i][0] & L_tail.bp_sets[i][0]) ? -2 :
((L_label.bp_sets[i][0] & L_tail.bp_sets[i][1]) |
(L_label.bp_sets[i][1] & L_tail.bp_sets[i][0]))
? -1 : 0;
if (td <= iter) {
no_need_add = true;
break;
}
}
}
if (no_need_add) {
continue;
}
if (SI_v_tail.is_candidate[label_root_id]) {
continue;
}
SI_v_tail.is_candidate[label_root_id] = 1;
SI_v_tail.candidates_que[SI_v_tail.end_candidates_que++] = label_root_id;
if (!got_candidates[v_tail_local]) {
// If v_tail_global is not in got_candidates_queue, add it in (prevent duplicate)
got_candidates[v_tail_local] = 1;
got_candidates_queue[end_got_candidates_queue++] = v_tail_local;
}
}
}
// {
// assert(iter >= iter);
// }
}
//// Function: pushes v_head's labels to v_head's every (master) neighbor
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::
//local_push_labels(
// VertexID v_head_local,
// VertexID roots_start,
// const DistGraph &G,
// std::vector<ShortIndex> &short_index,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
// std::vector<bool> &got_candidates,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
// std::vector<bool> &once_candidated,
// const std::vector<BPLabelType> &bp_labels_table,
// const std::vector<uint8_t> &used_bp_roots,
// UnweightedDist iter)
//{
// // The data structure of a message
//// std::vector< LabelUnitType > buffer_recv;
// const IndexType &Lv = L[v_head_local];
// // These 2 index are used for traversing v_head's last inserted labels
// VertexID l_i_start = Lv.distances.rbegin() -> start_index;
// VertexID l_i_bound = l_i_start + Lv.distances.rbegin() -> size;
// // Traverse v_head's every neighbor v_tail
// VertexID v_head_global = G.get_global_vertex_id(v_head_local);
// EdgeID e_i_start = G.vertices_idx[v_head_global];
// EdgeID e_i_bound = e_i_start + G.local_out_degrees[v_head_global];
// for (EdgeID e_i = e_i_start; e_i < e_i_bound; ++e_i) {
// VertexID v_tail_global = G.out_edges[e_i];
// if (used_bp_roots[v_tail_global]) {
// continue;
// }
// if (v_tail_global < roots_start) { // v_tail_global has higher rank than any roots, then no roots can push new labels to it.
// return;
// }
//
// // Traverse v_head's last inserted labels
// for (VertexID l_i = l_i_start; l_i < l_i_bound; ++l_i) {
// VertexID label_root_id = Lv.vertices[l_i];
// VertexID label_global_id = label_root_id + roots_start;
// if (v_tail_global <= label_global_id) {
// // v_tail_global has higher rank than the label
// continue;
// }
// VertexID v_tail_local = G.get_local_vertex_id(v_tail_global);
// const IndexType &L_tail = L[v_tail_local];
// ShortIndex &SI_v_tail = short_index[v_tail_local];
// if (SI_v_tail.indicator[label_root_id]) {
// // The label is already selected before
// continue;
// }
// // Record label_root_id as once selected by v_tail_global
// SI_v_tail.indicator.set(label_root_id);
// // Add into once_candidated_queue
//
// if (!once_candidated[v_tail_local]) {
// // If v_tail_global is not in the once_candidated_queue yet, add it in
// once_candidated[v_tail_local] = true;
// once_candidated_queue[end_once_candidated_queue++] = v_tail_local;
// }
//
// // Bit Parallel Checking: if label_global_id to v_tail_global has shorter distance already
// // ++total_check_count;
//// const IndexType &L_label = L[label_global_id];
//// _mm_prefetch(&L_label.bp_dist[0], _MM_HINT_T0);
//// _mm_prefetch(&L_label.bp_sets[0][0], _MM_HINT_T0);
//// bp_checking_ins_count.measure_start();
// const BPLabelType &L_label = bp_labels_table[label_root_id];
// bool no_need_add = false;
// for (VertexID i = 0; i < BITPARALLEL_SIZE; ++i) {
// VertexID td = L_label.bp_dist[i] + L_tail.bp_dist[i];
// if (td - 2 <= iter) {
// td +=
// (L_label.bp_sets[i][0] & L_tail.bp_sets[i][0]) ? -2 :
// ((L_label.bp_sets[i][0] & L_tail.bp_sets[i][1]) |
// (L_label.bp_sets[i][1] & L_tail.bp_sets[i][0]))
// ? -1 : 0;
// if (td <= iter) {
// no_need_add = true;
//// ++bp_hit_count;
// break;
// }
// }
// }
// if (no_need_add) {
//// bp_checking_ins_count.measure_stop();
// continue;
// }
//// bp_checking_ins_count.measure_stop();
// if (SI_v_tail.is_candidate[label_root_id]) {
// continue;
// }
// SI_v_tail.is_candidate[label_root_id] = true;
// SI_v_tail.candidates_que[SI_v_tail.end_candidates_que++] = label_root_id;
//
// if (!got_candidates[v_tail_local]) {
// // If v_tail_global is not in got_candidates_queue, add it in (prevent duplicate)
// got_candidates[v_tail_local] = true;
// got_candidates_queue[end_got_candidates_queue++] = v_tail_local;
// }
// }
// }
//
// {
// assert(iter >= iter);
// }
//}
//// DEPRECATED Function: in the scatter phase, synchronize local masters to mirrors on other hosts
//// Has some mysterious problem: when I call this function, some hosts will receive wrong messages; when I copy all
//// code of this function into the caller, all messages become right.
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::
//sync_masters_2_mirrors(
// const DistGraph &G,
// const std::vector<VertexID> &active_queue,
// VertexID end_active_queue,
// std::vector< std::pair<VertexID, VertexID> > &buffer_send,
// std::vector<MPI_Request> &requests_send
//)
//{
//// std::vector< std::pair<VertexID, VertexID> > buffer_send;
// // pair.first: Owener vertex ID of the label
// // pair.first: label vertex ID of the label
// // Prepare masters' newly added labels for sending
// for (VertexID i_q = 0; i_q < end_active_queue; ++i_q) {
// VertexID v_head_local = active_queue[i_q];
// VertexID v_head_global = G.get_global_vertex_id(v_head_local);
// const IndexType &Lv = L[v_head_local];
// // These 2 index are used for traversing v_head's last inserted labels
// VertexID l_i_start = Lv.distances.rbegin()->start_index;
// VertexID l_i_bound = l_i_start + Lv.distances.rbegin()->size;
// for (VertexID l_i = l_i_start; l_i < l_i_bound; ++l_i) {
// VertexID label_root_id = Lv.vertices[l_i];
// buffer_send.emplace_back(v_head_global, label_root_id);
//// {//test
//// if (1 == host_id) {
//// printf("@%u host_id: %u v_head_global: %u\n", __LINE__, host_id, v_head_global);//
//// }
//// }
// }
// }
// {
// if (!buffer_send.empty()) {
// printf("@%u host_id: %u sync_masters_2_mirrors: buffer_send.size: %lu buffer_send[0]:(%u %u)\n", __LINE__, host_id, buffer_send.size(), buffer_send[0].first, buffer_send[0].second);
// }
// assert(!requests_send.empty());
// }
//
// // Send messages
// for (int loc = 0; loc < num_hosts - 1; ++loc) {
// int dest_host_id = G.buffer_send_list_loc_2_master_host_id(loc);
// MPI_Isend(buffer_send.data(),
// MPI_Instance::get_sending_size(buffer_send),
// MPI_CHAR,
// dest_host_id,
// SENDING_MASTERS_TO_MIRRORS,
// MPI_COMM_WORLD,
// &requests_send[loc]);
// {
// if (!buffer_send.empty()) {
// printf("@%u host_id: %u dest_host_id: %u buffer_send.size: %lu buffer_send[0]:(%u %u)\n", __LINE__, host_id, dest_host_id, buffer_send.size(), buffer_send[0].first, buffer_send[0].second);
// }
// }
// }
//}
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
schedule_label_inserting_para(
const DistGraph &G,
const VertexID roots_start,
const VertexID roots_size,
std::vector<ShortIndex> &short_index,
const std::vector< std::vector<UnweightedDist> > &dist_table,
const std::vector<VertexID> &got_candidates_queue,
const VertexID start_got_candidates_queue,
const VertexID size_got_candidates_queue,
std::vector<uint8_t> &got_candidates,
std::vector<VertexID> &active_queue,
VertexID &end_active_queue,
std::vector<uint8_t> &is_active,
std::vector< std::pair<VertexID, VertexID> > &buffer_send,
const VertexID iter)
{
const VertexID bound_got_candidates_queue = start_got_candidates_queue + size_got_candidates_queue;
std::vector<VertexID> offsets_tmp_active_queue;
std::vector<VertexID> tmp_active_queue;
std::vector<VertexID> sizes_tmp_active_queue;
std::vector<EdgeID> offsets_tmp_buffer_send;
std::vector< std::pair<VertexID, VertexID> > tmp_buffer_send;
std::vector<EdgeID> sizes_tmp_buffer_send;
EdgeID total_send_labels;
try {
offsets_tmp_active_queue.resize(size_got_candidates_queue);
#pragma omp parallel for
for (VertexID i_q = 0; i_q < size_got_candidates_queue; ++i_q) {
offsets_tmp_active_queue[i_q] = i_q;
}
tmp_active_queue.resize(size_got_candidates_queue);
sizes_tmp_active_queue.resize(size_got_candidates_queue,
0); // Size will only be 0 or 1, but it will become offsets eventually.
// Prepare for parallel buffer_send
// std::vector<EdgeID> offsets_tmp_buffer_send(size_got_candidates_queue);
offsets_tmp_buffer_send.resize(size_got_candidates_queue);
#pragma omp parallel for
for (VertexID i_q = start_got_candidates_queue; i_q < bound_got_candidates_queue; ++i_q) {
VertexID v_id_local = got_candidates_queue[i_q];
VertexID v_global_id = G.get_global_vertex_id(v_id_local);
VertexID tmp_i_q = i_q - start_got_candidates_queue;
if (v_global_id >= roots_start && v_global_id < roots_start + roots_size) {
// If v_global_id is root, its new labels should be put into buffer_send
offsets_tmp_buffer_send[tmp_i_q] = short_index[v_id_local].end_candidates_que;
} else {
offsets_tmp_buffer_send[tmp_i_q] = 0;
}
}
total_send_labels = PADO::prefix_sum_for_offsets(offsets_tmp_buffer_send);
tmp_buffer_send.resize(total_send_labels);
sizes_tmp_buffer_send.resize(size_got_candidates_queue, 0);
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("L%u_tmp_buffer_send: bad_alloc "
"host_id: %d "
"iter: %u "
"size_got_candidates_queue: %u "
"total_send_labels: %u "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
__LINE__,
host_id,
iter,
size_got_candidates_queue,
total_send_labels,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
#pragma omp parallel for
for (VertexID i_queue = start_got_candidates_queue; i_queue < bound_got_candidates_queue; ++i_queue) {
VertexID v_id_local = got_candidates_queue[i_queue];
VertexID inserted_count = 0; //recording number of v_id's truly inserted candidates
got_candidates[v_id_local] = 0; // reset got_candidates
// Traverse v_id's all candidates
VertexID tmp_i_queue = i_queue - start_got_candidates_queue;
VertexID bound_cand_i = short_index[v_id_local].end_candidates_que;
for (VertexID cand_i = 0; cand_i < bound_cand_i; ++cand_i) {
VertexID cand_root_id = short_index[v_id_local].candidates_que[cand_i];
short_index[v_id_local].is_candidate[cand_root_id] = 0;
// Only insert cand_root_id into v_id's label if its distance to v_id is shorter than existing distance
if (distance_query(
cand_root_id,
v_id_local,
roots_start,
// L,
dist_table,
iter)) {
if (!is_active[v_id_local]) {
is_active[v_id_local] = 1;
// active_queue[end_active_queue++] = v_id_local;
tmp_active_queue[tmp_i_queue + sizes_tmp_active_queue[tmp_i_queue]++] = v_id_local;
}
++inserted_count;
// The candidate cand_root_id needs to be added into v_id's label
insert_label_only_para(
cand_root_id,
v_id_local,
roots_start,
roots_size,
G,
tmp_buffer_send,
sizes_tmp_buffer_send[tmp_i_queue],
offsets_tmp_buffer_send[tmp_i_queue]);
// buffer_send);
}
}
short_index[v_id_local].end_candidates_que = 0;
if (0 != inserted_count) {
// Update other arrays in L[v_id] if new labels were inserted in this iteration
update_label_indices(
v_id_local,
inserted_count,
// L,
// short_index,
// b_id,
iter);
}
}
{// Collect elements from tmp_active_queue to active_queue
VertexID total_new = PADO::prefix_sum_for_offsets(sizes_tmp_active_queue);
PADO::collect_into_queue(
tmp_active_queue,
offsets_tmp_active_queue,
sizes_tmp_active_queue,
total_new,
active_queue,
end_active_queue);
}
{// Collect elements from tmp_buffer_send to buffer_send
EdgeID old_size_buffer_send = buffer_send.size();
EdgeID total_new = PADO::prefix_sum_for_offsets(sizes_tmp_buffer_send);
try {
buffer_send.resize(total_new + old_size_buffer_send);
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("L%u_buffer_send: bad_alloc "
"iter: %u "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
__LINE__,
iter,
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
// EdgeID zero_size = 0;
PADO::collect_into_queue(
tmp_buffer_send,
offsets_tmp_buffer_send,
sizes_tmp_buffer_send,
total_new,
buffer_send,
old_size_buffer_send);
// zero_size);
}
}
// Function for distance query;
// traverse vertex v_id's labels;
// return false if shorter distance exists already, return true if the cand_root_id can be added into v_id's label.
template <VertexID BATCH_SIZE>
inline bool DistBVCPLL<BATCH_SIZE>::
distance_query(
VertexID cand_root_id,
VertexID v_id_local,
VertexID roots_start,
// const std::vector<IndexType> &L,
const std::vector< std::vector<UnweightedDist> > &dist_table,
UnweightedDist iter)
{
VertexID cand_real_id = cand_root_id + roots_start;
const IndexType &Lv = L[v_id_local];
// Traverse v_id's all existing labels
// VertexID b_i_bound = Lv.batches.size();
// _mm_prefetch(&Lv.batches[0], _MM_HINT_T0);
_mm_prefetch(&Lv.distances[0], _MM_HINT_T0);
_mm_prefetch(&Lv.vertices[0], _MM_HINT_T0);
//_mm_prefetch(&dist_table[cand_root_id][0], _MM_HINT_T0);
// for (VertexID b_i = 0; b_i < b_i_bound; ++b_i) {
// VertexID id_offset = Lv.batches[b_i].batch_id * BATCH_SIZE;
// VertexID dist_start_index = Lv.batches[b_i].start_index;
// VertexID dist_bound_index = dist_start_index + Lv.batches[b_i].size;
// Traverse dist_table
// for (VertexID dist_i = dist_start_index; dist_i < dist_bound_index; ++dist_i) {
VertexID dist_bound_index = Lv.distances.size();
for (VertexID dist_i = 0; dist_i < dist_bound_index; ++dist_i) {
UnweightedDist dist = Lv.distances[dist_i].dist;
// Cannot use this, because no batch_id any more, so distances are not all in order among batches.
// if (dist >= iter) { // In a batch, the labels' distances are increasingly ordered.
// // If the half path distance is already greater than their targeted distance, jump to next batch
// break;
// }
VertexID v_start_index = Lv.distances[dist_i].start_index;
VertexID v_bound_index = v_start_index + Lv.distances[dist_i].size;
// _mm_prefetch(&dist_table[cand_root_id][0], _MM_HINT_T0);
_mm_prefetch(reinterpret_cast<const char *>(dist_table[cand_root_id].data()), _MM_HINT_T0);
for (VertexID v_i = v_start_index; v_i < v_bound_index; ++v_i) {
// VertexID v = Lv.vertices[v_i] + id_offset; // v is a label hub of v_id
VertexID v = Lv.vertices[v_i]; // v is a label hub of v_id
if (v >= cand_real_id) {
// Vertex cand_real_id cannot have labels whose ranks are lower than it,
// in which case dist_table[cand_root_id][v] does not exist.
continue;
}
VertexID d_tmp = dist + dist_table[cand_root_id][v];
if (d_tmp <= iter) {
return false;
}
}
}
// }
return true;
}
//// Sequential version
// Function inserts candidate cand_root_id into vertex v_id's labels;
// update the distance buffer dist_table;
// but it only update the v_id's labels' vertices array;
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
insert_label_only_seq(
VertexID cand_root_id,
VertexID v_id_local,
VertexID roots_start,
VertexID roots_size,
const DistGraph &G,
// std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::pair<VertexID, VertexID> > &buffer_send)
// UnweightedDist iter)
{
try {
VertexID cand_real_id = cand_root_id + roots_start;
L[v_id_local].vertices.push_back(cand_real_id);
// L[v_id_local].vertices.push_back(cand_root_id);
// Update the distance buffer if v_id is a root
VertexID v_id_global = G.get_global_vertex_id(v_id_local);
VertexID v_root_id = v_id_global - roots_start;
if (v_id_global >= roots_start && v_root_id < roots_size) {
// VertexID cand_real_id = cand_root_id + roots_start;
// dist_table[v_root_id][cand_real_id] = iter;
// Put the update into the buffer_send for later sending
buffer_send.emplace_back(v_root_id, cand_real_id);
}
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("insert_label_only_seq: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
}
//// Parallel Version
// Function inserts candidate cand_root_id into vertex v_id's labels;
// update the distance buffer dist_table;
// but it only update the v_id's labels' vertices array;
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
insert_label_only_para(
VertexID cand_root_id,
VertexID v_id_local,
VertexID roots_start,
VertexID roots_size,
const DistGraph &G,
// std::vector< std::pair<VertexID, VertexID> > &buffer_send)
std::vector< std::pair<VertexID, VertexID> > &tmp_buffer_send,
EdgeID &size_tmp_buffer_send,
const EdgeID offset_tmp_buffer_send)
{
try {
VertexID cand_real_id = cand_root_id + roots_start;
L[v_id_local].vertices.push_back(cand_real_id);
// L[v_id_local].vertices.push_back(cand_root_id);
// Update the distance buffer if v_id is a root
VertexID v_id_global = G.get_global_vertex_id(v_id_local);
VertexID v_root_id = v_id_global - roots_start;
if (v_id_global >= roots_start && v_root_id < roots_size) {
// VertexID cand_real_id = cand_root_id + roots_start;
// Put the update into the buffer_send for later sending
tmp_buffer_send[offset_tmp_buffer_send + size_tmp_buffer_send++] = std::make_pair(v_root_id, cand_real_id);
}
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("insert_label_only_para: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
}
// Function updates those index arrays in v_id's label only if v_id has been inserted new labels
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
update_label_indices(
const VertexID v_id_local,
const VertexID inserted_count,
// std::vector<IndexType> &L,
// std::vector<ShortIndex> &short_index,
// VertexID b_id,
const UnweightedDist iter)
{
try {
IndexType &Lv = L[v_id_local];
// // indicator[BATCH_SIZE + 1] is true, means v got some labels already in this batch
// if (short_index[v_id_local].indicator[BATCH_SIZE]) {
// // Increase the batches' last element's size because a new distance element need to be added
// ++(Lv.batches.rbegin() -> size);
// } else {
// short_index[v_id_local].indicator[BATCH_SIZE] = 1;
//// short_index[v_id_local].indicator.set(BATCH_SIZE);
// // Insert a new Batch with batch_id, start_index, and size because a new distance element need to be added
// Lv.batches.emplace_back(
// b_id, // batch id
// Lv.distances.size(), // start index
// 1); // size
// }
// Insert a new distance element with start_index, size, and dist
Lv.distances.emplace_back(
Lv.vertices.size() - inserted_count, // start index
inserted_count, // size
iter); // distance
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("update_label_indices: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
}
// Function to reset dist_table the distance buffer to INF
// Traverse every root's labels to reset its distance buffer elements to INF.
// In this way to reduce the cost of initialization of the next batch.
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
reset_at_end(
const DistGraph &G,
// VertexID roots_start,
// const std::vector<VertexID> &roots_master_local,
std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::vector<VertexID> > &recved_dist_table,
std::vector<BPLabelType> &bp_labels_table,
const std::vector<VertexID> &once_candidated_queue,
const VertexID end_once_candidated_queue)
{
// // Reset dist_table according to local masters' labels
// for (VertexID r_local_id : roots_master_local) {
// IndexType &Lr = L[r_local_id];
// VertexID r_root_id = G.get_global_vertex_id(r_local_id) - roots_start;
// VertexID b_i_bound = Lr.batches.size();
// _mm_prefetch(&Lr.batches[0], _MM_HINT_T0);
// _mm_prefetch(&Lr.distances[0], _MM_HINT_T0);
// _mm_prefetch(&Lr.vertices[0], _MM_HINT_T0);
// for (VertexID b_i = 0; b_i < b_i_bound; ++b_i) {
// VertexID id_offset = Lr.batches[b_i].batch_id * BATCH_SIZE;
// VertexID dist_start_index = Lr.batches[b_i].start_index;
// VertexID dist_bound_index = dist_start_index + Lr.batches[b_i].size;
// // Traverse dist_table
// for (VertexID dist_i = dist_start_index; dist_i < dist_bound_index; ++dist_i) {
// VertexID v_start_index = Lr.distances[dist_i].start_index;
// VertexID v_bound_index = v_start_index + Lr.distances[dist_i].size;
// for (VertexID v_i = v_start_index; v_i < v_bound_index; ++v_i) {
// dist_table[r_root_id][Lr.vertices[v_i] + id_offset] = MAX_UNWEIGHTED_DIST;
// }
// }
// }
// }
// Reset dist_table according to received masters' labels from other hosts
for (VertexID r_root_id = 0; r_root_id < BATCH_SIZE; ++r_root_id) {
for (VertexID cand_real_id : recved_dist_table[r_root_id]) {
dist_table[r_root_id][cand_real_id] = MAX_UNWEIGHTED_DIST;
}
recved_dist_table[r_root_id].clear();
}
// Reset bit-parallel labels table
for (VertexID r_root_id = 0; r_root_id < BATCH_SIZE; ++r_root_id) {
memset(bp_labels_table[r_root_id].bp_dist, 0, sizeof(bp_labels_table[r_root_id].bp_dist));
memset(bp_labels_table[r_root_id].bp_sets, 0, sizeof(bp_labels_table[r_root_id].bp_sets));
}
// Remove labels of local minimum set
for (VertexID v_i = 0; v_i < end_once_candidated_queue; ++v_i) {
VertexID v_local_id = once_candidated_queue[v_i];
if (!G.is_local_minimum[v_local_id]) {
continue;
}
L[v_local_id].clean_all_indices();
}
}
template <VertexID BATCH_SIZE>
inline void DistBVCPLL<BATCH_SIZE>::
batch_process(
const DistGraph &G,
// const VertexID b_id,
const VertexID roots_start, // start id of roots
const VertexID roots_size, // how many roots in the batch
const std::vector<uint8_t> &used_bp_roots,
std::vector<VertexID> &active_queue,
VertexID &end_active_queue,
std::vector<VertexID> &got_candidates_queue,
VertexID &end_got_candidates_queue,
std::vector<ShortIndex> &short_index,
std::vector< std::vector<UnweightedDist> > &dist_table,
std::vector< std::vector<VertexID> > &recved_dist_table,
std::vector<BPLabelType> &bp_labels_table,
std::vector<uint8_t> &got_candidates,
// std::vector<bool> &got_candidates,
std::vector<uint8_t> &is_active,
// std::vector<bool> &is_active,
std::vector<VertexID> &once_candidated_queue,
VertexID &end_once_candidated_queue,
std::vector<uint8_t> &once_candidated)
// std::vector<bool> &once_candidated)
{
// At the beginning of a batch, initialize the labels L and distance buffer dist_table;
// initializing_time -= WallTimer::get_time_mark();
// The Maximum of active vertices among hosts.
VertexID global_num_actives = initialization(G,
short_index,
dist_table,
recved_dist_table,
bp_labels_table,
active_queue,
end_active_queue,
once_candidated_queue,
end_once_candidated_queue,
once_candidated,
// b_id,
roots_start,
roots_size,
// roots_master_local,
used_bp_roots);
// initializing_time += WallTimer::get_time_mark();
UnweightedDist iter = 0; // The iterator, also the distance for current iteration
// {//test
// if (0 == host_id) {
// printf("host_id: %u initialization finished.\n", host_id);
// }
// }
while (global_num_actives) {
++iter;
//#ifdef DEBUG_MESSAGES_ON
// {//test
//// if (0 == host_id) {
// double memtotal = 0;
// double memfree = 0;
// PADO::Utils::system_memory(memtotal, memfree);
// printf("iter: %u "
// "host_id: %d "
// "global_num_actives: %u "
// "L.size(): %.2fGB "
// "memtotal: %.2fGB "
// "memfree: %.2fGB\n",
// iter,
// host_id,
// global_num_actives,
// get_index_size() * 1.0 / (1 << 30),
// memtotal / 1024,
// memfree / 1024);
//// }
// }
//#endif
// Traverse active vertices to push their labels as candidates
// Send masters' newly added labels to other hosts
try
{
// scatter_time -= WallTimer::get_time_mark();
// Divide the pushing into many-time runs.
const VertexID chunk_size = 1 << 12;
VertexID remainder = global_num_actives % chunk_size;
VertexID bound_global_i = global_num_actives - remainder;
// VertexID remainder = end_active_queue % chunk_size;
// VertexID bound_active_queue = end_active_queue - remainder;
VertexID local_size;
for (VertexID global_i = 0; global_i < bound_global_i; global_i += chunk_size) {
if (global_i < end_active_queue) {
local_size = end_active_queue - global_i;
} else {
local_size = 0;
}
schedule_label_pushing_para(
G,
roots_start,
used_bp_roots,
active_queue,
global_i,
chunk_size,
local_size,
got_candidates_queue,
end_got_candidates_queue,
short_index,
bp_labels_table,
got_candidates,
is_active,
once_candidated_queue,
end_once_candidated_queue,
once_candidated,
iter);
}
if (remainder) {
if (bound_global_i < end_active_queue) {
local_size = end_active_queue - bound_global_i;
} else {
local_size = 0;
}
schedule_label_pushing_para(
G,
roots_start,
used_bp_roots,
active_queue,
bound_global_i,
remainder,
local_size,
got_candidates_queue,
end_got_candidates_queue,
short_index,
bp_labels_table,
got_candidates,
is_active,
once_candidated_queue,
end_once_candidated_queue,
once_candidated,
iter);
}
//
// schedule_label_pushing_para(
// G,
// roots_start,
// used_bp_roots,
// active_queue,
// 0,
// end_active_queue,
// got_candidates_queue,
// end_got_candidates_queue,
// short_index,
// bp_labels_table,
// got_candidates,
// is_active,
// once_candidated_queue,
// end_once_candidated_queue,
// once_candidated,
// iter);
end_active_queue = 0;
// scatter_time += WallTimer::get_time_mark();
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("pushing: bad_alloc "
"iter: %u "
"host_id: %d "
"global_num_actives: %u "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
iter,
host_id,
global_num_actives,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
// Traverse vertices in the got_candidates_queue to insert labels
{
// gather_time -= WallTimer::get_time_mark();
std::vector< std::pair<VertexID, VertexID> > buffer_send; // For sync elements in the dist_table
// pair.first: root id
// pair.second: label (global) id of the root
// if (true) {
if (end_got_candidates_queue >= THRESHOLD_PARALLEL) {
const VertexID chunk_size = 1 << 12;
VertexID remainder = end_got_candidates_queue % chunk_size;
VertexID bound_i_q = end_got_candidates_queue - remainder;
for (VertexID i_q = 0; i_q < bound_i_q; i_q += chunk_size) {
schedule_label_inserting_para(
G,
roots_start,
roots_size,
short_index,
dist_table,
got_candidates_queue,
i_q,
chunk_size,
got_candidates,
active_queue,
end_active_queue,
is_active,
buffer_send,
iter);
}
if (remainder) {
schedule_label_inserting_para(
G,
roots_start,
roots_size,
short_index,
dist_table,
got_candidates_queue,
bound_i_q,
remainder,
got_candidates,
active_queue,
end_active_queue,
is_active,
buffer_send,
iter);
}
////// Backup
// // Prepare for parallel active_queue
// // Don't need offsets_tmp_active_queue here, because the index i_queue is the offset already.
// // Actually we still need offsets_tmp_active_queue, because collect_into_queue() needs it.
// std::vector<VertexID> offsets_tmp_active_queue;
// std::vector<VertexID> tmp_active_queue;
// std::vector<VertexID> sizes_tmp_active_queue;
// std::vector<EdgeID> offsets_tmp_buffer_send;
// std::vector< std::pair<VertexID, VertexID> > tmp_buffer_send;
// std::vector<EdgeID> sizes_tmp_buffer_send;
// EdgeID total_send_labels;
//
// try {
// offsets_tmp_active_queue.resize(end_got_candidates_queue);
//#pragma omp parallel for
// for (VertexID i_q = 0; i_q < end_got_candidates_queue; ++i_q) {
// offsets_tmp_active_queue[i_q] = i_q;
// }
// tmp_active_queue.resize(end_got_candidates_queue);
// sizes_tmp_active_queue.resize(end_got_candidates_queue,
// 0); // Size will only be 0 or 1, but it will become offsets eventually.
//
// // Prepare for parallel buffer_send
//// std::vector<EdgeID> offsets_tmp_buffer_send(end_got_candidates_queue);
// offsets_tmp_buffer_send.resize(end_got_candidates_queue);
//#pragma omp parallel for
// for (VertexID i_q = 0; i_q < end_got_candidates_queue; ++i_q) {
// VertexID v_id_local = got_candidates_queue[i_q];
// VertexID v_global_id = G.get_global_vertex_id(v_id_local);
// if (v_global_id >= roots_start && v_global_id < roots_start + roots_size) {
// // If v_global_id is root, its new labels should be put into buffer_send
// offsets_tmp_buffer_send[i_q] = short_index[v_id_local].end_candidates_que;
// } else {
// offsets_tmp_buffer_send[i_q] = 0;
// }
// }
// total_send_labels = PADO::prefix_sum_for_offsets(offsets_tmp_buffer_send);
// tmp_buffer_send.resize(total_send_labels);
// sizes_tmp_buffer_send.resize(end_got_candidates_queue, 0);
// }
// catch (const std::bad_alloc &) {
// double memtotal = 0;
// double memfree = 0;
// PADO::Utils::system_memory(memtotal, memfree);
// printf("L%u_tmp_buffer_send: bad_alloc "
// "host_id: %d "
// "iter: %u "
// "end_got_candidates_queue: %u "
// "total_send_labels: %u "
// "L.size(): %.2fGB "
// "memtotal: %.2fGB "
// "memfree: %.2fGB\n",
// __LINE__,
// host_id,
// iter,
// end_got_candidates_queue,
// total_send_labels,
// get_index_size() * 1.0 / (1 << 30),
// memtotal / 1024,
// memfree / 1024);
// exit(1);
// }
//
//#pragma omp parallel for
// for (VertexID i_queue = 0; i_queue < end_got_candidates_queue; ++i_queue) {
// VertexID v_id_local = got_candidates_queue[i_queue];
// VertexID inserted_count = 0; //recording number of v_id's truly inserted candidates
// got_candidates[v_id_local] = 0; // reset got_candidates
// // Traverse v_id's all candidates
// VertexID bound_cand_i = short_index[v_id_local].end_candidates_que;
// for (VertexID cand_i = 0; cand_i < bound_cand_i; ++cand_i) {
// VertexID cand_root_id = short_index[v_id_local].candidates_que[cand_i];
// short_index[v_id_local].is_candidate[cand_root_id] = 0;
// // Only insert cand_root_id into v_id's label if its distance to v_id is shorter than existing distance
// if (distance_query(
// cand_root_id,
// v_id_local,
// roots_start,
// // L,
// dist_table,
// iter)) {
// if (!is_active[v_id_local]) {
// is_active[v_id_local] = 1;
//// active_queue[end_active_queue++] = v_id_local;
// tmp_active_queue[i_queue + sizes_tmp_active_queue[i_queue]++] = v_id_local;
// }
// ++inserted_count;
// // The candidate cand_root_id needs to be added into v_id's label
// insert_label_only_para(
// cand_root_id,
// v_id_local,
// roots_start,
// roots_size,
// G,
// tmp_buffer_send,
// sizes_tmp_buffer_send[i_queue],
// offsets_tmp_buffer_send[i_queue]);
//// buffer_send);
// }
// }
// short_index[v_id_local].end_candidates_que = 0;
// if (0 != inserted_count) {
// // Update other arrays in L[v_id] if new labels were inserted in this iteration
// update_label_indices(
// v_id_local,
// inserted_count,
// // L,
//// short_index,
//// b_id,
// iter);
// }
// }
//
// {// Collect elements from tmp_active_queue to active_queue
// VertexID total_new = PADO::prefix_sum_for_offsets(sizes_tmp_active_queue);
// PADO::collect_into_queue(
// tmp_active_queue,
// offsets_tmp_active_queue,
// sizes_tmp_active_queue,
// total_new,
// active_queue,
// end_active_queue);
// }
// {// Collect elements from tmp_buffer_send to buffer_send
// EdgeID total_new = PADO::prefix_sum_for_offsets(sizes_tmp_buffer_send);
// try {
// buffer_send.resize(total_new);
// }
// catch (const std::bad_alloc &) {
// double memtotal = 0;
// double memfree = 0;
// PADO::Utils::system_memory(memtotal, memfree);
// printf("L%u_buffer_send: bad_alloc "
// "iter: %u "
// "host_id: %d "
// "L.size(): %.2fGB "
// "memtotal: %.2fGB "
// "memfree: %.2fGB\n",
// __LINE__,
// iter,
// host_id,
// get_index_size() * 1.0 / (1 << 30),
// memtotal / 1024,
// memfree / 1024);
// exit(1);
// }
// EdgeID zero_size = 0;
// PADO::collect_into_queue(
// tmp_buffer_send,
// offsets_tmp_buffer_send,
// sizes_tmp_buffer_send,
// total_new,
// buffer_send,
// zero_size);
// }
} else {
for (VertexID i_queue = 0; i_queue < end_got_candidates_queue; ++i_queue) {
VertexID v_id_local = got_candidates_queue[i_queue];
VertexID inserted_count = 0; //recording number of v_id's truly inserted candidates
got_candidates[v_id_local] = 0; // reset got_candidates
// Traverse v_id's all candidates
VertexID bound_cand_i = short_index[v_id_local].end_candidates_que;
for (VertexID cand_i = 0; cand_i < bound_cand_i; ++cand_i) {
VertexID cand_root_id = short_index[v_id_local].candidates_que[cand_i];
short_index[v_id_local].is_candidate[cand_root_id] = 0;
// Only insert cand_root_id into v_id's label if its distance to v_id is shorter than existing distance
if (distance_query(
cand_root_id,
v_id_local,
roots_start,
// L,
dist_table,
iter)) {
if (!is_active[v_id_local]) {
is_active[v_id_local] = 1;
active_queue[end_active_queue++] = v_id_local;
}
++inserted_count;
// The candidate cand_root_id needs to be added into v_id's label
insert_label_only_seq(
cand_root_id,
v_id_local,
roots_start,
roots_size,
G,
// dist_table,
buffer_send);
// iter);
}
}
short_index[v_id_local].end_candidates_que = 0;
if (0 != inserted_count) {
// Update other arrays in L[v_id] if new labels were inserted in this iteration
update_label_indices(
v_id_local,
inserted_count,
// L,
// short_index,
// b_id,
iter);
}
}
}
// {//test
// printf("host_id: %u gather: buffer_send.size(); %lu bytes: %lu\n", host_id, buffer_send.size(), MPI_Instance::get_sending_size(buffer_send));
// }
end_got_candidates_queue = 0; // Set the got_candidates_queue empty
// Sync the dist_table
for (int root = 0; root < num_hosts; ++root) {
std::vector<std::pair<VertexID, VertexID>> buffer_recv;
one_host_bcasts_buffer_to_buffer(root,
buffer_send,
buffer_recv);
if (buffer_recv.empty()) {
continue;
}
EdgeID size_buffer_recv = buffer_recv.size();
try {
if (size_buffer_recv >= THRESHOLD_PARALLEL) {
// Get label number for every root
std::vector<VertexID> sizes_recved_root_labels(roots_size, 0);
#pragma omp parallel for
for (EdgeID i_l = 0; i_l < size_buffer_recv; ++i_l) {
const std::pair<VertexID, VertexID> &e = buffer_recv[i_l];
VertexID root_id = e.first;
__atomic_add_fetch(sizes_recved_root_labels.data() + root_id, 1, __ATOMIC_SEQ_CST);
}
// Resize the recved_dist_table for every root
#pragma omp parallel for
for (VertexID root_id = 0; root_id < roots_size; ++root_id) {
VertexID old_size = recved_dist_table[root_id].size();
VertexID tmp_size = sizes_recved_root_labels[root_id];
if (tmp_size) {
recved_dist_table[root_id].resize(old_size + tmp_size);
sizes_recved_root_labels[root_id] = old_size; // sizes_recved_root_labels now records old_size
}
// If tmp_size == 0, root_id has no received labels.
// sizes_recved_root_labels[root_id] = old_size; // sizes_recved_root_labels now records old_size
}
// Recorde received labels in recved_dist_table
#pragma omp parallel for
for (EdgeID i_l = 0; i_l < size_buffer_recv; ++i_l) {
const std::pair<VertexID, VertexID> &e = buffer_recv[i_l];
VertexID root_id = e.first;
VertexID cand_real_id = e.second;
dist_table[root_id][cand_real_id] = iter;
PADO::TS_enqueue(recved_dist_table[root_id], sizes_recved_root_labels[root_id],
cand_real_id);
}
} else {
for (const std::pair<VertexID, VertexID> &e : buffer_recv) {
VertexID root_id = e.first;
VertexID cand_real_id = e.second;
dist_table[root_id][cand_real_id] = iter;
// Record the received element, for future reset
recved_dist_table[root_id].push_back(cand_real_id);
}
}
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("recved_dist_table: bad_alloc "
"host_id: %d "
"iter: %u "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
iter,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
}
// Sync the global_num_actives
MPI_Allreduce(&end_active_queue,
&global_num_actives,
1,
V_ID_Type,
MPI_MAX,
// MPI_SUM,
MPI_COMM_WORLD);
// gather_time += WallTimer::get_time_mark();
}
// {//test
// if (0 == host_id) {
// printf("iter: %u inserting labels finished.\n", iter);
// }
// }
}
// Reset the dist_table
// clearup_time -= WallTimer::get_time_mark();
reset_at_end(
G,
// roots_start,
// roots_master_local,
dist_table,
recved_dist_table,
bp_labels_table,
once_candidated_queue,
end_once_candidated_queue);
// clearup_time += WallTimer::get_time_mark();
// {//test
// if (0 == host_id) {
// printf("host_id: %u resetting finished.\n", host_id);
// }
// }
}
//// Sequential Version
//template <VertexID BATCH_SIZE>
//inline void DistBVCPLL<BATCH_SIZE>::
//batch_process(
// const DistGraph &G,
// VertexID b_id,
// VertexID roots_start, // start id of roots
// VertexID roots_size, // how many roots in the batch
// const std::vector<uint8_t> &used_bp_roots,
// std::vector<VertexID> &active_queue,
// VertexID &end_active_queue,
// std::vector<VertexID> &got_candidates_queue,
// VertexID &end_got_candidates_queue,
// std::vector<ShortIndex> &short_index,
// std::vector< std::vector<UnweightedDist> > &dist_table,
// std::vector< std::vector<VertexID> > &recved_dist_table,
// std::vector<BPLabelType> &bp_labels_table,
// std::vector<uint8_t> &got_candidates,
//// std::vector<bool> &got_candidates,
// std::vector<uint8_t> &is_active,
//// std::vector<bool> &is_active,
// std::vector<VertexID> &once_candidated_queue,
// VertexID &end_once_candidated_queue,
// std::vector<uint8_t> &once_candidated)
//// std::vector<bool> &once_candidated)
//{
// // At the beginning of a batch, initialize the labels L and distance buffer dist_table;
// initializing_time -= WallTimer::get_time_mark();
// VertexID global_num_actives = initialization(G,
// short_index,
// dist_table,
// recved_dist_table,
// bp_labels_table,
// active_queue,
// end_active_queue,
// once_candidated_queue,
// end_once_candidated_queue,
// once_candidated,
// b_id,
// roots_start,
// roots_size,
//// roots_master_local,
// used_bp_roots);
// initializing_time += WallTimer::get_time_mark();
// UnweightedDist iter = 0; // The iterator, also the distance for current iteration
//// {//test
//// printf("host_id: %u initialization finished.\n", host_id);
//// }
//
//
// while (global_num_actives) {
////#ifdef DEBUG_MESSAGES_ON
//// {//
//// if (0 == host_id) {
//// printf("iter: %u global_num_actives: %u\n", iter, global_num_actives);
//// }
//// }
////#endif
// ++iter;
// // Traverse active vertices to push their labels as candidates
// // Send masters' newly added labels to other hosts
// {
// scatter_time -= WallTimer::get_time_mark();
// std::vector<std::pair<VertexID, VertexID> > buffer_send_indices(end_active_queue);
// //.first: Vertex ID
// //.second: size of labels
// std::vector<VertexID> buffer_send_labels;
// // Prepare masters' newly added labels for sending
// for (VertexID i_q = 0; i_q < end_active_queue; ++i_q) {
// VertexID v_head_local = active_queue[i_q];
// is_active[v_head_local] = 0; // reset is_active
// VertexID v_head_global = G.get_global_vertex_id(v_head_local);
// const IndexType &Lv = L[v_head_local];
// // Prepare the buffer_send_indices
// buffer_send_indices[i_q] = std::make_pair(v_head_global, Lv.distances.rbegin()->size);
// // These 2 index are used for traversing v_head's last inserted labels
// VertexID l_i_start = Lv.distances.rbegin()->start_index;
// VertexID l_i_bound = l_i_start + Lv.distances.rbegin()->size;
// for (VertexID l_i = l_i_start; l_i < l_i_bound; ++l_i) {
// VertexID label_root_id = Lv.vertices[l_i];
// buffer_send_labels.push_back(label_root_id);
// }
// }
// end_active_queue = 0;
//
// for (int root = 0; root < num_hosts; ++root) {
// // Get the indices
// std::vector< std::pair<VertexID, VertexID> > indices_buffer;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send_indices,
// indices_buffer);
// if (indices_buffer.empty()) {
// continue;
// }
// // Get the labels
// std::vector<VertexID> labels_buffer;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send_labels,
// labels_buffer);
// // Push those labels
// EdgeID start_index = 0;
// for (const std::pair<VertexID, VertexID> e : indices_buffer) {
// VertexID v_head_global = e.first;
// EdgeID bound_index = start_index + e.second;
// if (G.local_out_degrees[v_head_global]) {
// local_push_labels(
// v_head_global,
// start_index,
// bound_index,
// roots_start,
// labels_buffer,
// G,
// short_index,
// got_candidates_queue,
// end_got_candidates_queue,
// got_candidates,
// once_candidated_queue,
// end_once_candidated_queue,
// once_candidated,
// bp_labels_table,
// used_bp_roots,
// iter);
// }
// start_index = bound_index;
// }
// }
// scatter_time += WallTimer::get_time_mark();
// }
//
// // Traverse vertices in the got_candidates_queue to insert labels
// {
// gather_time -= WallTimer::get_time_mark();
// std::vector< std::pair<VertexID, VertexID> > buffer_send; // For sync elements in the dist_table
// // pair.first: root id
// // pair.second: label (global) id of the root
// for (VertexID i_queue = 0; i_queue < end_got_candidates_queue; ++i_queue) {
// VertexID v_id_local = got_candidates_queue[i_queue];
// VertexID inserted_count = 0; //recording number of v_id's truly inserted candidates
// got_candidates[v_id_local] = 0; // reset got_candidates
// // Traverse v_id's all candidates
// VertexID bound_cand_i = short_index[v_id_local].end_candidates_que;
// for (VertexID cand_i = 0; cand_i < bound_cand_i; ++cand_i) {
// VertexID cand_root_id = short_index[v_id_local].candidates_que[cand_i];
// short_index[v_id_local].is_candidate[cand_root_id] = 0;
// // Only insert cand_root_id into v_id's label if its distance to v_id is shorter than existing distance
// if ( distance_query(
// cand_root_id,
// v_id_local,
// roots_start,
// // L,
// dist_table,
// iter) ) {
// if (!is_active[v_id_local]) {
// is_active[v_id_local] = 1;
// active_queue[end_active_queue++] = v_id_local;
// }
// ++inserted_count;
// // The candidate cand_root_id needs to be added into v_id's label
// insert_label_only(
// cand_root_id,
// v_id_local,
// roots_start,
// roots_size,
// G,
//// dist_table,
// buffer_send);
//// iter);
// }
// }
// short_index[v_id_local].end_candidates_que = 0;
// if (0 != inserted_count) {
// // Update other arrays in L[v_id] if new labels were inserted in this iteration
// update_label_indices(
// v_id_local,
// inserted_count,
// // L,
// short_index,
// b_id,
// iter);
// }
// }
//// {//test
//// printf("host_id: %u gather: buffer_send.size(); %lu bytes: %lu\n", host_id, buffer_send.size(), MPI_Instance::get_sending_size(buffer_send));
//// }
// end_got_candidates_queue = 0; // Set the got_candidates_queue empty
// // Sync the dist_table
// for (int root = 0; root < num_hosts; ++root) {
// std::vector<std::pair<VertexID, VertexID>> buffer_recv;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send,
// buffer_recv);
// if (buffer_recv.empty()) {
// continue;
// }
// for (const std::pair<VertexID, VertexID> &e : buffer_recv) {
// VertexID root_id = e.first;
// VertexID cand_real_id = e.second;
// dist_table[root_id][cand_real_id] = iter;
// // Record the received element, for future reset
// recved_dist_table[root_id].push_back(cand_real_id);
// }
// }
//
// // Sync the global_num_actives
// MPI_Allreduce(&end_active_queue,
// &global_num_actives,
// 1,
// V_ID_Type,
// MPI_SUM,
// MPI_COMM_WORLD);
// gather_time += WallTimer::get_time_mark();
// }
// }
//
// // Reset the dist_table
// clearup_time -= WallTimer::get_time_mark();
// reset_at_end(
//// G,
//// roots_start,
//// roots_master_local,
// dist_table,
// recved_dist_table,
// bp_labels_table);
// clearup_time += WallTimer::get_time_mark();
//}
//// Function: every host broadcasts its sending buffer, and does fun for every element it received in the unit buffer.
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//template <typename E_T, typename F>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::
//every_host_bcasts_buffer_and_proc(
// std::vector<E_T> &buffer_send,
// F &fun)
//{
// // Every host h_i broadcast to others
// for (int root = 0; root < num_hosts; ++root) {
// std::vector<E_T> buffer_recv;
// one_host_bcasts_buffer_to_buffer(root,
// buffer_send,
// buffer_recv);
// if (buffer_recv.empty()) {
// continue;
// }
//// uint64_t size_buffer_send = buffer_send.size();
//// // Sync the size_buffer_send.
//// message_time -= WallTimer::get_time_mark();
//// MPI_Bcast(&size_buffer_send,
//// 1,
//// MPI_UINT64_T,
//// root,
//// MPI_COMM_WORLD);
//// message_time += WallTimer::get_time_mark();
////// {// test
////// printf("host_id: %u h_i: %u bcast_buffer_send.size(): %lu\n", host_id, h_i, size_buffer_send);
////// }
//// if (!size_buffer_send) {
//// continue;
//// }
//// message_time -= WallTimer::get_time_mark();
//// std::vector<E_T> buffer_recv(size_buffer_send);
//// if (host_id == root) {
//// buffer_recv.assign(buffer_send.begin(), buffer_send.end());
//// }
//// uint64_t bytes_buffer_send = size_buffer_send * ETypeSize;
//// if (bytes_buffer_send < static_cast<size_t>(INT_MAX)) {
//// // Only need 1 broadcast
////
//// MPI_Bcast(buffer_recv.data(),
//// bytes_buffer_send,
//// MPI_CHAR,
//// root,
//// MPI_COMM_WORLD);
//// } else {
//// const uint32_t num_unit_buffers = ((bytes_buffer_send - 1) / static_cast<size_t>(INT_MAX)) + 1;
//// const uint64_t unit_buffer_size = ((size_buffer_send - 1) / num_unit_buffers) + 1;
//// size_t offset = 0;
//// for (uint64_t b_i = 0; b_i < num_unit_buffers; ++b_i) {
////// size_t offset = b_i * unit_buffer_size;
//// size_t size_unit_buffer = b_i == num_unit_buffers - 1
//// ? size_buffer_send - offset
//// : unit_buffer_size;
//// MPI_Bcast(buffer_recv.data() + offset,
//// size_unit_buffer * ETypeSize,
//// MPI_CHAR,
//// root,
//// MPI_COMM_WORLD);
//// offset += unit_buffer_size;
//// }
//// }
//// message_time += WallTimer::get_time_mark();
// for (const E_T &e : buffer_recv) {
// fun(e);
// }
// }
//}
//// Function: every host broadcasts its sending buffer, and does fun for every element it received in the unit buffer.
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//template <typename E_T, typename F>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::
//every_host_bcasts_buffer_and_proc(
// std::vector<E_T> &buffer_send,
// F &fun)
//{
// // Host processes locally.
// for (const E_T &e : buffer_send) {
// fun(e);
// }
//
// // Every host sends to others
// for (int src = 0; src < num_hosts; ++src) {
// if (host_id == src) {
// // Send from src
// message_time -= WallTimer::get_time_mark();
// for (int hop = 1; hop < num_hosts; ++hop) {
// int dst = hop_2_root_host_id(hop, host_id);
// MPI_Instance::send_buffer_2_dst(buffer_send,
// dst,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// }
// message_time += WallTimer::get_time_mark();
// } else {
// // Receive from src
// for (int hop = 1; hop < num_hosts; ++hop) {
// int dst = hop_2_root_host_id(hop, src);
// if (host_id == dst) {
// message_time -= WallTimer::get_time_mark();
// std::vector<E_T> buffer_recv;
// MPI_Instance::recv_buffer_from_src(buffer_recv,
// src,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// message_time += WallTimer::get_time_mark();
// // Process
// for (const E_T &e : buffer_recv) {
// fun(e);
// }
// }
// }
// }
// }
//}
//// Function: every host broadcasts its sending buffer, and does fun for every element it received in the unit buffer.
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//template <typename E_T, typename F>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::
//every_host_bcasts_buffer_and_proc(
// std::vector<E_T> &buffer_send,
// F &fun)
//{
// // Host processes locally.
// for (const E_T &e : buffer_send) {
// fun(e);
// }
// // Every host sends (num_hosts - 1) times
// for (int hop = 1; hop < num_hosts; ++hop) {
// int src = hop_2_me_host_id(-hop);
// int dst = hop_2_me_host_id(hop);
// if (src != dst) { // Normal case
// // When host_id is odd, first receive, then send.
// if (static_cast<uint32_t>(host_id) & 1U) {
// message_time -= WallTimer::get_time_mark();
// // Receive first.
// std::vector<E_T> buffer_recv;
// MPI_Instance::recv_buffer_from_src(buffer_recv,
// src,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// {//test
// printf("host_id: %u recved_from: %u\n", host_id, src);
// }
// // Send then.
// MPI_Instance::send_buffer_2_dst(buffer_send,
// dst,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// {//test
// printf("host_id: %u send_to: %u\n", host_id, dst);
// }
// message_time += WallTimer::get_time_mark();
// // Process
// if (buffer_recv.empty()) {
// continue;
// }
// for (const E_T &e : buffer_recv) {
// fun(e);
// }
// } else { // When host_id is even, first send, then receive.
// // Send first.
// message_time -= WallTimer::get_time_mark();
// MPI_Instance::send_buffer_2_dst(buffer_send,
// dst,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// {//test
// printf("host_id: %u send_to: %u\n", host_id, dst);
// }
// // Receive then.
// std::vector<E_T> buffer_recv;
// MPI_Instance::recv_buffer_from_src(buffer_recv,
// src,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// {//test
// printf("host_id: %u recved_from: %u\n", host_id, src);
// }
// message_time += WallTimer::get_time_mark();
// // Process
// if (buffer_recv.empty()) {
// continue;
// }
// for (const E_T &e : buffer_recv) {
// fun(e);
// }
// }
// } else { // If host_id is higher than dst, first send, then receive
// // This is a special case. It only happens when the num_hosts is even and hop equals to num_hosts/2.
// if (host_id < dst) {
// // Send
// message_time -= WallTimer::get_time_mark();
// MPI_Instance::send_buffer_2_dst(buffer_send,
// dst,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// // Receive
// std::vector<E_T> buffer_recv;
// MPI_Instance::recv_buffer_from_src(buffer_recv,
// src,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// message_time += WallTimer::get_time_mark();
// // Process
// if (buffer_recv.empty()) {
// continue;
// }
// for (const E_T &e : buffer_recv) {
// fun(e);
// }
// } else { // Otherwise, if host_id is lower than dst, first receive, then send
// // Receive
// message_time -= WallTimer::get_time_mark();
// std::vector<E_T> buffer_recv;
// MPI_Instance::recv_buffer_from_src(buffer_recv,
// src,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// // Send
// MPI_Instance::send_buffer_2_dst(buffer_send,
// dst,
// SENDING_BUFFER_SEND,
// SENDING_SIZE_BUFFER_SEND);
// message_time += WallTimer::get_time_mark();
// // Process
// if (buffer_recv.empty()) {
// continue;
// }
// for (const E_T &e : buffer_recv) {
// fun(e);
// }
// }
// }
// }
//}
//// DEPRECATED version Function: every host broadcasts its sending buffer, and does fun for every element it received in the unit buffer.
//template <VertexID BATCH_SIZE, VertexID BITPARALLEL_SIZE>
//template <typename E_T, typename F>
//inline void DistBVCPLL<BATCH_SIZE, BITPARALLEL_SIZE>::
//every_host_bcasts_buffer_and_proc(
// std::vector<E_T> &buffer_send,
// F &fun)
//{
// const uint32_t UNIT_BUFFER_SIZE = 16U << 20U;
// // Every host h_i broadcast to others
// for (int h_i = 0; h_i < num_hosts; ++h_i) {
// uint64_t size_buffer_send = buffer_send.size();
// // Sync the size_buffer_send.
// message_time -= WallTimer::get_time_mark();
// MPI_Bcast(&size_buffer_send,
// 1,
// MPI_UINT64_T,
// h_i,
// MPI_COMM_WORLD);
// message_time += WallTimer::get_time_mark();
//// {// test
//// printf("host_id: %u h_i: %u bcast_buffer_send.size(): %lu\n", host_id, h_i, size_buffer_send);
//// }
// if (!size_buffer_send) {
// continue;
// }
// uint32_t num_unit_buffers = (size_buffer_send + UNIT_BUFFER_SIZE - 1) / UNIT_BUFFER_SIZE;
//
// // Broadcast the buffer_send
// for (uint32_t b_i = 0; b_i < num_unit_buffers; ++b_i) {
// // Prepare the unit buffer
// message_time -= WallTimer::get_time_mark();
// size_t offset = b_i * UNIT_BUFFER_SIZE;
// size_t size_unit_buffer = b_i == num_unit_buffers - 1
// ? size_buffer_send - offset
// : UNIT_BUFFER_SIZE;
// std::vector<E_T> unit_buffer(size_unit_buffer);
// // Copy the messages from buffer_send to unit buffer.
// if (host_id == h_i) {
// unit_buffer.assign(buffer_send.begin() + offset, buffer_send.begin() + offset + size_unit_buffer);
// }
// // Broadcast the unit buffer
// MPI_Bcast(unit_buffer.data(),
// MPI_Instance::get_sending_size(unit_buffer),
// MPI_CHAR,
// h_i,
// MPI_COMM_WORLD);
// message_time += WallTimer::get_time_mark();
// // Process every element of unit_buffer
// for (const E_T &e : unit_buffer) {
// fun(e);
// }
// }
// }
//}
// Function: Host root broadcasts its sending buffer to a receiving buffer.
template <VertexID BATCH_SIZE>
template <typename E_T>
inline void DistBVCPLL<BATCH_SIZE>::
one_host_bcasts_buffer_to_buffer(
int root,
std::vector<E_T> &buffer_send,
std::vector<E_T> &buffer_recv)
{
const size_t ETypeSize = sizeof(E_T);
uint64_t size_buffer_send = buffer_send.size();
// Sync the size_buffer_send.
// message_time -= WallTimer::get_time_mark();
MPI_Bcast(&size_buffer_send,
1,
MPI_UINT64_T,
root,
MPI_COMM_WORLD);
// message_time += WallTimer::get_time_mark();
try {
buffer_recv.resize(size_buffer_send);
}
catch (const std::bad_alloc &) {
double memtotal = 0;
double memfree = 0;
PADO::Utils::system_memory(memtotal, memfree);
printf("one_host_bcasts_buffer_to_buffer: bad_alloc "
"host_id: %d "
"L.size(): %.2fGB "
"memtotal: %.2fGB "
"memfree: %.2fGB\n",
host_id,
get_index_size() * 1.0 / (1 << 30),
memtotal / 1024,
memfree / 1024);
exit(1);
}
if (!size_buffer_send) {
return;
}
// Broadcast the buffer_send
// message_time -= WallTimer::get_time_mark();
if (host_id == root) {
// buffer_recv.assign(buffer_send.begin(), buffer_send.end());
buffer_recv.swap(buffer_send);
}
uint64_t bytes_buffer_send = size_buffer_send * ETypeSize;
if (bytes_buffer_send <= static_cast<size_t>(INT_MAX)) {
// Only need 1 broadcast
MPI_Bcast(buffer_recv.data(),
bytes_buffer_send,
MPI_CHAR,
root,
MPI_COMM_WORLD);
} else {
const uint32_t num_unit_buffers = ((bytes_buffer_send - 1) / static_cast<size_t>(INT_MAX)) + 1;
const uint64_t unit_buffer_size = ((size_buffer_send - 1) / num_unit_buffers) + 1;
size_t offset = 0;
for (uint64_t b_i = 0; b_i < num_unit_buffers; ++b_i) {
size_t size_unit_buffer = b_i == num_unit_buffers - 1
? size_buffer_send - offset
: unit_buffer_size;
MPI_Bcast(buffer_recv.data() + offset,
size_unit_buffer * ETypeSize,
MPI_CHAR,
root,
MPI_COMM_WORLD);
offset += unit_buffer_size;
}
}
// message_time += WallTimer::get_time_mark();
}
}
#endif //PADO_DPADO_H
|
Sema.h | //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// 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/DeclarationName.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.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/TypeLoc.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/LangOptions.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/ScopeInfo.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/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <deque>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
class InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class AttributeList;
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 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 OMPDeclareReductionDecl;
class OMPDeclareSimdDecl;
class OMPClause;
struct OverloadCandidate;
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 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 CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
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;
/// 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;
}
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
///\brief Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///\brief Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
// We are about to link these. It is now safe to compute the linkage of
// the new decl. If the new decl has external linkage, we will
// link it with the hidden decl (which also has external linkage) and
// it will keep having external linkage. If it has internal linkage, we
// will not link it. Since it has no previous decls, it will remain
// with internal linkage.
return isVisible(Old) || New->isExternallyVisible();
}
bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
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;
/// \brief Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// \brief Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// \brief 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
/// \brief 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;
/// \brief Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
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;
Slot(llvm::StringRef StackSlotLabel,
ValueType Value,
SourceLocation PragmaLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation) {}
};
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) {}
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).
/// \brief 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;
// 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*"
/// \brief 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;
/// \brief 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;
/// \brief Store a list 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.
llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
/// \brief Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
///
/// This array is never empty. Clients should ignore the first
/// element, which is used to cache a single FunctionScopeInfo
/// that's used to parse every top-level function.
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<const NamedDecl*, 16> NamedDeclSetType;
/// \brief Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// \brief Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// \brief 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;
/// \brief 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;
/// \brief All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// \brief 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;
/// \brief All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// \brief 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>
DelayedExceptionSpecChecks;
/// \brief All the members seen during a class definition which were both
/// explicitly defaulted and had explicitly-specified exception
/// specifications, along with the function type containing their
/// user-specified exception specification. Those exception specifications
/// were overridden with the default specifications, but we still need to
/// check whether they are compatible with the default specification, and
/// we can't do that until the nesting set of class definitions is complete.
SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
DelayedDefaultedMemberExceptionSpecs;
typedef llvm::MapVector<const FunctionDecl *,
std::unique_ptr<LateParsedTemplate>>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// \brief 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;
}
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 {
/// \brief 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();
}
};
/// \brief RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC)
{
S.PushFunctionScope();
S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
}
~SynthesizedFunctionScope() {
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;
/// \brief 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;
/// \brief The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// \brief The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
/// standard library.
LazyDeclPtr StdAlignValT;
/// \brief The C++ "std::experimental" namespace, where the experimental parts
/// of the standard library resides.
NamespaceDecl *StdExperimentalNamespaceCache;
/// \brief The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// \brief Caches identifiers/selectors for NSFoundation APIs.
std::unique_ptr<NSAPI> NSAPIObj;
/// \brief The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// \brief The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// \brief Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// \brief Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// \brief The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// \brief The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// \brief Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// \brief The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// \brief The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// \brief The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// \brief The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// \brief The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// \brief id<NSCopying> type.
QualType QIDNSCopying;
/// \brief 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;
/// \brief Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum ExpressionEvaluationContext {
/// \brief 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,
/// \brief 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,
/// \brief 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,
/// \brief 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,
/// \brief 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,
/// \brief 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,
/// \brief 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
};
/// \brief Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// \brief The expression evaluation context.
ExpressionEvaluationContext Context;
/// \brief Whether the enclosing context needed a cleanup.
CleanupInfo ParentCleanup;
/// \brief Whether we are in a decltype expression.
bool IsDecltype;
/// \brief The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// \brief The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
/// \brief The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// \brief 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;
/// \brief The context information used to mangle lambda expressions
/// and block literals within this context.
///
/// This mangling information is allocated lazily, since most contexts
/// do not have lambda expressions or block literals.
std::unique_ptr<MangleNumberingContext> MangleNumbering;
/// \brief 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;
/// \brief 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;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
CleanupInfo ParentCleanup,
Decl *ManglingContextDecl,
bool IsDecltype)
: Context(Context), ParentCleanup(ParentCleanup),
IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
NumTypos(0),
ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
/// \brief Retrieve the mangling numbering context, used to consistently
/// number constructs like lambdas for mangling.
MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
bool isUnevaluated() const {
return Context == Unevaluated || Context == UnevaluatedAbstract ||
Context == UnevaluatedList;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// \brief Compute the mangling number context for a lambda expression or
/// block literal.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
/// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
/// associated with the context, if relevant.
MangleNumberingContext *getCurrentMangleNumberContext(
const DeclContext *DC,
Decl *&ManglingContextDecl);
/// 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 llvm::FastFoldingSetNode {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
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); }
};
/// \brief A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
/// \brief A cache of the flags available in enumerations with the flag_bits
/// attribute.
mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
/// \brief 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;
/// \brief The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// \brief 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;
/// 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;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef std::pair<CXXRecordDecl*, 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::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
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);
/// \brief 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), OldFPContractState(S.FPFeatures.fp_contract) {}
~FPContractStateRAII() {
S.FPFeatures.fp_contract = OldFPContractState;
}
private:
Sema& S;
bool OldFPContractState : 1;
};
void addImplicitTypedef(StringRef Name, QualType T);
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// \brief 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; }
///\brief 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;
/// \brief 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;
}
};
/// \brief Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// \brief Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// \brief Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// \brief 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;
/// \brief Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// \brief Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
void ActOnEndOfTranslationUnit();
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// \brief 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);
void
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
const BlockExpr *blkExpr = nullptr);
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const {
if (FunctionScopes.empty())
return nullptr;
for (int e = FunctionScopes.size()-1; e >= 0; --e) {
if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
continue;
return FunctionScopes[e];
}
return nullptr;
}
template <typename ExprT>
void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
if (!isUnevaluatedContext())
getCurFunction()->recordUseOfWeak(E, IsRead);
}
void PushCompoundScope();
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// \brief Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// Retrieve the current lambda scope info, if any.
/// \param IgnoreCapturedRegions true if should find the top-most lambda scope
/// info ignoring all inner captured regions scope infos.
sema::LambdaScopeInfo *getCurLambda(bool IgnoreCapturedRegions = false);
/// \brief Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// \brief 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 BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
/// \brief 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);
TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
TypeSourceInfo *ReturnTypeInfo);
/// \brief 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 CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
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);
/// \brief The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// \brief 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,
llvm::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, llvm::index_sequence_for<Ts...>());
DB << T;
}
};
private:
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser *Diagnoser);
struct ModuleScope {
clang::Module *Module;
VisibleModuleSet OuterVisibleModules;
};
/// The modules we're currently parsing.
llvm::SmallVector<ModuleScope, 16> ModuleScopes;
VisibleModuleSet VisibleModules;
Module *CachedFakeTopLevelModule;
public:
/// \brief Get the module owning an entity.
Module *getOwningModule(Decl *Entity);
/// \brief Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
/// 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);
/// 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 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 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);
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), Previous(nullptr) {}
bool ShouldSkip;
NamedDecl *Previous;
};
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,
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 AllowClassTemplates = 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);
/// \brief Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
NC_Unknown,
NC_Error,
NC_Keyword,
NC_Type,
NC_Expression,
NC_NestedNameSpecifier,
NC_TypeTemplate,
NC_VarTemplate,
NC_FunctionTemplate
};
class NameClassification {
NameClassificationKind Kind;
ExprResult Expr;
TemplateName Template;
ParsedType Type;
const IdentifierInfo *Keyword;
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *Keyword)
: Kind(NC_Keyword), Keyword(Keyword) { }
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification NestedNameSpecifier() {
return NameClassification(NC_NestedNameSpecifier);
}
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;
}
NameClassificationKind getKind() const { return Kind; }
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
ExprResult getExpression() const {
assert(Kind == NC_Expression);
return Expr;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate);
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;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// \brief 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 IsAddressOfOperand True if this name is the operand of a unary
/// address of ('&') expression, assuming it is classified as an
/// expression.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification
ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
SourceLocation NameLoc, const Token &NextToken,
bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
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);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation(),
SourceLocation UnalignedQualLoc = SourceLocation());
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
void CheckShadow(VarDecl *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);
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);
bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
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 IsExplicitSpecialization);
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC);
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
void ActOnUninitializedDecl(Decl *dcl);
void ActOnInitializerError(Decl *Dcl);
bool canInitializeWithParenthesizedList(QualType TargetType);
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 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);
}
/// \brief 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);
/// \brief 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);
/// \brief Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
/// \brief 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);
/// \brief Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S,
AttributeList *AttrList,
SourceLocation SemiLoc);
enum class ModuleDeclKind {
Module, ///< 'module X;'
Partition, ///< 'module partition X;'
Implementation, ///< 'module implementation X;'
};
/// The parser has processed a module-declaration that begins the definition
/// of a module interface or implementation.
DeclGroupPtrTy ActOnModuleDecl(SourceLocation ModuleLoc, ModuleDeclKind MDK,
ModuleIdPath Path);
/// \brief The parser has processed a module import declaration.
///
/// \param AtLoc The location of the '@' symbol, if any.
///
/// \param ImportLoc The location of the 'import' keyword.
///
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
ModuleIdPath Path);
/// \brief 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);
/// \brief The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// \brief The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// \brief 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
};
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief Retrieve a suitable printing policy.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// \brief Retrieve a suitable printing policy.
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,
AttributeList *Attr, AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists,
bool &OwnedDecl, bool &IsDependent,
SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *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,
AttributeList *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);
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
bool Diagnose = false);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
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,
AttributeList *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);
typedef void *SkippedDefinitionContext;
/// \brief 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();
/// \brief 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 EnumUnderlyingIsImplicit,
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,
AttributeList *Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
Decl *EnumDecl,
ArrayRef<Decl *> Elements,
Scope *S, AttributeList *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);
/// \brief Make the given externally-produced declaration visible at the
/// top level scope.
///
/// \param D The externally-produced declaration to push.
///
/// \param Name The name of the externally-produced declaration.
void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
/// 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);
/// \brief Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// \brief Don't merge availability attributes at all.
AMK_None,
/// \brief Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// \brief Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override,
/// \brief Merge availability attributes for an implementation of
/// a protocol requirement.
AMK_ProtocolImplementation,
};
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
IdentifierInfo *Platform,
bool Implicit,
VersionTuple Introduced,
VersionTuple Deprecated,
VersionTuple Obsoleted,
bool IsUnavailable,
StringRef Message,
bool IsStrict, StringRef Replacement,
AvailabilityMergeKind AMK,
unsigned AttrSpellingListIndex);
TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
TypeVisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
VisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex, StringRef Uuid);
DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
MSInheritanceAttr *
mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
unsigned AttrSpellingListIndex,
MSInheritanceAttr::Spelling SemanticSpelling);
FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
IdentifierInfo *Format, int FormatIdx,
int FirstArg, unsigned AttrSpellingListIndex);
SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
unsigned AttrSpellingListIndex);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
IdentifierInfo *Ident,
unsigned AttrSpellingListIndex);
MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
IdentifierInfo *Ident,
unsigned AttrSpellingListIndex);
CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
unsigned AttrSpellingListIndex);
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);
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);
/// \brief Checks availability of the function depending on the current
/// function context.Inside an unavailable function,unavailability is ignored.
///
/// \returns true if \p FD is unavailable and current context is inside
/// an available function, false otherwise.
bool isFunctionConsideredUnavailable(FunctionDecl *FD);
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 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);
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.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// \brief 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) {}
/// \brief Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// \brief Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// \brief Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief 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);
}
/// \brief 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;
void AddOverloadCandidate(FunctionDecl *Function,
DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = false,
ConversionSequenceList EarlyConversions = None);
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false);
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);
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);
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
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 = {});
void AddConversionCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet& CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
SourceRange OpRange = SourceRange());
void AddBuiltinCandidate(QualType ResultTy, 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,
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);
/// 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 FunctionDecl *Function,
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);
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);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
BinaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS);
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.
//@{
/// @brief 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,
/// \brief Look up the name of an OpenMP user-defined reduction operation.
LookupOMPReductionName,
/// \brief Look up any declaration with any name.
LookupAnyName
};
/// \brief Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// \brief The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// \brief The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists.
ForRedeclaration
};
/// \brief The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// \brief The lookup resulted in an error.
LOLR_Error,
/// \brief The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// \brief The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// \brief 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,
/// \brief 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;
};
/// \brief The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// \brief Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// \brief 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;
/// \brief Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// \brief 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,
std::unique_ptr<CorrectionCandidateCallback> CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// \brief Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// \brief 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 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);
void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
DeclAccessPair Operator,
QualType T1, QualType T2);
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 isKnownName(StringRef name);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = 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,
std::unique_ptr<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,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// \brief 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 FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
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);
void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const AttributeList *AttrList);
void checkUnusedDeclAttributes(Declarator &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 AttributeList &attr, unsigned &value);
bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckNoReturnAttr(const AttributeList &attr);
bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
unsigned ArgNum, StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
void 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.
///
/// \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 nullabilityLoc The location of the nullability specifier.
///
/// \param isContextSensitive Whether this nullability specifier was
/// written as a context-sensitive keyword (in an Objective-C
/// method) or an Objective-C property attribute, rather than as an
/// underscored type specifier.
///
/// \param allowArrayTypes Whether to accept nullability specifiers on an
/// array type (e.g., because it will decay to a pointer).
///
/// \returns true if nullability cannot be applied, false otherwise.
bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
SourceLocation nullabilityLoc,
bool isContextSensitive,
bool allowArrayTypes);
/// \brief Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *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;
typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
/// 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);
void DefaultSynthesizeProperties(Scope *S, Decl *D);
/// 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,
Selector SetterSel,
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,
Selector SetterSel,
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);
/// \brief 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:
/// \brief - 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:
/// \brief - 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);
/// \brief 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).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg);
StmtResult ActOnExprStmtError();
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt();
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// \brief A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S): S(S) {
S.ActOnStartOfCompoundStmt();
}
~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);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
SourceLocation DotDotDotLoc, Expr *RHSVal,
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 *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation CoawaitLoc,
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);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
bool AllowParamOrMoveConstructible);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
bool AllowParamOrMoveConstructible);
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,
SourceLocation RParenLoc);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
llvm::InlineAsmIdentifierInfo &Info,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
llvm::InlineAsmIdentifierInfo &Info,
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;
/// \brief 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);
/// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
/// _Nonnull one.
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
SourceLocation Loc);
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 EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
StringRef Message, SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass,
const ObjCPropertyDecl *ObjCProperty,
bool ObjCPropertyAccess);
bool makeUnavailableInSystemHeader(SourceLocation loc,
UnavailableAttr::ImplicitReason reason);
/// \brief 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, SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
bool ObjCPropertyAccess=false);
void NoteDeletedFunction(FunctionDecl *FD);
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
bool IsDecltype = false);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
ReuseLambdaContextDecl_t,
bool IsDecltype = false);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(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);
void MarkMemberReferenced(MemberExpr *E);
void UpdateMarkingForLValueToRValue(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// \brief 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);
/// \brief Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// \brief Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// \brief 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);
/// \brief 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);
/// \brief Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// \brief 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);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
std::unique_ptr<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,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
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);
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
ExprResult
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
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::IdentType IT);
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);
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);
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,
bool IsExecConfig = false);
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
SourceLocation LParenLoc,
ArrayRef<Expr *> Arg,
SourceLocation RParenLoc,
Expr *Config = nullptr,
bool IsExecConfig = false);
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);
/// \brief 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 ActOnDesignatedInitializer(Designation &Desig,
SourceLocation Loc,
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); // "({..})"
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);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// \brief Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// \brief The symbol exists.
IER_Exists,
/// \brief The symbol does not exist.
IER_DoesNotExist,
/// \brief The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// \brief 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,
AttributeList *AttrList,
UsingDirectiveDecl * &UsingDecl);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
NamespaceDecl *lookupStdExperimentalNamespace();
CXXRecordDecl *getStdBadAlloc() const;
EnumDecl *getStdAlignValT() const;
/// \brief 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);
/// \brief 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);
/// \brief Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const CXXConstructorDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope,
SourceLocation UsingLoc,
SourceLocation NamespcLoc,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
AttributeList *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,
AttributeList *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,
AttributeList *AttrList);
Decl *ActOnAliasDeclaration(Scope *CurScope,
AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc,
UnqualifiedId &Name,
AttributeList *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);
/// \brief 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;
}
/// \brief Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(ComputedEST != EST_ComputedNoexcept &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// \brief The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// \brief The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// \brief Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// \brief Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E);
/// \brief 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_ComputedNoexcept;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// \brief Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// \brief 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);
/// \brief Determine what sort of exception specification a defautled
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
CXXConstructorDecl *CD);
/// \brief Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
/// \brief 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);
/// \brief 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);
/// \brief 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;
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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(CXXRecordDecl *ClassDecl,
CXXDestructorDecl *Destructor);
/// \brief Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief 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);
/// \brief Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// \brief Check a completed declaration of an implicit special member.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
/// \brief Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// \brief 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);
/// \brief Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// \brief 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 getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorType(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 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);
/// \brief 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);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// \brief Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// \brief 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;
/// \brief 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:
/// \brief 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, unsigned CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// \brief 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);
/// \brief 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 LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
/// 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,
Expr *ArraySize,
SourceRange DirectInitRange,
Expr *Initializer);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
bool UseGlobal, QualType AllocType, bool IsArray,
bool &PassAlignment, MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete);
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);
/// \brief 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 bianry 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) {
return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
: SourceLocation());
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue = false,
bool IsConstexpr = false,
bool IsLambdaInitCaptureInitializer = 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);
/// \brief 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);
/// \brief 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);
/// \brief Keeps information about an identifier in a nested-name-spec.
///
struct NestedNameSpecInfo {
/// \brief The type of the object, if we're parsing nested-name-specifier in
/// a member access expression.
ParsedType ObjectType;
/// \brief The identifier preceding the '::'.
IdentifierInfo *Identifier;
/// \brief The location of the identifier.
SourceLocation IdentifierLoc;
/// \brief The location of the '::'.
SourceLocation CCLoc;
/// \brief 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);
/// \brief 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 '::'.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo,
bool EnteringContext);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// \brief Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params,
bool IsConstexprSpecified);
/// \brief 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);
/// \brief 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, IdentifierInfo *Id,
LambdaCaptureInitKind InitKind, Expr *&Init) {
return ParsedType::make(buildLambdaInitCaptureInitialization(
Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
}
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
IdentifierInfo *Id,
bool DirectInit, Expr *&Init);
/// \brief 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,
IdentifierInfo *Id,
unsigned InitStyle, Expr *Init);
/// \brief Build the implicit field for an init-capture.
FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// \brief Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief Introduce the lambda parameters into scope.
void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
/// \brief 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);
/// \brief Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// \brief 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);
/// \brief 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);
// 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
//
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,
AttributeList *Attrs = nullptr);
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);
/// \brief 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;
/// \brief The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// \brief 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;
/// \brief Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// \brief Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// \brief 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);
/// \brief 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);
/// \brief 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 referenceDLLExportedClassMethods();
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
void CheckCompletedCXXClass(CXXRecordDecl *Record);
void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Decl *TagDecl,
SourceLocation LBrac,
SourceLocation RBrac,
AttributeList *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 CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
const FunctionProtoType *T);
void CheckDelayedMemberExceptionSpecs();
//===--------------------------------------------------------------------===//
// 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 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, DeclContext *Ctx);
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);
/// \brief 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 hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true);
void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
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);
Decl *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);
Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
Decl *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<Decl *> Params,
SourceLocation RAngleLoc,
Expr *RequiresClause);
/// \brief 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);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *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);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false);
/// \brief 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 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,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template);
DeclResult
ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc,
SourceLocation ModulePrivateLoc,
TemplateIdAnnotation &TemplateId,
AttributeList *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 CheckMemberSpecialization(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,
AttributeList *Attr);
DeclResult
ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec,
SourceLocation KWLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
AttributeList *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);
/// \brief Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// \brief The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// \brief The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// \brief 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);
/// \brief 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.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted);
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 CheckTemplateArgument(TemplateTemplateParmDecl *Param,
TemplateArgumentLoc &Arg,
unsigned ArgumentPackIndex);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// \brief Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// \brief 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,
/// \brief 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,
/// \brief 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);
/// \brief 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);
/// \brief 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 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 ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
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);
//===--------------------------------------------------------------------===//
// 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();
/// \brief 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 {
/// \brief An arbitrary expression.
UPPC_Expression = 0,
/// \brief The base type of a class type.
UPPC_BaseType,
/// \brief The type of an arbitrary declaration.
UPPC_DeclarationType,
/// \brief The type of a data member.
UPPC_DataMemberType,
/// \brief The size of a bit-field.
UPPC_BitFieldWidth,
/// \brief The expression in a static assertion.
UPPC_StaticAssertExpression,
/// \brief The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// \brief The enumerator value.
UPPC_EnumeratorValue,
/// \brief A using declaration.
UPPC_UsingDeclaration,
/// \brief A friend declaration.
UPPC_FriendDeclaration,
/// \brief A declaration qualifier.
UPPC_DeclarationQualifier,
/// \brief An initializer.
UPPC_Initializer,
/// \brief A default argument.
UPPC_DefaultArgument,
/// \brief The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// \brief The type of an exception.
UPPC_ExceptionType,
/// \brief Partial specialization.
UPPC_PartialSpecialization,
/// \brief Microsoft __if_exists.
UPPC_IfExists,
/// \brief Microsoft __if_not_exists.
UPPC_IfNotExists,
/// \brief Lambda expression.
UPPC_Lambda,
/// \brief Block expression,
UPPC_Block
};
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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 {
/// \brief Template argument deduction was successful.
TDK_Success = 0,
/// \brief The declaration was invalid; do nothing.
TDK_Invalid,
/// \brief Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// \brief Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// \brief Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// \brief 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,
/// \brief Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// \brief After substituting deduced template arguments, a dependent
/// parameter type did not match the corresponding argument.
TDK_DeducedMismatch,
/// \brief 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,
/// \brief A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// \brief When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// \brief When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// \brief The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// \brief Checking non-dependent argument conversions failed.
TDK_NonDependentConversionFailure,
/// \brief Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure,
/// \brief 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);
/// \brief Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// \brief Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// \brief 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);
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);
/// \brief A template instantiation that is currently in progress.
struct ActiveTemplateInstantiation {
/// \brief The kind of template instantiation we are performing
enum InstantiationKind {
/// 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 instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation
} Kind;
/// \brief The point of instantiation within the source code.
SourceLocation PointOfInstantiation;
/// \brief The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// \brief The entity that is being instantiated.
Decl *Entity;
/// \brief The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
/// \brief The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
ArrayRef<TemplateArgument> template_arguments() const {
return {TemplateArgs, NumTemplateArgs};
}
/// \brief The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// \brief The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
ActiveTemplateInstantiation()
: Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
/// \brief Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
friend bool operator==(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
if (X.Kind != Y.Kind)
return false;
if (X.Entity != Y.Entity)
return false;
switch (X.Kind) {
case TemplateInstantiation:
case ExceptionSpecInstantiation:
return true;
case PriorTemplateArgumentSubstitution:
case DefaultTemplateArgumentChecking:
return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
case DefaultTemplateArgumentInstantiation:
case ExplicitTemplateArgumentSubstitution:
case DeducedTemplateArgumentSubstitution:
case DefaultFunctionArgumentInstantiation:
return X.TemplateArgs == Y.TemplateArgs;
}
llvm_unreachable("Invalid InstantiationKind!");
}
friend bool operator!=(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
return !(X == Y);
}
};
/// \brief List of active template instantiations.
///
/// This vector is treated as a stack. As one template instantiation
/// requires another template instantiation, additional
/// instantiations are pushed onto the stack up to a
/// user-configurable limit LangOptions::InstantiationDepth.
SmallVector<ActiveTemplateInstantiation, 16>
ActiveTemplateInstantiations;
/// 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;
/// \brief Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
/// \brief 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;
/// \brief 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();
/// \brief Map from the most recent declaration of a namespace to the most
/// recent visible declaration of that namespace.
llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
/// \brief 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;
/// \brief The number of ActiveTemplateInstantiation entries in
/// \c ActiveTemplateInstantiations that are not actual instantiations and,
/// therefore, should not be counted as part of the instantiation depth.
unsigned NonInstantiationEntries;
/// \brief The last template from which a template instantiation
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant template
/// instantiation backtraces when there are multiple errors in the
/// same instantiation. FIXME: Does this belong in Sema? It's tough
/// to implement it anywhere else.
ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
/// \brief 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;
/// \brief 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;
/// \brief 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;
/// \brief 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 {
/// \brief 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 {};
/// \brief Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// \brief 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());
/// \brief 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,
ActiveTemplateInstantiation::InstantiationKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief 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());
/// \brief 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());
/// \brief 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());
/// \brief 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());
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// \brief Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
/// \brief 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 SavedInNonInstantiationSFINAEContext;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind 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 PrintInstantiationStack();
/// \brief 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;
/// \brief 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();
}
/// \brief 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;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
}
/// \brief Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// \brief 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;
}
};
/// \brief The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// \brief Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// \brief The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// \brief 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;
/// \brief Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// \brief 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;
/// \brief The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
class SavePendingInstantiationsAndVTableUsesRAII {
public:
SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
~SavePendingInstantiationsAndVTableUsesRAII() {
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;
};
/// \brief 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 SavePendingLocalImplicitInstantiationsRAII {
public:
SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
~SavePendingLocalImplicitInstantiationsRAII() {
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);
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,
unsigned ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
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);
/// \brief 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);
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);
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);
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);
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 InstantiateStaticDataMemberDefinition(
SourceLocation PointOfInstantiation,
VarDecl *Var,
bool Recursive = false,
bool DefinitionRequired = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs);
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,
AttributeList *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,
AttributeList *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);
Decl *ActOnStartClassImplementation(
SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc);
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,
AttributeList *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);
/// Check the application of the Objective-C '__kindof' qualifier to
/// the given type.
bool checkObjCKindOfType(QualType &type, SourceLocation loc);
/// 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.
AttributeList *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
AttributeList *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);
/// \brief Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// \brief The message is sent to 'super'.
ObjCSuperMessage,
/// \brief The message is an instance message.
ObjCInstanceMessage,
/// \brief 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);
/// \brief 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);
/// \brief Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
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
};
/// 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);
/// 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);
/// \brief 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);
/// \brief 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);
/// \brief Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// \brief Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// \brief 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
void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
/// 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);
/// \brief Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// \brief 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;
}
/// \brief 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);
/// \brief 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(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex, bool IsPackExpansion);
void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
unsigned SpellingListIndex, bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
unsigned SpellingListIndex);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
Expr *MinBlocks, unsigned SpellingListIndex);
/// AddModeAttr - Adds a mode attribute to a particular declaration.
void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
unsigned SpellingListIndex, bool InInstantiation = false);
void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
ParameterABI ABI, unsigned SpellingListIndex);
void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
unsigned SpellingListIndex, bool isNSConsumed,
bool isTemplateInstantiation);
//===--------------------------------------------------------------------===//
// C++ Coroutines TS
//
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
StmtResult ActOnCoreturnStmt(SourceLocation KwLoc, Expr *E);
ExprResult BuildCoawaitExpr(SourceLocation KwLoc, Expr *E);
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E);
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
//===--------------------------------------------------------------------===//
// 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;
}
void setCurrentOpenCLExtension(llvm::StringRef Ext) {
CurrOpenCLExtension = Ext;
}
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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);
/// \brief 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 Decl &D, const Expr &E);
//===--------------------------------------------------------------------===//
// OpenMP directives and clauses.
//
private:
void *VarDataSharingAttributesStack;
/// Set to true inside '#pragma omp declare target' region.
bool IsInOpenMPDeclareTargetContext = false;
/// \brief 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;
/// 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());
public:
/// \brief 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.
bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
/// \brief 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);
ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
ExprObjectKind OK, SourceLocation Loc);
/// \brief 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(ValueDecl *D, unsigned Level);
/// \brief 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(ValueDecl *D, unsigned Level);
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// \brief Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// \brief Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// \brief End analysis of clauses.
void EndOpenMPClause();
/// \brief Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// \brief 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.
/// \brief Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id);
/// \brief Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Check if the specified type is allowed to be used in 'omp declare
/// reduction' construct.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
TypeResult ParsedType);
/// \brief 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);
/// \brief Initialize declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
/// \brief Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
/// \brief Initialize declare reduction construct initializer.
void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
/// \brief Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
/// \brief Called at the end of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
/// 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();
/// Called on correct id-expression from the '#pragma omp declare target'.
void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
OMPDeclareTargetDeclAttr::MapTypeTy MT,
NamedDeclSetType &SameDirectiveDecls);
/// Check declaration inside target region.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
/// Return true inside OpenMP target region.
bool isInOpenMPDeclareTargetContext() const {
return IsInOpenMPDeclareTargetContext;
}
/// \brief Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// \brief 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);
/// \brief Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief 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);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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);
/// \brief Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief 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);
/// \brief Called on well-formed '\#pragma omp target enter data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp target exit data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief 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);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// \brief Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp distribute' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp target update'.
StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief 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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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,
llvm::DenseMap<ValueDecl *, Expr *> &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(ValueDecl *D, SourceLocation ELoc,
OpenMPLinearClauseKind LinKind, QualType Type);
/// \brief 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);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation NameModifierLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'simdlen' clause.
OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'ordered' clause.
OMPClause *
ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
SourceLocation LParenLoc = SourceLocation(),
Expr *NumForLoops = nullptr);
/// \brief Called on well-formed 'grainsize' clause.
OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'num_tasks' clause.
OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief 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);
/// \brief Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief 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);
/// \brief 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);
/// \brief Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'threads' clause.
OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'simd' clause.
OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'nogroup' clause.
OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
SourceLocation DepLinMapLoc);
/// \brief Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief 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);
/// \brief 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);
/// \brief Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'device' clause.
OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'map' clause.
OMPClause *
ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
SourceLocation MapLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc);
/// \brief Called on well-formed 'num_teams' clause.
OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'thread_limit' clause.
OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'priority' clause.
OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'dist_schedule' clause.
OMPClause *ActOnOpenMPDistScheduleClause(
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
SourceLocation CommaLoc, SourceLocation EndLoc);
/// \brief Called on well-formed 'defaultmap' clause.
OMPClause *ActOnOpenMPDefaultmapClause(
OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
SourceLocation KindLoc, SourceLocation EndLoc);
/// \brief Called on well-formed 'to' clause.
OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'from' clause.
OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'use_device_ptr' clause.
OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'is_device_ptr' clause.
OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief The kind of conversion being performed.
enum CheckedConversionKind {
/// \brief An implicit conversion.
CCK_ImplicitConversion,
/// \brief A C-style cast.
CCK_CStyleCast,
/// \brief A functional-style cast.
CCK_FunctionalCast,
/// \brief A cast other than a C-style cast.
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,
/// 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);
// \brief 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);
/// 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 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);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, bool isRelational);
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, bool isRelational);
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);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// \brief Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// \brief 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);
/// \brief 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,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
/// \brief Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds.
ARCConversionResult CheckObjCARCConversion(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(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);
/// \brief 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(QualType ReceiverType,
ObjCMethodDecl *Method,
bool isClassMessage, bool isSuperMessage);
/// \brief 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);
/// \brief 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);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// \brief 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);
/// \brief 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>>
CUDADeferredDiags;
/// 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>
CUDAKnownEmittedFns;
/// A partial call graph maintained during CUDA 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 CUDAKnownEmittedFns.
llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
/* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
SourceLocation>>
CUDACallGraph;
/// Diagnostic builder for CUDA 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 CUDADiagBuilder {
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
};
CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
FunctionDecl *Fn, Sema &S);
~CUDADiagBuilder();
/// 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 (CUDADiagBuilder(...) << foo << bar)
/// return ExprError();
///
/// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
/// want to use these instead of creating a CUDADiagBuilder yourself.
operator bool() const { return ImmediateDiag.hasValue(); }
template <typename T>
friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
const T &Value) {
if (Diag.ImmediateDiag.hasValue())
*Diag.ImmediateDiag << Value;
else if (Diag.PartialDiag.hasValue())
*Diag.PartialDiag << 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<PartialDiagnostic> PartialDiag;
};
/// Creates a CUDADiagBuilder 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.
CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a CUDADiagBuilder that emits the diagnostic if the current context
/// is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
CUDADiagBuilder CUDADiagIfHostCode(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 AttributeList *Attr);
/// 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);
/// 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);
/// \name Code completion
//@{
/// \brief Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// \brief Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// \brief Code completion occurs within a class, struct, or union.
PCC_Class,
/// \brief Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// \brief Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// \brief Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// \brief Code completion occurs following one or more template
/// headers.
PCC_Template,
/// \brief Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// \brief Code completion occurs within an expression.
PCC_Expression,
/// \brief Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// \brief Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// \brief Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// \brief 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,
/// \brief Code completion occurs where only a type is permitted.
PCC_Type,
/// \brief Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// \brief 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 CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteBracketDeclarator(Scope *S);
void CodeCompleteCase(Scope *S);
void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
ArrayRef<Expr *> Args);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteReturn(Scope *S);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
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,
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 CodeCompleteNaturalLanguage();
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);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
bool SemaBuiltinVAStart(CallExpr *TheCall);
bool SemaBuiltinMSVAStart(CallExpr *TheCall);
bool SemaBuiltinVAStartARM(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
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);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
int Low, int High);
bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
unsigned Multiple);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
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);
void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// \brief 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);
/// \brief Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// \brief 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:
/// \brief 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:
/// \brief A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// \brief 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 Expr * const *ExprArgs);
/// \brief 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);
/// \brief 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;
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;
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// \brief 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;
}
/// \brief The diagnostic we should emit for \c D, or \c AR_Available.
///
/// \param D The declaration to check. Note that this may be altered to point
/// to another declaration that \c D gets it's availability from. i.e., we
/// walk the list of typedefs to find an availability attribute.
///
/// \param Message If non-null, this will be populated with the message from
/// the availability attribute that is selected.
AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
std::string *Message);
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;
}
/// \brief 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;
private:
/// \brief 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; }
};
/// \brief Small set of gathered accesses to potentially misaligned members
/// due to the packed attribute.
SmallVector<MisalignedMember, 4> MisalignedMembers;
/// \brief Adds an expression to the set of gathered misaligned members.
void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment);
public:
/// \brief Diagnoses the current set of gathered accesses. This typically
/// happens at full expression level. The set is cleared after emitting the
/// diagnostics.
void DiagnoseMisalignedMembers();
/// \brief 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);
/// \brief 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);
};
/// \brief 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,
bool IsDecltype = false,
bool ShouldEnter = true)
: Actions(Actions), Entered(ShouldEnter) {
if (Entered)
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
IsDecltype);
}
EnterExpressionEvaluationContext(Sema &Actions,
Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
bool IsDecltype = false)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(NewContext,
Sema::ReuseLambdaContextDecl,
IsDecltype);
}
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::UnevaluatedList, nullptr,
false);
Entered = true;
}
}
~EnterExpressionEvaluationContext() {
if (Entered)
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// \brief Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// \brief 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
|
libperf.c | /**
* Copyright (C) Mellanox Technologies Ltd. 2001-2019. ALL RIGHTS RESERVED.
* Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED.
* Copyright (C) The University of Tennessee and The University
* of Tennessee Research Foundation. 2015-2016. ALL RIGHTS RESERVED.
* Copyright (C) ARM Ltd. 2017. ALL RIGHTS RESERVED.
* See file LICENSE for terms.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <ucs/debug/log.h>
#include <ucs/arch/bitops.h>
#include <ucs/sys/module.h>
#include <string.h>
#include <tools/perf/lib/libperf_int.h>
#include <unistd.h>
#if _OPENMP
#include <omp.h>
#endif /* _OPENMP */
#define ATOMIC_OP_CONFIG(_size, _op32, _op64, _op, _msg, _params, _status) \
_status = __get_atomic_flag((_size), (_op32), (_op64), (_op)); \
if (_status != UCS_OK) { \
ucs_error("%s/%s does not support atomic %s for message size %zu bytes", \
(_params)->uct.tl_name, (_params)->uct.dev_name, \
(_msg)[_op], (_size)); \
return _status; \
}
#define ATOMIC_OP_CHECK(_size, _attr, _required, _params, _msg) \
if (!ucs_test_all_flags(_attr, _required)) { \
if ((_params)->flags & UCX_PERF_TEST_FLAG_VERBOSE) { \
ucs_error("%s/%s does not support required "#_size"-bit atomic: %s", \
(_params)->uct.tl_name, (_params)->uct.dev_name, \
(_msg)[ucs_ffs64(~(_attr) & (_required))]); \
} \
return UCS_ERR_UNSUPPORTED; \
}
typedef struct {
union {
struct {
size_t dev_addr_len;
size_t iface_addr_len;
size_t ep_addr_len;
} uct;
struct {
size_t addr_len;
} ucp;
};
size_t rkey_size;
unsigned long recv_buffer;
} ucx_perf_ep_info_t;
const ucx_perf_allocator_t* ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_LAST];
static const char *perf_iface_ops[] = {
[ucs_ilog2(UCT_IFACE_FLAG_AM_SHORT)] = "am short",
[ucs_ilog2(UCT_IFACE_FLAG_AM_BCOPY)] = "am bcopy",
[ucs_ilog2(UCT_IFACE_FLAG_AM_ZCOPY)] = "am zcopy",
[ucs_ilog2(UCT_IFACE_FLAG_PUT_SHORT)] = "put short",
[ucs_ilog2(UCT_IFACE_FLAG_PUT_BCOPY)] = "put bcopy",
[ucs_ilog2(UCT_IFACE_FLAG_PUT_ZCOPY)] = "put zcopy",
[ucs_ilog2(UCT_IFACE_FLAG_GET_SHORT)] = "get short",
[ucs_ilog2(UCT_IFACE_FLAG_GET_BCOPY)] = "get bcopy",
[ucs_ilog2(UCT_IFACE_FLAG_GET_ZCOPY)] = "get zcopy",
[ucs_ilog2(UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE)] = "peer failure handler",
[ucs_ilog2(UCT_IFACE_FLAG_CONNECT_TO_IFACE)] = "connect to iface",
[ucs_ilog2(UCT_IFACE_FLAG_CONNECT_TO_EP)] = "connect to ep",
[ucs_ilog2(UCT_IFACE_FLAG_AM_DUP)] = "full reliability",
[ucs_ilog2(UCT_IFACE_FLAG_CB_SYNC)] = "sync callback",
[ucs_ilog2(UCT_IFACE_FLAG_CB_ASYNC)] = "async callback",
[ucs_ilog2(UCT_IFACE_FLAG_EVENT_SEND_COMP)] = "send completion event",
[ucs_ilog2(UCT_IFACE_FLAG_EVENT_RECV)] = "tag or active message event",
[ucs_ilog2(UCT_IFACE_FLAG_EVENT_RECV_SIG)] = "signaled message event",
[ucs_ilog2(UCT_IFACE_FLAG_PENDING)] = "pending",
[ucs_ilog2(UCT_IFACE_FLAG_TAG_EAGER_SHORT)] = "tag eager short",
[ucs_ilog2(UCT_IFACE_FLAG_TAG_EAGER_BCOPY)] = "tag eager bcopy",
[ucs_ilog2(UCT_IFACE_FLAG_TAG_EAGER_ZCOPY)] = "tag eager zcopy",
[ucs_ilog2(UCT_IFACE_FLAG_TAG_RNDV_ZCOPY)] = "tag rndv zcopy"
};
static const char *perf_atomic_op[] = {
[UCT_ATOMIC_OP_ADD] = "add",
[UCT_ATOMIC_OP_AND] = "and",
[UCT_ATOMIC_OP_OR] = "or" ,
[UCT_ATOMIC_OP_XOR] = "xor"
};
static const char *perf_atomic_fop[] = {
[UCT_ATOMIC_OP_ADD] = "fetch-add",
[UCT_ATOMIC_OP_AND] = "fetch-and",
[UCT_ATOMIC_OP_OR] = "fetch-or",
[UCT_ATOMIC_OP_XOR] = "fetch-xor",
[UCT_ATOMIC_OP_SWAP] = "swap",
[UCT_ATOMIC_OP_CSWAP] = "cswap"
};
/*
* This Quickselect routine is based on the algorithm described in
* "Numerical recipes in C", Second Edition,
* Cambridge University Press, 1992, Section 8.5, ISBN 0-521-43108-5
* This code by Nicolas Devillard - 1998. Public domain.
*/
static ucs_time_t __find_median_quick_select(ucs_time_t arr[], int n)
{
int low, high ;
int median;
int middle, ll, hh;
#define ELEM_SWAP(a,b) { register ucs_time_t t=(a);(a)=(b);(b)=t; }
low = 0 ; high = n-1 ; median = (low + high) / 2;
for (;;) {
if (high <= low) /* One element only */
return arr[median] ;
if (high == low + 1) { /* Two elements only */
if (arr[low] > arr[high])
ELEM_SWAP(arr[low], arr[high]) ;
return arr[median] ;
}
/* Find median of low, middle and high items; swap into position low */
middle = (low + high) / 2;
if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]) ;
if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]) ;
if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]) ;
/* Swap low item (now in position middle) into position (low+1) */
ELEM_SWAP(arr[middle], arr[low+1]) ;
/* Nibble from each end towards middle, swapping items when stuck */
ll = low + 1;
hh = high;
for (;;) {
do ll++; while (arr[low] > arr[ll]) ;
do hh--; while (arr[hh] > arr[low]) ;
if (hh < ll)
break;
ELEM_SWAP(arr[ll], arr[hh]) ;
}
/* Swap middle item (in position low) back into correct position */
ELEM_SWAP(arr[low], arr[hh]) ;
/* Re-set active partition */
if (hh <= median)
low = ll;
if (hh >= median)
high = hh - 1;
}
}
static ucs_status_t uct_perf_test_alloc_mem(ucx_perf_context_t *perf)
{
ucx_perf_params_t *params = &perf->params;
ucs_status_t status;
unsigned flags;
size_t buffer_size;
if ((UCT_PERF_DATA_LAYOUT_ZCOPY == params->uct.data_layout) && params->iov_stride) {
buffer_size = params->msg_size_cnt * params->iov_stride;
} else {
buffer_size = ucx_perf_get_message_size(params);
}
/* TODO use params->alignment */
flags = (params->flags & UCX_PERF_TEST_FLAG_MAP_NONBLOCK) ?
UCT_MD_MEM_FLAG_NONBLOCK : 0;
flags |= UCT_MD_MEM_ACCESS_ALL;
/* Allocate send buffer memory */
status = uct_iface_mem_alloc(perf->uct.iface,
buffer_size * params->thread_count,
flags, "perftest", &perf->uct.send_mem);
if (status != UCS_OK) {
ucs_error("Failed allocate send buffer: %s", ucs_status_string(status));
goto err;
}
ucs_assert(perf->uct.send_mem.md == perf->uct.md);
perf->send_buffer = perf->uct.send_mem.address;
/* Allocate receive buffer memory */
status = uct_iface_mem_alloc(perf->uct.iface,
buffer_size * params->thread_count,
flags, "perftest", &perf->uct.recv_mem);
if (status != UCS_OK) {
ucs_error("Failed allocate receive buffer: %s", ucs_status_string(status));
goto err_free_send;
}
ucs_assert(perf->uct.recv_mem.md == perf->uct.md);
perf->recv_buffer = perf->uct.recv_mem.address;
/* Allocate IOV datatype memory */
perf->params.msg_size_cnt = params->msg_size_cnt;
perf->uct.iov = malloc(sizeof(*perf->uct.iov) *
perf->params.msg_size_cnt *
params->thread_count);
if (NULL == perf->uct.iov) {
status = UCS_ERR_NO_MEMORY;
ucs_error("Failed allocate send IOV(%lu) buffer: %s",
perf->params.msg_size_cnt, ucs_status_string(status));
goto err_free_send;
}
perf->offset = 0;
ucs_debug("allocated memory. Send buffer %p, Recv buffer %p",
perf->send_buffer, perf->recv_buffer);
return UCS_OK;
err_free_send:
uct_iface_mem_free(&perf->uct.send_mem);
err:
return status;
}
static void uct_perf_test_free_mem(ucx_perf_context_t *perf)
{
uct_iface_mem_free(&perf->uct.send_mem);
uct_iface_mem_free(&perf->uct.recv_mem);
free(perf->uct.iov);
}
void ucx_perf_test_start_clock(ucx_perf_context_t *perf)
{
ucs_time_t start_time = ucs_get_time();
perf->start_time_acc = ucs_get_accurate_time();
perf->end_time = (perf->params.max_time == 0.0) ? UINT64_MAX :
ucs_time_from_sec(perf->params.max_time) + start_time;
perf->prev_time = start_time;
perf->prev.time = start_time;
perf->prev.time_acc = perf->start_time_acc;
perf->current.time_acc = perf->start_time_acc;
}
/* Initialize/reset all parameters that could be modified by the warm-up run */
static void ucx_perf_test_prepare_new_run(ucx_perf_context_t *perf,
ucx_perf_params_t *params)
{
unsigned i;
perf->max_iter = (perf->params.max_iter == 0) ? UINT64_MAX :
perf->params.max_iter;
perf->report_interval = ucs_time_from_sec(perf->params.report_interval);
perf->current.time = 0;
perf->current.msgs = 0;
perf->current.bytes = 0;
perf->current.iters = 0;
perf->prev.msgs = 0;
perf->prev.bytes = 0;
perf->prev.iters = 0;
perf->timing_queue_head = 0;
for (i = 0; i < TIMING_QUEUE_SIZE; ++i) {
perf->timing_queue[i] = 0;
}
ucx_perf_test_start_clock(perf);
}
static void ucx_perf_test_init(ucx_perf_context_t *perf,
ucx_perf_params_t *params)
{
perf->params = *params;
perf->offset = 0;
perf->allocator = ucx_perf_mem_type_allocators[params->mem_type];
ucx_perf_test_prepare_new_run(perf, params);
}
void ucx_perf_calc_result(ucx_perf_context_t *perf, ucx_perf_result_t *result)
{
ucs_time_t median;
double factor;
if (perf->params.test_type == UCX_PERF_TEST_TYPE_PINGPONG) {
factor = 2.0;
} else {
factor = 1.0;
}
result->iters = perf->current.iters;
result->bytes = perf->current.bytes;
result->elapsed_time = perf->current.time_acc - perf->start_time_acc;
/* Latency */
median = __find_median_quick_select(perf->timing_queue, TIMING_QUEUE_SIZE);
result->latency.typical = ucs_time_to_sec(median) / factor;
result->latency.moment_average =
(perf->current.time_acc - perf->prev.time_acc)
/ (perf->current.iters - perf->prev.iters)
/ factor;
result->latency.total_average =
(perf->current.time_acc - perf->start_time_acc)
/ perf->current.iters
/ factor;
/* Bandwidth */
result->bandwidth.typical = 0.0; // Undefined
result->bandwidth.moment_average =
(perf->current.bytes - perf->prev.bytes) /
(perf->current.time_acc - perf->prev.time_acc) * factor;
result->bandwidth.total_average =
perf->current.bytes /
(perf->current.time_acc - perf->start_time_acc) * factor;
/* Packet rate */
result->msgrate.typical = 0.0; // Undefined
result->msgrate.moment_average =
(perf->current.msgs - perf->prev.msgs) /
(perf->current.time_acc - perf->prev.time_acc) * factor;
result->msgrate.total_average =
perf->current.msgs /
(perf->current.time_acc - perf->start_time_acc) * factor;
}
static ucs_status_t ucx_perf_test_check_params(ucx_perf_params_t *params)
{
size_t it;
if (ucx_perf_get_message_size(params) < 1) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Message size too small, need to be at least 1");
}
return UCS_ERR_INVALID_PARAM;
}
if (params->max_outstanding < 1) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("max_outstanding, need to be at least 1");
}
return UCS_ERR_INVALID_PARAM;
}
/* check if particular message size fit into stride size */
if (params->iov_stride) {
for (it = 0; it < params->msg_size_cnt; ++it) {
if (params->msg_size_list[it] > params->iov_stride) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Buffer size %lu bigger than stride %lu",
params->msg_size_list[it], params->iov_stride);
}
return UCS_ERR_INVALID_PARAM;
}
}
}
return UCS_OK;
}
void uct_perf_iface_flush_b(ucx_perf_context_t *perf)
{
ucs_status_t status;
do {
status = uct_iface_flush(perf->uct.iface, 0, NULL);
uct_worker_progress(perf->uct.worker);
} while (status == UCS_INPROGRESS);
}
static inline uint64_t __get_flag(uct_perf_data_layout_t layout, uint64_t short_f,
uint64_t bcopy_f, uint64_t zcopy_f)
{
return (layout == UCT_PERF_DATA_LAYOUT_SHORT) ? short_f :
(layout == UCT_PERF_DATA_LAYOUT_BCOPY) ? bcopy_f :
(layout == UCT_PERF_DATA_LAYOUT_ZCOPY) ? zcopy_f :
0;
}
static inline ucs_status_t __get_atomic_flag(size_t size, uint64_t *op32,
uint64_t *op64, uint64_t op)
{
if (size == sizeof(uint32_t)) {
*op32 = UCS_BIT(op);
return UCS_OK;
} else if (size == sizeof(uint64_t)) {
*op64 = UCS_BIT(op);
return UCS_OK;
}
return UCS_ERR_UNSUPPORTED;
}
static inline size_t __get_max_size(uct_perf_data_layout_t layout, size_t short_m,
size_t bcopy_m, uint64_t zcopy_m)
{
return (layout == UCT_PERF_DATA_LAYOUT_SHORT) ? short_m :
(layout == UCT_PERF_DATA_LAYOUT_BCOPY) ? bcopy_m :
(layout == UCT_PERF_DATA_LAYOUT_ZCOPY) ? zcopy_m :
0;
}
static ucs_status_t uct_perf_test_check_capabilities(ucx_perf_params_t *params,
uct_iface_h iface)
{
uint64_t required_flags = 0;
uint64_t atomic_op32 = 0;
uint64_t atomic_op64 = 0;
uint64_t atomic_fop32 = 0;
uint64_t atomic_fop64 = 0;
uct_iface_attr_t attr;
ucs_status_t status;
size_t min_size, max_size, max_iov, message_size;
status = uct_iface_query(iface, &attr);
if (status != UCS_OK) {
return status;
}
min_size = 0;
max_iov = 1;
message_size = ucx_perf_get_message_size(params);
switch (params->command) {
case UCX_PERF_CMD_AM:
required_flags = __get_flag(params->uct.data_layout, UCT_IFACE_FLAG_AM_SHORT,
UCT_IFACE_FLAG_AM_BCOPY, UCT_IFACE_FLAG_AM_ZCOPY);
required_flags |= UCT_IFACE_FLAG_CB_SYNC;
min_size = __get_max_size(params->uct.data_layout, 0, 0,
attr.cap.am.min_zcopy);
max_size = __get_max_size(params->uct.data_layout, attr.cap.am.max_short,
attr.cap.am.max_bcopy, attr.cap.am.max_zcopy);
max_iov = attr.cap.am.max_iov;
break;
case UCX_PERF_CMD_PUT:
required_flags = __get_flag(params->uct.data_layout, UCT_IFACE_FLAG_PUT_SHORT,
UCT_IFACE_FLAG_PUT_BCOPY, UCT_IFACE_FLAG_PUT_ZCOPY);
min_size = __get_max_size(params->uct.data_layout, 0, 0,
attr.cap.put.min_zcopy);
max_size = __get_max_size(params->uct.data_layout, attr.cap.put.max_short,
attr.cap.put.max_bcopy, attr.cap.put.max_zcopy);
max_iov = attr.cap.put.max_iov;
break;
case UCX_PERF_CMD_GET:
required_flags = __get_flag(params->uct.data_layout, UCT_IFACE_FLAG_GET_SHORT,
UCT_IFACE_FLAG_GET_BCOPY, UCT_IFACE_FLAG_GET_ZCOPY);
min_size = __get_max_size(params->uct.data_layout, 0, 0,
attr.cap.get.min_zcopy);
max_size = __get_max_size(params->uct.data_layout, attr.cap.get.max_short,
attr.cap.get.max_bcopy, attr.cap.get.max_zcopy);
max_iov = attr.cap.get.max_iov;
break;
case UCX_PERF_CMD_ADD:
ATOMIC_OP_CONFIG(message_size, &atomic_op32, &atomic_op64, UCT_ATOMIC_OP_ADD,
perf_atomic_op, params, status);
max_size = 8;
break;
case UCX_PERF_CMD_FADD:
ATOMIC_OP_CONFIG(message_size, &atomic_fop32, &atomic_fop64, UCT_ATOMIC_OP_ADD,
perf_atomic_fop, params, status);
max_size = 8;
break;
case UCX_PERF_CMD_SWAP:
ATOMIC_OP_CONFIG(message_size, &atomic_fop32, &atomic_fop64, UCT_ATOMIC_OP_SWAP,
perf_atomic_fop, params, status);
max_size = 8;
break;
case UCX_PERF_CMD_CSWAP:
ATOMIC_OP_CONFIG(message_size, &atomic_fop32, &atomic_fop64, UCT_ATOMIC_OP_CSWAP,
perf_atomic_fop, params, status);
max_size = 8;
break;
default:
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Invalid test command");
}
return UCS_ERR_INVALID_PARAM;
}
status = ucx_perf_test_check_params(params);
if (status != UCS_OK) {
return status;
}
/* check atomics first */
ATOMIC_OP_CHECK(32, attr.cap.atomic32.op_flags, atomic_op32, params, perf_atomic_op);
ATOMIC_OP_CHECK(64, attr.cap.atomic64.op_flags, atomic_op64, params, perf_atomic_op);
ATOMIC_OP_CHECK(32, attr.cap.atomic32.fop_flags, atomic_fop32, params, perf_atomic_fop);
ATOMIC_OP_CHECK(64, attr.cap.atomic64.fop_flags, atomic_fop64, params, perf_atomic_fop);
/* check iface flags */
if (!(atomic_op32 | atomic_op64 | atomic_fop32 | atomic_fop64) &&
(!ucs_test_all_flags(attr.cap.flags, required_flags) || !required_flags)) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("%s/%s does not support operation %s",
params->uct.tl_name, params->uct.dev_name,
perf_iface_ops[ucs_ffs64(~attr.cap.flags & required_flags)]);
}
return UCS_ERR_UNSUPPORTED;
}
if (message_size < min_size) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Message size (%zu) is smaller than min supported (%zu)",
message_size, min_size);
}
return UCS_ERR_UNSUPPORTED;
}
if (message_size > max_size) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Message size (%zu) is larger than max supported (%zu)",
message_size, max_size);
}
return UCS_ERR_UNSUPPORTED;
}
if (params->command == UCX_PERF_CMD_AM) {
if ((params->uct.data_layout == UCT_PERF_DATA_LAYOUT_SHORT) &&
(params->am_hdr_size != sizeof(uint64_t)))
{
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Short AM header size must be 8 bytes");
}
return UCS_ERR_INVALID_PARAM;
}
if ((params->uct.data_layout == UCT_PERF_DATA_LAYOUT_ZCOPY) &&
(params->am_hdr_size > attr.cap.am.max_hdr))
{
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("AM header size (%zu) is larger than max supported (%zu)",
params->am_hdr_size, attr.cap.am.max_hdr);
}
return UCS_ERR_UNSUPPORTED;
}
if (params->am_hdr_size > message_size) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("AM header size (%zu) is larger than message size (%zu)",
params->am_hdr_size, message_size);
}
return UCS_ERR_INVALID_PARAM;
}
if (params->uct.fc_window > UCT_PERF_TEST_MAX_FC_WINDOW) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("AM flow-control window (%d) too large (should be <= %d)",
params->uct.fc_window, UCT_PERF_TEST_MAX_FC_WINDOW);
}
return UCS_ERR_INVALID_PARAM;
}
if ((params->flags & UCX_PERF_TEST_FLAG_ONE_SIDED) &&
(params->flags & UCX_PERF_TEST_FLAG_VERBOSE))
{
ucs_warn("Running active-message test with on-sided progress");
}
}
if (UCT_PERF_DATA_LAYOUT_ZCOPY == params->uct.data_layout) {
if (params->msg_size_cnt > max_iov) {
if ((params->flags & UCX_PERF_TEST_FLAG_VERBOSE) ||
!params->msg_size_cnt) {
ucs_error("Wrong number of IOV entries. Requested is %lu, "
"should be in the range 1...%lu", params->msg_size_cnt,
max_iov);
}
return UCS_ERR_UNSUPPORTED;
}
/* if msg_size_cnt == 1 the message size checked above */
if ((UCX_PERF_CMD_AM == params->command) && (params->msg_size_cnt > 1)) {
if (params->am_hdr_size > params->msg_size_list[0]) {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("AM header size (%lu) larger than the first IOV "
"message size (%lu)", params->am_hdr_size,
params->msg_size_list[0]);
}
return UCS_ERR_INVALID_PARAM;
}
}
}
return UCS_OK;
}
static ucs_status_t uct_perf_test_setup_endpoints(ucx_perf_context_t *perf)
{
const size_t buffer_size = 2048;
ucx_perf_ep_info_t info, *remote_info;
unsigned group_size, i, group_index;
uct_device_addr_t *dev_addr;
uct_iface_addr_t *iface_addr;
uct_ep_addr_t *ep_addr;
uct_iface_attr_t iface_attr;
uct_md_attr_t md_attr;
uct_ep_params_t ep_params;
void *rkey_buffer;
ucs_status_t status;
struct iovec vec[5];
void *buffer;
void *req;
buffer = malloc(buffer_size);
if (buffer == NULL) {
ucs_error("Failed to allocate RTE buffer");
status = UCS_ERR_NO_MEMORY;
goto err;
}
status = uct_iface_query(perf->uct.iface, &iface_attr);
if (status != UCS_OK) {
ucs_error("Failed to uct_iface_query: %s", ucs_status_string(status));
goto err_free;
}
status = uct_md_query(perf->uct.md, &md_attr);
if (status != UCS_OK) {
ucs_error("Failed to uct_md_query: %s", ucs_status_string(status));
goto err_free;
}
if (md_attr.cap.flags & (UCT_MD_FLAG_ALLOC|UCT_MD_FLAG_REG)) {
info.rkey_size = md_attr.rkey_packed_size;
} else {
info.rkey_size = 0;
}
info.uct.dev_addr_len = iface_attr.device_addr_len;
info.uct.iface_addr_len = iface_attr.iface_addr_len;
info.uct.ep_addr_len = iface_attr.ep_addr_len;
info.recv_buffer = (uintptr_t)perf->recv_buffer;
rkey_buffer = buffer;
dev_addr = (void*)rkey_buffer + info.rkey_size;
iface_addr = (void*)dev_addr + info.uct.dev_addr_len;
ep_addr = (void*)iface_addr + info.uct.iface_addr_len;
ucs_assert_always((void*)ep_addr + info.uct.ep_addr_len <= buffer + buffer_size);
status = uct_iface_get_device_address(perf->uct.iface, dev_addr);
if (status != UCS_OK) {
ucs_error("Failed to uct_iface_get_device_address: %s",
ucs_status_string(status));
goto err_free;
}
status = uct_iface_get_address(perf->uct.iface, iface_addr);
if (status != UCS_OK) {
ucs_error("Failed to uct_iface_get_address: %s", ucs_status_string(status));
goto err_free;
}
if (info.rkey_size > 0) {
memset(rkey_buffer, 0, info.rkey_size);
status = uct_md_mkey_pack(perf->uct.md, perf->uct.recv_mem.memh, rkey_buffer);
if (status != UCS_OK) {
ucs_error("Failed to uct_rkey_pack: %s", ucs_status_string(status));
goto err_free;
}
}
group_size = rte_call(perf, group_size);
group_index = rte_call(perf, group_index);
perf->uct.peers = calloc(group_size, sizeof(*perf->uct.peers));
if (perf->uct.peers == NULL) {
goto err_free;
}
ep_params.field_mask = UCT_EP_PARAM_FIELD_IFACE;
ep_params.iface = perf->uct.iface;
if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_EP) {
for (i = 0; i < group_size; ++i) {
if (i == group_index) {
continue;
}
status = uct_ep_create(&ep_params, &perf->uct.peers[i].ep);
if (status != UCS_OK) {
ucs_error("Failed to uct_ep_create: %s", ucs_status_string(status));
goto err_destroy_eps;
}
status = uct_ep_get_address(perf->uct.peers[i].ep, ep_addr);
if (status != UCS_OK) {
ucs_error("Failed to uct_ep_get_address: %s", ucs_status_string(status));
goto err_destroy_eps;
}
}
} else if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_IFACE) {
ep_params.field_mask |= UCT_EP_PARAM_FIELD_DEV_ADDR |
UCT_EP_PARAM_FIELD_IFACE_ADDR;
}
vec[0].iov_base = &info;
vec[0].iov_len = sizeof(info);
vec[1].iov_base = buffer;
vec[1].iov_len = info.rkey_size + info.uct.dev_addr_len +
info.uct.iface_addr_len + info.uct.ep_addr_len;
rte_call(perf, post_vec, vec, 2, &req);
rte_call(perf, exchange_vec, req);
for (i = 0; i < group_size; ++i) {
if (i == group_index) {
continue;
}
rte_call(perf, recv, i, buffer, buffer_size, req);
remote_info = buffer;
rkey_buffer = remote_info + 1;
dev_addr = (void*)rkey_buffer + remote_info->rkey_size;
iface_addr = (void*)dev_addr + remote_info->uct.dev_addr_len;
ep_addr = (void*)iface_addr + remote_info->uct.iface_addr_len;
perf->uct.peers[i].remote_addr = remote_info->recv_buffer;
if (!uct_iface_is_reachable(perf->uct.iface, dev_addr,
remote_info->uct.iface_addr_len ?
iface_addr : NULL)) {
ucs_error("Destination is unreachable");
status = UCS_ERR_UNREACHABLE;
goto err_destroy_eps;
}
if (remote_info->rkey_size > 0) {
status = uct_rkey_unpack(perf->uct.cmpt, rkey_buffer,
&perf->uct.peers[i].rkey);
if (status != UCS_OK) {
ucs_error("Failed to uct_rkey_unpack: %s", ucs_status_string(status));
goto err_destroy_eps;
}
} else {
perf->uct.peers[i].rkey.handle = NULL;
perf->uct.peers[i].rkey.rkey = UCT_INVALID_RKEY;
}
if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_EP) {
status = uct_ep_connect_to_ep(perf->uct.peers[i].ep, dev_addr, ep_addr);
} else if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_IFACE) {
ep_params.dev_addr = dev_addr;
ep_params.iface_addr = iface_addr;
status = uct_ep_create(&ep_params, &perf->uct.peers[i].ep);
} else {
status = UCS_ERR_UNSUPPORTED;
}
if (status != UCS_OK) {
ucs_error("Failed to connect endpoint: %s", ucs_status_string(status));
goto err_destroy_eps;
}
}
uct_perf_iface_flush_b(perf);
free(buffer);
uct_perf_barrier(perf);
return UCS_OK;
err_destroy_eps:
for (i = 0; i < group_size; ++i) {
if (perf->uct.peers[i].rkey.rkey != UCT_INVALID_RKEY) {
uct_rkey_release(perf->uct.cmpt, &perf->uct.peers[i].rkey);
}
if (perf->uct.peers[i].ep != NULL) {
uct_ep_destroy(perf->uct.peers[i].ep);
}
}
free(perf->uct.peers);
err_free:
free(buffer);
err:
return status;
}
static void uct_perf_test_cleanup_endpoints(ucx_perf_context_t *perf)
{
unsigned group_size, group_index, i;
uct_perf_barrier(perf);
uct_iface_set_am_handler(perf->uct.iface, UCT_PERF_TEST_AM_ID, NULL, NULL, 0);
group_size = rte_call(perf, group_size);
group_index = rte_call(perf, group_index);
for (i = 0; i < group_size; ++i) {
if (i != group_index) {
if (perf->uct.peers[i].rkey.rkey != UCT_INVALID_RKEY) {
uct_rkey_release(perf->uct.cmpt, &perf->uct.peers[i].rkey);
}
if (perf->uct.peers[i].ep) {
uct_ep_destroy(perf->uct.peers[i].ep);
}
}
}
free(perf->uct.peers);
}
static ucs_status_t ucp_perf_test_fill_params(ucx_perf_params_t *params,
ucp_params_t *ucp_params)
{
ucs_status_t status, message_size;
message_size = ucx_perf_get_message_size(params);
switch (params->command) {
case UCX_PERF_CMD_PUT:
case UCX_PERF_CMD_GET:
ucp_params->features |= UCP_FEATURE_RMA;
break;
case UCX_PERF_CMD_ADD:
case UCX_PERF_CMD_FADD:
case UCX_PERF_CMD_SWAP:
case UCX_PERF_CMD_CSWAP:
if (message_size == sizeof(uint32_t)) {
ucp_params->features |= UCP_FEATURE_AMO32;
} else if (message_size == sizeof(uint64_t)) {
ucp_params->features |= UCP_FEATURE_AMO64;
} else {
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Atomic size should be either 32 or 64 bit");
}
return UCS_ERR_INVALID_PARAM;
}
break;
case UCX_PERF_CMD_TAG:
case UCX_PERF_CMD_TAG_SYNC:
ucp_params->features |= UCP_FEATURE_TAG;
ucp_params->field_mask |= UCP_PARAM_FIELD_REQUEST_SIZE;
ucp_params->request_size = sizeof(ucp_perf_request_t);
break;
case UCX_PERF_CMD_STREAM:
ucp_params->features |= UCP_FEATURE_STREAM;
ucp_params->field_mask |= UCP_PARAM_FIELD_REQUEST_SIZE;
ucp_params->request_size = sizeof(ucp_perf_request_t);
break;
default:
if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Invalid test command");
}
return UCS_ERR_INVALID_PARAM;
}
status = ucx_perf_test_check_params(params);
if (status != UCS_OK) {
return status;
}
return UCS_OK;
}
static ucs_status_t ucp_perf_test_alloc_iov_mem(ucp_perf_datatype_t datatype,
size_t iovcnt, unsigned thread_count,
ucp_dt_iov_t **iov_p)
{
ucp_dt_iov_t *iov;
if (UCP_PERF_DATATYPE_IOV == datatype) {
iov = malloc(sizeof(*iov) * iovcnt * thread_count);
if (NULL == iov) {
ucs_error("Failed allocate IOV buffer with iovcnt=%lu", iovcnt);
return UCS_ERR_NO_MEMORY;
}
*iov_p = iov;
}
return UCS_OK;
}
static ucs_status_t
ucp_perf_test_alloc_host(ucx_perf_context_t *perf, size_t length,
void **address_p, ucp_mem_h *memh, int non_blk_flag)
{
ucp_mem_map_params_t mem_map_params;
ucp_mem_attr_t mem_attr;
ucs_status_t status;
mem_map_params.field_mask = UCP_MEM_MAP_PARAM_FIELD_ADDRESS |
UCP_MEM_MAP_PARAM_FIELD_LENGTH |
UCP_MEM_MAP_PARAM_FIELD_FLAGS;
mem_map_params.address = *address_p;
mem_map_params.length = length;
mem_map_params.flags = UCP_MEM_MAP_ALLOCATE;
if (perf->params.flags & UCX_PERF_TEST_FLAG_MAP_NONBLOCK) {
mem_map_params.flags |= non_blk_flag;
}
status = ucp_mem_map(perf->ucp.context, &mem_map_params, memh);
if (status != UCS_OK) {
goto err;
}
mem_attr.field_mask = UCP_MEM_ATTR_FIELD_ADDRESS;
status = ucp_mem_query(*memh, &mem_attr);
if (status != UCS_OK) {
goto err;
}
*address_p = mem_attr.address;
return UCS_OK;
err:
return status;
}
static void ucp_perf_test_free_host(ucx_perf_context_t *perf, void *address,
ucp_mem_h memh)
{
ucs_status_t status;
status = ucp_mem_unmap(perf->ucp.context, memh);
if (status != UCS_OK) {
ucs_warn("ucp_mem_unmap() failed: %s", ucs_status_string(status));
}
}
static ucs_status_t ucp_perf_test_alloc_mem(ucx_perf_context_t *perf)
{
ucx_perf_params_t *params = &perf->params;
ucs_status_t status;
size_t buffer_size;
if (params->iov_stride) {
buffer_size = params->msg_size_cnt * params->iov_stride;
} else {
buffer_size = ucx_perf_get_message_size(params);
}
/* Allocate send buffer memory */
perf->send_buffer = NULL;
status = perf->allocator->ucp_alloc(perf, buffer_size * params->thread_count,
&perf->send_buffer, &perf->ucp.send_memh,
UCP_MEM_MAP_NONBLOCK);
if (status != UCS_OK) {
goto err;
}
/* Allocate receive buffer memory */
perf->recv_buffer = NULL;
status = perf->allocator->ucp_alloc(perf, buffer_size * params->thread_count,
&perf->recv_buffer, &perf->ucp.recv_memh,
0);
if (status != UCS_OK) {
goto err_free_send_buffer;
}
/* Allocate IOV datatype memory */
perf->ucp.send_iov = NULL;
status = ucp_perf_test_alloc_iov_mem(params->ucp.send_datatype,
perf->params.msg_size_cnt,
params->thread_count,
&perf->ucp.send_iov);
if (UCS_OK != status) {
goto err_free_buffers;
}
perf->ucp.recv_iov = NULL;
status = ucp_perf_test_alloc_iov_mem(params->ucp.recv_datatype,
perf->params.msg_size_cnt,
params->thread_count,
&perf->ucp.recv_iov);
if (UCS_OK != status) {
goto err_free_send_iov_buffers;
}
return UCS_OK;
err_free_send_iov_buffers:
free(perf->ucp.send_iov);
err_free_buffers:
perf->allocator->ucp_free(perf, perf->recv_buffer, perf->ucp.recv_memh);
err_free_send_buffer:
perf->allocator->ucp_free(perf, perf->send_buffer, perf->ucp.send_memh);
err:
return UCS_ERR_NO_MEMORY;
}
static void ucp_perf_test_free_mem(ucx_perf_context_t *perf)
{
free(perf->ucp.recv_iov);
free(perf->ucp.send_iov);
perf->allocator->ucp_free(perf, perf->recv_buffer, perf->ucp.recv_memh);
perf->allocator->ucp_free(perf, perf->send_buffer, perf->ucp.send_memh);
}
static void ucp_perf_test_destroy_eps(ucx_perf_context_t* perf,
unsigned group_size)
{
ucs_status_ptr_t *reqs;
ucp_tag_recv_info_t info;
ucs_status_t status;
unsigned i;
reqs = calloc(sizeof(*reqs), group_size);
for (i = 0; i < group_size; ++i) {
if (perf->ucp.peers[i].rkey != NULL) {
ucp_rkey_destroy(perf->ucp.peers[i].rkey);
}
if (perf->ucp.peers[i].ep != NULL) {
reqs[i] = ucp_disconnect_nb(perf->ucp.peers[i].ep);
}
}
for (i = 0; i < group_size; ++i) {
if (!UCS_PTR_IS_PTR(reqs[i])) {
continue;
}
do {
ucp_worker_progress(perf->ucp.worker);
status = ucp_request_test(reqs[i], &info);
} while (status == UCS_INPROGRESS);
ucp_request_release(reqs[i]);
}
free(reqs);
free(perf->ucp.peers);
}
static ucs_status_t ucp_perf_test_exchange_status(ucx_perf_context_t *perf,
ucs_status_t status)
{
unsigned group_size = rte_call(perf, group_size);
ucs_status_t collective_status = status;
struct iovec vec;
void *req = NULL;
unsigned i;
vec.iov_base = &status;
vec.iov_len = sizeof(status);
rte_call(perf, post_vec, &vec, 1, &req);
rte_call(perf, exchange_vec, req);
for (i = 0; i < group_size; ++i) {
rte_call(perf, recv, i, &status, sizeof(status), req);
if (status != UCS_OK) {
collective_status = status;
}
}
return collective_status;
}
static ucs_status_t ucp_perf_test_setup_endpoints(ucx_perf_context_t *perf,
uint64_t features)
{
const size_t buffer_size = 2048;
ucx_perf_ep_info_t info, *remote_info;
unsigned group_size, i, group_index;
ucp_address_t *address;
size_t address_length = 0;
ucp_ep_params_t ep_params;
ucs_status_t status;
struct iovec vec[3];
void *rkey_buffer;
void *req = NULL;
void *buffer;
group_size = rte_call(perf, group_size);
group_index = rte_call(perf, group_index);
status = ucp_worker_get_address(perf->ucp.worker, &address, &address_length);
if (status != UCS_OK) {
if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("ucp_worker_get_address() failed: %s", ucs_status_string(status));
}
goto err;
}
info.ucp.addr_len = address_length;
info.recv_buffer = (uintptr_t)perf->recv_buffer;
vec[0].iov_base = &info;
vec[0].iov_len = sizeof(info);
vec[1].iov_base = address;
vec[1].iov_len = address_length;
if (features & (UCP_FEATURE_RMA|UCP_FEATURE_AMO32|UCP_FEATURE_AMO64)) {
status = ucp_rkey_pack(perf->ucp.context, perf->ucp.recv_memh,
&rkey_buffer, &info.rkey_size);
if (status != UCS_OK) {
if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("ucp_rkey_pack() failed: %s", ucs_status_string(status));
}
ucp_worker_release_address(perf->ucp.worker, address);
goto err;
}
vec[2].iov_base = rkey_buffer;
vec[2].iov_len = info.rkey_size;
rte_call(perf, post_vec, vec, 3, &req);
ucp_rkey_buffer_release(rkey_buffer);
} else {
info.rkey_size = 0;
rte_call(perf, post_vec, vec, 2, &req);
}
ucp_worker_release_address(perf->ucp.worker, address);
rte_call(perf, exchange_vec, req);
perf->ucp.peers = calloc(group_size, sizeof(*perf->ucp.peers));
if (perf->ucp.peers == NULL) {
goto err;
}
buffer = malloc(buffer_size);
if (buffer == NULL) {
ucs_error("Failed to allocate RTE receive buffer");
status = UCS_ERR_NO_MEMORY;
goto err_destroy_eps;
}
for (i = 0; i < group_size; ++i) {
if (i == group_index) {
continue;
}
rte_call(perf, recv, i, buffer, buffer_size, req);
remote_info = buffer;
address = (void*)(remote_info + 1);
rkey_buffer = (void*)address + remote_info->ucp.addr_len;
perf->ucp.peers[i].remote_addr = remote_info->recv_buffer;
ep_params.field_mask = UCP_EP_PARAM_FIELD_REMOTE_ADDRESS;
ep_params.address = address;
status = ucp_ep_create(perf->ucp.worker, &ep_params, &perf->ucp.peers[i].ep);
if (status != UCS_OK) {
if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("ucp_ep_create() failed: %s", ucs_status_string(status));
}
goto err_free_buffer;
}
if (remote_info->rkey_size > 0) {
status = ucp_ep_rkey_unpack(perf->ucp.peers[i].ep, rkey_buffer,
&perf->ucp.peers[i].rkey);
if (status != UCS_OK) {
if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_fatal("ucp_rkey_unpack() failed: %s", ucs_status_string(status));
}
goto err_free_buffer;
}
} else {
perf->ucp.peers[i].rkey = NULL;
}
}
free(buffer);
status = ucp_perf_test_exchange_status(perf, UCS_OK);
if (status != UCS_OK) {
ucp_perf_test_destroy_eps(perf, group_size);
}
/* force wireup completion */
status = ucp_worker_flush(perf->ucp.worker);
if (status != UCS_OK) {
ucs_warn("ucp_worker_flush() failed: %s", ucs_status_string(status));
}
return status;
err_free_buffer:
free(buffer);
err_destroy_eps:
ucp_perf_test_destroy_eps(perf, group_size);
err:
(void)ucp_perf_test_exchange_status(perf, status);
return status;
}
static void ucp_perf_test_cleanup_endpoints(ucx_perf_context_t *perf)
{
unsigned group_size;
ucp_perf_barrier(perf);
group_size = rte_call(perf, group_size);
ucp_perf_test_destroy_eps(perf, group_size);
}
static void ucx_perf_set_warmup(ucx_perf_context_t* perf, ucx_perf_params_t* params)
{
perf->max_iter = ucs_min(params->warmup_iter, ucs_div_round_up(params->max_iter, 10));
perf->report_interval = -1;
}
static ucs_status_t uct_perf_create_md(ucx_perf_context_t *perf)
{
uct_component_h *uct_components;
uct_component_attr_t component_attr;
uct_tl_resource_desc_t *tl_resources;
unsigned md_index, num_components;
unsigned tl_index, num_tl_resources;
unsigned cmpt_index;
ucs_status_t status;
uct_md_h md;
uct_md_config_t *md_config;
status = uct_query_components(&uct_components, &num_components);
if (status != UCS_OK) {
goto out;
}
for (cmpt_index = 0; cmpt_index < num_components; ++cmpt_index) {
component_attr.field_mask = UCT_COMPONENT_ATTR_FIELD_MD_RESOURCE_COUNT;
status = uct_component_query(uct_components[cmpt_index], &component_attr);
if (status != UCS_OK) {
goto out_release_components_list;
}
component_attr.field_mask = UCT_COMPONENT_ATTR_FIELD_MD_RESOURCES;
component_attr.md_resources = alloca(sizeof(*component_attr.md_resources) *
component_attr.md_resource_count);
status = uct_component_query(uct_components[cmpt_index], &component_attr);
if (status != UCS_OK) {
goto out_release_components_list;
}
for (md_index = 0; md_index < component_attr.md_resource_count; ++md_index) {
status = uct_md_config_read(uct_components[cmpt_index], NULL, NULL,
&md_config);
if (status != UCS_OK) {
goto out_release_components_list;
}
status = uct_md_open(uct_components[cmpt_index],
component_attr.md_resources[md_index].md_name,
md_config, &md);
uct_config_release(md_config);
if (status != UCS_OK) {
goto out_release_components_list;
}
status = uct_md_query_tl_resources(md, &tl_resources, &num_tl_resources);
if (status != UCS_OK) {
uct_md_close(md);
goto out_release_components_list;
}
for (tl_index = 0; tl_index < num_tl_resources; ++tl_index) {
if (!strcmp(perf->params.uct.tl_name, tl_resources[tl_index].tl_name) &&
!strcmp(perf->params.uct.dev_name, tl_resources[tl_index].dev_name))
{
uct_release_tl_resource_list(tl_resources);
perf->uct.cmpt = uct_components[cmpt_index];
perf->uct.md = md;
status = UCS_OK;
goto out_release_components_list;
}
}
uct_md_close(md);
uct_release_tl_resource_list(tl_resources);
}
}
ucs_error("Cannot use transport %s on device %s", perf->params.uct.tl_name,
perf->params.uct.dev_name);
status = UCS_ERR_NO_DEVICE;
out_release_components_list:
uct_release_component_list(uct_components);
out:
return status;
}
void uct_perf_barrier(ucx_perf_context_t *perf)
{
rte_call(perf, barrier, (void(*)(void*))uct_worker_progress,
(void*)perf->uct.worker);
}
void ucp_perf_barrier(ucx_perf_context_t *perf)
{
rte_call(perf, barrier, (void(*)(void*))ucp_worker_progress,
(void*)perf->ucp.worker);
}
static ucs_status_t uct_perf_setup(ucx_perf_context_t *perf)
{
ucx_perf_params_t *params = &perf->params;
uct_iface_config_t *iface_config;
ucs_status_t status;
uct_iface_params_t iface_params = {
.field_mask = UCT_IFACE_PARAM_FIELD_OPEN_MODE |
UCT_IFACE_PARAM_FIELD_STATS_ROOT |
UCT_IFACE_PARAM_FIELD_RX_HEADROOM |
UCT_IFACE_PARAM_FIELD_CPU_MASK,
.open_mode = UCT_IFACE_OPEN_MODE_DEVICE,
.mode.device.tl_name = params->uct.tl_name,
.mode.device.dev_name = params->uct.dev_name,
.stats_root = ucs_stats_get_root(),
.rx_headroom = 0
};
UCS_CPU_ZERO(&iface_params.cpu_mask);
status = ucs_async_context_init(&perf->uct.async, params->async_mode);
if (status != UCS_OK) {
goto out;
}
status = uct_worker_create(&perf->uct.async, params->thread_mode,
&perf->uct.worker);
if (status != UCS_OK) {
goto out_cleanup_async;
}
status = uct_perf_create_md(perf);
if (status != UCS_OK) {
goto out_destroy_worker;
}
status = uct_md_iface_config_read(perf->uct.md, params->uct.tl_name, NULL,
NULL, &iface_config);
if (status != UCS_OK) {
goto out_destroy_md;
}
status = uct_iface_open(perf->uct.md, perf->uct.worker, &iface_params,
iface_config, &perf->uct.iface);
uct_config_release(iface_config);
if (status != UCS_OK) {
ucs_error("Failed to open iface: %s", ucs_status_string(status));
goto out_destroy_md;
}
status = uct_perf_test_check_capabilities(params, perf->uct.iface);
/* sync status across all processes */
status = ucp_perf_test_exchange_status(perf, status);
if (status != UCS_OK) {
goto out_iface_close;
}
status = uct_perf_test_alloc_mem(perf);
if (status != UCS_OK) {
goto out_iface_close;
}
/* Enable progress before `uct_iface_flush` and `uct_worker_progress` called
* to give a chance to finish connection for some tranports (ib/ud, tcp).
* They may return UCS_INPROGRESS from `uct_iface_flush` when connections are
* in progress */
uct_iface_progress_enable(perf->uct.iface,
UCT_PROGRESS_SEND | UCT_PROGRESS_RECV);
status = uct_perf_test_setup_endpoints(perf);
if (status != UCS_OK) {
ucs_error("Failed to setup endpoints: %s", ucs_status_string(status));
goto out_free_mem;
}
return UCS_OK;
out_free_mem:
uct_perf_test_free_mem(perf);
out_iface_close:
uct_iface_close(perf->uct.iface);
out_destroy_md:
uct_md_close(perf->uct.md);
out_destroy_worker:
uct_worker_destroy(perf->uct.worker);
out_cleanup_async:
ucs_async_context_cleanup(&perf->uct.async);
out:
return status;
}
static void uct_perf_cleanup(ucx_perf_context_t *perf)
{
uct_perf_test_cleanup_endpoints(perf);
uct_perf_test_free_mem(perf);
uct_iface_close(perf->uct.iface);
uct_md_close(perf->uct.md);
uct_worker_destroy(perf->uct.worker);
ucs_async_context_cleanup(&perf->uct.async);
}
static ucs_status_t ucp_perf_setup(ucx_perf_context_t *perf)
{
ucp_params_t ucp_params;
ucp_worker_params_t worker_params;
ucp_config_t *config;
ucs_status_t status;
ucp_params.field_mask = UCP_PARAM_FIELD_FEATURES;
ucp_params.features = 0;
status = ucp_perf_test_fill_params(&perf->params, &ucp_params);
if (status != UCS_OK) {
goto err;
}
status = ucp_config_read(NULL, NULL, &config);
if (status != UCS_OK) {
goto err;
}
status = ucp_init(&ucp_params, config, &perf->ucp.context);
ucp_config_release(config);
if (status != UCS_OK) {
goto err;
}
worker_params.field_mask = UCP_WORKER_PARAM_FIELD_THREAD_MODE;
worker_params.thread_mode = perf->params.thread_mode;
status = ucp_worker_create(perf->ucp.context, &worker_params,
&perf->ucp.worker);
if (status != UCS_OK) {
goto err_cleanup;
}
status = ucp_perf_test_alloc_mem(perf);
if (status != UCS_OK) {
ucs_warn("ucp test failed to alocate memory");
goto err_destroy_worker;
}
status = ucp_perf_test_setup_endpoints(perf, ucp_params.features);
if (status != UCS_OK) {
if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) {
ucs_error("Failed to setup endpoints: %s", ucs_status_string(status));
}
goto err_free_mem;
}
return UCS_OK;
err_free_mem:
ucp_perf_test_free_mem(perf);
err_destroy_worker:
ucp_worker_destroy(perf->ucp.worker);
err_cleanup:
ucp_cleanup(perf->ucp.context);
err:
return status;
}
static void ucp_perf_cleanup(ucx_perf_context_t *perf)
{
ucp_perf_test_cleanup_endpoints(perf);
ucp_perf_barrier(perf);
ucp_perf_test_free_mem(perf);
ucp_worker_destroy(perf->ucp.worker);
ucp_cleanup(perf->ucp.context);
}
static struct {
ucs_status_t (*setup)(ucx_perf_context_t *perf);
void (*cleanup)(ucx_perf_context_t *perf);
ucs_status_t (*run)(ucx_perf_context_t *perf);
void (*barrier)(ucx_perf_context_t *perf);
} ucx_perf_funcs[] = {
[UCX_PERF_API_UCT] = {uct_perf_setup, uct_perf_cleanup,
uct_perf_test_dispatch, uct_perf_barrier},
[UCX_PERF_API_UCP] = {ucp_perf_setup, ucp_perf_cleanup,
ucp_perf_test_dispatch, ucp_perf_barrier}
};
static int ucx_perf_thread_spawn(ucx_perf_context_t *perf,
ucx_perf_result_t* result);
ucs_status_t ucx_perf_run(ucx_perf_params_t *params, ucx_perf_result_t *result)
{
ucx_perf_context_t *perf;
ucs_status_t status;
ucx_perf_global_init();
if (params->command == UCX_PERF_CMD_LAST) {
ucs_error("Test is not selected");
status = UCS_ERR_INVALID_PARAM;
goto out;
}
if ((params->api != UCX_PERF_API_UCT) && (params->api != UCX_PERF_API_UCP)) {
ucs_error("Invalid test API parameter (should be UCT or UCP)");
status = UCS_ERR_INVALID_PARAM;
goto out;
}
perf = malloc(sizeof(*perf));
if (perf == NULL) {
status = UCS_ERR_NO_MEMORY;
goto out;
}
ucx_perf_test_init(perf, params);
if (perf->allocator == NULL) {
ucs_error("Unsupported memory type");
status = UCS_ERR_UNSUPPORTED;
goto out_free;
}
status = perf->allocator->init(perf);
if (status != UCS_OK) {
goto out_free;
}
status = ucx_perf_funcs[params->api].setup(perf);
if (status != UCS_OK) {
goto out_free;
}
if (UCS_THREAD_MODE_SINGLE == params->thread_mode) {
if (params->warmup_iter > 0) {
ucx_perf_set_warmup(perf, params);
status = ucx_perf_funcs[params->api].run(perf);
if (status != UCS_OK) {
goto out_cleanup;
}
ucx_perf_funcs[params->api].barrier(perf);
ucx_perf_test_prepare_new_run(perf, params);
}
/* Run test */
status = ucx_perf_funcs[params->api].run(perf);
ucx_perf_funcs[params->api].barrier(perf);
if (status == UCS_OK) {
ucx_perf_calc_result(perf, result);
rte_call(perf, report, result, perf->params.report_arg, 1);
}
} else {
status = ucx_perf_thread_spawn(perf, result);
}
out_cleanup:
ucx_perf_funcs[params->api].cleanup(perf);
out_free:
free(perf);
out:
return status;
}
#if _OPENMP
/* multiple threads sharing the same worker/iface */
typedef struct {
pthread_t pt;
int tid;
int ntid;
ucs_status_t* statuses;
ucx_perf_context_t perf;
ucx_perf_result_t result;
} ucx_perf_thread_context_t;
static void* ucx_perf_thread_run_test(void* arg)
{
ucx_perf_thread_context_t* tctx = (ucx_perf_thread_context_t*) arg;
ucx_perf_result_t* result = &tctx->result;
ucx_perf_context_t* perf = &tctx->perf;
ucx_perf_params_t* params = &perf->params;
ucs_status_t* statuses = tctx->statuses;
int tid = tctx->tid;
int i;
if (params->warmup_iter > 0) {
ucx_perf_set_warmup(perf, params);
statuses[tid] = ucx_perf_funcs[params->api].run(perf);
ucx_perf_funcs[params->api].barrier(perf);
for (i = 0; i < tctx->ntid; i++) {
if (UCS_OK != statuses[i]) {
goto out;
}
}
ucx_perf_test_prepare_new_run(perf, params);
}
/* Run test */
#pragma omp barrier
statuses[tid] = ucx_perf_funcs[params->api].run(perf);
ucx_perf_funcs[params->api].barrier(perf);
for (i = 0; i < tctx->ntid; i++) {
if (UCS_OK != statuses[i]) {
goto out;
}
}
#pragma omp master
{
/* Assuming all threads are fairly treated, reporting only tid==0
TODO: aggregate reports */
ucx_perf_calc_result(perf, result);
rte_call(perf, report, result, perf->params.report_arg, 1);
}
out:
return &statuses[tid];
}
static int ucx_perf_thread_spawn(ucx_perf_context_t *perf,
ucx_perf_result_t* result)
{
ucx_perf_thread_context_t* tctx;
ucs_status_t* statuses;
size_t message_size;
ucs_status_t status;
int ti, nti;
message_size = ucx_perf_get_message_size(&perf->params);
omp_set_num_threads(perf->params.thread_count);
nti = perf->params.thread_count;
tctx = calloc(nti, sizeof(ucx_perf_thread_context_t));
statuses = calloc(nti, sizeof(ucs_status_t));
if ((tctx == NULL) || (statuses == NULL)) {
status = UCS_ERR_NO_MEMORY;
goto out_free;
}
#pragma omp parallel private(ti)
{
ti = omp_get_thread_num();
tctx[ti].tid = ti;
tctx[ti].ntid = nti;
tctx[ti].statuses = statuses;
tctx[ti].perf = *perf;
/* Doctor the src and dst buffers to make them thread specific */
tctx[ti].perf.send_buffer += ti * message_size;
tctx[ti].perf.recv_buffer += ti * message_size;
tctx[ti].perf.offset = ti * message_size;
ucx_perf_thread_run_test((void*)&tctx[ti]);
}
status = UCS_OK;
for (ti = 0; ti < nti; ti++) {
if (UCS_OK != statuses[ti]) {
ucs_error("Thread %d failed to run test: %s", tctx[ti].tid,
ucs_status_string(statuses[ti]));
status = statuses[ti];
}
}
out_free:
free(statuses);
free(tctx);
return status;
}
#else
static int ucx_perf_thread_spawn(ucx_perf_context_t *perf,
ucx_perf_result_t* result) {
ucs_error("Invalid test parameter (thread mode requested without OpenMP capabilities)");
return UCS_ERR_INVALID_PARAM;
}
#endif /* _OPENMP */
void ucx_perf_global_init()
{
static ucx_perf_allocator_t host_allocator = {
.init = ucs_empty_function_return_success,
.ucp_alloc = ucp_perf_test_alloc_host,
.ucp_free = ucp_perf_test_free_host,
.memset = memset
};
UCS_MODULE_FRAMEWORK_DECLARE(ucx_perftest);
ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_HOST] = &host_allocator;
/* FIXME Memtype allocator modules must be loaded to global scope, otherwise
* alloc hooks, which are using dlsym() to get pointer to original function,
* do not work. Need to use bistro for memtype hooks to fix it.
*/
UCS_MODULE_FRAMEWORK_LOAD(ucx_perftest, UCS_MODULE_LOAD_FLAG_GLOBAL);
}
|
ASTMatchers.h | //===- ASTMatchers.h - Structural query framework ---------------*- 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 implements matchers to be used together with the MatchFinder to
// match AST nodes.
//
// Matchers are created by generator functions, which can be combined in
// a functional in-language DSL to express queries over the C++ AST.
//
// For example, to match a class with a certain name, one would call:
// cxxRecordDecl(hasName("MyClass"))
// which returns a matcher that can be used to find all AST nodes that declare
// a class named 'MyClass'.
//
// For more complicated match expressions we're often interested in accessing
// multiple parts of the matched AST nodes once a match is found. In that case,
// call `.bind("name")` on match expressions that match the nodes you want to
// access.
//
// For example, when we're interested in child classes of a certain class, we
// would write:
// cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child")))
// When the match is found via the MatchFinder, a user provided callback will
// be called with a BoundNodes instance that contains a mapping from the
// strings that we provided for the `.bind()` calls to the nodes that were
// matched.
// In the given example, each time our matcher finds a match we get a callback
// where "child" is bound to the RecordDecl node of the matching child
// class declaration.
//
// See ASTMatchersInternal.h for a more in-depth explanation of the
// implementation details of the matcher framework.
//
// See ASTMatchFinder.h for how to use the generated matchers to run over
// an AST.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/LambdaCapture.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/ParentMapContext.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtOpenMP.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/ASTMatchers/ASTMatchersInternal.h"
#include "clang/ASTMatchers/ASTMatchersMacros.h"
#include "clang/Basic/AttrKinds.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TypeTraits.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Regex.h"
#include <cassert>
#include <cstddef>
#include <iterator>
#include <limits>
#include <string>
#include <utility>
#include <vector>
namespace clang {
namespace ast_matchers {
/// Maps string IDs to AST nodes matched by parts of a matcher.
///
/// The bound nodes are generated by calling \c bind("id") on the node matchers
/// of the nodes we want to access later.
///
/// The instances of BoundNodes are created by \c MatchFinder when the user's
/// callbacks are executed every time a match is found.
class BoundNodes {
public:
/// Returns the AST node bound to \c ID.
///
/// Returns NULL if there was no node bound to \c ID or if there is a node but
/// it cannot be converted to the specified type.
template <typename T>
const T *getNodeAs(StringRef ID) const {
return MyBoundNodes.getNodeAs<T>(ID);
}
/// Type of mapping from binding identifiers to bound nodes. This type
/// is an associative container with a key type of \c std::string and a value
/// type of \c clang::DynTypedNode
using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
/// Retrieve mapping from binding identifiers to bound nodes.
const IDToNodeMap &getMap() const {
return MyBoundNodes.getMap();
}
private:
friend class internal::BoundNodesTreeBuilder;
/// Create BoundNodes from a pre-filled map of bindings.
BoundNodes(internal::BoundNodesMap &MyBoundNodes)
: MyBoundNodes(MyBoundNodes) {}
internal::BoundNodesMap MyBoundNodes;
};
/// Types of matchers for the top-level classes in the AST class
/// hierarchy.
/// @{
using DeclarationMatcher = internal::Matcher<Decl>;
using StatementMatcher = internal::Matcher<Stmt>;
using TypeMatcher = internal::Matcher<QualType>;
using TypeLocMatcher = internal::Matcher<TypeLoc>;
using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
/// @}
/// Matches any node.
///
/// Useful when another matcher requires a child matcher, but there's no
/// additional constraint. This will often be used with an explicit conversion
/// to an \c internal::Matcher<> type such as \c TypeMatcher.
///
/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
/// \code
/// "int* p" and "void f()" in
/// int* p;
/// void f();
/// \endcode
///
/// Usable as: Any Matcher
inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
/// Matches the top declaration context.
///
/// Given
/// \code
/// int X;
/// namespace NS {
/// int Y;
/// } // namespace NS
/// \endcode
/// decl(hasDeclContext(translationUnitDecl()))
/// matches "int X", but not "int Y".
extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
translationUnitDecl;
/// Matches typedef declarations.
///
/// Given
/// \code
/// typedef int X;
/// using Y = int;
/// \endcode
/// typedefDecl()
/// matches "typedef int X", but not "using Y = int"
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
typedefDecl;
/// Matches typedef name declarations.
///
/// Given
/// \code
/// typedef int X;
/// using Y = int;
/// \endcode
/// typedefNameDecl()
/// matches "typedef int X" and "using Y = int"
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
typedefNameDecl;
/// Matches type alias declarations.
///
/// Given
/// \code
/// typedef int X;
/// using Y = int;
/// \endcode
/// typeAliasDecl()
/// matches "using Y = int", but not "typedef int X"
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
typeAliasDecl;
/// Matches type alias template declarations.
///
/// typeAliasTemplateDecl() matches
/// \code
/// template <typename T>
/// using Y = X<T>;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
typeAliasTemplateDecl;
/// Matches AST nodes that were expanded within the main-file.
///
/// Example matches X but not Y
/// (matcher = cxxRecordDecl(isExpansionInMainFile())
/// \code
/// #include <Y.h>
/// class X {};
/// \endcode
/// Y.h:
/// \code
/// class Y {};
/// \endcode
///
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
auto &SourceManager = Finder->getASTContext().getSourceManager();
return SourceManager.isInMainFile(
SourceManager.getExpansionLoc(Node.getBeginLoc()));
}
/// Matches AST nodes that were expanded within system-header-files.
///
/// Example matches Y but not X
/// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
/// \code
/// #include <SystemHeader.h>
/// class X {};
/// \endcode
/// SystemHeader.h:
/// \code
/// class Y {};
/// \endcode
///
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
auto &SourceManager = Finder->getASTContext().getSourceManager();
auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
if (ExpansionLoc.isInvalid()) {
return false;
}
return SourceManager.isInSystemHeader(ExpansionLoc);
}
/// Matches AST nodes that were expanded within files whose name is
/// partially matching a given regex.
///
/// Example matches Y but not X
/// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
/// \code
/// #include "ASTMatcher.h"
/// class X {};
/// \endcode
/// ASTMatcher.h:
/// \code
/// class Y {};
/// \endcode
///
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt,
TypeLoc),
RegExp) {
auto &SourceManager = Finder->getASTContext().getSourceManager();
auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
if (ExpansionLoc.isInvalid()) {
return false;
}
auto FileEntry =
SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
if (!FileEntry) {
return false;
}
auto Filename = FileEntry->getName();
return RegExp->match(Filename);
}
/// Matches statements that are (transitively) expanded from the named macro.
/// Does not match if only part of the statement is expanded from that macro or
/// if different parts of the the statement are expanded from different
/// appearances of the macro.
///
/// FIXME: Change to be a polymorphic matcher that works on any syntactic
/// node. There's nothing `Stmt`-specific about it.
AST_MATCHER_P(Stmt, isExpandedFromMacro, llvm::StringRef, MacroName) {
// Verifies that the statement' beginning and ending are both expanded from
// the same instance of the given macro.
auto& Context = Finder->getASTContext();
llvm::Optional<SourceLocation> B =
internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
if (!B) return false;
llvm::Optional<SourceLocation> E =
internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
if (!E) return false;
return *B == *E;
}
/// Matches declarations.
///
/// Examples matches \c X, \c C, and the friend declaration inside \c C;
/// \code
/// void X();
/// class C {
/// friend X;
/// };
/// \endcode
extern const internal::VariadicAllOfMatcher<Decl> decl;
/// Matches a declaration of a linkage specification.
///
/// Given
/// \code
/// extern "C" {}
/// \endcode
/// linkageSpecDecl()
/// matches "extern "C" {}"
extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
linkageSpecDecl;
/// Matches a declaration of anything that could have a name.
///
/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
/// \code
/// typedef int X;
/// struct S {
/// union {
/// int i;
/// } U;
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
/// Matches a declaration of label.
///
/// Given
/// \code
/// goto FOO;
/// FOO: bar();
/// \endcode
/// labelDecl()
/// matches 'FOO:'
extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
/// Matches a declaration of a namespace.
///
/// Given
/// \code
/// namespace {}
/// namespace test {}
/// \endcode
/// namespaceDecl()
/// matches "namespace {}" and "namespace test {}"
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
namespaceDecl;
/// Matches a declaration of a namespace alias.
///
/// Given
/// \code
/// namespace test {}
/// namespace alias = ::test;
/// \endcode
/// namespaceAliasDecl()
/// matches "namespace alias" but not "namespace test"
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
namespaceAliasDecl;
/// Matches class, struct, and union declarations.
///
/// Example matches \c X, \c Z, \c U, and \c S
/// \code
/// class X;
/// template<class T> class Z {};
/// struct S {};
/// union U {};
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
/// Matches C++ class declarations.
///
/// Example matches \c X, \c Z
/// \code
/// class X;
/// template<class T> class Z {};
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
cxxRecordDecl;
/// Matches C++ class template declarations.
///
/// Example matches \c Z
/// \code
/// template<class T> class Z {};
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
classTemplateDecl;
/// Matches C++ class template specializations.
///
/// Given
/// \code
/// template<typename T> class A {};
/// template<> class A<double> {};
/// A<int> a;
/// \endcode
/// classTemplateSpecializationDecl()
/// matches the specializations \c A<int> and \c A<double>
extern const internal::VariadicDynCastAllOfMatcher<
Decl, ClassTemplateSpecializationDecl>
classTemplateSpecializationDecl;
/// Matches C++ class template partial specializations.
///
/// Given
/// \code
/// template<class T1, class T2, int I>
/// class A {};
///
/// template<class T, int I>
/// class A<T, T*, I> {};
///
/// template<>
/// class A<int, int, 1> {};
/// \endcode
/// classTemplatePartialSpecializationDecl()
/// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
extern const internal::VariadicDynCastAllOfMatcher<
Decl, ClassTemplatePartialSpecializationDecl>
classTemplatePartialSpecializationDecl;
/// Matches declarator declarations (field, variable, function
/// and non-type template parameter declarations).
///
/// Given
/// \code
/// class X { int y; };
/// \endcode
/// declaratorDecl()
/// matches \c int y.
extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
declaratorDecl;
/// Matches parameter variable declarations.
///
/// Given
/// \code
/// void f(int x);
/// \endcode
/// parmVarDecl()
/// matches \c int x.
extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
parmVarDecl;
/// Matches C++ access specifier declarations.
///
/// Given
/// \code
/// class C {
/// public:
/// int a;
/// };
/// \endcode
/// accessSpecDecl()
/// matches 'public:'
extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
accessSpecDecl;
/// Matches constructor initializers.
///
/// Examples matches \c i(42).
/// \code
/// class C {
/// C() : i(42) {}
/// int i;
/// };
/// \endcode
extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
cxxCtorInitializer;
/// Matches template arguments.
///
/// Given
/// \code
/// template <typename T> struct C {};
/// C<int> c;
/// \endcode
/// templateArgument()
/// matches 'int' in C<int>.
extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
/// Matches template name.
///
/// Given
/// \code
/// template <typename T> class X { };
/// X<int> xi;
/// \endcode
/// templateName()
/// matches 'X' in X<int>.
extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
/// Matches non-type template parameter declarations.
///
/// Given
/// \code
/// template <typename T, int N> struct C {};
/// \endcode
/// nonTypeTemplateParmDecl()
/// matches 'N', but not 'T'.
extern const internal::VariadicDynCastAllOfMatcher<Decl,
NonTypeTemplateParmDecl>
nonTypeTemplateParmDecl;
/// Matches template type parameter declarations.
///
/// Given
/// \code
/// template <typename T, int N> struct C {};
/// \endcode
/// templateTypeParmDecl()
/// matches 'T', but not 'N'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
templateTypeParmDecl;
/// Matches public C++ declarations and C++ base specifers that specify public
/// inheritance.
///
/// Examples:
/// \code
/// class C {
/// public: int a; // fieldDecl(isPublic()) matches 'a'
/// protected: int b;
/// private: int c;
/// };
/// \endcode
///
/// \code
/// class Base {};
/// class Derived1 : public Base {}; // matches 'Base'
/// struct Derived2 : Base {}; // matches 'Base'
/// \endcode
AST_POLYMORPHIC_MATCHER(isPublic,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
CXXBaseSpecifier)) {
return getAccessSpecifier(Node) == AS_public;
}
/// Matches protected C++ declarations and C++ base specifers that specify
/// protected inheritance.
///
/// Examples:
/// \code
/// class C {
/// public: int a;
/// protected: int b; // fieldDecl(isProtected()) matches 'b'
/// private: int c;
/// };
/// \endcode
///
/// \code
/// class Base {};
/// class Derived : protected Base {}; // matches 'Base'
/// \endcode
AST_POLYMORPHIC_MATCHER(isProtected,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
CXXBaseSpecifier)) {
return getAccessSpecifier(Node) == AS_protected;
}
/// Matches private C++ declarations and C++ base specifers that specify private
/// inheritance.
///
/// Examples:
/// \code
/// class C {
/// public: int a;
/// protected: int b;
/// private: int c; // fieldDecl(isPrivate()) matches 'c'
/// };
/// \endcode
///
/// \code
/// struct Base {};
/// struct Derived1 : private Base {}; // matches 'Base'
/// class Derived2 : Base {}; // matches 'Base'
/// \endcode
AST_POLYMORPHIC_MATCHER(isPrivate,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
CXXBaseSpecifier)) {
return getAccessSpecifier(Node) == AS_private;
}
/// Matches non-static data members that are bit-fields.
///
/// Given
/// \code
/// class C {
/// int a : 2;
/// int b;
/// };
/// \endcode
/// fieldDecl(isBitField())
/// matches 'int a;' but not 'int b;'.
AST_MATCHER(FieldDecl, isBitField) {
return Node.isBitField();
}
/// Matches non-static data members that are bit-fields of the specified
/// bit width.
///
/// Given
/// \code
/// class C {
/// int a : 2;
/// int b : 4;
/// int c : 2;
/// };
/// \endcode
/// fieldDecl(hasBitWidth(2))
/// matches 'int a;' and 'int c;' but not 'int b;'.
AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
return Node.isBitField() &&
Node.getBitWidthValue(Finder->getASTContext()) == Width;
}
/// Matches non-static data members that have an in-class initializer.
///
/// Given
/// \code
/// class C {
/// int a = 2;
/// int b = 3;
/// int c;
/// };
/// \endcode
/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
/// matches 'int a;' but not 'int b;'.
/// fieldDecl(hasInClassInitializer(anything()))
/// matches 'int a;' and 'int b;' but not 'int c;'.
AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *Initializer = Node.getInClassInitializer();
return (Initializer != nullptr &&
InnerMatcher.matches(*Initializer, Finder, Builder));
}
/// Determines whether the function is "main", which is the entry point
/// into an executable program.
AST_MATCHER(FunctionDecl, isMain) {
return Node.isMain();
}
/// Matches the specialized template of a specialization declaration.
///
/// Given
/// \code
/// template<typename T> class A {}; #1
/// template<> class A<int> {}; #2
/// \endcode
/// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
/// matches '#2' with classTemplateDecl() matching the class template
/// declaration of 'A' at #1.
AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
return (Decl != nullptr &&
InnerMatcher.matches(*Decl, Finder, Builder));
}
/// Matches a declaration that has been implicitly added
/// by the compiler (eg. implicit default/copy constructors).
AST_MATCHER(Decl, isImplicit) {
return Node.isImplicit();
}
/// Matches classTemplateSpecializations, templateSpecializationType and
/// functionDecl that have at least one TemplateArgument matching the given
/// InnerMatcher.
///
/// Given
/// \code
/// template<typename T> class A {};
/// template<> class A<double> {};
/// A<int> a;
///
/// template<typename T> f() {};
/// void func() { f<int>(); };
/// \endcode
///
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToType(asString("int"))))
/// matches the specialization \c A<int>
///
/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
/// matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P(
hasAnyTemplateArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
TemplateSpecializationType,
FunctionDecl),
internal::Matcher<TemplateArgument>, InnerMatcher) {
ArrayRef<TemplateArgument> List =
internal::getTemplateSpecializationArgs(Node);
return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
Builder);
}
/// Causes all nested matchers to be matched with the specified traversal kind.
///
/// Given
/// \code
/// void foo()
/// {
/// int i = 3.0;
/// }
/// \endcode
/// The matcher
/// \code
/// traverse(TK_IgnoreImplicitCastsAndParentheses,
/// varDecl(hasInitializer(floatLiteral().bind("init")))
/// )
/// \endcode
/// matches the variable declaration with "init" bound to the "3.0".
template <typename T>
internal::Matcher<T> traverse(TraversalKind TK,
const internal::Matcher<T> &InnerMatcher) {
return internal::DynTypedMatcher::constructRestrictedWrapper(
new internal::TraversalMatcher<T>(TK, InnerMatcher),
InnerMatcher.getID().first)
.template unconditionalConvertTo<T>();
}
template <typename T>
internal::BindableMatcher<T>
traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
return internal::BindableMatcher<T>(
internal::DynTypedMatcher::constructRestrictedWrapper(
new internal::TraversalMatcher<T>(TK, InnerMatcher),
InnerMatcher.getID().first)
.template unconditionalConvertTo<T>());
}
template <typename... T>
internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
traverse(TraversalKind TK,
const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
TK, InnerMatcher);
}
template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
typename T, typename ToTypes>
internal::TraversalWrapper<
internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
return internal::TraversalWrapper<
internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
ToTypes>>(TK, InnerMatcher);
}
template <template <typename T, typename P1> class MatcherT, typename P1,
typename ReturnTypesF>
internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam1<
MatcherT, P1, ReturnTypesF> &InnerMatcher) {
return internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>(
TK, InnerMatcher);
}
template <template <typename T, typename P1, typename P2> class MatcherT,
typename P1, typename P2, typename ReturnTypesF>
internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam2<
MatcherT, P1, P2, ReturnTypesF> &InnerMatcher) {
return internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>(
TK, InnerMatcher);
}
/// Matches expressions that match InnerMatcher after any implicit AST
/// nodes are stripped off.
///
/// Parentheses and explicit casts are not discarded.
/// Given
/// \code
/// class C {};
/// C a = C();
/// C b;
/// C c = b;
/// \endcode
/// The matchers
/// \code
/// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
/// \endcode
/// would match the declarations for a, b, and c.
/// While
/// \code
/// varDecl(hasInitializer(cxxConstructExpr()))
/// \endcode
/// only match the declarations for b and c.
AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
}
/// Matches expressions that match InnerMatcher after any implicit casts
/// are stripped off.
///
/// Parentheses and explicit casts are not discarded.
/// Given
/// \code
/// int arr[5];
/// int a = 0;
/// char b = 0;
/// const int c = a;
/// int *d = arr;
/// long e = (long) 0l;
/// \endcode
/// The matchers
/// \code
/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
/// \endcode
/// would match the declarations for a, b, c, and d, but not e.
/// While
/// \code
/// varDecl(hasInitializer(integerLiteral()))
/// varDecl(hasInitializer(declRefExpr()))
/// \endcode
/// only match the declarations for b, c, and d.
AST_MATCHER_P(Expr, ignoringImpCasts,
internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
}
/// Matches expressions that match InnerMatcher after parentheses and
/// casts are stripped off.
///
/// Implicit and non-C Style casts are also discarded.
/// Given
/// \code
/// int a = 0;
/// char b = (0);
/// void* c = reinterpret_cast<char*>(0);
/// char d = char(0);
/// \endcode
/// The matcher
/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
/// would match the declarations for a, b, c, and d.
/// while
/// varDecl(hasInitializer(integerLiteral()))
/// only match the declaration for a.
AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
}
/// Matches expressions that match InnerMatcher after implicit casts and
/// parentheses are stripped off.
///
/// Explicit casts are not discarded.
/// Given
/// \code
/// int arr[5];
/// int a = 0;
/// char b = (0);
/// const int c = a;
/// int *d = (arr);
/// long e = ((long) 0l);
/// \endcode
/// The matchers
/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
/// would match the declarations for a, b, c, and d, but not e.
/// while
/// varDecl(hasInitializer(integerLiteral()))
/// varDecl(hasInitializer(declRefExpr()))
/// would only match the declaration for a.
AST_MATCHER_P(Expr, ignoringParenImpCasts,
internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
}
/// Matches types that match InnerMatcher after any parens are stripped.
///
/// Given
/// \code
/// void (*fp)(void);
/// \endcode
/// The matcher
/// \code
/// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
/// \endcode
/// would match the declaration for fp.
AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
InnerMatcher, 0) {
return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
}
/// Overload \c ignoringParens for \c Expr.
///
/// Given
/// \code
/// const char* str = ("my-string");
/// \endcode
/// The matcher
/// \code
/// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
/// \endcode
/// would match the implicit cast resulting from the assignment.
AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
InnerMatcher, 1) {
const Expr *E = Node.IgnoreParens();
return InnerMatcher.matches(*E, Finder, Builder);
}
/// Matches expressions that are instantiation-dependent even if it is
/// neither type- nor value-dependent.
///
/// In the following example, the expression sizeof(sizeof(T() + T()))
/// is instantiation-dependent (since it involves a template parameter T),
/// but is neither type- nor value-dependent, since the type of the inner
/// sizeof is known (std::size_t) and therefore the size of the outer
/// sizeof is known.
/// \code
/// template<typename T>
/// void f(T x, T y) { sizeof(sizeof(T() + T()); }
/// \endcode
/// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
AST_MATCHER(Expr, isInstantiationDependent) {
return Node.isInstantiationDependent();
}
/// Matches expressions that are type-dependent because the template type
/// is not yet instantiated.
///
/// For example, the expressions "x" and "x + y" are type-dependent in
/// the following code, but "y" is not type-dependent:
/// \code
/// template<typename T>
/// void add(T x, int y) {
/// x + y;
/// }
/// \endcode
/// expr(isTypeDependent()) matches x + y
AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
/// Matches expression that are value-dependent because they contain a
/// non-type template parameter.
///
/// For example, the array bound of "Chars" in the following example is
/// value-dependent.
/// \code
/// template<int Size> int f() { return Size; }
/// \endcode
/// expr(isValueDependent()) matches return Size
AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
/// Matches classTemplateSpecializations, templateSpecializationType and
/// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
///
/// Given
/// \code
/// template<typename T, typename U> class A {};
/// A<bool, int> b;
/// A<int, bool> c;
///
/// template<typename T> void f() {}
/// void func() { f<int>(); };
/// \endcode
/// classTemplateSpecializationDecl(hasTemplateArgument(
/// 1, refersToType(asString("int"))))
/// matches the specialization \c A<bool, int>
///
/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
/// matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P2(
hasTemplateArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
TemplateSpecializationType,
FunctionDecl),
unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
ArrayRef<TemplateArgument> List =
internal::getTemplateSpecializationArgs(Node);
if (List.size() <= N)
return false;
return InnerMatcher.matches(List[N], Finder, Builder);
}
/// Matches if the number of template arguments equals \p N.
///
/// Given
/// \code
/// template<typename T> struct C {};
/// C<int> c;
/// \endcode
/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
/// matches C<int>.
AST_POLYMORPHIC_MATCHER_P(
templateArgumentCountIs,
AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
TemplateSpecializationType),
unsigned, N) {
return internal::getTemplateSpecializationArgs(Node).size() == N;
}
/// Matches a TemplateArgument that refers to a certain type.
///
/// Given
/// \code
/// struct X {};
/// template<typename T> struct A {};
/// A<X> a;
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToType(class(hasName("X")))))
/// matches the specialization \c A<X>
AST_MATCHER_P(TemplateArgument, refersToType,
internal::Matcher<QualType>, InnerMatcher) {
if (Node.getKind() != TemplateArgument::Type)
return false;
return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
}
/// Matches a TemplateArgument that refers to a certain template.
///
/// Given
/// \code
/// template<template <typename> class S> class X {};
/// template<typename T> class Y {};
/// X<Y> xi;
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToTemplate(templateName())))
/// matches the specialization \c X<Y>
AST_MATCHER_P(TemplateArgument, refersToTemplate,
internal::Matcher<TemplateName>, InnerMatcher) {
if (Node.getKind() != TemplateArgument::Template)
return false;
return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
}
/// Matches a canonical TemplateArgument that refers to a certain
/// declaration.
///
/// Given
/// \code
/// struct B { int next; };
/// template<int(B::*next_ptr)> struct A {};
/// A<&B::next> a;
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToDeclaration(fieldDecl(hasName("next")))))
/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
/// \c B::next
AST_MATCHER_P(TemplateArgument, refersToDeclaration,
internal::Matcher<Decl>, InnerMatcher) {
if (Node.getKind() == TemplateArgument::Declaration)
return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
return false;
}
/// Matches a sugar TemplateArgument that refers to a certain expression.
///
/// Given
/// \code
/// struct B { int next; };
/// template<int(B::*next_ptr)> struct A {};
/// A<&B::next> a;
/// \endcode
/// templateSpecializationType(hasAnyTemplateArgument(
/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
/// \c B::next
AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
if (Node.getKind() == TemplateArgument::Expression)
return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
return false;
}
/// Matches a TemplateArgument that is an integral value.
///
/// Given
/// \code
/// template<int T> struct C {};
/// C<42> c;
/// \endcode
/// classTemplateSpecializationDecl(
/// hasAnyTemplateArgument(isIntegral()))
/// matches the implicit instantiation of C in C<42>
/// with isIntegral() matching 42.
AST_MATCHER(TemplateArgument, isIntegral) {
return Node.getKind() == TemplateArgument::Integral;
}
/// Matches a TemplateArgument that referes to an integral type.
///
/// Given
/// \code
/// template<int T> struct C {};
/// C<42> c;
/// \endcode
/// classTemplateSpecializationDecl(
/// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
/// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument, refersToIntegralType,
internal::Matcher<QualType>, InnerMatcher) {
if (Node.getKind() != TemplateArgument::Integral)
return false;
return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
}
/// Matches a TemplateArgument of integral type with a given value.
///
/// Note that 'Value' is a string as the template argument's value is
/// an arbitrary precision integer. 'Value' must be euqal to the canonical
/// representation of that integral value in base 10.
///
/// Given
/// \code
/// template<int T> struct C {};
/// C<42> c;
/// \endcode
/// classTemplateSpecializationDecl(
/// hasAnyTemplateArgument(equalsIntegralValue("42")))
/// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
std::string, Value) {
if (Node.getKind() != TemplateArgument::Integral)
return false;
return Node.getAsIntegral().toString(10) == Value;
}
/// Matches an Objective-C autorelease pool statement.
///
/// Given
/// \code
/// @autoreleasepool {
/// int x = 0;
/// }
/// \endcode
/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
/// inside the autorelease pool.
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
/// Matches any value declaration.
///
/// Example matches A, B, C and F
/// \code
/// enum X { A, B, C };
/// void F();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
/// Matches C++ constructor declarations.
///
/// Example matches Foo::Foo() and Foo::Foo(int)
/// \code
/// class Foo {
/// public:
/// Foo();
/// Foo(int);
/// int DoSomething();
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
cxxConstructorDecl;
/// Matches explicit C++ destructor declarations.
///
/// Example matches Foo::~Foo()
/// \code
/// class Foo {
/// public:
/// virtual ~Foo();
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
cxxDestructorDecl;
/// Matches enum declarations.
///
/// Example matches X
/// \code
/// enum X {
/// A, B, C
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
/// Matches enum constants.
///
/// Example matches A, B, C
/// \code
/// enum X {
/// A, B, C
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
enumConstantDecl;
/// Matches tag declarations.
///
/// Example matches X, Z, U, S, E
/// \code
/// class X;
/// template<class T> class Z {};
/// struct S {};
/// union U {};
/// enum E {
/// A, B, C
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
/// Matches method declarations.
///
/// Example matches y
/// \code
/// class X { void y(); };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
cxxMethodDecl;
/// Matches conversion operator declarations.
///
/// Example matches the operator.
/// \code
/// class X { operator int() const; };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
cxxConversionDecl;
/// Matches user-defined and implicitly generated deduction guide.
///
/// Example matches the deduction guide.
/// \code
/// template<typename T>
/// class X { X(int) };
/// X(int) -> X<int>;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
cxxDeductionGuideDecl;
/// Matches variable declarations.
///
/// Note: this does not match declarations of member variables, which are
/// "field" declarations in Clang parlance.
///
/// Example matches a
/// \code
/// int a;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
/// Matches field declarations.
///
/// Given
/// \code
/// class X { int m; };
/// \endcode
/// fieldDecl()
/// matches 'm'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
/// Matches indirect field declarations.
///
/// Given
/// \code
/// struct X { struct { int a; }; };
/// \endcode
/// indirectFieldDecl()
/// matches 'a'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
indirectFieldDecl;
/// Matches function declarations.
///
/// Example matches f
/// \code
/// void f();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
functionDecl;
/// Matches C++ function template declarations.
///
/// Example matches f
/// \code
/// template<class T> void f(T t) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
functionTemplateDecl;
/// Matches friend declarations.
///
/// Given
/// \code
/// class X { friend void foo(); };
/// \endcode
/// friendDecl()
/// matches 'friend void foo()'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
/// Matches statements.
///
/// Given
/// \code
/// { ++a; }
/// \endcode
/// stmt()
/// matches both the compound statement '{ ++a; }' and '++a'.
extern const internal::VariadicAllOfMatcher<Stmt> stmt;
/// Matches declaration statements.
///
/// Given
/// \code
/// int a;
/// \endcode
/// declStmt()
/// matches 'int a'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
/// Matches member expressions.
///
/// Given
/// \code
/// class Y {
/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
/// int a; static int b;
/// };
/// \endcode
/// memberExpr()
/// matches this->x, x, y.x, a, this->b
extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
/// Matches unresolved member expressions.
///
/// Given
/// \code
/// struct X {
/// template <class T> void f();
/// void g();
/// };
/// template <class T> void h() { X x; x.f<T>(); x.g(); }
/// \endcode
/// unresolvedMemberExpr()
/// matches x.f<T>
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
unresolvedMemberExpr;
/// Matches member expressions where the actual member referenced could not be
/// resolved because the base expression or the member name was dependent.
///
/// Given
/// \code
/// template <class T> void f() { T t; t.g(); }
/// \endcode
/// cxxDependentScopeMemberExpr()
/// matches t.g
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
CXXDependentScopeMemberExpr>
cxxDependentScopeMemberExpr;
/// Matches call expressions.
///
/// Example matches x.y() and y()
/// \code
/// X x;
/// x.y();
/// y();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
/// Matches call expressions which were resolved using ADL.
///
/// Example matches y(x) but not y(42) or NS::y(x).
/// \code
/// namespace NS {
/// struct X {};
/// void y(X);
/// }
///
/// void y(...);
///
/// void test() {
/// NS::X x;
/// y(x); // Matches
/// NS::y(x); // Doesn't match
/// y(42); // Doesn't match
/// using NS::y;
/// y(x); // Found by both unqualified lookup and ADL, doesn't match
// }
/// \endcode
AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
/// Matches lambda expressions.
///
/// Example matches [&](){return 5;}
/// \code
/// [&](){return 5;}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
/// Matches member call expressions.
///
/// Example matches x.y()
/// \code
/// X x;
/// x.y();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
cxxMemberCallExpr;
/// Matches ObjectiveC Message invocation expressions.
///
/// The innermost message send invokes the "alloc" class method on the
/// NSString class, while the outermost message send invokes the
/// "initWithString" instance method on the object returned from
/// NSString's "alloc". This matcher should match both message sends.
/// \code
/// [[NSString alloc] initWithString:@"Hello"]
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
objcMessageExpr;
/// Matches Objective-C interface declarations.
///
/// Example matches Foo
/// \code
/// @interface Foo
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
objcInterfaceDecl;
/// Matches Objective-C implementation declarations.
///
/// Example matches Foo
/// \code
/// @implementation Foo
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
objcImplementationDecl;
/// Matches Objective-C protocol declarations.
///
/// Example matches FooDelegate
/// \code
/// @protocol FooDelegate
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
objcProtocolDecl;
/// Matches Objective-C category declarations.
///
/// Example matches Foo (Additions)
/// \code
/// @interface Foo (Additions)
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
objcCategoryDecl;
/// Matches Objective-C category definitions.
///
/// Example matches Foo (Additions)
/// \code
/// @implementation Foo (Additions)
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
objcCategoryImplDecl;
/// Matches Objective-C method declarations.
///
/// Example matches both declaration and definition of -[Foo method]
/// \code
/// @interface Foo
/// - (void)method;
/// @end
///
/// @implementation Foo
/// - (void)method {}
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
objcMethodDecl;
/// Matches block declarations.
///
/// Example matches the declaration of the nameless block printing an input
/// integer.
///
/// \code
/// myFunc(^(int p) {
/// printf("%d", p);
/// })
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
blockDecl;
/// Matches Objective-C instance variable declarations.
///
/// Example matches _enabled
/// \code
/// @implementation Foo {
/// BOOL _enabled;
/// }
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
objcIvarDecl;
/// Matches Objective-C property declarations.
///
/// Example matches enabled
/// \code
/// @interface Foo
/// @property BOOL enabled;
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
objcPropertyDecl;
/// Matches Objective-C \@throw statements.
///
/// Example matches \@throw
/// \code
/// @throw obj;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
objcThrowStmt;
/// Matches Objective-C @try statements.
///
/// Example matches @try
/// \code
/// @try {}
/// @catch (...) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
objcTryStmt;
/// Matches Objective-C @catch statements.
///
/// Example matches @catch
/// \code
/// @try {}
/// @catch (...) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
objcCatchStmt;
/// Matches Objective-C @finally statements.
///
/// Example matches @finally
/// \code
/// @try {}
/// @finally {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
objcFinallyStmt;
/// Matches expressions that introduce cleanups to be run at the end
/// of the sub-expression's evaluation.
///
/// Example matches std::string()
/// \code
/// const std::string str = std::string();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
exprWithCleanups;
/// Matches init list expressions.
///
/// Given
/// \code
/// int a[] = { 1, 2 };
/// struct B { int x, y; };
/// B b = { 5, 6 };
/// \endcode
/// initListExpr()
/// matches "{ 1, 2 }" and "{ 5, 6 }"
extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
initListExpr;
/// Matches the syntactic form of init list expressions
/// (if expression have it).
AST_MATCHER_P(InitListExpr, hasSyntacticForm,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *SyntForm = Node.getSyntacticForm();
return (SyntForm != nullptr &&
InnerMatcher.matches(*SyntForm, Finder, Builder));
}
/// Matches C++ initializer list expressions.
///
/// Given
/// \code
/// std::vector<int> a({ 1, 2, 3 });
/// std::vector<int> b = { 4, 5 };
/// int c[] = { 6, 7 };
/// std::pair<int, int> d = { 8, 9 };
/// \endcode
/// cxxStdInitializerListExpr()
/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
CXXStdInitializerListExpr>
cxxStdInitializerListExpr;
/// Matches implicit initializers of init list expressions.
///
/// Given
/// \code
/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
/// \endcode
/// implicitValueInitExpr()
/// matches "[0].y" (implicitly)
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
implicitValueInitExpr;
/// Matches paren list expressions.
/// ParenListExprs don't have a predefined type and are used for late parsing.
/// In the final AST, they can be met in template declarations.
///
/// Given
/// \code
/// template<typename T> class X {
/// void f() {
/// X x(*this);
/// int a = 0, b = 1; int i = (a, b);
/// }
/// };
/// \endcode
/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
/// has a predefined type and is a ParenExpr, not a ParenListExpr.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
parenListExpr;
/// Matches substitutions of non-type template parameters.
///
/// Given
/// \code
/// template <int N>
/// struct A { static const int n = N; };
/// struct B : public A<42> {};
/// \endcode
/// substNonTypeTemplateParmExpr()
/// matches "N" in the right-hand side of "static const int n = N;"
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
SubstNonTypeTemplateParmExpr>
substNonTypeTemplateParmExpr;
/// Matches using declarations.
///
/// Given
/// \code
/// namespace X { int x; }
/// using X::x;
/// \endcode
/// usingDecl()
/// matches \code using X::x \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
/// Matches using namespace declarations.
///
/// Given
/// \code
/// namespace X { int x; }
/// using namespace X;
/// \endcode
/// usingDirectiveDecl()
/// matches \code using namespace X \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
usingDirectiveDecl;
/// Matches reference to a name that can be looked up during parsing
/// but could not be resolved to a specific declaration.
///
/// Given
/// \code
/// template<typename T>
/// T foo() { T a; return a; }
/// template<typename T>
/// void bar() {
/// foo<T>();
/// }
/// \endcode
/// unresolvedLookupExpr()
/// matches \code foo<T>() \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
unresolvedLookupExpr;
/// Matches unresolved using value declarations.
///
/// Given
/// \code
/// template<typename X>
/// class C : private X {
/// using X::x;
/// };
/// \endcode
/// unresolvedUsingValueDecl()
/// matches \code using X::x \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl,
UnresolvedUsingValueDecl>
unresolvedUsingValueDecl;
/// Matches unresolved using value declarations that involve the
/// typename.
///
/// Given
/// \code
/// template <typename T>
/// struct Base { typedef T Foo; };
///
/// template<typename T>
/// struct S : private Base<T> {
/// using typename Base<T>::Foo;
/// };
/// \endcode
/// unresolvedUsingTypenameDecl()
/// matches \code using Base<T>::Foo \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl,
UnresolvedUsingTypenameDecl>
unresolvedUsingTypenameDecl;
/// Matches a constant expression wrapper.
///
/// Example matches the constant in the case statement:
/// (matcher = constantExpr())
/// \code
/// switch (a) {
/// case 37: break;
/// }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
constantExpr;
/// Matches parentheses used in expressions.
///
/// Example matches (foo() + 1)
/// \code
/// int foo() { return 1; }
/// int a = (foo() + 1);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
/// Matches constructor call expressions (including implicit ones).
///
/// Example matches string(ptr, n) and ptr within arguments of f
/// (matcher = cxxConstructExpr())
/// \code
/// void f(const string &a, const string &b);
/// char *ptr;
/// int n;
/// f(string(ptr, n), ptr);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
cxxConstructExpr;
/// Matches unresolved constructor call expressions.
///
/// Example matches T(t) in return statement of f
/// (matcher = cxxUnresolvedConstructExpr())
/// \code
/// template <typename T>
/// void f(const T& t) { return T(t); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
CXXUnresolvedConstructExpr>
cxxUnresolvedConstructExpr;
/// Matches implicit and explicit this expressions.
///
/// Example matches the implicit this expression in "return i".
/// (matcher = cxxThisExpr())
/// \code
/// struct foo {
/// int i;
/// int f() { return i; }
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
cxxThisExpr;
/// Matches nodes where temporaries are created.
///
/// Example matches FunctionTakesString(GetStringByValue())
/// (matcher = cxxBindTemporaryExpr())
/// \code
/// FunctionTakesString(GetStringByValue());
/// FunctionTakesStringByPointer(GetStringPointer());
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
cxxBindTemporaryExpr;
/// Matches nodes where temporaries are materialized.
///
/// Example: Given
/// \code
/// struct T {void func();};
/// T f();
/// void g(T);
/// \endcode
/// materializeTemporaryExpr() matches 'f()' in these statements
/// \code
/// T u(f());
/// g(f());
/// f().func();
/// \endcode
/// but does not match
/// \code
/// f();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
MaterializeTemporaryExpr>
materializeTemporaryExpr;
/// Matches new expressions.
///
/// Given
/// \code
/// new X;
/// \endcode
/// cxxNewExpr()
/// matches 'new X'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
/// Matches delete expressions.
///
/// Given
/// \code
/// delete X;
/// \endcode
/// cxxDeleteExpr()
/// matches 'delete X'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
cxxDeleteExpr;
/// Matches noexcept expressions.
///
/// Given
/// \code
/// bool a() noexcept;
/// bool b() noexcept(true);
/// bool c() noexcept(false);
/// bool d() noexcept(noexcept(a()));
/// bool e = noexcept(b()) || noexcept(c());
/// \endcode
/// cxxNoexceptExpr()
/// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
/// doesn't match the noexcept specifier in the declarations a, b, c or d.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
cxxNoexceptExpr;
/// Matches array subscript expressions.
///
/// Given
/// \code
/// int i = a[1];
/// \endcode
/// arraySubscriptExpr()
/// matches "a[1]"
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
arraySubscriptExpr;
/// Matches the value of a default argument at the call site.
///
/// Example matches the CXXDefaultArgExpr placeholder inserted for the
/// default value of the second parameter in the call expression f(42)
/// (matcher = cxxDefaultArgExpr())
/// \code
/// void f(int x, int y = 0);
/// f(42);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
cxxDefaultArgExpr;
/// Matches overloaded operator calls.
///
/// Note that if an operator isn't overloaded, it won't match. Instead, use
/// binaryOperator matcher.
/// Currently it does not match operators such as new delete.
/// FIXME: figure out why these do not match?
///
/// Example matches both operator<<((o << b), c) and operator<<(o, b)
/// (matcher = cxxOperatorCallExpr())
/// \code
/// ostream &operator<< (ostream &out, int i) { };
/// ostream &o; int b = 1, c = 1;
/// o << b << c;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
cxxOperatorCallExpr;
/// Matches expressions.
///
/// Example matches x()
/// \code
/// void f() { x(); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
/// Matches expressions that refer to declarations.
///
/// Example matches x in if (x)
/// \code
/// bool x;
/// if (x) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
declRefExpr;
/// Matches a reference to an ObjCIvar.
///
/// Example: matches "a" in "init" method:
/// \code
/// @implementation A {
/// NSString *a;
/// }
/// - (void) init {
/// a = @"hello";
/// }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
objcIvarRefExpr;
/// Matches a reference to a block.
///
/// Example: matches "^{}":
/// \code
/// void f() { ^{}(); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
/// Matches if statements.
///
/// Example matches 'if (x) {}'
/// \code
/// if (x) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
/// Matches for statements.
///
/// Example matches 'for (;;) {}'
/// \code
/// for (;;) {}
/// int i[] = {1, 2, 3}; for (auto a : i);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
/// Matches the increment statement of a for loop.
///
/// Example:
/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
/// matches '++x' in
/// \code
/// for (x; x < N; ++x) { }
/// \endcode
AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
InnerMatcher) {
const Stmt *const Increment = Node.getInc();
return (Increment != nullptr &&
InnerMatcher.matches(*Increment, Finder, Builder));
}
/// Matches the initialization statement of a for loop.
///
/// Example:
/// forStmt(hasLoopInit(declStmt()))
/// matches 'int x = 0' in
/// \code
/// for (int x = 0; x < N; ++x) { }
/// \endcode
AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
InnerMatcher) {
const Stmt *const Init = Node.getInit();
return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
}
/// Matches range-based for statements.
///
/// cxxForRangeStmt() matches 'for (auto a : i)'
/// \code
/// int i[] = {1, 2, 3}; for (auto a : i);
/// for(int j = 0; j < 5; ++j);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
cxxForRangeStmt;
/// Matches the initialization statement of a for loop.
///
/// Example:
/// forStmt(hasLoopVariable(anything()))
/// matches 'int x' in
/// \code
/// for (int x : a) { }
/// \endcode
AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
InnerMatcher) {
const VarDecl *const Var = Node.getLoopVariable();
return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
}
/// Matches the range initialization statement of a for loop.
///
/// Example:
/// forStmt(hasRangeInit(anything()))
/// matches 'a' in
/// \code
/// for (int x : a) { }
/// \endcode
AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *const Init = Node.getRangeInit();
return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
}
/// Matches while statements.
///
/// Given
/// \code
/// while (true) {}
/// \endcode
/// whileStmt()
/// matches 'while (true) {}'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
/// Matches do statements.
///
/// Given
/// \code
/// do {} while (true);
/// \endcode
/// doStmt()
/// matches 'do {} while(true)'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
/// Matches break statements.
///
/// Given
/// \code
/// while (true) { break; }
/// \endcode
/// breakStmt()
/// matches 'break'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
/// Matches continue statements.
///
/// Given
/// \code
/// while (true) { continue; }
/// \endcode
/// continueStmt()
/// matches 'continue'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
continueStmt;
/// Matches return statements.
///
/// Given
/// \code
/// return 1;
/// \endcode
/// returnStmt()
/// matches 'return 1'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
/// Matches goto statements.
///
/// Given
/// \code
/// goto FOO;
/// FOO: bar();
/// \endcode
/// gotoStmt()
/// matches 'goto FOO'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
/// Matches label statements.
///
/// Given
/// \code
/// goto FOO;
/// FOO: bar();
/// \endcode
/// labelStmt()
/// matches 'FOO:'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
/// Matches address of label statements (GNU extension).
///
/// Given
/// \code
/// FOO: bar();
/// void *ptr = &&FOO;
/// goto *bar;
/// \endcode
/// addrLabelExpr()
/// matches '&&FOO'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
addrLabelExpr;
/// Matches switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// switchStmt()
/// matches 'switch(a)'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
/// Matches case and default statements inside switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// switchCase()
/// matches 'case 42:' and 'default:'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
/// Matches case statements inside switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// caseStmt()
/// matches 'case 42:'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
/// Matches default statements inside switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// defaultStmt()
/// matches 'default:'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
defaultStmt;
/// Matches compound statements.
///
/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
/// \code
/// for (;;) {{}}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
compoundStmt;
/// Matches catch statements.
///
/// \code
/// try {} catch(int i) {}
/// \endcode
/// cxxCatchStmt()
/// matches 'catch(int i)'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
cxxCatchStmt;
/// Matches try statements.
///
/// \code
/// try {} catch(int i) {}
/// \endcode
/// cxxTryStmt()
/// matches 'try {}'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
/// Matches throw expressions.
///
/// \code
/// try { throw 5; } catch(int i) {}
/// \endcode
/// cxxThrowExpr()
/// matches 'throw 5'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
cxxThrowExpr;
/// Matches null statements.
///
/// \code
/// foo();;
/// \endcode
/// nullStmt()
/// matches the second ';'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
/// Matches asm statements.
///
/// \code
/// int i = 100;
/// __asm("mov al, 2");
/// \endcode
/// asmStmt()
/// matches '__asm("mov al, 2")'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
/// Matches bool literals.
///
/// Example matches true
/// \code
/// true
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
cxxBoolLiteral;
/// Matches string literals (also matches wide string literals).
///
/// Example matches "abcd", L"abcd"
/// \code
/// char *s = "abcd";
/// wchar_t *ws = L"abcd";
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
stringLiteral;
/// Matches character literals (also matches wchar_t).
///
/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
/// though.
///
/// Example matches 'a', L'a'
/// \code
/// char ch = 'a';
/// wchar_t chw = L'a';
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
characterLiteral;
/// Matches integer literals of all sizes / encodings, e.g.
/// 1, 1L, 0x1 and 1U.
///
/// Does not match character-encoded integers such as L'a'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
integerLiteral;
/// Matches float literals of all sizes / encodings, e.g.
/// 1.0, 1.0f, 1.0L and 1e10.
///
/// Does not match implicit conversions such as
/// \code
/// float a = 10;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
floatLiteral;
/// Matches imaginary literals, which are based on integer and floating
/// point literals e.g.: 1i, 1.0i
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
imaginaryLiteral;
/// Matches fixed point literals
extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
fixedPointLiteral;
/// Matches user defined literal operator call.
///
/// Example match: "foo"_suffix
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
userDefinedLiteral;
/// Matches compound (i.e. non-scalar) literals
///
/// Example match: {1}, (1, 2)
/// \code
/// int array[4] = {1};
/// vector int myvec = (vector int)(1, 2);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
compoundLiteralExpr;
/// Matches nullptr literal.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
cxxNullPtrLiteralExpr;
/// Matches GNU __builtin_choose_expr.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
chooseExpr;
/// Matches GNU __null expression.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
gnuNullExpr;
/// Matches atomic builtins.
/// Example matches __atomic_load_n(ptr, 1)
/// \code
/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
/// Matches statement expression (GNU extension).
///
/// Example match: ({ int X = 4; X; })
/// \code
/// int C = ({ int X = 4; X; });
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
/// Matches binary operator expressions.
///
/// Example matches a || b
/// \code
/// !(a || b)
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
binaryOperator;
/// Matches unary operator expressions.
///
/// Example matches !a
/// \code
/// !a || b
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
unaryOperator;
/// Matches conditional operator expressions.
///
/// Example matches a ? b : c
/// \code
/// (a ? b : c) + 42
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
conditionalOperator;
/// Matches binary conditional operator expressions (GNU extension).
///
/// Example matches a ?: b
/// \code
/// (a ?: b) + 42;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
BinaryConditionalOperator>
binaryConditionalOperator;
/// Matches opaque value expressions. They are used as helpers
/// to reference another expressions and can be met
/// in BinaryConditionalOperators, for example.
///
/// Example matches 'a'
/// \code
/// (a ?: c) + 42;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
opaqueValueExpr;
/// Matches a C++ static_assert declaration.
///
/// Example:
/// staticAssertExpr()
/// matches
/// static_assert(sizeof(S) == sizeof(int))
/// in
/// \code
/// struct S {
/// int x;
/// };
/// static_assert(sizeof(S) == sizeof(int));
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
staticAssertDecl;
/// Matches a reinterpret_cast expression.
///
/// Either the source expression or the destination type can be matched
/// using has(), but hasDestinationType() is more specific and can be
/// more readable.
///
/// Example matches reinterpret_cast<char*>(&p) in
/// \code
/// void* p = reinterpret_cast<char*>(&p);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
cxxReinterpretCastExpr;
/// Matches a C++ static_cast expression.
///
/// \see hasDestinationType
/// \see reinterpretCast
///
/// Example:
/// cxxStaticCastExpr()
/// matches
/// static_cast<long>(8)
/// in
/// \code
/// long eight(static_cast<long>(8));
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
cxxStaticCastExpr;
/// Matches a dynamic_cast expression.
///
/// Example:
/// cxxDynamicCastExpr()
/// matches
/// dynamic_cast<D*>(&b);
/// in
/// \code
/// struct B { virtual ~B() {} }; struct D : B {};
/// B b;
/// D* p = dynamic_cast<D*>(&b);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
cxxDynamicCastExpr;
/// Matches a const_cast expression.
///
/// Example: Matches const_cast<int*>(&r) in
/// \code
/// int n = 42;
/// const int &r(n);
/// int* p = const_cast<int*>(&r);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
cxxConstCastExpr;
/// Matches a C-style cast expression.
///
/// Example: Matches (int) 2.2f in
/// \code
/// int i = (int) 2.2f;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
cStyleCastExpr;
/// Matches explicit cast expressions.
///
/// Matches any cast expression written in user code, whether it be a
/// C-style cast, a functional-style cast, or a keyword cast.
///
/// Does not match implicit conversions.
///
/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
/// Clang uses the term "cast" to apply to implicit conversions as well as to
/// actual cast expressions.
///
/// \see hasDestinationType.
///
/// Example: matches all five of the casts in
/// \code
/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
/// \endcode
/// but does not match the implicit conversion in
/// \code
/// long ell = 42;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
explicitCastExpr;
/// Matches the implicit cast nodes of Clang's AST.
///
/// This matches many different places, including function call return value
/// eliding, as well as any type conversions.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
implicitCastExpr;
/// Matches any cast nodes of Clang's AST.
///
/// Example: castExpr() matches each of the following:
/// \code
/// (int) 3;
/// const_cast<Expr *>(SubExpr);
/// char c = 0;
/// \endcode
/// but does not match
/// \code
/// int i = (0);
/// int k = 0;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
/// Matches functional cast expressions
///
/// Example: Matches Foo(bar);
/// \code
/// Foo f = bar;
/// Foo g = (Foo) bar;
/// Foo h = Foo(bar);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
cxxFunctionalCastExpr;
/// Matches functional cast expressions having N != 1 arguments
///
/// Example: Matches Foo(bar, bar)
/// \code
/// Foo h = Foo(bar, bar);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
cxxTemporaryObjectExpr;
/// Matches predefined identifier expressions [C99 6.4.2.2].
///
/// Example: Matches __func__
/// \code
/// printf("%s", __func__);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
predefinedExpr;
/// Matches C99 designated initializer expressions [C99 6.7.8].
///
/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
/// \code
/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
designatedInitExpr;
/// Matches designated initializer expressions that contain
/// a specific number of designators.
///
/// Example: Given
/// \code
/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
/// \endcode
/// designatorCountIs(2)
/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
return Node.size() == N;
}
/// Matches \c QualTypes in the clang AST.
extern const internal::VariadicAllOfMatcher<QualType> qualType;
/// Matches \c Types in the clang AST.
extern const internal::VariadicAllOfMatcher<Type> type;
/// Matches \c TypeLocs in the clang AST.
extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
/// Matches if any of the given matchers matches.
///
/// Unlike \c anyOf, \c eachOf will generate a match result for each
/// matching submatcher.
///
/// For example, in:
/// \code
/// class A { int a; int b; };
/// \endcode
/// The matcher:
/// \code
/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
/// has(fieldDecl(hasName("b")).bind("v"))))
/// \endcode
/// will generate two results binding "v", the first of which binds
/// the field declaration of \c a, the second the field declaration of
/// \c b.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<
2, std::numeric_limits<unsigned>::max()>
eachOf;
/// Matches if any of the given matchers matches.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<
2, std::numeric_limits<unsigned>::max()>
anyOf;
/// Matches if all given matchers match.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<
2, std::numeric_limits<unsigned>::max()>
allOf;
/// Matches any node regardless of the submatcher.
///
/// However, \c optionally will retain any bindings generated by the submatcher.
/// Useful when additional information which may or may not present about a main
/// matching node is desired.
///
/// For example, in:
/// \code
/// class Foo {
/// int bar;
/// }
/// \endcode
/// The matcher:
/// \code
/// cxxRecordDecl(
/// optionally(has(
/// fieldDecl(hasName("bar")).bind("var")
/// ))).bind("record")
/// \endcode
/// will produce a result binding for both "record" and "var".
/// The matcher will produce a "record" binding for even if there is no data
/// member named "bar" in that class.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
///
/// Given
/// \code
/// Foo x = bar;
/// int y = sizeof(x) + alignof(x);
/// \endcode
/// unaryExprOrTypeTraitExpr()
/// matches \c sizeof(x) and \c alignof(x)
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
UnaryExprOrTypeTraitExpr>
unaryExprOrTypeTraitExpr;
/// Matches unary expressions that have a specific type of argument.
///
/// Given
/// \code
/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
/// \endcode
/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
/// matches \c sizeof(a) and \c alignof(c)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
internal::Matcher<QualType>, InnerMatcher) {
const QualType ArgumentType = Node.getTypeOfArgument();
return InnerMatcher.matches(ArgumentType, Finder, Builder);
}
/// Matches unary expressions of a certain kind.
///
/// Given
/// \code
/// int x;
/// int s = sizeof(x) + alignof(x)
/// \endcode
/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
/// matches \c sizeof(x)
///
/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
return Node.getKind() == Kind;
}
/// Same as unaryExprOrTypeTraitExpr, but only matching
/// alignof.
inline internal::BindableMatcher<Stmt> alignOfExpr(
const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
return stmt(unaryExprOrTypeTraitExpr(
allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
InnerMatcher)));
}
/// Same as unaryExprOrTypeTraitExpr, but only matching
/// sizeof.
inline internal::BindableMatcher<Stmt> sizeOfExpr(
const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
return stmt(unaryExprOrTypeTraitExpr(
allOf(ofKind(UETT_SizeOf), InnerMatcher)));
}
/// Matches NamedDecl nodes that have the specified name.
///
/// Supports specifying enclosing namespaces or classes by prefixing the name
/// with '<enclosing>::'.
/// Does not match typedefs of an underlying type with the given name.
///
/// Example matches X (Name == "X")
/// \code
/// class X;
/// \endcode
///
/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
/// \code
/// namespace a { namespace b { class X; } }
/// \endcode
inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
return internal::Matcher<NamedDecl>(
new internal::HasNameMatcher({std::string(Name)}));
}
/// Matches NamedDecl nodes that have any of the specified names.
///
/// This matcher is only provided as a performance optimization of hasName.
/// \code
/// hasAnyName(a, b, c)
/// \endcode
/// is equivalent to, but faster than
/// \code
/// anyOf(hasName(a), hasName(b), hasName(c))
/// \endcode
extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
internal::hasAnyNameFunc>
hasAnyName;
/// Matches NamedDecl nodes whose fully qualified names contain
/// a substring matched by the given RegExp.
///
/// Supports specifying enclosing namespaces or classes by
/// prefixing the name with '<enclosing>::'. Does not match typedefs
/// of an underlying type with the given name.
///
/// Example matches X (regexp == "::X")
/// \code
/// class X;
/// \endcode
///
/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
/// \code
/// namespace foo { namespace bar { class X; } }
/// \endcode
AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
std::string FullNameString = "::" + Node.getQualifiedNameAsString();
return RegExp->match(FullNameString);
}
/// Matches overloaded operator names.
///
/// Matches overloaded operator names specified in strings without the
/// "operator" prefix: e.g. "<<".
///
/// Given:
/// \code
/// class A { int operator*(); };
/// const A &operator<<(const A &a, const A &b);
/// A a;
/// a << a; // <-- This matches
/// \endcode
///
/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
/// specified line and
/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
/// matches the declaration of \c A.
///
/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
inline internal::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
hasOverloadedOperatorName(StringRef Name) {
return internal::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(
{std::string(Name)});
}
/// Matches overloaded operator names.
///
/// Matches overloaded operator names specified in strings without the
/// "operator" prefix: e.g. "<<".
///
/// hasAnyOverloadesOperatorName("+", "-")
/// Is equivalent to
/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
extern const internal::VariadicFunction<
internal::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>,
StringRef, internal::hasAnyOverloadedOperatorNameFunc>
hasAnyOverloadedOperatorName;
/// Matches C++ classes that are directly or indirectly derived from a class
/// matching \c Base, or Objective-C classes that directly or indirectly
/// subclass a class matching \c Base.
///
/// Note that a class is not considered to be derived from itself.
///
/// Example matches Y, Z, C (Base == hasName("X"))
/// \code
/// class X;
/// class Y : public X {}; // directly derived
/// class Z : public Y {}; // indirectly derived
/// typedef X A;
/// typedef A B;
/// class C : public B {}; // derived from a typedef of X
/// \endcode
///
/// In the following example, Bar matches isDerivedFrom(hasName("X")):
/// \code
/// class Foo;
/// typedef Foo X;
/// class Bar : public Foo {}; // derived from a type that X is a typedef of
/// \endcode
///
/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
/// \code
/// @interface NSObject @end
/// @interface Bar : NSObject @end
/// \endcode
///
/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
AST_POLYMORPHIC_MATCHER_P(
isDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
internal::Matcher<NamedDecl>, Base) {
// Check if the node is a C++ struct/union/class.
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
// The node must be an Objective-C class.
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
/*Directly=*/false);
}
/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
std::string, BaseName, 1) {
if (BaseName.empty())
return false;
const auto M = isDerivedFrom(hasName(BaseName));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Matches C++ classes that have a direct or indirect base matching \p
/// BaseSpecMatcher.
///
/// Example:
/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
/// \code
/// class Foo;
/// class Bar : Foo {};
/// class Baz : Bar {};
/// class SpecialBase;
/// class Proxy : SpecialBase {}; // matches Proxy
/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
/// \endcode
///
// FIXME: Refactor this and isDerivedFrom to reuse implementation.
AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
BaseSpecMatcher) {
return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
}
/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
///
/// Example:
/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
/// \code
/// class Foo;
/// class Bar : Foo {};
/// class Baz : Bar {};
/// class SpecialBase;
/// class Proxy : SpecialBase {}; // matches Proxy
/// class IndirectlyDerived : Proxy {}; // doesn't match
/// \endcode
AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
BaseSpecMatcher) {
return Node.hasDefinition() &&
llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
return BaseSpecMatcher.matches(Base, Finder, Builder);
});
}
/// Similar to \c isDerivedFrom(), but also matches classes that directly
/// match \c Base.
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isSameOrDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
internal::Matcher<NamedDecl>, Base, 0) {
const auto M = anyOf(Base, isDerivedFrom(Base));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Overloaded method as shortcut for
/// \c isSameOrDerivedFrom(hasName(...)).
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isSameOrDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
std::string, BaseName, 1) {
if (BaseName.empty())
return false;
const auto M = isSameOrDerivedFrom(hasName(BaseName));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Matches C++ or Objective-C classes that are directly derived from a class
/// matching \c Base.
///
/// Note that a class is not considered to be derived from itself.
///
/// Example matches Y, C (Base == hasName("X"))
/// \code
/// class X;
/// class Y : public X {}; // directly derived
/// class Z : public Y {}; // indirectly derived
/// typedef X A;
/// typedef A B;
/// class C : public B {}; // derived from a typedef of X
/// \endcode
///
/// In the following example, Bar matches isDerivedFrom(hasName("X")):
/// \code
/// class Foo;
/// typedef Foo X;
/// class Bar : public Foo {}; // derived from a type that X is a typedef of
/// \endcode
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isDirectlyDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
internal::Matcher<NamedDecl>, Base, 0) {
// Check if the node is a C++ struct/union/class.
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
// The node must be an Objective-C class.
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
/*Directly=*/true);
}
/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isDirectlyDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
std::string, BaseName, 1) {
if (BaseName.empty())
return false;
const auto M = isDirectlyDerivedFrom(hasName(BaseName));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Matches the first method of a class or struct that satisfies \c
/// InnerMatcher.
///
/// Given:
/// \code
/// class A { void func(); };
/// class B { void member(); };
/// \endcode
///
/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
/// \c A but not \c B.
AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
Node.method_end(), Finder, Builder);
}
/// Matches the generated class of lambda expressions.
///
/// Given:
/// \code
/// auto x = []{};
/// \endcode
///
/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
/// \c decltype(x)
AST_MATCHER(CXXRecordDecl, isLambda) {
return Node.isLambda();
}
/// Matches AST nodes that have child AST nodes that match the
/// provided matcher.
///
/// Example matches X, Y
/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
/// \code
/// class X {}; // Matches X, because X::X is a class of name X inside X.
/// class Y { class X {}; };
/// class Z { class Y { class X {}; }; }; // Does not match Z.
/// \endcode
///
/// ChildT must be an AST base type.
///
/// Usable as: Any Matcher
/// Note that has is direct matcher, so it also matches things like implicit
/// casts and paren casts. If you are matching with expr then you should
/// probably consider using ignoringParenImpCasts like:
/// has(ignoringParenImpCasts(expr())).
extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
/// Matches AST nodes that have descendant AST nodes that match the
/// provided matcher.
///
/// Example matches X, Y, Z
/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
/// \code
/// class X {}; // Matches X, because X::X is a class of name X inside X.
/// class Y { class X {}; };
/// class Z { class Y { class X {}; }; };
/// \endcode
///
/// DescendantT must be an AST base type.
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::HasDescendantMatcher>
hasDescendant;
/// Matches AST nodes that have child AST nodes that match the
/// provided matcher.
///
/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
/// \code
/// class X {};
/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
/// // inside Y.
/// class Z { class Y { class X {}; }; }; // Does not match Z.
/// \endcode
///
/// ChildT must be an AST base type.
///
/// As opposed to 'has', 'forEach' will cause a match for each result that
/// matches instead of only on the first one.
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
forEach;
/// Matches AST nodes that have descendant AST nodes that match the
/// provided matcher.
///
/// Example matches X, A, A::X, B, B::C, B::C::X
/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
/// \code
/// class X {};
/// class A { class X {}; }; // Matches A, because A::X is a class of name
/// // X inside A.
/// class B { class C { class X {}; }; };
/// \endcode
///
/// DescendantT must be an AST base type.
///
/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
/// each result that matches instead of only on the first one.
///
/// Note: Recursively combined ForEachDescendant can cause many matches:
/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
/// forEachDescendant(cxxRecordDecl())
/// )))
/// will match 10 times (plus injected class name matches) on:
/// \code
/// class A { class B { class C { class D { class E {}; }; }; }; };
/// \endcode
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::ForEachDescendantMatcher>
forEachDescendant;
/// Matches if the node or any descendant matches.
///
/// Generates results for each match.
///
/// For example, in:
/// \code
/// class A { class B {}; class C {}; };
/// \endcode
/// The matcher:
/// \code
/// cxxRecordDecl(hasName("::A"),
/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
/// \endcode
/// will generate results for \c A, \c B and \c C.
///
/// Usable as: Any Matcher
template <typename T>
internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
return eachOf(Matcher, forEachDescendant(Matcher));
}
/// Matches AST nodes that have a parent that matches the provided
/// matcher.
///
/// Given
/// \code
/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
/// \endcode
/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::HasParentMatcher,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
hasParent;
/// Matches AST nodes that have an ancestor that matches the provided
/// matcher.
///
/// Given
/// \code
/// void f() { if (true) { int x = 42; } }
/// void g() { for (;;) { int x = 43; } }
/// \endcode
/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::HasAncestorMatcher,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
hasAncestor;
/// Matches if the provided matcher does not match.
///
/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
/// \code
/// class X {};
/// class Y {};
/// \endcode
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
/// Matches a node if the declaration associated with that node
/// matches the given matcher.
///
/// The associated declaration is:
/// - for type nodes, the declaration of the underlying type
/// - for CallExpr, the declaration of the callee
/// - for MemberExpr, the declaration of the referenced member
/// - for CXXConstructExpr, the declaration of the constructor
/// - for CXXNewExpr, the declaration of the operator new
/// - for ObjCIvarExpr, the declaration of the ivar
///
/// For type nodes, hasDeclaration will generally match the declaration of the
/// sugared type. Given
/// \code
/// class X {};
/// typedef X Y;
/// Y y;
/// \endcode
/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
/// typedefDecl. A common use case is to match the underlying, desugared type.
/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
/// \code
/// varDecl(hasType(hasUnqualifiedDesugaredType(
/// recordType(hasDeclaration(decl())))))
/// \endcode
/// In this matcher, the decl will match the CXXRecordDecl of class X.
///
/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
/// Matcher<UnresolvedUsingType>
inline internal::PolymorphicMatcherWithParam1<
internal::HasDeclarationMatcher, internal::Matcher<Decl>,
void(internal::HasDeclarationSupportedTypes)>
hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
return internal::PolymorphicMatcherWithParam1<
internal::HasDeclarationMatcher, internal::Matcher<Decl>,
void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
}
/// Matches a \c NamedDecl whose underlying declaration matches the given
/// matcher.
///
/// Given
/// \code
/// namespace N { template<class T> void f(T t); }
/// template <class T> void g() { using N::f; f(T()); }
/// \endcode
/// \c unresolvedLookupExpr(hasAnyDeclaration(
/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
/// matches the use of \c f in \c g() .
AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
InnerMatcher) {
const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
return UnderlyingDecl != nullptr &&
InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
}
/// Matches on the implicit object argument of a member call expression, after
/// stripping off any parentheses or implicit casts.
///
/// Given
/// \code
/// class Y { public: void m(); };
/// Y g();
/// class X : public Y {};
/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
/// \endcode
/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
/// matches `y.m()` and `(g()).m()`.
/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
/// matches `x.m()`.
/// cxxMemberCallExpr(on(callExpr()))
/// matches `(g()).m()`.
///
/// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *ExprNode = Node.getImplicitObjectArgument()
->IgnoreParenImpCasts();
return (ExprNode != nullptr &&
InnerMatcher.matches(*ExprNode, Finder, Builder));
}
/// Matches on the receiver of an ObjectiveC Message expression.
///
/// Example
/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
/// matches the [webView ...] message invocation.
/// \code
/// NSString *webViewJavaScript = ...
/// UIWebView *webView = ...
/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
/// \endcode
AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
InnerMatcher) {
const QualType TypeDecl = Node.getReceiverType();
return InnerMatcher.matches(TypeDecl, Finder, Builder);
}
/// Returns true when the Objective-C method declaration is a class method.
///
/// Example
/// matcher = objcMethodDecl(isClassMethod())
/// matches
/// \code
/// @interface I + (void)foo; @end
/// \endcode
/// but not
/// \code
/// @interface I - (void)bar; @end
/// \endcode
AST_MATCHER(ObjCMethodDecl, isClassMethod) {
return Node.isClassMethod();
}
/// Returns true when the Objective-C method declaration is an instance method.
///
/// Example
/// matcher = objcMethodDecl(isInstanceMethod())
/// matches
/// \code
/// @interface I - (void)bar; @end
/// \endcode
/// but not
/// \code
/// @interface I + (void)foo; @end
/// \endcode
AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
return Node.isInstanceMethod();
}
/// Returns true when the Objective-C message is sent to a class.
///
/// Example
/// matcher = objcMessageExpr(isClassMessage())
/// matches
/// \code
/// [NSString stringWithFormat:@"format"];
/// \endcode
/// but not
/// \code
/// NSString *x = @"hello";
/// [x containsString:@"h"];
/// \endcode
AST_MATCHER(ObjCMessageExpr, isClassMessage) {
return Node.isClassMessage();
}
/// Returns true when the Objective-C message is sent to an instance.
///
/// Example
/// matcher = objcMessageExpr(isInstanceMessage())
/// matches
/// \code
/// NSString *x = @"hello";
/// [x containsString:@"h"];
/// \endcode
/// but not
/// \code
/// [NSString stringWithFormat:@"format"];
/// \endcode
AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
return Node.isInstanceMessage();
}
/// Matches if the Objective-C message is sent to an instance,
/// and the inner matcher matches on that instance.
///
/// For example the method call in
/// \code
/// NSString *x = @"hello";
/// [x containsString:@"h"];
/// \endcode
/// is matched by
/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *ReceiverNode = Node.getInstanceReceiver();
return (ReceiverNode != nullptr &&
InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
Builder));
}
/// Matches when BaseName == Selector.getAsString()
///
/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
/// matches the outer message expr in the code below, but NOT the message
/// invocation for self.bodyView.
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
Selector Sel = Node.getSelector();
return BaseName.compare(Sel.getAsString()) == 0;
}
/// Matches when at least one of the supplied string equals to the
/// Selector.getAsString()
///
/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
/// matches both of the expressions below:
/// \code
/// [myObj methodA:argA];
/// [myObj methodB:argB];
/// \endcode
extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
StringRef,
internal::hasAnySelectorFunc>
hasAnySelector;
/// Matches ObjC selectors whose name contains
/// a substring matched by the given RegExp.
/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
/// matches the outer message expr in the code below, but NOT the message
/// invocation for self.bodyView.
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
std::string SelectorString = Node.getSelector().getAsString();
return RegExp->match(SelectorString);
}
/// Matches when the selector is the empty selector
///
/// Matches only when the selector of the objCMessageExpr is NULL. This may
/// represent an error condition in the tree!
AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
return Node.getSelector().isNull();
}
/// Matches when the selector is a Unary Selector
///
/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
/// matches self.bodyView in the code below, but NOT the outer message
/// invocation of "loadHTMLString:baseURL:".
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
return Node.getSelector().isUnarySelector();
}
/// Matches when the selector is a keyword selector
///
/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
/// message expression in
///
/// \code
/// UIWebView *webView = ...;
/// CGRect bodyFrame = webView.frame;
/// bodyFrame.size.height = self.bodyContentHeight;
/// webView.frame = bodyFrame;
/// // ^---- matches here
/// \endcode
AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
return Node.getSelector().isKeywordSelector();
}
/// Matches when the selector has the specified number of arguments
///
/// matcher = objCMessageExpr(numSelectorArgs(0));
/// matches self.bodyView in the code below
///
/// matcher = objCMessageExpr(numSelectorArgs(2));
/// matches the invocation of "loadHTMLString:baseURL:" but not that
/// of self.bodyView
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
return Node.getSelector().getNumArgs() == N;
}
/// Matches if the call expression's callee expression matches.
///
/// Given
/// \code
/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
/// void f() { f(); }
/// \endcode
/// callExpr(callee(expr()))
/// matches this->x(), x(), y.x(), f()
/// with callee(...)
/// matching this->x, x, y.x, f respectively
///
/// Note: Callee cannot take the more general internal::Matcher<Expr>
/// because this introduces ambiguous overloads with calls to Callee taking a
/// internal::Matcher<Decl>, as the matcher hierarchy is purely
/// implemented in terms of implicit casts.
AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
InnerMatcher) {
const Expr *ExprNode = Node.getCallee();
return (ExprNode != nullptr &&
InnerMatcher.matches(*ExprNode, Finder, Builder));
}
/// Matches if the call expression's callee's declaration matches the
/// given matcher.
///
/// Example matches y.x() (matcher = callExpr(callee(
/// cxxMethodDecl(hasName("x")))))
/// \code
/// class Y { public: void x(); };
/// void z() { Y y; y.x(); }
/// \endcode
AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
1) {
return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
}
/// Matches if the expression's or declaration's type matches a type
/// matcher.
///
/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
/// and U (matcher = typedefDecl(hasType(asString("int")))
/// and friend class X (matcher = friendDecl(hasType("X"))
/// \code
/// class X {};
/// void y(X &x) { x; X z; }
/// typedef int U;
/// class Y { friend class X; };
/// \endcode
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
hasType,
AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
ValueDecl),
internal::Matcher<QualType>, InnerMatcher, 0) {
QualType QT = internal::getUnderlyingType(Node);
if (!QT.isNull())
return InnerMatcher.matches(QT, Finder, Builder);
return false;
}
/// Overloaded to match the declaration of the expression's or value
/// declaration's type.
///
/// In case of a value declaration (for example a variable declaration),
/// this resolves one layer of indirection. For example, in the value
/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
/// declaration of x.
///
/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
/// and friend class X (matcher = friendDecl(hasType("X"))
/// \code
/// class X {};
/// void y(X &x) { x; X z; }
/// class Y { friend class X; };
/// \endcode
///
/// Example matches class Derived
/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
/// \code
/// class Base {};
/// class Derived : Base {};
/// \endcode
///
/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
/// Matcher<CXXBaseSpecifier>
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
hasType,
AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl,
CXXBaseSpecifier),
internal::Matcher<Decl>, InnerMatcher, 1) {
QualType QT = internal::getUnderlyingType(Node);
if (!QT.isNull())
return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
return false;
}
/// Matches if the type location of the declarator decl's type matches
/// the inner matcher.
///
/// Given
/// \code
/// int x;
/// \endcode
/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
/// matches int x
AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
if (!Node.getTypeSourceInfo())
// This happens for example for implicit destructors.
return false;
return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
}
/// Matches if the matched type is represented by the given string.
///
/// Given
/// \code
/// class Y { public: void x(); };
/// void z() { Y* y; y->x(); }
/// \endcode
/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
/// matches y->x()
AST_MATCHER_P(QualType, asString, std::string, Name) {
return Name == Node.getAsString();
}
/// Matches if the matched type is a pointer type and the pointee type
/// matches the specified matcher.
///
/// Example matches y->x()
/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
/// cxxRecordDecl(hasName("Y")))))))
/// \code
/// class Y { public: void x(); };
/// void z() { Y *y; y->x(); }
/// \endcode
AST_MATCHER_P(
QualType, pointsTo, internal::Matcher<QualType>,
InnerMatcher) {
return (!Node.isNull() && Node->isAnyPointerType() &&
InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
}
/// Overloaded to match the pointee type's declaration.
AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
InnerMatcher, 1) {
return pointsTo(qualType(hasDeclaration(InnerMatcher)))
.matches(Node, Finder, Builder);
}
/// Matches if the matched type matches the unqualified desugared
/// type of the matched node.
///
/// For example, in:
/// \code
/// class A {};
/// using B = A;
/// \endcode
/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
/// both B and A.
AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
InnerMatcher) {
return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
Builder);
}
/// Matches if the matched type is a reference type and the referenced
/// type matches the specified matcher.
///
/// Example matches X &x and const X &y
/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
/// \code
/// class X {
/// void a(X b) {
/// X &x = b;
/// const X &y = b;
/// }
/// };
/// \endcode
AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
InnerMatcher) {
return (!Node.isNull() && Node->isReferenceType() &&
InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
}
/// Matches QualTypes whose canonical type matches InnerMatcher.
///
/// Given:
/// \code
/// typedef int &int_ref;
/// int a;
/// int_ref b = a;
/// \endcode
///
/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
/// declaration of b but \c
/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
InnerMatcher) {
if (Node.isNull())
return false;
return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
}
/// Overloaded to match the referenced type's declaration.
AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
InnerMatcher, 1) {
return references(qualType(hasDeclaration(InnerMatcher)))
.matches(Node, Finder, Builder);
}
/// Matches on the implicit object argument of a member call expression. Unlike
/// `on`, matches the argument directly without stripping away anything.
///
/// Given
/// \code
/// class Y { public: void m(); };
/// Y g();
/// class X : public Y { void g(); };
/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
/// \endcode
/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
/// cxxRecordDecl(hasName("Y")))))
/// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
/// cxxMemberCallExpr(on(callExpr()))
/// does not match `(g()).m()`, because the parens are not ignored.
///
/// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *ExprNode = Node.getImplicitObjectArgument();
return (ExprNode != nullptr &&
InnerMatcher.matches(*ExprNode, Finder, Builder));
}
/// Matches if the type of the expression's implicit object argument either
/// matches the InnerMatcher, or is a pointer to a type that matches the
/// InnerMatcher.
///
/// Given
/// \code
/// class Y { public: void m(); };
/// class X : public Y { void g(); };
/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
/// \endcode
/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
/// cxxRecordDecl(hasName("Y")))))
/// matches `y.m()`, `p->m()` and `x.m()`.
/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
/// cxxRecordDecl(hasName("X")))))
/// matches `x.g()`.
AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
internal::Matcher<QualType>, InnerMatcher, 0) {
return onImplicitObjectArgument(
anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
.matches(Node, Finder, Builder);
}
/// Overloaded to match the type's declaration.
AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
internal::Matcher<Decl>, InnerMatcher, 1) {
return onImplicitObjectArgument(
anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
.matches(Node, Finder, Builder);
}
/// Matches a DeclRefExpr that refers to a declaration that matches the
/// specified matcher.
///
/// Example matches x in if(x)
/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
/// \code
/// bool x;
/// if (x) {}
/// \endcode
AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
InnerMatcher) {
const Decl *DeclNode = Node.getDecl();
return (DeclNode != nullptr &&
InnerMatcher.matches(*DeclNode, Finder, Builder));
}
/// Matches a \c DeclRefExpr that refers to a declaration through a
/// specific using shadow declaration.
///
/// Given
/// \code
/// namespace a { void f() {} }
/// using a::f;
/// void g() {
/// f(); // Matches this ..
/// a::f(); // .. but not this.
/// }
/// \endcode
/// declRefExpr(throughUsingDecl(anything()))
/// matches \c f()
AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
internal::Matcher<UsingShadowDecl>, InnerMatcher) {
const NamedDecl *FoundDecl = Node.getFoundDecl();
if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
return InnerMatcher.matches(*UsingDecl, Finder, Builder);
return false;
}
/// Matches an \c OverloadExpr if any of the declarations in the set of
/// overloads matches the given matcher.
///
/// Given
/// \code
/// template <typename T> void foo(T);
/// template <typename T> void bar(T);
/// template <typename T> void baz(T t) {
/// foo(t);
/// bar(t);
/// }
/// \endcode
/// unresolvedLookupExpr(hasAnyDeclaration(
/// functionTemplateDecl(hasName("foo"))))
/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
Node.decls_end(), Finder, Builder);
}
/// Matches the Decl of a DeclStmt which has a single declaration.
///
/// Given
/// \code
/// int a, b;
/// int c;
/// \endcode
/// declStmt(hasSingleDecl(anything()))
/// matches 'int c;' but not 'int a, b;'.
AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
if (Node.isSingleDecl()) {
const Decl *FoundDecl = Node.getSingleDecl();
return InnerMatcher.matches(*FoundDecl, Finder, Builder);
}
return false;
}
/// Matches a variable declaration that has an initializer expression
/// that matches the given matcher.
///
/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
/// \code
/// bool y() { return true; }
/// bool x = y();
/// \endcode
AST_MATCHER_P(
VarDecl, hasInitializer, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *Initializer = Node.getAnyInitializer();
return (Initializer != nullptr &&
InnerMatcher.matches(*Initializer, Finder, Builder));
}
/// \brief Matches a static variable with local scope.
///
/// Example matches y (matcher = varDecl(isStaticLocal()))
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// static int z;
/// \endcode
AST_MATCHER(VarDecl, isStaticLocal) {
return Node.isStaticLocal();
}
/// Matches a variable declaration that has function scope and is a
/// non-static local variable.
///
/// Example matches x (matcher = varDecl(hasLocalStorage())
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// int z;
/// \endcode
AST_MATCHER(VarDecl, hasLocalStorage) {
return Node.hasLocalStorage();
}
/// Matches a variable declaration that does not have local storage.
///
/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// int z;
/// \endcode
AST_MATCHER(VarDecl, hasGlobalStorage) {
return Node.hasGlobalStorage();
}
/// Matches a variable declaration that has automatic storage duration.
///
/// Example matches x, but not y, z, or a.
/// (matcher = varDecl(hasAutomaticStorageDuration())
/// \code
/// void f() {
/// int x;
/// static int y;
/// thread_local int z;
/// }
/// int a;
/// \endcode
AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
return Node.getStorageDuration() == SD_Automatic;
}
/// Matches a variable declaration that has static storage duration.
/// It includes the variable declared at namespace scope and those declared
/// with "static" and "extern" storage class specifiers.
///
/// \code
/// void f() {
/// int x;
/// static int y;
/// thread_local int z;
/// }
/// int a;
/// static int b;
/// extern int c;
/// varDecl(hasStaticStorageDuration())
/// matches the function declaration y, a, b and c.
/// \endcode
AST_MATCHER(VarDecl, hasStaticStorageDuration) {
return Node.getStorageDuration() == SD_Static;
}
/// Matches a variable declaration that has thread storage duration.
///
/// Example matches z, but not x, z, or a.
/// (matcher = varDecl(hasThreadStorageDuration())
/// \code
/// void f() {
/// int x;
/// static int y;
/// thread_local int z;
/// }
/// int a;
/// \endcode
AST_MATCHER(VarDecl, hasThreadStorageDuration) {
return Node.getStorageDuration() == SD_Thread;
}
/// Matches a variable declaration that is an exception variable from
/// a C++ catch block, or an Objective-C \@catch statement.
///
/// Example matches x (matcher = varDecl(isExceptionVariable())
/// \code
/// void f(int y) {
/// try {
/// } catch (int x) {
/// }
/// }
/// \endcode
AST_MATCHER(VarDecl, isExceptionVariable) {
return Node.isExceptionVariable();
}
/// Checks that a call expression or a constructor call expression has
/// a specific number of arguments (including absent default arguments).
///
/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
/// \code
/// void f(int x, int y);
/// f(0, 0);
/// \endcode
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
CXXConstructExpr,
ObjCMessageExpr),
unsigned, N) {
return Node.getNumArgs() == N;
}
/// Matches the n'th argument of a call expression or a constructor
/// call expression.
///
/// Example matches y in x(y)
/// (matcher = callExpr(hasArgument(0, declRefExpr())))
/// \code
/// void x(int) { int y; x(y); }
/// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
CXXConstructExpr,
ObjCMessageExpr),
unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
return (N < Node.getNumArgs() &&
InnerMatcher.matches(
*Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
}
/// Matches the n'th item of an initializer list expression.
///
/// Example matches y.
/// (matcher = initListExpr(hasInit(0, expr())))
/// \code
/// int x{y}.
/// \endcode
AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
return N < Node.getNumInits() &&
InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
}
/// Matches declaration statements that contain a specific number of
/// declarations.
///
/// Example: Given
/// \code
/// int a, b;
/// int c;
/// int d = 2, e;
/// \endcode
/// declCountIs(2)
/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
}
/// Matches the n'th declaration of a declaration statement.
///
/// Note that this does not work for global declarations because the AST
/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
/// DeclStmt's.
/// Example: Given non-global declarations
/// \code
/// int a, b = 0;
/// int c;
/// int d = 2, e;
/// \endcode
/// declStmt(containsDeclaration(
/// 0, varDecl(hasInitializer(anything()))))
/// matches only 'int d = 2, e;', and
/// declStmt(containsDeclaration(1, varDecl()))
/// \code
/// matches 'int a, b = 0' as well as 'int d = 2, e;'
/// but 'int c;' is not matched.
/// \endcode
AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
internal::Matcher<Decl>, InnerMatcher) {
const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
if (N >= NumDecls)
return false;
DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
std::advance(Iterator, N);
return InnerMatcher.matches(**Iterator, Finder, Builder);
}
/// Matches a C++ catch statement that has a catch-all handler.
///
/// Given
/// \code
/// try {
/// // ...
/// } catch (int) {
/// // ...
/// } catch (...) {
/// // ...
/// }
/// \endcode
/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
AST_MATCHER(CXXCatchStmt, isCatchAll) {
return Node.getExceptionDecl() == nullptr;
}
/// Matches a constructor initializer.
///
/// Given
/// \code
/// struct Foo {
/// Foo() : foo_(1) { }
/// int foo_;
/// };
/// \endcode
/// cxxRecordDecl(has(cxxConstructorDecl(
/// hasAnyConstructorInitializer(anything())
/// )))
/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
Node.init_end(), Finder, Builder);
}
/// Matches the field declaration of a constructor initializer.
///
/// Given
/// \code
/// struct Foo {
/// Foo() : foo_(1) { }
/// int foo_;
/// };
/// \endcode
/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
/// forField(hasName("foo_"))))))
/// matches Foo
/// with forField matching foo_
AST_MATCHER_P(CXXCtorInitializer, forField,
internal::Matcher<FieldDecl>, InnerMatcher) {
const FieldDecl *NodeAsDecl = Node.getAnyMember();
return (NodeAsDecl != nullptr &&
InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
}
/// Matches the initializer expression of a constructor initializer.
///
/// Given
/// \code
/// struct Foo {
/// Foo() : foo_(1) { }
/// int foo_;
/// };
/// \endcode
/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
/// withInitializer(integerLiteral(equals(1)))))))
/// matches Foo
/// with withInitializer matching (1)
AST_MATCHER_P(CXXCtorInitializer, withInitializer,
internal::Matcher<Expr>, InnerMatcher) {
const Expr* NodeAsExpr = Node.getInit();
return (NodeAsExpr != nullptr &&
InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
}
/// Matches a constructor initializer if it is explicitly written in
/// code (as opposed to implicitly added by the compiler).
///
/// Given
/// \code
/// struct Foo {
/// Foo() { }
/// Foo(int) : foo_("A") { }
/// string foo_;
/// };
/// \endcode
/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
/// will match Foo(int), but not Foo()
AST_MATCHER(CXXCtorInitializer, isWritten) {
return Node.isWritten();
}
/// Matches a constructor initializer if it is initializing a base, as
/// opposed to a member.
///
/// Given
/// \code
/// struct B {};
/// struct D : B {
/// int I;
/// D(int i) : I(i) {}
/// };
/// struct E : B {
/// E() : B() {}
/// };
/// \endcode
/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
/// will match E(), but not match D(int).
AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
return Node.isBaseInitializer();
}
/// Matches a constructor initializer if it is initializing a member, as
/// opposed to a base.
///
/// Given
/// \code
/// struct B {};
/// struct D : B {
/// int I;
/// D(int i) : I(i) {}
/// };
/// struct E : B {
/// E() : B() {}
/// };
/// \endcode
/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
/// will match D(int), but not match E().
AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
return Node.isMemberInitializer();
}
/// Matches any argument of a call expression or a constructor call
/// expression, or an ObjC-message-send expression.
///
/// Given
/// \code
/// void x(int, int, int) { int y; x(1, y, 42); }
/// \endcode
/// callExpr(hasAnyArgument(declRefExpr()))
/// matches x(1, y, 42)
/// with hasAnyArgument(...)
/// matching y
///
/// For ObjectiveC, given
/// \code
/// @interface I - (void) f:(int) y; @end
/// void foo(I *i) { [i f:12]; }
/// \endcode
/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
/// matches [i f:12]
AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(
CallExpr, CXXConstructExpr,
CXXUnresolvedConstructExpr, ObjCMessageExpr),
internal::Matcher<Expr>, InnerMatcher) {
for (const Expr *Arg : Node.arguments()) {
BoundNodesTreeBuilder Result(*Builder);
if (InnerMatcher.matches(*Arg, Finder, &Result)) {
*Builder = std::move(Result);
return true;
}
}
return false;
}
/// Matches any capture of a lambda expression.
///
/// Given
/// \code
/// void foo() {
/// int x;
/// auto f = [x](){};
/// }
/// \endcode
/// lambdaExpr(hasAnyCapture(anything()))
/// matches [x](){};
AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<VarDecl>,
InnerMatcher, 0) {
for (const LambdaCapture &Capture : Node.captures()) {
if (Capture.capturesVariable()) {
BoundNodesTreeBuilder Result(*Builder);
if (InnerMatcher.matches(*Capture.getCapturedVar(), Finder, &Result)) {
*Builder = std::move(Result);
return true;
}
}
}
return false;
}
/// Matches any capture of 'this' in a lambda expression.
///
/// Given
/// \code
/// struct foo {
/// void bar() {
/// auto f = [this](){};
/// }
/// }
/// \endcode
/// lambdaExpr(hasAnyCapture(cxxThisExpr()))
/// matches [this](){};
AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture,
internal::Matcher<CXXThisExpr>, InnerMatcher, 1) {
return llvm::any_of(Node.captures(), [](const LambdaCapture &LC) {
return LC.capturesThis();
});
}
/// Matches a constructor call expression which uses list initialization.
AST_MATCHER(CXXConstructExpr, isListInitialization) {
return Node.isListInitialization();
}
/// Matches a constructor call expression which requires
/// zero initialization.
///
/// Given
/// \code
/// void foo() {
/// struct point { double x; double y; };
/// point pt[2] = { { 1.0, 2.0 } };
/// }
/// \endcode
/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
/// will match the implicit array filler for pt[1].
AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
return Node.requiresZeroInitialization();
}
/// Matches the n'th parameter of a function or an ObjC method
/// declaration or a block.
///
/// Given
/// \code
/// class X { void f(int x) {} };
/// \endcode
/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
/// matches f(int x) {}
/// with hasParameter(...)
/// matching int x
///
/// For ObjectiveC, given
/// \code
/// @interface I - (void) f:(int) y; @end
/// \endcode
//
/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
/// matches the declaration of method f with hasParameter
/// matching y.
AST_POLYMORPHIC_MATCHER_P2(hasParameter,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
ObjCMethodDecl,
BlockDecl),
unsigned, N, internal::Matcher<ParmVarDecl>,
InnerMatcher) {
return (N < Node.parameters().size()
&& InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
}
/// Matches all arguments and their respective ParmVarDecl.
///
/// Given
/// \code
/// void f(int i);
/// int y;
/// f(y);
/// \endcode
/// callExpr(
/// forEachArgumentWithParam(
/// declRefExpr(to(varDecl(hasName("y")))),
/// parmVarDecl(hasType(isInteger()))
/// ))
/// matches f(y);
/// with declRefExpr(...)
/// matching int y
/// and parmVarDecl(...)
/// matching int i
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
CXXConstructExpr),
internal::Matcher<Expr>, ArgMatcher,
internal::Matcher<ParmVarDecl>, ParamMatcher) {
BoundNodesTreeBuilder Result;
// The first argument of an overloaded member operator is the implicit object
// argument of the method which should not be matched against a parameter, so
// we skip over it here.
BoundNodesTreeBuilder Matches;
unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
.matches(Node, Finder, &Matches)
? 1
: 0;
int ParamIndex = 0;
bool Matched = false;
for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
BoundNodesTreeBuilder ArgMatches(*Builder);
if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
Finder, &ArgMatches)) {
BoundNodesTreeBuilder ParamMatches(ArgMatches);
if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
hasParameter(ParamIndex, ParamMatcher)))),
callExpr(callee(functionDecl(
hasParameter(ParamIndex, ParamMatcher))))))
.matches(Node, Finder, &ParamMatches)) {
Result.addMatch(ParamMatches);
Matched = true;
}
}
++ParamIndex;
}
*Builder = std::move(Result);
return Matched;
}
/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
/// list. The parameter list could be that of either a block, function, or
/// objc-method.
///
///
/// Given
///
/// \code
/// void f(int a, int b, int c) {
/// }
/// \endcode
///
/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
///
/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
return false;
}
/// Matches any parameter of a function or an ObjC method declaration or a
/// block.
///
/// Does not match the 'this' parameter of a method.
///
/// Given
/// \code
/// class X { void f(int x, int y, int z) {} };
/// \endcode
/// cxxMethodDecl(hasAnyParameter(hasName("y")))
/// matches f(int x, int y, int z) {}
/// with hasAnyParameter(...)
/// matching int y
///
/// For ObjectiveC, given
/// \code
/// @interface I - (void) f:(int) y; @end
/// \endcode
//
/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
/// matches the declaration of method f with hasParameter
/// matching y.
///
/// For blocks, given
/// \code
/// b = ^(int y) { printf("%d", y) };
/// \endcode
///
/// the matcher blockDecl(hasAnyParameter(hasName("y")))
/// matches the declaration of the block b with hasParameter
/// matching y.
AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
ObjCMethodDecl,
BlockDecl),
internal::Matcher<ParmVarDecl>,
InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
Node.param_end(), Finder, Builder);
}
/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
/// specific parameter count.
///
/// Given
/// \code
/// void f(int i) {}
/// void g(int i, int j) {}
/// void h(int i, int j);
/// void j(int i);
/// void k(int x, int y, int z, ...);
/// \endcode
/// functionDecl(parameterCountIs(2))
/// matches \c g and \c h
/// functionProtoType(parameterCountIs(2))
/// matches \c g and \c h
/// functionProtoType(parameterCountIs(3))
/// matches \c k
AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
FunctionProtoType),
unsigned, N) {
return Node.getNumParams() == N;
}
/// Matches \c FunctionDecls that have a noreturn attribute.
///
/// Given
/// \code
/// void nope();
/// [[noreturn]] void a();
/// __attribute__((noreturn)) void b();
/// struct c { [[noreturn]] c(); };
/// \endcode
/// functionDecl(isNoReturn())
/// matches all of those except
/// \code
/// void nope();
/// \endcode
AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
/// Matches the return type of a function declaration.
///
/// Given:
/// \code
/// class X { int f() { return 1; } };
/// \endcode
/// cxxMethodDecl(returns(asString("int")))
/// matches int f() { return 1; }
AST_MATCHER_P(FunctionDecl, returns,
internal::Matcher<QualType>, InnerMatcher) {
return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
}
/// Matches extern "C" function or variable declarations.
///
/// Given:
/// \code
/// extern "C" void f() {}
/// extern "C" { void g() {} }
/// void h() {}
/// extern "C" int x = 1;
/// extern "C" int y = 2;
/// int z = 3;
/// \endcode
/// functionDecl(isExternC())
/// matches the declaration of f and g, but not the declaration of h.
/// varDecl(isExternC())
/// matches the declaration of x and y, but not the declaration of z.
AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
return Node.isExternC();
}
/// Matches variable/function declarations that have "static" storage
/// class specifier ("static" keyword) written in the source.
///
/// Given:
/// \code
/// static void f() {}
/// static int i = 0;
/// extern int j;
/// int k;
/// \endcode
/// functionDecl(isStaticStorageClass())
/// matches the function declaration f.
/// varDecl(isStaticStorageClass())
/// matches the variable declaration i.
AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
return Node.getStorageClass() == SC_Static;
}
/// Matches deleted function declarations.
///
/// Given:
/// \code
/// void Func();
/// void DeletedFunc() = delete;
/// \endcode
/// functionDecl(isDeleted())
/// matches the declaration of DeletedFunc, but not Func.
AST_MATCHER(FunctionDecl, isDeleted) {
return Node.isDeleted();
}
/// Matches defaulted function declarations.
///
/// Given:
/// \code
/// class A { ~A(); };
/// class B { ~B() = default; };
/// \endcode
/// functionDecl(isDefaulted())
/// matches the declaration of ~B, but not ~A.
AST_MATCHER(FunctionDecl, isDefaulted) {
return Node.isDefaulted();
}
/// Matches functions that have a dynamic exception specification.
///
/// Given:
/// \code
/// void f();
/// void g() noexcept;
/// void h() noexcept(true);
/// void i() noexcept(false);
/// void j() throw();
/// void k() throw(int);
/// void l() throw(...);
/// \endcode
/// functionDecl(hasDynamicExceptionSpec()) and
/// functionProtoType(hasDynamicExceptionSpec())
/// match the declarations of j, k, and l, but not f, g, h, or i.
AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
FunctionProtoType)) {
if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
return FnTy->hasDynamicExceptionSpec();
return false;
}
/// Matches functions that have a non-throwing exception specification.
///
/// Given:
/// \code
/// void f();
/// void g() noexcept;
/// void h() throw();
/// void i() throw(int);
/// void j() noexcept(false);
/// \endcode
/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
/// match the declarations of g, and h, but not f, i or j.
AST_POLYMORPHIC_MATCHER(isNoThrow,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
FunctionProtoType)) {
const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
// If the function does not have a prototype, then it is assumed to be a
// throwing function (as it would if the function did not have any exception
// specification).
if (!FnTy)
return false;
// Assume the best for any unresolved exception specification.
if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
return true;
return FnTy->isNothrow();
}
/// Matches constexpr variable and function declarations,
/// and if constexpr.
///
/// Given:
/// \code
/// constexpr int foo = 42;
/// constexpr int bar();
/// void baz() { if constexpr(1 > 0) {} }
/// \endcode
/// varDecl(isConstexpr())
/// matches the declaration of foo.
/// functionDecl(isConstexpr())
/// matches the declaration of bar.
/// ifStmt(isConstexpr())
/// matches the if statement in baz.
AST_POLYMORPHIC_MATCHER(isConstexpr,
AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
FunctionDecl,
IfStmt)) {
return Node.isConstexpr();
}
/// Matches selection statements with initializer.
///
/// Given:
/// \code
/// void foo() {
/// if (int i = foobar(); i > 0) {}
/// switch (int i = foobar(); i) {}
/// for (auto& a = get_range(); auto& x : a) {}
/// }
/// void bar() {
/// if (foobar() > 0) {}
/// switch (foobar()) {}
/// for (auto& x : get_range()) {}
/// }
/// \endcode
/// ifStmt(hasInitStatement(anything()))
/// matches the if statement in foo but not in bar.
/// switchStmt(hasInitStatement(anything()))
/// matches the switch statement in foo but not in bar.
/// cxxForRangeStmt(hasInitStatement(anything()))
/// matches the range for statement in foo but not in bar.
AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt,
CXXForRangeStmt),
internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *Init = Node.getInit();
return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
}
/// Matches the condition expression of an if statement, for loop,
/// switch statement or conditional operator.
///
/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
/// \code
/// if (true) {}
/// \endcode
AST_POLYMORPHIC_MATCHER_P(
hasCondition,
AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
SwitchStmt, AbstractConditionalOperator),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *const Condition = Node.getCond();
return (Condition != nullptr &&
InnerMatcher.matches(*Condition, Finder, Builder));
}
/// Matches the then-statement of an if statement.
///
/// Examples matches the if statement
/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
/// \code
/// if (false) true; else false;
/// \endcode
AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *const Then = Node.getThen();
return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
}
/// Matches the else-statement of an if statement.
///
/// Examples matches the if statement
/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
/// \code
/// if (false) false; else true;
/// \endcode
AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *const Else = Node.getElse();
return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
}
/// Matches if a node equals a previously bound node.
///
/// Matches a node if it equals the node previously bound to \p ID.
///
/// Given
/// \code
/// class X { int a; int b; };
/// \endcode
/// cxxRecordDecl(
/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
/// matches the class \c X, as \c a and \c b have the same type.
///
/// Note that when multiple matches are involved via \c forEach* matchers,
/// \c equalsBoundNodes acts as a filter.
/// For example:
/// compoundStmt(
/// forEachDescendant(varDecl().bind("d")),
/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
/// will trigger a match for each combination of variable declaration
/// and reference to that variable declaration within a compound statement.
AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
QualType),
std::string, ID) {
// FIXME: Figure out whether it makes sense to allow this
// on any other node types.
// For *Loc it probably does not make sense, as those seem
// unique. For NestedNameSepcifier it might make sense, as
// those also have pointer identity, but I'm not sure whether
// they're ever reused.
internal::NotEqualsBoundNodePredicate Predicate;
Predicate.ID = ID;
Predicate.Node = DynTypedNode::create(Node);
return Builder->removeBindings(Predicate);
}
/// Matches the condition variable statement in an if statement.
///
/// Given
/// \code
/// if (A* a = GetAPointer()) {}
/// \endcode
/// hasConditionVariableStatement(...)
/// matches 'A* a = GetAPointer()'.
AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
internal::Matcher<DeclStmt>, InnerMatcher) {
const DeclStmt* const DeclarationStatement =
Node.getConditionVariableDeclStmt();
return DeclarationStatement != nullptr &&
InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
}
/// Matches the index expression of an array subscript expression.
///
/// Given
/// \code
/// int i[5];
/// void f() { i[1] = 42; }
/// \endcode
/// arraySubscriptExpression(hasIndex(integerLiteral()))
/// matches \c i[1] with the \c integerLiteral() matching \c 1
AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
internal::Matcher<Expr>, InnerMatcher) {
if (const Expr* Expression = Node.getIdx())
return InnerMatcher.matches(*Expression, Finder, Builder);
return false;
}
/// Matches the base expression of an array subscript expression.
///
/// Given
/// \code
/// int i[5];
/// void f() { i[1] = 42; }
/// \endcode
/// arraySubscriptExpression(hasBase(implicitCastExpr(
/// hasSourceExpression(declRefExpr()))))
/// matches \c i[1] with the \c declRefExpr() matching \c i
AST_MATCHER_P(ArraySubscriptExpr, hasBase,
internal::Matcher<Expr>, InnerMatcher) {
if (const Expr* Expression = Node.getBase())
return InnerMatcher.matches(*Expression, Finder, Builder);
return false;
}
/// Matches a 'for', 'while', 'do while' statement or a function
/// definition that has a given body.
///
/// Given
/// \code
/// for (;;) {}
/// \endcode
/// hasBody(compoundStmt())
/// matches 'for (;;) {}'
/// with compoundStmt()
/// matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasBody,
AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
WhileStmt,
CXXForRangeStmt,
FunctionDecl),
internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
return (Statement != nullptr &&
InnerMatcher.matches(*Statement, Finder, Builder));
}
/// Matches compound statements where at least one substatement matches
/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
///
/// Given
/// \code
/// { {}; 1+2; }
/// \endcode
/// hasAnySubstatement(compoundStmt())
/// matches '{ {}; 1+2; }'
/// with compoundStmt()
/// matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
StmtExpr),
internal::Matcher<Stmt>, InnerMatcher) {
const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
CS->body_end(), Finder, Builder);
}
/// Checks that a compound statement contains a specific number of
/// child statements.
///
/// Example: Given
/// \code
/// { for (;;) {} }
/// \endcode
/// compoundStmt(statementCountIs(0)))
/// matches '{}'
/// but does not match the outer compound statement.
AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
return Node.size() == N;
}
/// Matches literals that are equal to the given value of type ValueT.
///
/// Given
/// \code
/// f('\0', false, 3.14, 42);
/// \endcode
/// characterLiteral(equals(0))
/// matches '\0'
/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
/// match false
/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
/// match 3.14
/// integerLiteral(equals(42))
/// matches 42
///
/// Note that you cannot directly match a negative numeric literal because the
/// minus sign is not part of the literal: It is a unary operator whose operand
/// is the positive numeric literal. Instead, you must use a unaryOperator()
/// matcher to match the minus sign:
///
/// unaryOperator(hasOperatorName("-"),
/// hasUnaryOperand(integerLiteral(equals(13))))
///
/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
template <typename ValueT>
internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
equals(const ValueT &Value) {
return internal::PolymorphicMatcherWithParam1<
internal::ValueEqualsMatcher,
ValueT>(Value);
}
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
CXXBoolLiteralExpr,
IntegerLiteral),
bool, Value, 0) {
return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
.matchesNode(Node);
}
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
CXXBoolLiteralExpr,
IntegerLiteral),
unsigned, Value, 1) {
return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
.matchesNode(Node);
}
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
CXXBoolLiteralExpr,
FloatingLiteral,
IntegerLiteral),
double, Value, 2) {
return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
.matchesNode(Node);
}
/// Matches the operator Name of operator expressions (binary or
/// unary).
///
/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
/// \code
/// !(a || b)
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
UnaryOperator),
std::string, Name) {
return Name == Node.getOpcodeStr(Node.getOpcode());
}
/// Matches operator expressions (binary or unary) that have any of the
/// specified names.
///
/// hasAnyOperatorName("+", "-")
/// Is equivalent to
/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
extern const internal::VariadicFunction<
internal::PolymorphicMatcherWithParam1<
internal::HasAnyOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, UnaryOperator)>,
StringRef, internal::hasAnyOperatorNameFunc>
hasAnyOperatorName;
/// Matches all kinds of assignment operators.
///
/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
/// \code
/// if (a == b)
/// a += b;
/// \endcode
///
/// Example 2: matches s1 = s2
/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
/// \code
/// struct S { S& operator=(const S&); };
/// void x() { S s1, s2; s1 = s2; }
/// \endcode
AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
CXXOperatorCallExpr)) {
return Node.isAssignmentOp();
}
/// Matches comparison operators.
///
/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
/// \code
/// if (a == b)
/// a += b;
/// \endcode
///
/// Example 2: matches s1 < s2
/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
/// \code
/// struct S { bool operator<(const S& other); };
/// void x(S s1, S s2) { bool b1 = s1 < s2; }
/// \endcode
AST_POLYMORPHIC_MATCHER(isComparisonOperator,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
CXXOperatorCallExpr)) {
return Node.isComparisonOp();
}
/// Matches the left hand side of binary operator expressions.
///
/// Example matches a (matcher = binaryOperator(hasLHS()))
/// \code
/// a || b
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasLHS,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
ArraySubscriptExpr),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *LeftHandSide = Node.getLHS();
return (LeftHandSide != nullptr &&
InnerMatcher.matches(*LeftHandSide, Finder, Builder));
}
/// Matches the right hand side of binary operator expressions.
///
/// Example matches b (matcher = binaryOperator(hasRHS()))
/// \code
/// a || b
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasRHS,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
ArraySubscriptExpr),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *RightHandSide = Node.getRHS();
return (RightHandSide != nullptr &&
InnerMatcher.matches(*RightHandSide, Finder, Builder));
}
/// Matches if either the left hand side or the right hand side of a
/// binary operator matches.
inline internal::Matcher<BinaryOperator> hasEitherOperand(
const internal::Matcher<Expr> &InnerMatcher) {
return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
}
/// Matches if both matchers match with opposite sides of the binary operator.
///
/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
/// integerLiteral(equals(2)))
/// \code
/// 1 + 2 // Match
/// 2 + 1 // Match
/// 1 + 1 // No match
/// 2 + 2 // No match
/// \endcode
inline internal::Matcher<BinaryOperator>
hasOperands(const internal::Matcher<Expr> &Matcher1,
const internal::Matcher<Expr> &Matcher2) {
return anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
allOf(hasLHS(Matcher2), hasRHS(Matcher1)));
}
/// Matches if the operand of a unary operator matches.
///
/// Example matches true (matcher = hasUnaryOperand(
/// cxxBoolLiteral(equals(true))))
/// \code
/// !true
/// \endcode
AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
internal::Matcher<Expr>, InnerMatcher) {
const Expr * const Operand = Node.getSubExpr();
return (Operand != nullptr &&
InnerMatcher.matches(*Operand, Finder, Builder));
}
/// Matches if the cast's source expression
/// or opaque value's source expression matches the given matcher.
///
/// Example 1: matches "a string"
/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
/// \code
/// class URL { URL(string); };
/// URL url = "a string";
/// \endcode
///
/// Example 2: matches 'b' (matcher =
/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
/// \code
/// int a = b ?: 1;
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
OpaqueValueExpr),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *const SubExpression =
internal::GetSourceExpressionMatcher<NodeType>::get(Node);
return (SubExpression != nullptr &&
InnerMatcher.matches(*SubExpression, Finder, Builder));
}
/// Matches casts that has a given cast kind.
///
/// Example: matches the implicit cast around \c 0
/// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
/// \code
/// int *p = 0;
/// \endcode
///
/// If the matcher is use from clang-query, CastKind parameter
/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
return Node.getCastKind() == Kind;
}
/// Matches casts whose destination type matches a given matcher.
///
/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
/// actual casts "explicit" casts.)
AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
internal::Matcher<QualType>, InnerMatcher) {
const QualType NodeType = Node.getTypeAsWritten();
return InnerMatcher.matches(NodeType, Finder, Builder);
}
/// Matches implicit casts whose destination type matches a given
/// matcher.
///
/// FIXME: Unit test this matcher
AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
internal::Matcher<QualType>, InnerMatcher) {
return InnerMatcher.matches(Node.getType(), Finder, Builder);
}
/// Matches TagDecl object that are spelled with "struct."
///
/// Example matches S, but not C, U or E.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isStruct) {
return Node.isStruct();
}
/// Matches TagDecl object that are spelled with "union."
///
/// Example matches U, but not C, S or E.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isUnion) {
return Node.isUnion();
}
/// Matches TagDecl object that are spelled with "class."
///
/// Example matches C, but not S, U or E.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isClass) {
return Node.isClass();
}
/// Matches TagDecl object that are spelled with "enum."
///
/// Example matches E, but not C, S or U.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isEnum) {
return Node.isEnum();
}
/// Matches the true branch expression of a conditional operator.
///
/// Example 1 (conditional ternary operator): matches a
/// \code
/// condition ? a : b
/// \endcode
///
/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
/// \code
/// condition ?: b
/// \endcode
AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *Expression = Node.getTrueExpr();
return (Expression != nullptr &&
InnerMatcher.matches(*Expression, Finder, Builder));
}
/// Matches the false branch expression of a conditional operator
/// (binary or ternary).
///
/// Example matches b
/// \code
/// condition ? a : b
/// condition ?: b
/// \endcode
AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *Expression = Node.getFalseExpr();
return (Expression != nullptr &&
InnerMatcher.matches(*Expression, Finder, Builder));
}
/// Matches if a declaration has a body attached.
///
/// Example matches A, va, fa
/// \code
/// class A {};
/// class B; // Doesn't match, as it has no body.
/// int va;
/// extern int vb; // Doesn't match, as it doesn't define the variable.
/// void fa() {}
/// void fb(); // Doesn't match, as it has no body.
/// @interface X
/// - (void)ma; // Doesn't match, interface is declaration.
/// @end
/// @implementation X
/// - (void)ma {}
/// @end
/// \endcode
///
/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
/// Matcher<ObjCMethodDecl>
AST_POLYMORPHIC_MATCHER(isDefinition,
AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
ObjCMethodDecl,
FunctionDecl)) {
return Node.isThisDeclarationADefinition();
}
/// Matches if a function declaration is variadic.
///
/// Example matches f, but not g or h. The function i will not match, even when
/// compiled in C mode.
/// \code
/// void f(...);
/// void g(int);
/// template <typename... Ts> void h(Ts...);
/// void i();
/// \endcode
AST_MATCHER(FunctionDecl, isVariadic) {
return Node.isVariadic();
}
/// Matches the class declaration that the given method declaration
/// belongs to.
///
/// FIXME: Generalize this for other kinds of declarations.
/// FIXME: What other kind of declarations would we need to generalize
/// this to?
///
/// Example matches A() in the last line
/// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
/// ofClass(hasName("A"))))))
/// \code
/// class A {
/// public:
/// A();
/// };
/// A a = A();
/// \endcode
AST_MATCHER_P(CXXMethodDecl, ofClass,
internal::Matcher<CXXRecordDecl>, InnerMatcher) {
const CXXRecordDecl *Parent = Node.getParent();
return (Parent != nullptr &&
InnerMatcher.matches(*Parent, Finder, Builder));
}
/// Matches each method overridden by the given method. This matcher may
/// produce multiple matches.
///
/// Given
/// \code
/// class A { virtual void f(); };
/// class B : public A { void f(); };
/// class C : public B { void f(); };
/// \endcode
/// cxxMethodDecl(ofClass(hasName("C")),
/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
/// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
/// that B::f is not overridden by C::f).
///
/// The check can produce multiple matches in case of multiple inheritance, e.g.
/// \code
/// class A1 { virtual void f(); };
/// class A2 { virtual void f(); };
/// class C : public A1, public A2 { void f(); };
/// \endcode
/// cxxMethodDecl(ofClass(hasName("C")),
/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
/// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
/// once with "b" binding "A2::f" and "d" binding "C::f".
AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
internal::Matcher<CXXMethodDecl>, InnerMatcher) {
BoundNodesTreeBuilder Result;
bool Matched = false;
for (const auto *Overridden : Node.overridden_methods()) {
BoundNodesTreeBuilder OverriddenBuilder(*Builder);
const bool OverriddenMatched =
InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
if (OverriddenMatched) {
Matched = true;
Result.addMatch(OverriddenBuilder);
}
}
*Builder = std::move(Result);
return Matched;
}
/// Matches declarations of virtual methods and C++ base specifers that specify
/// virtual inheritance.
///
/// Example:
/// \code
/// class A {
/// public:
/// virtual void x(); // matches x
/// };
/// \endcode
///
/// Example:
/// \code
/// class Base {};
/// class DirectlyDerived : virtual Base {}; // matches Base
/// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
/// \endcode
///
/// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
AST_POLYMORPHIC_MATCHER(isVirtual,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl,
CXXBaseSpecifier)) {
return Node.isVirtual();
}
/// Matches if the given method declaration has an explicit "virtual".
///
/// Given
/// \code
/// class A {
/// public:
/// virtual void x();
/// };
/// class B : public A {
/// public:
/// void x();
/// };
/// \endcode
/// matches A::x but not B::x
AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
return Node.isVirtualAsWritten();
}
/// Matches if the given method or class declaration is final.
///
/// Given:
/// \code
/// class A final {};
///
/// struct B {
/// virtual void f();
/// };
///
/// struct C : B {
/// void f() final;
/// };
/// \endcode
/// matches A and C::f, but not B, C, or B::f
AST_POLYMORPHIC_MATCHER(isFinal,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
CXXMethodDecl)) {
return Node.template hasAttr<FinalAttr>();
}
/// Matches if the given method declaration is pure.
///
/// Given
/// \code
/// class A {
/// public:
/// virtual void x() = 0;
/// };
/// \endcode
/// matches A::x
AST_MATCHER(CXXMethodDecl, isPure) {
return Node.isPure();
}
/// Matches if the given method declaration is const.
///
/// Given
/// \code
/// struct A {
/// void foo() const;
/// void bar();
/// };
/// \endcode
///
/// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
AST_MATCHER(CXXMethodDecl, isConst) {
return Node.isConst();
}
/// Matches if the given method declaration declares a copy assignment
/// operator.
///
/// Given
/// \code
/// struct A {
/// A &operator=(const A &);
/// A &operator=(A &&);
/// };
/// \endcode
///
/// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
/// the second one.
AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
return Node.isCopyAssignmentOperator();
}
/// Matches if the given method declaration declares a move assignment
/// operator.
///
/// Given
/// \code
/// struct A {
/// A &operator=(const A &);
/// A &operator=(A &&);
/// };
/// \endcode
///
/// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
/// the first one.
AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
return Node.isMoveAssignmentOperator();
}
/// Matches if the given method declaration overrides another method.
///
/// Given
/// \code
/// class A {
/// public:
/// virtual void x();
/// };
/// class B : public A {
/// public:
/// virtual void x();
/// };
/// \endcode
/// matches B::x
AST_MATCHER(CXXMethodDecl, isOverride) {
return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
}
/// Matches method declarations that are user-provided.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &) = default; // #2
/// S(S &&) = delete; // #3
/// };
/// \endcode
/// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
AST_MATCHER(CXXMethodDecl, isUserProvided) {
return Node.isUserProvided();
}
/// Matches member expressions that are called with '->' as opposed
/// to '.'.
///
/// Member calls on the implicit this pointer match as called with '->'.
///
/// Given
/// \code
/// class Y {
/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
/// template <class T> void f() { this->f<T>(); f<T>(); }
/// int a;
/// static int b;
/// };
/// template <class T>
/// class Z {
/// void x() { this->m; }
/// };
/// \endcode
/// memberExpr(isArrow())
/// matches this->x, x, y.x, a, this->b
/// cxxDependentScopeMemberExpr(isArrow())
/// matches this->m
/// unresolvedMemberExpr(isArrow())
/// matches this->f<T>, f<T>
AST_POLYMORPHIC_MATCHER(
isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
CXXDependentScopeMemberExpr)) {
return Node.isArrow();
}
/// Matches QualType nodes that are of integer type.
///
/// Given
/// \code
/// void a(int);
/// void b(long);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isInteger())))
/// matches "a(int)", "b(long)", but not "c(double)".
AST_MATCHER(QualType, isInteger) {
return Node->isIntegerType();
}
/// Matches QualType nodes that are of unsigned integer type.
///
/// Given
/// \code
/// void a(int);
/// void b(unsigned long);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
/// matches "b(unsigned long)", but not "a(int)" and "c(double)".
AST_MATCHER(QualType, isUnsignedInteger) {
return Node->isUnsignedIntegerType();
}
/// Matches QualType nodes that are of signed integer type.
///
/// Given
/// \code
/// void a(int);
/// void b(unsigned long);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
/// matches "a(int)", but not "b(unsigned long)" and "c(double)".
AST_MATCHER(QualType, isSignedInteger) {
return Node->isSignedIntegerType();
}
/// Matches QualType nodes that are of character type.
///
/// Given
/// \code
/// void a(char);
/// void b(wchar_t);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
/// matches "a(char)", "b(wchar_t)", but not "c(double)".
AST_MATCHER(QualType, isAnyCharacter) {
return Node->isAnyCharacterType();
}
/// Matches QualType nodes that are of any pointer type; this includes
/// the Objective-C object pointer type, which is different despite being
/// syntactically similar.
///
/// Given
/// \code
/// int *i = nullptr;
///
/// @interface Foo
/// @end
/// Foo *f;
///
/// int j;
/// \endcode
/// varDecl(hasType(isAnyPointer()))
/// matches "int *i" and "Foo *f", but not "int j".
AST_MATCHER(QualType, isAnyPointer) {
return Node->isAnyPointerType();
}
/// Matches QualType nodes that are const-qualified, i.e., that
/// include "top-level" const.
///
/// Given
/// \code
/// void a(int);
/// void b(int const);
/// void c(const int);
/// void d(const int*);
/// void e(int const) {};
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
/// matches "void b(int const)", "void c(const int)" and
/// "void e(int const) {}". It does not match d as there
/// is no top-level const on the parameter type "const int *".
AST_MATCHER(QualType, isConstQualified) {
return Node.isConstQualified();
}
/// Matches QualType nodes that are volatile-qualified, i.e., that
/// include "top-level" volatile.
///
/// Given
/// \code
/// void a(int);
/// void b(int volatile);
/// void c(volatile int);
/// void d(volatile int*);
/// void e(int volatile) {};
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
/// matches "void b(int volatile)", "void c(volatile int)" and
/// "void e(int volatile) {}". It does not match d as there
/// is no top-level volatile on the parameter type "volatile int *".
AST_MATCHER(QualType, isVolatileQualified) {
return Node.isVolatileQualified();
}
/// Matches QualType nodes that have local CV-qualifiers attached to
/// the node, not hidden within a typedef.
///
/// Given
/// \code
/// typedef const int const_int;
/// const_int i;
/// int *const j;
/// int *volatile k;
/// int m;
/// \endcode
/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
/// \c i is const-qualified but the qualifier is not local.
AST_MATCHER(QualType, hasLocalQualifiers) {
return Node.hasLocalQualifiers();
}
/// Matches a member expression where the member is matched by a
/// given matcher.
///
/// Given
/// \code
/// struct { int first, second; } first, second;
/// int i(second.first);
/// int j(first.second);
/// \endcode
/// memberExpr(member(hasName("first")))
/// matches second.first
/// but not first.second (because the member name there is "second").
AST_MATCHER_P(MemberExpr, member,
internal::Matcher<ValueDecl>, InnerMatcher) {
return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
}
/// Matches a member expression where the object expression is matched by a
/// given matcher. Implicit object expressions are included; that is, it matches
/// use of implicit `this`.
///
/// Given
/// \code
/// struct X {
/// int m;
/// int f(X x) { x.m; return m; }
/// };
/// \endcode
/// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
/// matches `x.m`, but not `m`; however,
/// memberExpr(hasObjectExpression(hasType(pointsTo(
// cxxRecordDecl(hasName("X"))))))
/// matches `m` (aka. `this->m`), but not `x.m`.
AST_POLYMORPHIC_MATCHER_P(
hasObjectExpression,
AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
CXXDependentScopeMemberExpr),
internal::Matcher<Expr>, InnerMatcher) {
if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
if (E->isImplicitAccess())
return false;
if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
if (E->isImplicitAccess())
return false;
return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
}
/// Matches any using shadow declaration.
///
/// Given
/// \code
/// namespace X { void b(); }
/// using X::b;
/// \endcode
/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
/// matches \code using X::b \endcode
AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
internal::Matcher<UsingShadowDecl>, InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
Node.shadow_end(), Finder, Builder);
}
/// Matches a using shadow declaration where the target declaration is
/// matched by the given matcher.
///
/// Given
/// \code
/// namespace X { int a; void b(); }
/// using X::a;
/// using X::b;
/// \endcode
/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
/// matches \code using X::b \endcode
/// but not \code using X::a \endcode
AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
internal::Matcher<NamedDecl>, InnerMatcher) {
return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
}
/// Matches template instantiations of function, class, or static
/// member variable template instantiations.
///
/// Given
/// \code
/// template <typename T> class X {}; class A {}; X<A> x;
/// \endcode
/// or
/// \code
/// template <typename T> class X {}; class A {}; template class X<A>;
/// \endcode
/// or
/// \code
/// template <typename T> class X {}; class A {}; extern template class X<A>;
/// \endcode
/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
/// matches the template instantiation of X<A>.
///
/// But given
/// \code
/// template <typename T> class X {}; class A {};
/// template <> class X<A> {}; X<A> x;
/// \endcode
/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
/// does not match, as X<A> is an explicit template specialization.
///
/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
CXXRecordDecl)) {
return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
Node.getTemplateSpecializationKind() ==
TSK_ExplicitInstantiationDefinition ||
Node.getTemplateSpecializationKind() ==
TSK_ExplicitInstantiationDeclaration);
}
/// Matches declarations that are template instantiations or are inside
/// template instantiations.
///
/// Given
/// \code
/// template<typename T> void A(T t) { T i; }
/// A(0);
/// A(0U);
/// \endcode
/// functionDecl(isInstantiated())
/// matches 'A(int) {...};' and 'A(unsigned) {...}'.
AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
functionDecl(isTemplateInstantiation())));
return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
}
/// Matches statements inside of a template instantiation.
///
/// Given
/// \code
/// int j;
/// template<typename T> void A(T t) { T i; j += 42;}
/// A(0);
/// A(0U);
/// \endcode
/// declStmt(isInTemplateInstantiation())
/// matches 'int i;' and 'unsigned i'.
/// unless(stmt(isInTemplateInstantiation()))
/// will NOT match j += 42; as it's shared between the template definition and
/// instantiation.
AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
return stmt(
hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
functionDecl(isTemplateInstantiation())))));
}
/// Matches explicit template specializations of function, class, or
/// static member variable template instantiations.
///
/// Given
/// \code
/// template<typename T> void A(T t) { }
/// template<> void A(int N) { }
/// \endcode
/// functionDecl(isExplicitTemplateSpecialization())
/// matches the specialization A<int>().
///
/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
CXXRecordDecl)) {
return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
}
/// Matches \c TypeLocs for which the given inner
/// QualType-matcher matches.
AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
internal::Matcher<QualType>, InnerMatcher, 0) {
return internal::BindableMatcher<TypeLoc>(
new internal::TypeLocTypeMatcher(InnerMatcher));
}
/// Matches type \c bool.
///
/// Given
/// \code
/// struct S { bool func(); };
/// \endcode
/// functionDecl(returns(booleanType()))
/// matches "bool func();"
AST_MATCHER(Type, booleanType) {
return Node.isBooleanType();
}
/// Matches type \c void.
///
/// Given
/// \code
/// struct S { void func(); };
/// \endcode
/// functionDecl(returns(voidType()))
/// matches "void func();"
AST_MATCHER(Type, voidType) {
return Node.isVoidType();
}
template <typename NodeType>
using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
/// Matches builtin Types.
///
/// Given
/// \code
/// struct A {};
/// A a;
/// int b;
/// float c;
/// bool d;
/// \endcode
/// builtinType()
/// matches "int b", "float c" and "bool d"
extern const AstTypeMatcher<BuiltinType> builtinType;
/// Matches all kinds of arrays.
///
/// Given
/// \code
/// int a[] = { 2, 3 };
/// int b[4];
/// void f() { int c[a[0]]; }
/// \endcode
/// arrayType()
/// matches "int a[]", "int b[4]" and "int c[a[0]]";
extern const AstTypeMatcher<ArrayType> arrayType;
/// Matches C99 complex types.
///
/// Given
/// \code
/// _Complex float f;
/// \endcode
/// complexType()
/// matches "_Complex float f"
extern const AstTypeMatcher<ComplexType> complexType;
/// Matches any real floating-point type (float, double, long double).
///
/// Given
/// \code
/// int i;
/// float f;
/// \endcode
/// realFloatingPointType()
/// matches "float f" but not "int i"
AST_MATCHER(Type, realFloatingPointType) {
return Node.isRealFloatingType();
}
/// Matches arrays and C99 complex types that have a specific element
/// type.
///
/// Given
/// \code
/// struct A {};
/// A a[7];
/// int b[7];
/// \endcode
/// arrayType(hasElementType(builtinType()))
/// matches "int b[7]"
///
/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
ComplexType));
/// Matches C arrays with a specified constant size.
///
/// Given
/// \code
/// void() {
/// int a[2];
/// int b[] = { 2, 3 };
/// int c[b[0]];
/// }
/// \endcode
/// constantArrayType()
/// matches "int a[2]"
extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
/// Matches nodes that have the specified size.
///
/// Given
/// \code
/// int a[42];
/// int b[2 * 21];
/// int c[41], d[43];
/// char *s = "abcd";
/// wchar_t *ws = L"abcd";
/// char *w = "a";
/// \endcode
/// constantArrayType(hasSize(42))
/// matches "int a[42]" and "int b[2 * 21]"
/// stringLiteral(hasSize(4))
/// matches "abcd", L"abcd"
AST_POLYMORPHIC_MATCHER_P(hasSize,
AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
StringLiteral),
unsigned, N) {
return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
}
/// Matches C++ arrays whose size is a value-dependent expression.
///
/// Given
/// \code
/// template<typename T, int Size>
/// class array {
/// T data[Size];
/// };
/// \endcode
/// dependentSizedArrayType
/// matches "T data[Size]"
extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
/// Matches C arrays with unspecified size.
///
/// Given
/// \code
/// int a[] = { 2, 3 };
/// int b[42];
/// void f(int c[]) { int d[a[0]]; };
/// \endcode
/// incompleteArrayType()
/// matches "int a[]" and "int c[]"
extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
/// Matches C arrays with a specified size that is not an
/// integer-constant-expression.
///
/// Given
/// \code
/// void f() {
/// int a[] = { 2, 3 }
/// int b[42];
/// int c[a[0]];
/// }
/// \endcode
/// variableArrayType()
/// matches "int c[a[0]]"
extern const AstTypeMatcher<VariableArrayType> variableArrayType;
/// Matches \c VariableArrayType nodes that have a specific size
/// expression.
///
/// Given
/// \code
/// void f(int b) {
/// int a[b];
/// }
/// \endcode
/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
/// varDecl(hasName("b")))))))
/// matches "int a[b]"
AST_MATCHER_P(VariableArrayType, hasSizeExpr,
internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
}
/// Matches atomic types.
///
/// Given
/// \code
/// _Atomic(int) i;
/// \endcode
/// atomicType()
/// matches "_Atomic(int) i"
extern const AstTypeMatcher<AtomicType> atomicType;
/// Matches atomic types with a specific value type.
///
/// Given
/// \code
/// _Atomic(int) i;
/// _Atomic(float) f;
/// \endcode
/// atomicType(hasValueType(isInteger()))
/// matches "_Atomic(int) i"
///
/// Usable as: Matcher<AtomicType>
AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
/// Matches types nodes representing C++11 auto types.
///
/// Given:
/// \code
/// auto n = 4;
/// int v[] = { 2, 3 }
/// for (auto i : v) { }
/// \endcode
/// autoType()
/// matches "auto n" and "auto i"
extern const AstTypeMatcher<AutoType> autoType;
/// Matches types nodes representing C++11 decltype(<expr>) types.
///
/// Given:
/// \code
/// short i = 1;
/// int j = 42;
/// decltype(i + j) result = i + j;
/// \endcode
/// decltypeType()
/// matches "decltype(i + j)"
extern const AstTypeMatcher<DecltypeType> decltypeType;
/// Matches \c AutoType nodes where the deduced type is a specific type.
///
/// Note: There is no \c TypeLoc for the deduced type and thus no
/// \c getDeducedLoc() matcher.
///
/// Given
/// \code
/// auto a = 1;
/// auto b = 2.0;
/// \endcode
/// autoType(hasDeducedType(isInteger()))
/// matches "auto a"
///
/// Usable as: Matcher<AutoType>
AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
/// Matches \c DecltypeType nodes to find out the underlying type.
///
/// Given
/// \code
/// decltype(1) a = 1;
/// decltype(2.0) b = 2.0;
/// \endcode
/// decltypeType(hasUnderlyingType(isInteger()))
/// matches the type of "a"
///
/// Usable as: Matcher<DecltypeType>
AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
/// Matches \c FunctionType nodes.
///
/// Given
/// \code
/// int (*f)(int);
/// void g();
/// \endcode
/// functionType()
/// matches "int (*f)(int)" and the type of "g".
extern const AstTypeMatcher<FunctionType> functionType;
/// Matches \c FunctionProtoType nodes.
///
/// Given
/// \code
/// int (*f)(int);
/// void g();
/// \endcode
/// functionProtoType()
/// matches "int (*f)(int)" and the type of "g" in C++ mode.
/// In C mode, "g" is not matched because it does not contain a prototype.
extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
/// Matches \c ParenType nodes.
///
/// Given
/// \code
/// int (*ptr_to_array)[4];
/// int *array_of_ptrs[4];
/// \endcode
///
/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
/// \c array_of_ptrs.
extern const AstTypeMatcher<ParenType> parenType;
/// Matches \c ParenType nodes where the inner type is a specific type.
///
/// Given
/// \code
/// int (*ptr_to_array)[4];
/// int (*ptr_to_func)(int);
/// \endcode
///
/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
/// \c ptr_to_func but not \c ptr_to_array.
///
/// Usable as: Matcher<ParenType>
AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
/// Matches block pointer types, i.e. types syntactically represented as
/// "void (^)(int)".
///
/// The \c pointee is always required to be a \c FunctionType.
extern const AstTypeMatcher<BlockPointerType> blockPointerType;
/// Matches member pointer types.
/// Given
/// \code
/// struct A { int i; }
/// A::* ptr = A::i;
/// \endcode
/// memberPointerType()
/// matches "A::* ptr"
extern const AstTypeMatcher<MemberPointerType> memberPointerType;
/// Matches pointer types, but does not match Objective-C object pointer
/// types.
///
/// Given
/// \code
/// int *a;
/// int &b = *a;
/// int c = 5;
///
/// @interface Foo
/// @end
/// Foo *f;
/// \endcode
/// pointerType()
/// matches "int *a", but does not match "Foo *f".
extern const AstTypeMatcher<PointerType> pointerType;
/// Matches an Objective-C object pointer type, which is different from
/// a pointer type, despite being syntactically similar.
///
/// Given
/// \code
/// int *a;
///
/// @interface Foo
/// @end
/// Foo *f;
/// \endcode
/// pointerType()
/// matches "Foo *f", but does not match "int *a".
extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
/// Matches both lvalue and rvalue reference types.
///
/// Given
/// \code
/// int *a;
/// int &b = *a;
/// int &&c = 1;
/// auto &d = b;
/// auto &&e = c;
/// auto &&f = 2;
/// int g = 5;
/// \endcode
///
/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
extern const AstTypeMatcher<ReferenceType> referenceType;
/// Matches lvalue reference types.
///
/// Given:
/// \code
/// int *a;
/// int &b = *a;
/// int &&c = 1;
/// auto &d = b;
/// auto &&e = c;
/// auto &&f = 2;
/// int g = 5;
/// \endcode
///
/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
/// matched since the type is deduced as int& by reference collapsing rules.
extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
/// Matches rvalue reference types.
///
/// Given:
/// \code
/// int *a;
/// int &b = *a;
/// int &&c = 1;
/// auto &d = b;
/// auto &&e = c;
/// auto &&f = 2;
/// int g = 5;
/// \endcode
///
/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
/// matched as it is deduced to int& by reference collapsing rules.
extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
/// Narrows PointerType (and similar) matchers to those where the
/// \c pointee matches a given matcher.
///
/// Given
/// \code
/// int *a;
/// int const *b;
/// float const *f;
/// \endcode
/// pointerType(pointee(isConstQualified(), isInteger()))
/// matches "int const *b"
///
/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
/// Matcher<PointerType>, Matcher<ReferenceType>
AST_TYPELOC_TRAVERSE_MATCHER_DECL(
pointee, getPointee,
AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
PointerType, ReferenceType));
/// Matches typedef types.
///
/// Given
/// \code
/// typedef int X;
/// \endcode
/// typedefType()
/// matches "typedef int X"
extern const AstTypeMatcher<TypedefType> typedefType;
/// Matches enum types.
///
/// Given
/// \code
/// enum C { Green };
/// enum class S { Red };
///
/// C c;
/// S s;
/// \endcode
//
/// \c enumType() matches the type of the variable declarations of both \c c and
/// \c s.
extern const AstTypeMatcher<EnumType> enumType;
/// Matches template specialization types.
///
/// Given
/// \code
/// template <typename T>
/// class C { };
///
/// template class C<int>; // A
/// C<char> var; // B
/// \endcode
///
/// \c templateSpecializationType() matches the type of the explicit
/// instantiation in \c A and the type of the variable declaration in \c B.
extern const AstTypeMatcher<TemplateSpecializationType>
templateSpecializationType;
/// Matches C++17 deduced template specialization types, e.g. deduced class
/// template types.
///
/// Given
/// \code
/// template <typename T>
/// class C { public: C(T); };
///
/// C c(123);
/// \endcode
/// \c deducedTemplateSpecializationType() matches the type in the declaration
/// of the variable \c c.
extern const AstTypeMatcher<DeducedTemplateSpecializationType>
deducedTemplateSpecializationType;
/// Matches types nodes representing unary type transformations.
///
/// Given:
/// \code
/// typedef __underlying_type(T) type;
/// \endcode
/// unaryTransformType()
/// matches "__underlying_type(T)"
extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
/// Matches record types (e.g. structs, classes).
///
/// Given
/// \code
/// class C {};
/// struct S {};
///
/// C c;
/// S s;
/// \endcode
///
/// \c recordType() matches the type of the variable declarations of both \c c
/// and \c s.
extern const AstTypeMatcher<RecordType> recordType;
/// Matches tag types (record and enum types).
///
/// Given
/// \code
/// enum E {};
/// class C {};
///
/// E e;
/// C c;
/// \endcode
///
/// \c tagType() matches the type of the variable declarations of both \c e
/// and \c c.
extern const AstTypeMatcher<TagType> tagType;
/// Matches types specified with an elaborated type keyword or with a
/// qualified name.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// class C {};
///
/// class C c;
/// N::M::D d;
/// \endcode
///
/// \c elaboratedType() matches the type of the variable declarations of both
/// \c c and \c d.
extern const AstTypeMatcher<ElaboratedType> elaboratedType;
/// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
/// matches \c InnerMatcher if the qualifier exists.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// N::M::D d;
/// \endcode
///
/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
/// matches the type of the variable declaration of \c d.
AST_MATCHER_P(ElaboratedType, hasQualifier,
internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
return InnerMatcher.matches(*Qualifier, Finder, Builder);
return false;
}
/// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// N::M::D d;
/// \endcode
///
/// \c elaboratedType(namesType(recordType(
/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
/// declaration of \c d.
AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
InnerMatcher) {
return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
}
/// Matches types that represent the result of substituting a type for a
/// template type parameter.
///
/// Given
/// \code
/// template <typename T>
/// void F(T t) {
/// int i = 1 + t;
/// }
/// \endcode
///
/// \c substTemplateTypeParmType() matches the type of 't' but not '1'
extern const AstTypeMatcher<SubstTemplateTypeParmType>
substTemplateTypeParmType;
/// Matches template type parameter substitutions that have a replacement
/// type that matches the provided matcher.
///
/// Given
/// \code
/// template <typename T>
/// double F(T t);
/// int i;
/// double j = F(i);
/// \endcode
///
/// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
AST_TYPE_TRAVERSE_MATCHER(
hasReplacementType, getReplacementType,
AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
/// Matches template type parameter types.
///
/// Example matches T, but not int.
/// (matcher = templateTypeParmType())
/// \code
/// template <typename T> void f(int i);
/// \endcode
extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
/// Matches injected class name types.
///
/// Example matches S s, but not S<T> s.
/// (matcher = parmVarDecl(hasType(injectedClassNameType())))
/// \code
/// template <typename T> struct S {
/// void f(S s);
/// void g(S<T> s);
/// };
/// \endcode
extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
/// Matches decayed type
/// Example matches i[] in declaration of f.
/// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
/// Example matches i[1].
/// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
/// \code
/// void f(int i[]) {
/// i[1] = 0;
/// }
/// \endcode
extern const AstTypeMatcher<DecayedType> decayedType;
/// Matches the decayed type, whos decayed type matches \c InnerMatcher
AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
InnerType) {
return InnerType.matches(Node.getDecayedType(), Finder, Builder);
}
/// Matches declarations whose declaration context, interpreted as a
/// Decl, matches \c InnerMatcher.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// \endcode
///
/// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
/// declaration of \c class \c D.
AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
const DeclContext *DC = Node.getDeclContext();
if (!DC) return false;
return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
}
/// Matches nested name specifiers.
///
/// Given
/// \code
/// namespace ns {
/// struct A { static void f(); };
/// void A::f() {}
/// void g() { A::f(); }
/// }
/// ns::A a;
/// \endcode
/// nestedNameSpecifier()
/// matches "ns::" and both "A::"
extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
nestedNameSpecifier;
/// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
nestedNameSpecifierLoc;
/// Matches \c NestedNameSpecifierLocs for which the given inner
/// NestedNameSpecifier-matcher matches.
AST_MATCHER_FUNCTION_P_OVERLOAD(
internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
return internal::BindableMatcher<NestedNameSpecifierLoc>(
new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
InnerMatcher));
}
/// Matches nested name specifiers that specify a type matching the
/// given \c QualType matcher without qualifiers.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifier(specifiesType(
/// hasDeclaration(cxxRecordDecl(hasName("A")))
/// ))
/// matches "A::"
AST_MATCHER_P(NestedNameSpecifier, specifiesType,
internal::Matcher<QualType>, InnerMatcher) {
if (!Node.getAsType())
return false;
return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
}
/// Matches nested name specifier locs that specify a type matching the
/// given \c TypeLoc.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
/// hasDeclaration(cxxRecordDecl(hasName("A")))))))
/// matches "A::"
AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
internal::Matcher<TypeLoc>, InnerMatcher) {
return Node && Node.getNestedNameSpecifier()->getAsType() &&
InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
}
/// Matches on the prefix of a \c NestedNameSpecifier.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
/// matches "A::"
AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
internal::Matcher<NestedNameSpecifier>, InnerMatcher,
0) {
const NestedNameSpecifier *NextNode = Node.getPrefix();
if (!NextNode)
return false;
return InnerMatcher.matches(*NextNode, Finder, Builder);
}
/// Matches on the prefix of a \c NestedNameSpecifierLoc.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
/// matches "A::"
AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
1) {
NestedNameSpecifierLoc NextNode = Node.getPrefix();
if (!NextNode)
return false;
return InnerMatcher.matches(NextNode, Finder, Builder);
}
/// Matches nested name specifiers that specify a namespace matching the
/// given namespace matcher.
///
/// Given
/// \code
/// namespace ns { struct A {}; }
/// ns::A a;
/// \endcode
/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
/// matches "ns::"
AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
internal::Matcher<NamespaceDecl>, InnerMatcher) {
if (!Node.getAsNamespace())
return false;
return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
}
/// Overloads for the \c equalsNode matcher.
/// FIXME: Implement for other node types.
/// @{
/// Matches if a node equals another node.
///
/// \c Decl has pointer identity in the AST.
AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
return &Node == Other;
}
/// Matches if a node equals another node.
///
/// \c Stmt has pointer identity in the AST.
AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
return &Node == Other;
}
/// Matches if a node equals another node.
///
/// \c Type has pointer identity in the AST.
AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
return &Node == Other;
}
/// @}
/// Matches each case or default statement belonging to the given switch
/// statement. This matcher may produce multiple matches.
///
/// Given
/// \code
/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
/// \endcode
/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
/// matches four times, with "c" binding each of "case 1:", "case 2:",
/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
/// "switch (1)", "switch (2)" and "switch (2)".
AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
InnerMatcher) {
BoundNodesTreeBuilder Result;
// FIXME: getSwitchCaseList() does not necessarily guarantee a stable
// iteration order. We should use the more general iterating matchers once
// they are capable of expressing this matcher (for example, it should ignore
// case statements belonging to nested switch statements).
bool Matched = false;
for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
SC = SC->getNextSwitchCase()) {
BoundNodesTreeBuilder CaseBuilder(*Builder);
bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
if (CaseMatched) {
Matched = true;
Result.addMatch(CaseBuilder);
}
}
*Builder = std::move(Result);
return Matched;
}
/// Matches each constructor initializer in a constructor definition.
///
/// Given
/// \code
/// class A { A() : i(42), j(42) {} int i; int j; };
/// \endcode
/// cxxConstructorDecl(forEachConstructorInitializer(
/// forField(decl().bind("x"))
/// ))
/// will trigger two matches, binding for 'i' and 'j' respectively.
AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
BoundNodesTreeBuilder Result;
bool Matched = false;
for (const auto *I : Node.inits()) {
BoundNodesTreeBuilder InitBuilder(*Builder);
if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
Matched = true;
Result.addMatch(InitBuilder);
}
}
*Builder = std::move(Result);
return Matched;
}
/// Matches constructor declarations that are copy constructors.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &); // #2
/// S(S &&); // #3
/// };
/// \endcode
/// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
return Node.isCopyConstructor();
}
/// Matches constructor declarations that are move constructors.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &); // #2
/// S(S &&); // #3
/// };
/// \endcode
/// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
return Node.isMoveConstructor();
}
/// Matches constructor declarations that are default constructors.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &); // #2
/// S(S &&); // #3
/// };
/// \endcode
/// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
return Node.isDefaultConstructor();
}
/// Matches constructors that delegate to another constructor.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(int) {} // #2
/// S(S &&) : S() {} // #3
/// };
/// S::S() : S(0) {} // #4
/// \endcode
/// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
/// #1 or #2.
AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
return Node.isDelegatingConstructor();
}
/// Matches constructor, conversion function, and deduction guide declarations
/// that have an explicit specifier if this explicit specifier is resolved to
/// true.
///
/// Given
/// \code
/// template<bool b>
/// struct S {
/// S(int); // #1
/// explicit S(double); // #2
/// operator int(); // #3
/// explicit operator bool(); // #4
/// explicit(false) S(bool) // # 7
/// explicit(true) S(char) // # 8
/// explicit(b) S(S) // # 9
/// };
/// S(int) -> S<true> // #5
/// explicit S(double) -> S<false> // #6
/// \endcode
/// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
/// cxxConversionDecl(isExplicit()) will match #4, but not #3.
/// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
CXXConstructorDecl, CXXConversionDecl,
CXXDeductionGuideDecl)) {
return Node.isExplicit();
}
/// Matches the expression in an explicit specifier if present in the given
/// declaration.
///
/// Given
/// \code
/// template<bool b>
/// struct S {
/// S(int); // #1
/// explicit S(double); // #2
/// operator int(); // #3
/// explicit operator bool(); // #4
/// explicit(false) S(bool) // # 7
/// explicit(true) S(char) // # 8
/// explicit(b) S(S) // # 9
/// };
/// S(int) -> S<true> // #5
/// explicit S(double) -> S<false> // #6
/// \endcode
/// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
/// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
/// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
InnerMatcher) {
ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
if (!ES.getExpr())
return false;
return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
}
/// Matches function and namespace declarations that are marked with
/// the inline keyword.
///
/// Given
/// \code
/// inline void f();
/// void g();
/// namespace n {
/// inline namespace m {}
/// }
/// \endcode
/// functionDecl(isInline()) will match ::f().
/// namespaceDecl(isInline()) will match n::m.
AST_POLYMORPHIC_MATCHER(isInline,
AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
FunctionDecl)) {
// This is required because the spelling of the function used to determine
// whether inline is specified or not differs between the polymorphic types.
if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
return FD->isInlineSpecified();
else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
return NSD->isInline();
llvm_unreachable("Not a valid polymorphic type");
}
/// Matches anonymous namespace declarations.
///
/// Given
/// \code
/// namespace n {
/// namespace {} // #1
/// }
/// \endcode
/// namespaceDecl(isAnonymous()) will match #1 but not ::n.
AST_MATCHER(NamespaceDecl, isAnonymous) {
return Node.isAnonymousNamespace();
}
/// Matches declarations in the namespace `std`, but not in nested namespaces.
///
/// Given
/// \code
/// class vector {};
/// namespace foo {
/// class vector {};
/// namespace std {
/// class vector {};
/// }
/// }
/// namespace std {
/// inline namespace __1 {
/// class vector {}; // #1
/// namespace experimental {
/// class vector {};
/// }
/// }
/// }
/// \endcode
/// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
/// If the given case statement does not use the GNU case range
/// extension, matches the constant given in the statement.
///
/// Given
/// \code
/// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
/// \endcode
/// caseStmt(hasCaseConstant(integerLiteral()))
/// matches "case 1:"
AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
InnerMatcher) {
if (Node.getRHS())
return false;
return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
}
/// Matches declaration that has a given attribute.
///
/// Given
/// \code
/// __attribute__((device)) void f() { ... }
/// \endcode
/// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
/// f. If the matcher is used from clang-query, attr::Kind parameter should be
/// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
for (const auto *Attr : Node.attrs()) {
if (Attr->getKind() == AttrKind)
return true;
}
return false;
}
/// Matches the return value expression of a return statement
///
/// Given
/// \code
/// return a + b;
/// \endcode
/// hasReturnValue(binaryOperator())
/// matches 'return a + b'
/// with binaryOperator()
/// matching 'a + b'
AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
InnerMatcher) {
if (const auto *RetValue = Node.getRetValue())
return InnerMatcher.matches(*RetValue, Finder, Builder);
return false;
}
/// Matches CUDA kernel call expression.
///
/// Example matches,
/// \code
/// kernel<<<i,j>>>();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
cudaKernelCallExpr;
/// Matches expressions that resolve to a null pointer constant, such as
/// GNU's __null, C++11's nullptr, or C's NULL macro.
///
/// Given:
/// \code
/// void *v1 = NULL;
/// void *v2 = nullptr;
/// void *v3 = __null; // GNU extension
/// char *cp = (char *)0;
/// int *ip = 0;
/// int i = 0;
/// \endcode
/// expr(nullPointerConstant())
/// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
/// initializer for i.
AST_MATCHER(Expr, nullPointerConstant) {
return Node.isNullPointerConstant(Finder->getASTContext(),
Expr::NPC_ValueDependentIsNull);
}
/// Matches declaration of the function the statement belongs to
///
/// Given:
/// \code
/// F& operator=(const F& o) {
/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
/// return *this;
/// }
/// \endcode
/// returnStmt(forFunction(hasName("operator=")))
/// matches 'return *this'
/// but does not match 'return v > 0'
AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
InnerMatcher) {
const auto &Parents = Finder->getASTContext().getParents(Node);
llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
while(!Stack.empty()) {
const auto &CurNode = Stack.back();
Stack.pop_back();
if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
return true;
}
} else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
Finder, Builder)) {
return true;
}
} else {
for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
Stack.push_back(Parent);
}
}
return false;
}
/// Matches a declaration that has external formal linkage.
///
/// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// int z;
/// \endcode
///
/// Example matches f() because it has external formal linkage despite being
/// unique to the translation unit as though it has internal likage
/// (matcher = functionDecl(hasExternalFormalLinkage()))
///
/// \code
/// namespace {
/// void f() {}
/// }
/// \endcode
AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
return Node.hasExternalFormalLinkage();
}
/// Matches a declaration that has default arguments.
///
/// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
/// \code
/// void x(int val) {}
/// void y(int val = 0) {}
/// \endcode
///
/// Deprecated. Use hasInitializer() instead to be able to
/// match on the contents of the default argument. For example:
///
/// \code
/// void x(int val = 7) {}
/// void y(int val = 42) {}
/// \endcode
/// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
/// matches the parameter of y
///
/// A matcher such as
/// parmVarDecl(hasInitializer(anything()))
/// is equivalent to parmVarDecl(hasDefaultArgument()).
AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
return Node.hasDefaultArg();
}
/// Matches array new expressions.
///
/// Given:
/// \code
/// MyClass *p1 = new MyClass[10];
/// \endcode
/// cxxNewExpr(isArray())
/// matches the expression 'new MyClass[10]'.
AST_MATCHER(CXXNewExpr, isArray) {
return Node.isArray();
}
/// Matches placement new expression arguments.
///
/// Given:
/// \code
/// MyClass *p1 = new (Storage, 16) MyClass();
/// \endcode
/// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
/// matches the expression 'new (Storage, 16) MyClass()'.
AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
internal::Matcher<Expr>, InnerMatcher) {
return Node.getNumPlacementArgs() > Index &&
InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder);
}
/// Matches any placement new expression arguments.
///
/// Given:
/// \code
/// MyClass *p1 = new (Storage) MyClass();
/// \endcode
/// cxxNewExpr(hasAnyPlacementArg(anything()))
/// matches the expression 'new (Storage, 16) MyClass()'.
AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
InnerMatcher) {
return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
return InnerMatcher.matches(*Arg, Finder, Builder);
});
}
/// Matches array new expressions with a given array size.
///
/// Given:
/// \code
/// MyClass *p1 = new MyClass[10];
/// \endcode
/// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
/// matches the expression 'new MyClass[10]'.
AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
return Node.isArray() && *Node.getArraySize() &&
InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
}
/// Matches a class declaration that is defined.
///
/// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
/// \code
/// class x {};
/// class y;
/// \endcode
AST_MATCHER(CXXRecordDecl, hasDefinition) {
return Node.hasDefinition();
}
/// Matches C++11 scoped enum declaration.
///
/// Example matches Y (matcher = enumDecl(isScoped()))
/// \code
/// enum X {};
/// enum class Y {};
/// \endcode
AST_MATCHER(EnumDecl, isScoped) {
return Node.isScoped();
}
/// Matches a function declared with a trailing return type.
///
/// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
/// \code
/// int X() {}
/// auto Y() -> int {}
/// \endcode
AST_MATCHER(FunctionDecl, hasTrailingReturn) {
if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
return F->hasTrailingReturn();
return false;
}
/// Matches expressions that match InnerMatcher that are possibly wrapped in an
/// elidable constructor and other corresponding bookkeeping nodes.
///
/// In C++17, elidable copy constructors are no longer being generated in the
/// AST as it is not permitted by the standard. They are, however, part of the
/// AST in C++14 and earlier. So, a matcher must abstract over these differences
/// to work in all language modes. This matcher skips elidable constructor-call
/// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
/// various implicit nodes inside the constructor calls, all of which will not
/// appear in the C++17 AST.
///
/// Given
///
/// \code
/// struct H {};
/// H G();
/// void f() {
/// H D = G();
/// }
/// \endcode
///
/// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
/// matches ``H D = G()`` in C++11 through C++17 (and beyond).
AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
// E tracks the node that we are examining.
const Expr *E = &Node;
// If present, remove an outer `ExprWithCleanups` corresponding to the
// underlying `CXXConstructExpr`. This check won't cover all cases of added
// `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
// EWC is placed on the outermost node of the expression, which this may not
// be), but, it still improves the coverage of this matcher.
if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
E = CleanupsExpr->getSubExpr();
if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
if (CtorExpr->isElidable()) {
if (const auto *MaterializeTemp =
dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder,
Builder);
}
}
}
return InnerMatcher.matches(Node, Finder, Builder);
}
//----------------------------------------------------------------------------//
// OpenMP handling.
//----------------------------------------------------------------------------//
/// Matches any ``#pragma omp`` executable directive.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// #pragma omp taskyield
/// \endcode
///
/// ``ompExecutableDirective()`` matches ``omp parallel``,
/// ``omp parallel default(none)`` and ``omp taskyield``.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
ompExecutableDirective;
/// Matches standalone OpenMP directives,
/// i.e., directives that can't have a structured block.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// {}
/// #pragma omp taskyield
/// \endcode
///
/// ``ompExecutableDirective(isStandaloneDirective()))`` matches
/// ``omp taskyield``.
AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
return Node.isStandaloneDirective();
}
/// Matches the structured-block of the OpenMP executable directive
///
/// Prerequisite: the executable directive must not be standalone directive.
/// If it is, it will never match.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// ;
/// #pragma omp parallel
/// {}
/// \endcode
///
/// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
internal::Matcher<Stmt>, InnerMatcher) {
if (Node.isStandaloneDirective())
return false; // Standalone directives have no structured blocks.
return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
}
/// Matches any clause in an OpenMP directive.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// \endcode
///
/// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
/// ``omp parallel default(none)``.
AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
internal::Matcher<OMPClause>, InnerMatcher) {
ArrayRef<OMPClause *> Clauses = Node.clauses();
return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
Clauses.end(), Finder, Builder);
}
/// Matches OpenMP ``default`` clause.
///
/// Given
///
/// \code
/// #pragma omp parallel default(none)
/// #pragma omp parallel default(shared)
/// #pragma omp parallel
/// \endcode
///
/// ``ompDefaultClause()`` matches ``default(none)`` and ``default(shared)``.
extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
ompDefaultClause;
/// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// #pragma omp parallel default(shared)
/// \endcode
///
/// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
AST_MATCHER(OMPDefaultClause, isNoneKind) {
return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
}
/// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// #pragma omp parallel default(shared)
/// \endcode
///
/// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
AST_MATCHER(OMPDefaultClause, isSharedKind) {
return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
}
/// Matches if the OpenMP directive is allowed to contain the specified OpenMP
/// clause kind.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel for
/// #pragma omp for
/// \endcode
///
/// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
/// ``omp parallel`` and ``omp parallel for``.
///
/// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
/// should be passed as a quoted string. e.g.,
/// ``isAllowedToContainClauseKind("OMPC_default").``
AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
OpenMPClauseKind, CKind) {
return llvm::omp::isAllowedClauseForDirective(
Node.getDirectiveKind(), CKind,
Finder->getASTContext().getLangOpts().OpenMP);
}
//----------------------------------------------------------------------------//
// End OpenMP handling.
//----------------------------------------------------------------------------//
} // namespace ast_matchers
} // namespace clang
#endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
|
GB_binop__min_int64.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__min_int64
// A.*B function (eWiseMult): GB_AemultB__min_int64
// A*D function (colscale): GB_AxD__min_int64
// D*A function (rowscale): GB_DxB__min_int64
// C+=B function (dense accum): GB_Cdense_accumB__min_int64
// C+=b function (dense accum): GB_Cdense_accumb__min_int64
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__min_int64
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__min_int64
// C=scalar+B GB_bind1st__min_int64
// C=scalar+B' GB_bind1st_tran__min_int64
// C=A+scalar GB_bind2nd__min_int64
// C=A'+scalar GB_bind2nd_tran__min_int64
// C type: int64_t
// A type: int64_t
// B,b type: int64_t
// BinaryOp: cij = GB_IMIN (aij, bij)
#define GB_ATYPE \
int64_t
#define GB_BTYPE \
int64_t
#define GB_CTYPE \
int64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
int64_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
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_INT64 || GxB_NO_MIN_INT64)
//------------------------------------------------------------------------------
// 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_int64
(
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_int64
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__min_int64
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__min_int64
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int64_t
int64_t bwork = (*((int64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__min_int64
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *GB_RESTRICT Cx = (int64_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__min_int64
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *GB_RESTRICT Cx = (int64_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
#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__min_int64
(
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__min_int64
(
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__min_int64
(
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
int64_t *Cx = (int64_t *) Cx_output ;
int64_t x = (*((int64_t *) x_input)) ;
int64_t *Bx = (int64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
int64_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_int64
(
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 ;
int64_t *Cx = (int64_t *) Cx_output ;
int64_t *Ax = (int64_t *) Ax_input ;
int64_t y = (*((int64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int64_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 typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = Ax [pA] ; \
Cx [pC] = GB_IMIN (x, aij) ; \
}
GrB_Info GB_bind1st_tran__min_int64
(
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 \
int64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t x = (*((const int64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = Ax [pA] ; \
Cx [pC] = GB_IMIN (aij, y) ; \
}
GrB_Info GB_bind2nd_tran__min_int64
(
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
int64_t y = (*((const int64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
laplace_par.h | #ifndef _LAPLACE_PAR_
#define _LAPLACE_PAR_
#include<omp.h>
template<int SIZE>
inline void initialize(double a[SIZE + 2][SIZE + 2], double b[SIZE + 2][SIZE + 2])
{
//TODO implement your solution in here
#pragma omp parallel for
for (int i = 0; i < SIZE + 2; i++)
for (int j = 0; j < SIZE + 2; j++)
{
a[i][j] = 0.0;
b[i][j] = 0.0;
}
}
template<int SIZE>
inline void time_step(double a[SIZE + 2][SIZE + 2], double b[SIZE + 2][SIZE + 2], int n)
{
//TODO implement your solution in here
if (n % 2 == 0)
{
#pragma omp parallel for
for (int i = 1; i < SIZE + 1; i++)
for (int j = 1; j < SIZE + 1; j++)
b[i][j] = (a[i + 1][j] + a[i - 1][j] + a[i][j - 1] + a[i][j + 1]) *0.25;
}
else
{
#pragma omp parallel for
for (int i = 1; i < SIZE + 1; i++)
for (int j = 1; j < SIZE + 1; j++)
a[i][j] = (b[i + 1][j] + b[i - 1][j] + b[i][j - 1] + b[i][j + 1])*0.25;
}
}
#endif // !_LAPLACE_PAR_
|
DRB044-adi-tile-no.c | /**
* adi.c: This file is part of the PolyBench/C 3.2 test suite.
* Alternating Direction Implicit solver with tiling and nested SIMD.
*
* Contact: Louis-Noel Pouchet <pouchet@cse.ohio-state.edu>
* Web address: http://polybench.sourceforge.net
* License: /LICENSE.OSU.txt
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include "polybench/polybench.h"
/* Include benchmark-specific header. */
/* Default data type is double, default size is 10x1024x1024. */
#include "polybench/adi.h"
/* Array initialization. */
static void init_array(int n,double X[500 + 0][500 + 0],double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int i;
//int j;
{
int c1;
int c3;
int c2;
int c4;
if (n >= 1) {
#pragma omp parallel for private(c4, c2, c3)
for (c1 = 0; c1 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c1++) {
for (c2 = 0; c2 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c2++) {
for (c3 = 16 * c1; c3 <= ((16 * c1 + 15 < n + -1?16 * c1 + 15 : n + -1)); c3++) {
#pragma omp simd
for (c4 = 16 * c2; c4 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c4++) {
X[c3][c4] = (((double )c3) * (c4 + 1) + 1) / n;
A[c3][c4] = (((double )c3) * (c4 + 2) + 2) / n;
B[c3][c4] = (((double )c3) * (c4 + 3) + 3) / n;
}
}
}
}
}
}
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static void print_array(int n,double X[500 + 0][500 + 0])
{
int i;
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
fprintf(stderr,"%0.2lf ",X[i][j]);
if ((i * 500 + j) % 20 == 0)
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static void kernel_adi(int tsteps,int n,double X[500 + 0][500 + 0],double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int t;
//int i1;
//int i2;
//#pragma scop
{
int c0;
int c2;
int c8;
int c9;
int c15;
if (n >= 1 && tsteps >= 1) {
for (c0 = 0; c0 <= tsteps + -1; c0++) {
if (n >= 2) {
#pragma omp parallel for private(c15, c9, c8)
for (c2 = 0; c2 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c2++) {
for (c8 = 0; c8 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c8++) {
for (c9 = (1 > 16 * c8?1 : 16 * c8); c9 <= ((16 * c8 + 15 < n + -1?16 * c8 + 15 : n + -1)); c9++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
B[c15][c9] = B[c15][c9] - A[c15][c9] * A[c15][c9] / B[c15][c9 - 1];
}
}
}
for (c8 = 0; c8 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c8++) {
for (c9 = (1 > 16 * c8?1 : 16 * c8); c9 <= ((16 * c8 + 15 < n + -1?16 * c8 + 15 : n + -1)); c9++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
X[c15][c9] = X[c15][c9] - X[c15][c9 - 1] * A[c15][c9] / B[c15][c9 - 1];
}
}
}
for (c8 = 0; c8 <= (((n + -3) * 16 < 0?((16 < 0?-((-(n + -3) + 16 + 1) / 16) : -((-(n + -3) + 16 - 1) / 16))) : (n + -3) / 16)); c8++) {
for (c9 = 16 * c8; c9 <= ((16 * c8 + 15 < n + -3?16 * c8 + 15 : n + -3)); c9++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
X[c15][n - c9 - 2] = (X[c15][n - 2 - c9] - X[c15][n - 2 - c9 - 1] * A[c15][n - c9 - 3]) / B[c15][n - 3 - c9];
}
}
}
}
}
#pragma omp parallel for private(c15)
for (c2 = 0; c2 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c2++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
X[c15][n - 1] = X[c15][n - 1] / B[c15][n - 1];
}
}
if (n >= 2) {
#pragma omp parallel for private(c15, c9, c8)
for (c2 = 0; c2 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c2++) {
for (c8 = 0; c8 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c8++) {
for (c9 = (1 > 16 * c8?1 : 16 * c8); c9 <= ((16 * c8 + 15 < n + -1?16 * c8 + 15 : n + -1)); c9++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
B[c9][c15] = B[c9][c15] - A[c9][c15] * A[c9][c15] / B[c9 - 1][c15];
}
}
}
for (c8 = 0; c8 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c8++) {
for (c9 = (1 > 16 * c8?1 : 16 * c8); c9 <= ((16 * c8 + 15 < n + -1?16 * c8 + 15 : n + -1)); c9++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
X[c9][c15] = X[c9][c15] - X[c9 - 1][c15] * A[c9][c15] / B[c9 - 1][c15];
}
}
}
for (c8 = 0; c8 <= (((n + -3) * 16 < 0?((16 < 0?-((-(n + -3) + 16 + 1) / 16) : -((-(n + -3) + 16 - 1) / 16))) : (n + -3) / 16)); c8++) {
for (c9 = 16 * c8; c9 <= ((16 * c8 + 15 < n + -3?16 * c8 + 15 : n + -3)); c9++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
X[n - 2 - c9][c15] = (X[n - 2 - c9][c15] - X[n - c9 - 3][c15] * A[n - 3 - c9][c15]) / B[n - 2 - c9][c15];
}
}
}
}
}
#pragma omp parallel for private(c15)
for (c2 = 0; c2 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c2++) {
#pragma omp simd
for (c15 = 16 * c2; c15 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c15++) {
X[n - 1][c15] = X[n - 1][c15] / B[n - 1][c15];
}
}
}
}
}
//#pragma endscop
}
int main(int argc,char **argv)
{
/* Retrieve problem size. */
int n = 500;
int tsteps = 10;
/* Variable declaration/allocation. */
double (*X)[500 + 0][500 + 0];
X = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
double (*A)[500 + 0][500 + 0];
A = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
double (*B)[500 + 0][500 + 0];
B = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
/* Initialize array(s). */
init_array(n, *X, *A, *B);
/* Start timer. */
polybench_timer_start();
;
/* Run kernel. */
kernel_adi(tsteps,n, *X, *A, *B);
/* Stop and print timer. */
polybench_timer_stop();
;
polybench_timer_print();
;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
if (argc > 42 && !strcmp(argv[0],""))
print_array(n, *X);
/* Be clean. */
free(((void *)X));
;
free(((void *)A));
;
free(((void *)B));
;
return 0;
}
|
canonical_cpn.h | /// \file
///
/// \brief Canonical CP(N) action
#pragma once
#include "../src/gaugegroups/u1.h"
#include "./cpn_common_aux.h"
template <typename T, size_t N, size_t dim>
class CanonicalCPNAction {
private:
FullLattice<CP<T, N>, U1, dim> const *lattice;
double beta;
typedef CP<T, N> CPtype;
public:
// **********************************************************************
// Constructors
// **********************************************************************
/// Default constructor
CanonicalCPNAction() : beta(1.0) { lattice = nullptr; }
/// Construct with given lattice
CanonicalCPNAction(FullLattice<CP<T, N>, U1, dim> const &orig,
const double &coupling = 1.0)
: lattice(&orig), beta(coupling)
{
}
// **********************************************************************
// Deconstructor
// **********************************************************************
~CanonicalCPNAction() = default;
// **********************************************************************
// Member Functions
// **********************************************************************
/// Setter for beta
void setbeta(const double &coupling) { beta = coupling; }
/// Getter for beta
double getbeta() { return this->beta; }
template <typename P = double>
auto atSite(size_t const &idx, const BoundaryCondition<P, dim> &bc =
BoundaryCondition<P, dim>()) const
-> decltype(std::abs(T(1.)))
{
auto lat = *lattice;
FullLatticeIterator<const FullLattice<CPtype, U1, dim>> fli(idx, lat);
auto sum = T(0.0);
auto site = fli.site();
for (auto i = 0lu; i < dim; i++) {
sum += scalar_prod(site, fli.neighborSite(i, Direction::FORWARD, bc)) *
fli.link(i).value();
}
return -2. * (this->beta) * N * std::real(sum);
}
template <typename P = double>
auto
total(const BoundaryCondition<P, dim> &bc = BoundaryCondition<P, dim>()) const
-> decltype(std::abs(T(1.)))
{
const auto lat = *lattice;
FullLatticeIterator<const FullLattice<CPtype, U1, dim>> fli(lat);
auto res = T(0.0);
// Loop over all sites
for (fli = lat.begin(); fli != lat.end(); ++fli) {
auto site = fli.site();
for (auto i = 0lu; i < dim; i++) {
res += scalar_prod(site, fli.neighborSite(i, Direction::FORWARD, bc)) *
fli.link(i).value();
}
}
return -2. * (this->beta) * N * (std::real(res));
}
template <typename P = double>
auto average(const BoundaryCondition<P, dim> &bc =
BoundaryCondition<P, dim>()) const -> decltype(std::abs(T(1.)))
{
auto vol = static_cast<double>(lattice->volume());
return total(bc) / vol;
}
template <typename P = double>
auto energyDensity(
const BoundaryCondition<P, dim> &bc = BoundaryCondition<P, dim>()) const
-> decltype(std::abs(T(1.)))
{
auto vol = static_cast<double>(lattice->volume());
return -total(bc) / (vol * this->beta);
}
};
template <typename T, size_t N, size_t dim>
class CanonicalCPNObservables {
private:
FullLattice<CP<T, N>, U1, dim> const *lattice;
double beta;
typedef CP<T, N> CPtype;
public:
// **********************************************************************
// Constructors
// **********************************************************************
/// Default constructor
CanonicalCPNObservables() : beta(1.0) { lattice = nullptr; }
/// Construct with given lattice
CanonicalCPNObservables(FullLattice<CP<T, N>, U1, dim> const &orig,
const double &coupling = 1.0)
: lattice(&orig), beta(coupling)
{
}
// **********************************************************************
// Deconstructor
// **********************************************************************
~CanonicalCPNObservables() = default;
// **********************************************************************
// Member Functions
// **********************************************************************
bool check_normalisation(double norm_eps = 1.e-9)
{
const auto lat = *lattice;
FullLatticeIterator<const FullLattice<CPtype, U1, dim>> fli(lat);
/// Loop over all sites
for (fli = lat.begin(); fli != lat.end(); ++fli) {
auto site = fli.site();
auto snorm = site.norm();
if (std::abs(snorm - 1) > norm_eps) {
// std::cout << "Site norm at index " << fli.index() << " is " << snorm
// << std::endl;
return false;
}
for (auto i = 0lu; i < dim; i++) {
auto lnorm = fli.link(i).norm();
if (std::abs(lnorm - 1) > norm_eps) {
std::cout << "Link norm at index " << fli.index() << " and site " << i
<< " is " << snorm << std::endl;
return false;
}
}
}
return true;
}
/// Returns (the real part of the trace of ) the plaquette
template <typename P = double>
auto plaquette(
size_t site, size_t mu, size_t nu,
BoundaryCondition<P, dim> const &bc = BoundaryCondition<P, dim>()) const
-> decltype(std::real(trace(U1(1.))))
{
if (site >= lattice->volume()) {
throw std::runtime_error("Site out of range");
}
if (mu >= dim) {
throw std::runtime_error("mu out of range");
}
if (nu >= dim) {
throw std::runtime_error("nu out of range");
}
if (mu == nu) {
throw std::runtime_error("mu must not equal nu");
}
auto it = lattice->begin();
it = it[site];
// U_µν(x) =U_µ(x)U_ν(x+µ)dagger(U_µ(n+ν))dagger(U_ν(x))
auto plaq = it.link(mu);
plaq *= it.neighborLink(mu, nu, Direction::FORWARD, bc);
plaq *= dagger(it.neighborLink(nu, mu, Direction::FORWARD, bc));
plaq *= dagger(it.link(nu));
// auto coord = lattice->linearIndexToCoord(site);
// std::cout << "( ";
// for (auto && el : coord)
// {
// std::cout << el << "\t";
// }
// std::cout << ") ";
// std::cout << "Site: " << site << "\tIt: " << it.index()
// << "\tIt_nu: " << it_nu.index()
// << "\tIt_mu: " << it_mu.index() << "\n";
return std::real(trace(plaq));
}
/// Compute mean plaquette in the mu-nu plane
template <typename P = double>
auto meanPlaquette(size_t mu, size_t nu, BoundaryCondition<P, dim> const &bc =
BoundaryCondition<P, dim>()) const
-> decltype(std::real(trace(U1(1.))))
{
auto res = plaquette(0lu, mu, nu, bc);
for (auto i = 1ul; i < lattice->volume(); ++i) {
res += plaquette(i, mu, nu);
}
return res / static_cast<double>(lattice->volume());
}
/// Compute global plaquette average
template <typename P = double>
auto meanPlaquette(
BoundaryCondition<P, dim> const &bc = BoundaryCondition<P, dim>()) const
-> decltype(std::real(trace(U1(1.))))
{
decltype(std::real(trace(U1(1.)))) res = 0.0;
for (auto mu = 0lu; mu < dim; ++mu) {
for (auto nu = mu + 1lu; nu < dim; ++nu) {
auto res_mu_nu = plaquette(0ul, mu, nu);
for (auto i = 1ul; i < lattice->volume(); ++i) {
res_mu_nu += plaquette(i, mu, nu, bc);
}
res_mu_nu *= 1. / static_cast<double>(lattice->volume());
res += res_mu_nu;
}
}
return 2.0 * res / (static_cast<double>(dim * (dim - 1)));
}
/// Compute trace of P(x)*P(y), where P is the tensor product of a CP(N-1)
/// field z, i.e
/// P_ij=conj(z_i)*z_J
auto tracePP(size_t x, size_t y) -> decltype(std::abs(T(1.)))
{
auto V = lattice->volume();
if (x >= V || y >= V) {
throw std::runtime_error("Site out of range");
}
auto sp = scalar_prod(lattice->getSite(x), lattice->getSite(y));
auto res = std::abs(sp);
res *= res;
res = res - 1. / static_cast<double>(N);
return res;
}
/// Magnetic susceptibility chi_m
auto chi_m() -> decltype(std::abs(T(1.)))
{
if (dim != 2) {
throw std::runtime_error("chi_m not implemented for dim != 2.");
}
auto V = lattice->volume();
auto res = std::abs(T(0.0));
for (auto x = 0ul; x < V; ++x) {
for (auto y = 0ul; y < V; ++y) {
auto trace = tracePP(x, y);
res += trace;
}
}
return res / static_cast<double>(V);
}
/// Correlation length xi_G
/// For a defintion see for example Campostrini,Rossi and Vicari PRD 46,
/// 6, 1992, p 2647
/// The time component has index zero!
/// Not implemented for dim != 2
auto xi_G() -> decltype(std::abs(T(1.)))
{
if (dim != 2) {
throw std::runtime_error("xi_G not implemented for dim != 2.");
}
std::complex<double> II(0., 1.);
constexpr double pi_2 = 2. * M_PI;
T G_00(0.0);
T G_10(0.0);
auto L = lattice->dimensionsArray()[0];
auto factor = II * pi_2 / static_cast<double>(L);
for (auto x = 0ul; x < lattice->volume(); ++x) {
auto x_cord = lattice->linearIndexToCoord(x);
auto t_x = x_cord[0];
for (auto y = 0ul; y < lattice->volume(); ++y) {
auto y_cord = lattice->linearIndexToCoord(y);
auto t_y = y_cord[0];
auto trace = tracePP(x, y);
// time difference
auto t_diff = static_cast<double>((t_x - t_y + L) % L);
G_00 += trace;
G_10 += trace * std::exp(factor * t_diff);
}
}
auto ratio = G_00 / G_10 - 1.;
auto sin_factor = 2.0 * std::sin(pi_2 / (2. * static_cast<double>(L)));
sin_factor *= sin_factor;
// This should be real ... shouldn't it ? ...
auto res = std::sqrt(ratio / sin_factor);
// Well ...
return std::abs(res);
}
/// Compute all Wall-Wall correlators
/// Not implemented for dim != 2
auto WW_correlators() -> std::vector<decltype(std::abs(T(1.)))>
{
if (dim != 2) {
throw std::runtime_error(
"Wall-Wall correlators not implemented for dim != 2.");
}
auto dims = lattice->dimensionsArray();
auto Lt = dims[0];
auto Ls = dims[1];
std::vector<decltype(std::abs(T(1.)))> WW_res(Lt, std::abs(T(0.0)));
for (auto x = 0ul; x < lattice->volume(); ++x) {
auto x_cord = lattice->linearIndexToCoord(x);
auto t_x = x_cord[0];
for (auto y = 0ul; y < lattice->volume(); ++y) {
auto y_cord = lattice->linearIndexToCoord(y);
auto t_y = y_cord[0];
auto trace = tracePP(x, y);
// time difference
auto t_diff = (t_x - t_y + Lt) % Lt;
WW_res[t_diff] += trace;
}
}
// Normalise
for (auto i = 0LU; i < WW_res.size(); ++i) {
WW_res[i] /= static_cast<double>(Ls);
}
return WW_res;
}
/// Top. Plaquette, an observable needed for our top. charge definition
/// on the lattice.
template <typename P = double>
auto
top_plaq(size_t site,
const BoundaryCondition<P, dim> &bc = BoundaryCondition<P, dim>())
-> decltype(std::abs(T(1.0)))
{
if (site >= lattice->volume()) {
throw std::runtime_error("Site out of range");
}
if (dim != 2) {
throw std::runtime_error(
"'Topological plaquette' not implemented for dim != 2.");
}
auto res = std::abs(T(0.0));
auto it = lattice->begin();
it = it[site];
auto neib = it.neighbor(0, 1);
auto z_x = it.site();
auto z_x_mu = it.neighborSite(0, Direction::FORWARD, bc);
auto z_x_nu = it.neighborSite(1, Direction::FORWARD, bc);
auto z_x_mu_nu = neib.neighborSite(1, Direction::FORWARD, bc);
// + θx,µ
res += std::arg(scalar_prod(z_x, z_x_mu));
// + θx+µ,ν
res += std::arg(scalar_prod(z_x_mu, z_x_mu_nu));
// - θx+ν,µ
res -= std::arg(scalar_prod(z_x_nu, z_x_mu_nu));
// - θx,ν
res -= std::arg(scalar_prod(z_x, z_x_nu));
// Bring to (-pi, pi] interval
while (res <= -1. * M_PI) {
res += 2 * M_PI;
}
while (res > M_PI) {
res -= 2 * M_PI;
}
return res;
}
/// Top. Plaquette, an observable needed for our top. charge definition
/// on the lattice.
template <typename P = double>
auto Q_top(const BoundaryCondition<P, dim> &bc = BoundaryCondition<P, dim>())
-> decltype(std::abs(T(1.0)))
{
auto res = std::abs(T(0.0));
for (auto x = 0ul; x < lattice->volume(); ++x) {
res += top_plaq(x, bc);
}
return res / (2. * M_PI);
}
auto GaugeFieldSpatialSum()
-> std::vector<std::array<decltype(std::abs(T(1.))), dim>>
{
auto dims = lattice->dimensionsArray();
std::array<decltype(std::abs(T(1.))), dim> A;
std::vector<std::array<decltype(std::abs(T(1.))), dim>> Avec;
A.fill(std::abs(T(0.)));
// Output vector has size of temporal lattice extend
for (auto l = 0LU; l < dims[0]; ++l) {
Avec.push_back(A); // Init with "zero"
}
// Loop over all lattice sites
// std::vector<size_t> tvec;
// tvec.resize(Avec.size());
for (auto fli = lattice->begin(); fli != lattice->end(); ++fli) {
auto cord = lattice->linearIndexToCoord(fli.index());
auto t = cord[0];
// tvec[t]++;
for (auto mu = 0LU; mu < dim; ++mu) {
(Avec[t])[mu] += std::sin((fli.link(mu)).phase());
}
}
// std::cout << "TVEC: ";
// std::for_each(tvec.begin(),tvec.end(),[](auto a){std::cout << a <<
// "\t";});
// No normalisation !!!
return Avec;
}
};
/// Class that implements gauge fixing and related functions
/// \brief Gauge fixing class
///
/// \note The functions defined here only make sense for PERIODIC boundary
/// conditions.
template <typename T, size_t N, size_t dim>
class CanonicalCPNGaugeFix {
private:
FullLattice<CP<T, N>, U1, dim> *const lattice;
double beta;
typedef CP<T, N> CPtype;
public:
// **********************************************************************
// Constructors
// **********************************************************************
/// Default constructor
CanonicalCPNGaugeFix() : beta(1.0) { lattice = nullptr; }
/// Construct with given lattice
CanonicalCPNGaugeFix(FullLattice<CP<T, N>, U1, dim> &orig,
const double &coupling = 1.0)
: lattice(&orig), beta(coupling)
{
}
// **********************************************************************
// Deconstructor
// **********************************************************************
~CanonicalCPNGaugeFix() = default;
// **********************************************************************
// Member Functions
// **********************************************************************
void randomGaugeTransformation()
{
auto &lat = *lattice;
FullLatticeIterator<FullLattice<CPtype, U1, dim>> fli(0, lat);
// Init ranlux with true random number (Well, at least we try. The C++
// standard does not guaranty std::random_device() gives a true random
// number)
std::random_device rd;
std::seed_seq sseq({ rd(), rd(), rd() });
// std::seed_seq sseq ({1,2,3,4});
std::ranlux48 generator(sseq);
// std::ostream_iterator<unsigned> out (std::cout," ");
// sseq.param(out); std::cout << "\n" << generator << "\n" << std::endl;
// Uniformly pick a phase from [-pi,pi)
// Note that this is consistent with the std::arg function from std::complex
std::uniform_real_distribution<double> dist(-1.0, 1.0);
for (fli = lat.begin(); fli != lat.end(); ++fli) {
double rphase = M_PI * dist(generator);
// Apply gauge transformation to site ...
std::complex<double> ii(0, 1);
(*fli).site *= std::exp(-ii * rphase);
// ... and to all adjacent links
for (auto i = 0UL; i < dim; ++i) {
auto n_dir = fli.neighbor(i, -1);
(*fli).links[i] *= std::exp(-ii * rphase);
(*n_dir).links[i] *= std::exp(ii * rphase);
}
}
}
double LandauGaugeFunctional() const
{
double res = 0;
for (auto it = lattice->begin(); it != lattice->end(); ++it) {
auto links = it.linkarray();
for (size_t i = 0; i < lattice->dimensions(); ++i) {
res += std::cos(links[i].phase());
}
}
return res;
}
void localLandauGauge(size_t const &idx, const double or_param = 1.0)
{
auto &lat = *lattice;
FullLatticeIterator<FullLattice<CPtype, U1, dim>> fli(idx, lat);
// Calculate the phase to locally fix the config to Landau gauge
double num = 0.0;
double den = 0.0;
for (auto i = 0UL; i < dim; ++i) {
auto n_dir = fli.neighbor(i, -1);
auto here = (fli.link(i)).phase();
auto neib = (n_dir.link(i)).phase();
num += (std::sin(here) - std::sin(neib));
den += (std::cos(here) + std::cos(neib));
}
auto phase = or_param * std::atan(num / den);
// Apply gauge transformation to site ...
std::complex<double> ii(0, 1);
(*fli).site *= std::exp(-ii * phase);
// ... and to all adjacent links
for (auto i = 0UL; i < dim; ++i) {
auto n_dir = fli.neighbor(i, -1);
(*fli).links[i] *= std::exp(-ii * phase);
(*n_dir).links[i] *= std::exp(ii * phase);
}
}
double localLandauGaugeQuality(size_t const &idx)
{
auto &lat = *lattice;
FullLatticeIterator<FullLattice<CPtype, U1, dim>> fli(idx, lat);
double res = 0.0;
for (auto i = 0UL; i < dim; ++i) {
auto n_dir = fli.neighbor(i, -1);
auto here = (fli.link(i)).phase();
auto neib = (n_dir.link(i)).phase();
res += (std::sin(here) - std::sin(neib));
}
return res * res;
}
/// \Todo Implement boundary condition
void LandauGaugeSweep(const double or_param = 1.0)
{
auto lat = *lattice;
// FullLatticeIterator<FullLattice<CPtype,U1, dim>> fli(lat);
// size_t count[] = {0,0};
// Loop over all even and odd sites separately
for (auto eo = 0; eo < 2; ++eo) {
// for (fli=lat.begin(); fli != lat.end(); ++fli)
#pragma omp parallel for
for (auto idx = 0LU; idx < lat.volume(); ++idx) {
// auto idx = fli.index();
auto coords = lat.linearIndexToCoord(idx);
auto csum = std::accumulate(coords.begin(), coords.end(), 0);
if (eo == csum % 2) {
localLandauGauge(idx, or_param);
// count[eo]++;
}
}
}
// std::cout << "Sites: " << count[0] << "/" << count[1] << std::endl;
// std::cout << "Volume: " << lat.volume() << std::endl;
}
double LandauGaugeQuality()
{
auto lat = *lattice;
double res = 0.0;
for (auto idx = 0LU; idx < lat.volume(); ++idx) {
res += localLandauGaugeQuality(idx);
}
return res / static_cast<double>(lat.volume());
}
size_t LandauGaugeDriver(const size_t gc_num, const size_t sw_num,
const double or_param = 1.0)
{
double minus_inf = std::numeric_limits<double>::lowest();
FullLattice<CPtype, U1, dim> gauge_copy(*lattice), best_copy(*lattice);
double best = minus_inf; // Init with large negative number
double last = 0;
size_t iter = 0LU;
for (auto i = 0UL; i < gc_num; ++i) {
CanonicalCPNGaugeFix<T, N, dim> gc_gf(gauge_copy, this->beta);
if (0LU != i) // Use the original config once
{
gc_gf.randomGaugeTransformation();
}
// double last_LF=gc_gf.LandauGaugeFunctional();
for (auto s = 0UL; s < sw_num; ++s) {
gc_gf.LandauGaugeSweep(or_param);
++iter;
// double new_LF=gc_gf.LandauGaugeFunctional();
// if (std::abs(new_LF-last_LF) <
// 1.e-6/static_cast<double>((*lattice).volume()))
if (gc_gf.LandauGaugeQuality() < 1.e-9) {
// last_LF = new_LF;
last = gc_gf.LandauGaugeFunctional();
// std::cout << "\t\t Best local LF: " << last_LF << "\t (best global:
// " << best << ")"
// << "(" << ++s << " sweeps)" << std::endl;
break;
}
// last_LF = new_LF;
}
// last = last_LF;
if (last > best) {
best_copy = gauge_copy;
best = last;
}
}
*lattice = best_copy;
return iter;
}
};
// ####################################################################################################
// ####################################################################################################
// Langevin related code
// ####################################################################################################
// ####################################################################################################
// --------------------------------------------------------------------------------
// Helper functions
// --------------------------------------------------------------------------------
namespace CanonicalCPNHelpers {
template <size_t N, size_t dim>
struct CPForceStruct {
nummat<N> site{ 0.0 };
std::array<std::complex<double>, dim> links;
};
/// Simple printing of CPForce struct
template <size_t N, size_t dim>
std::ostream &operator<<(std::ostream &stream, CPForceStruct<N, dim> const &cfs)
{
stream.precision(6);
stream << std::scientific << "Force site: " << cfs.site;
for (auto i = 0LU; i < dim; i++) {
stream << "\n"
<< "Force links:" << cfs.links[i];
}
stream << std::endl;
return stream;
}
template <size_t N>
struct CPCasimirStruct {
const double site = static_cast<double>(N);
const double links = 0.;
};
/// Simple printing of Casimir struct
template <size_t N>
std::ostream &operator<<(std::ostream &stream, CPCasimirStruct<N> const &cps)
{
stream.precision(6);
stream << std::scientific << "Casimir site: " << cps.site << "\n"
<< "Casimir links:" << cps.links;
return stream;
}
template <size_t N, size_t dim>
SiteAndLinks<CP<std::complex<double>, N>, U1, dim>
operator*(CPForceStruct<N, dim> const &cpdf,
SiteAndLinks<CP<std::complex<double>, N>, U1, dim> const &sl)
{
SiteAndLinks<CP<std::complex<double>, N>, U1, dim> res;
res.site = cpdf.site * sl.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = cpdf.links[i] * sl.links[i];
}
return res;
}
template <size_t N, size_t dim>
CPForceStruct<N, dim> exp(CPForceStruct<N, dim> const &cpdf)
{
CPForceStruct<N, dim> res;
res.site = exp(cpdf.site);
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = exp(cpdf.links[i]);
}
return res;
}
template <size_t N, size_t dim>
CPForceStruct<N, dim> operator*(CPForceStruct<N, dim> const &cpdf,
std::complex<double> const &scalar)
{
CPForceStruct<N, dim> res;
res.site = scalar * cpdf.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = cpdf.links[i] * scalar;
}
return res;
}
template <size_t N, size_t dim>
CPForceStruct<N, dim> operator*(CPForceStruct<N, dim> const &lcpdf,
CPCasimirStruct<N> const &CA)
{
CPForceStruct<N, dim> res;
res.site = lcpdf.site * CA.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = lcpdf.links[i] * CA.links;
}
return res;
}
template <size_t N, size_t dim>
CPForceStruct<N, dim> operator*(CPCasimirStruct<N> const &CA,
CPForceStruct<N, dim> const &rcpdf)
{
CPForceStruct<N, dim> res;
res.site = CA.site * rcpdf.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = CA.links * rcpdf.links[i];
}
return res;
}
template <size_t N, size_t dim>
CPForceStruct<N, dim> operator+(CPForceStruct<N, dim> const &L,
CPForceStruct<N, dim> const &R)
{
CPForceStruct<N, dim> res;
res.site = L.site + R.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = L.links[i] + R.links[i];
}
return res;
}
template <size_t N, size_t dim>
CPForceStruct<N, dim> operator-(CPForceStruct<N, dim> const &L,
CPForceStruct<N, dim> const &R)
{
CPForceStruct<N, dim> res;
res.site = L.site - R.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = L.links[i] - R.links[i];
}
return res;
}
template <size_t N, size_t dim>
CPForceStruct<N, dim> operator*(std::complex<double> const &scalar,
CPForceStruct<N, dim> const &cpdf)
{
return cpdf * scalar;
}
} // End of namespace "CanonicalCPNHelpers "
namespace CanonicalCPNExpHelpers {
/// Multiplication of U1 and CP expansions
template <size_t N, size_t order>
auto operator*(Expansion<U1, order> const &left,
Expansion<CP<std::complex<double>, N>, order> const &right)
-> Expansion<CP<std::complex<double>, N>, order>
{
Expansion<CP<std::complex<double>, N>, order> res;
for (auto n = 0LU; n < order; ++n) {
for (auto i = 0LU; i <= n; ++i) {
res[n] += left[n - i] * right[i];
}
}
return res;
}
template <size_t N, size_t order>
auto operator*(Expansion<CP<std::complex<double>, N>, order> const &left,
Expansion<U1, order> const &right)
-> Expansion<CP<std::complex<double>, N>, order>
{
return right * left;
}
/// Multiplication of U1 and std::complex<double> expansions
template <size_t order>
auto operator*(Expansion<U1, order> const &left,
Expansion<std::complex<double>, order> const &right)
-> Expansion<std::complex<double>, order>
{
Expansion<std::complex<double>, order> res;
for (auto n = 0LU; n < order; ++n) {
for (auto i = 0LU; i <= n; ++i) {
res[n] += left[n - i].value() * right[i];
}
}
return res;
}
template <size_t order>
auto operator*(Expansion<std::complex<double>, order> const &left,
Expansion<U1, order> const &right)
-> Expansion<std::complex<double>, order>
{
return right * left;
}
template <typename T, size_t order>
std::ostream &operator<<(std::ostream &stream, Expansion<T, order> const &e)
{
for (auto i = 0ul; i < order; ++i) {
stream << "order: " << i << " --> " << e[i] << std::endl;
}
return stream;
}
/// Computes the Hermitian matrix
/// scalar*left*dagger(right)+right*dagger(scalar*left) and adds it to M.
/// Warning! This only fills the upper part of the Hermitian matrix. M should be
/// a compressed Hermitian matrix in CblasUpper form!
template <size_t N, size_t order>
void external_product(Expansion<U1, order> const &scalar,
Expansion<CP<std::complex<double>, N>, order> const &x,
Expansion<CP<std::complex<double>, N>, order> const &y,
Expansion<nummat<N>, order> &M)
{
// Multiply x by scalar
auto xbar = scalar * x;
constexpr std::complex<double> dummy{ 1., 0. };
for (auto n = 0LU; n < order; ++n) {
for (auto l = 0LU; l <= n; ++l) {
cblas_zher2(CBLAS_ORDER::CblasRowMajor, CBLAS_UPLO::CblasUpper, N,
reinterpret_cast<const double *>(&dummy),
reinterpret_cast<const double *>(&xbar[l][0]), 1,
reinterpret_cast<const double *>(&y[n - l][0]), 1,
reinterpret_cast<double *>(M[n].data()), N);
}
}
}
template <size_t N, size_t dim>
struct CPForceStruct {
nummat<N> site{ 0.0 };
std::array<std::complex<double>, dim> links;
};
template <typename T, size_t N, size_t dim>
CPForceStruct<N, dim> operator*(T const &lhs, CPForceStruct<N, dim> rhs)
{
rhs.site = lhs * rhs.site;
for (auto i = 0LU; i < dim; ++i) {
rhs.links[i] = lhs * rhs.links[i];
}
return rhs;
}
template <size_t N, size_t dim, typename Generator>
class randomCPdf {
public:
CPForceStruct<N, dim> operator()(Generator &rng) const
{
CPForceStruct<N, dim> rd;
rd.site = noiseSUN<N, Generator>(rng, CP_Langevin_noise_scale);
for (auto i = 0LU; i < rd.links.size(); ++i) {
rd.links[i] = noiseU1(rng, CP_Langevin_noise_scale);
}
return rd;
}
};
template <size_t N, size_t dim, size_t order>
struct CPForceStructExp {
Expansion<nummat<N>, order> site{ 0.0 };
std::array<Expansion<std::complex<double>, order>, dim> links;
};
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order> operator+(CPForceStruct<N, dim> const &lhs,
CPForceStructExp<N, dim, order> rhs)
{
if (order > 1) {
rhs.site[1] = lhs.site + rhs.site[1];
for (auto i = 0LU; i < dim; ++i) {
rhs.links[i][1] = lhs.links[i] + rhs.links[i][1];
}
}
return rhs;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order> operator+(CPForceStructExp<N, dim, order> lhs,
CPForceStruct<N, dim> const &rhs)
{
return (rhs + lhs);
}
template <size_t N>
struct CPCasimirStruct {
const double site = static_cast<double>(N);
const double links = 0.;
};
template <size_t N, size_t dim, size_t order>
using SiteAndLinksExp =
SiteAndLinks<Expansion<CP<std::complex<double>, N>, order>,
Expansion<U1, order>, dim>;
template <size_t N, size_t dim, size_t order>
SiteAndLinksExp<N, dim, order>
operator*(CPForceStructExp<N, dim, order> const &cpdf,
SiteAndLinksExp<N, dim, order> const &sl)
{
SiteAndLinksExp<N, dim, order> res;
res.site = cpdf.site * sl.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = cpdf.links[i] * sl.links[i];
}
return res;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order> exp(CPForceStructExp<N, dim, order> const &cpdf)
{
CPForceStructExp<N, dim, order> res;
res.site = exp(cpdf.site);
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = exp(cpdf.links[i]);
}
return res;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order>
operator*(CPForceStructExp<N, dim, order> const &cpdf,
std::complex<double> const &scalar)
{
CPForceStructExp<N, dim, order> res;
res.site = scalar * cpdf.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = cpdf.links[i] * scalar;
}
return res;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order>
operator*(CPForceStructExp<N, dim, order> const &lcpdf,
CPCasimirStruct<N> const &CA)
{
CPForceStructExp<N, dim, order> res;
res.site = lcpdf.site * CA.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = lcpdf.links[i] * CA.links;
}
return res;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order>
operator*(CPCasimirStruct<N> const &CA,
CPForceStructExp<N, dim, order> const &rcpdf)
{
return rcpdf * CA;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order>
operator+(CPForceStructExp<N, dim, order> const &L,
CPForceStructExp<N, dim, order> const &R)
{
CPForceStructExp<N, dim, order> res;
res.site = L.site + R.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = L.links[i] + R.links[i];
}
return res;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order>
operator-(CPForceStructExp<N, dim, order> const &L,
CPForceStructExp<N, dim, order> const &R)
{
CPForceStructExp<N, dim, order> res;
res.site = L.site - R.site;
for (auto i = 0LU; i < dim; ++i) {
res.links[i] = L.links[i] - R.links[i];
}
return res;
}
template <size_t N, size_t dim, size_t order>
CPForceStructExp<N, dim, order>
operator*(std::complex<double> const &scalar,
CPForceStructExp<N, dim, order> const &cpdf)
{
return cpdf * scalar;
}
// template<size_t order>
// auto operator+=( Expansion< std::complex<double>, order > &one,
// Expansion< double, order > const &other)
// -> Expansion< std::complex<double>, order >
// {
// for( size_t i=0; i < order; ++i) {
// one[i] += other[i];
// }
// return one;
// }
// template<size_t N, size_t order>
// auto operator*( Expansion<std::complex<double>,order> const &left, nummat<N>
// const & right)
// -> Expansion< nummat<N>, order >
// {
// Expansion< nummat<N>, order > res;
// for (auto i=0LU; i<order; ++i){
// res[i]=left[i]*right;
// }
// return res;
// }
// template<size_t N, size_t order>
// auto operator*( Expansion<std::complex<double>,order> const &left,
// Expansion<nummat<N>,order> const & right)
// -> Expansion< nummat<N>, order >
// {
// Expansion< nummat<N>, order > res;
// for( size_t n = 0; n < order; ++n )
// {
// for( size_t i = 0; i <= n; ++i )
// {
// res[ n ] += left[ n - i ] * right[ i ];
// }
// }
// return res;
// }
// template<size_t N, size_t order>
// auto operator*( Expansion<nummat<N>,order> const &left,
// Expansion<std::complex<double>,order> const & right)
// -> Expansion< nummat<N>, order >
// {
// return right*left;
// }
// template<size_t N, size_t order>
// auto operator*( Expansion<nummat<N>,order> const &left,
// Expansion<CP<std::complex<double>,N>,order> const & right)
// -> Expansion< CP<std::complex<double>,N>, order >
// {
// Expansion< CP<std::complex<double>,N>, order > res;
// for( size_t n = 0; n < order; ++n )
// {
// for( size_t i = 0; i <= n; ++i )
// {
// res[ n ] += left[ n - i ] * right[ i ];
// }
// }
// return res;
// }
} // End of namespace "CanonicalCPNExpHelpers"
// --------------------------------------------------------------------------------
// Drift Force
// --------------------------------------------------------------------------------
namespace NoExpansion {
using namespace CanonicalCPNHelpers;
/// CP(N-1) Drift Force
template <size_t N, size_t dim, typename P = double, typename L = double>
class CPForce : public Force<FullLattice<CP<std::complex<double>, N>, U1, dim>,
std::vector<CPForceStruct<N, dim>>> {
private:
BoundaryCondition<P, dim> sbc;
BoundaryCondition<L, dim> lbc;
public:
typedef CPForceStruct<N, dim> CPdf;
typedef std::vector<CPdf> CPForceField;
typedef FullLattice<CP<std::complex<double>, N>, U1, dim> CPlattice;
/// Returns force field using standard boundary cond.
CPForceField operator()(CPlattice const &lat) const
{
// Pre-allocate memory
CPForceField FF;
FF.reserve(lat.volume());
for (auto it = lat.begin(); it != lat.end(); ++it) {
// ################################################################################
CPdf res;
const auto II = std::complex<double>(0.0, 1.0);
auto unit_matrix = cmplx(0.0);
for (auto i = 0lu; i < dim; i++) {
auto link = it.link(i).value();
auto link_bwd = it.neighborLink(i, i, Direction::BACKWARD, lbc).value();
auto field = it.site();
auto field_fwd = it.neighborSite(i, Direction::FORWARD, sbc);
auto field_bwd = it.neighborSite(i, Direction::BACKWARD, sbc);
// CP field
// ----------------------------------------------------------------------
// First
// -----------------------
// External product part
auto factor = -1. * link_bwd * II * 0.5;
// std::cout << "nu: " << i << "\tfactor:" << factor << std::endl;
external_product(factor * N, field, field_bwd, res.site);
// Diagonal part
unit_matrix += 2 * std::real(scalar_prod(field_bwd, field) * factor);
// std::cout << "res:\n" << res.site <<std::endl;
// Second (relative minus sign!)
// -----------------------
factor = link * II * 0.5;
// std::cout << "nu: " << i << "\tfactor:" << factor << std::endl;
// External product part
external_product(factor * N, field_fwd, field, res.site);
// Diagonal part
auto s_f_ffwd = 2 * std::real(scalar_prod(field, field_fwd) * factor);
// std::cout << "res:\n" << res.site <<std::endl;
unit_matrix += s_f_ffwd;
// Links
// ----------------------------------------------------------------------
// res.links[i] = -2*s_f_ffwd*NN;
res.links[i] = 2 * N * std::imag(scalar_prod(field, field_fwd) * link);
/* std::cout << 2*std::imag(link*s_f_ffwd) << std::endl; */
}
inflate(res.site);
// std::cout << "Unit Matrix: " << unit_matrix << std::endl;
res.site += (unit_matrix * nummat<N>(-1.0));
FF.push_back(res);
// ################################################################################
}
return FF;
}
/// Constructor
explicit CPForce()
: sbc(BoundaryCondition<P, dim>()), lbc(BoundaryCondition<L, dim>())
{
}
explicit CPForce(const BoundaryCondition<P, dim> &_sbc,
const BoundaryCondition<L, dim> &_lbc)
: sbc(_sbc), lbc(_lbc)
{
}
~CPForce() {}
/// Compiler complains about constexpr here ???
bool isGroupValued() const { return false; }
};
} // End of namespace "NoExpansion"
namespace Expan {
using namespace CanonicalCPNExpHelpers;
using namespace CommonCPNExpHelpers;
const double CP_Langevin_noise_scale = sqrt(2.);
/// CP(N-1) Drift Force
template <size_t N, size_t dim, size_t order, typename P = double,
typename L = double>
class CPForce
: public Force<FullLattice<Expansion<CP<std::complex<double>, N>, order>,
Expansion<U1, order>, dim>,
std::vector<CPForceStructExp<N, dim, order>>> {
private:
BoundaryCondition<P, dim> sbc;
BoundaryCondition<L, dim> lbc;
public:
typedef CPForceStructExp<N, dim, order> CPdf;
typedef std::vector<CPdf> CPForceField;
typedef FullLattice<Expansion<CP<std::complex<double>, N>, order>,
Expansion<U1, order>, dim>
CPlattice;
/// Returns force field using standard boundary cond.
CPForceField operator()(CPlattice const &lat) const
{
// Pre-allocate memory
CPForceField FF;
FF.reserve(lat.volume());
for (auto it = lat.begin(); it != lat.end(); ++it) {
// ################################################################################
CPdf res;
const auto II = std::complex<double>(0.0, 1.0);
Expansion<std::complex<double>, order> unit_matrix(
std::complex<double>(0.0));
for (auto i = 0lu; i < dim; i++) {
auto link = it.link(i);
auto link_bwd = it.neighborLink(i, i, Direction::BACKWARD, lbc);
auto field = it.site();
auto field_fwd = it.neighborSite(i, Direction::FORWARD, sbc);
auto field_bwd = it.neighborSite(i, Direction::BACKWARD, sbc);
// CP field
// ----------------------------------------------------------------------
// First
// -----------------------
// External product part
auto factor = (-1. * II * 0.5) * link_bwd;
// std::cout << "nu: " << i << "\tfactor:" << factor << std::endl;
external_product(factor * static_cast<double>(N), field, field_bwd,
res.site);
// Diagonal part
unit_matrix += 2. * real(scalar_prod(field_bwd, field) * factor);
// std::cout << "res:\n" << res.site <<std::endl;
// Second (relative minus sign!)
// -----------------------
factor = link * (II * 0.5);
// std::cout << "nu: " << i << "\tfactor:" << factor << std::endl;
// External product part
external_product(factor * static_cast<double>(N), field_fwd, field,
res.site);
// Diagonal part
auto s_f_ffwd = 2 * real(scalar_prod(field, field_fwd) * factor);
// std::cout << "res:\n" << res.site <<std::endl;
unit_matrix += s_f_ffwd;
// Links
// ----------------------------------------------------------------------
// res.links[i] = -2*s_f_ffwd*NN;
res.links[i] = 2. * static_cast<double>(N) *
imag(scalar_prod(field, field_fwd) * link);
/* std::cout << 2*std::imag(link*s_f_ffwd) << std::endl; */
}
for (auto i = 0LU; i < order; ++i) {
inflate(res.site[i]);
}
// //std::cout << "Unit Matrix: " << unit_matrix << std::endl;
res.site += (unit_matrix) * (nummat<N>(-1.0));
FF.push_back(res);
// ################################################################################
}
return FF;
}
~CPForce(){};
explicit CPForce()
: sbc(BoundaryCondition<P, dim>()), lbc(BoundaryCondition<L, dim>())
{
}
explicit CPForce(const BoundaryCondition<P, dim> &_sbc,
const BoundaryCondition<L, dim> &_lbc)
: sbc(_sbc), lbc(_lbc){};
/// Compiler complains about constexpr here ???
bool isGroupValued() const { return false; }
};
} // End of namespace "Expan"
|
core_single_cpu_lcg.c | /* -*- mode: C; tab-width: 2; indent-tabs-mode: nil; -*- */
/*
* This code has been contributed by the DARPA HPCS program. Contact
* David Koester <dkoester@mitre.org> or Bob Lucas <rflucas@isi.edu>
* if you have questions.
*
* GUPS (Giga UPdates per Second) is a measurement that profiles the memory
* architecture of a system and is a measure of performance similar to MFLOPS.
* The HPCS HPCchallenge RandomAccess benchmark is intended to exercise the
* GUPS capability of a system, much like the LINPACK benchmark is intended to
* exercise the MFLOPS capability of a computer. In each case, we would
* expect these benchmarks to achieve close to the "peak" capability of the
* memory system. The extent of the similarities between RandomAccess and
* LINPACK are limited to both benchmarks attempting to calculate a peak system
* capability.
*
* GUPS is calculated by identifying the number of memory locations that can be
* randomly updated in one second, divided by 1 billion (1e9). The term "randomly"
* means that there is little relationship between one address to be updated and
* the next, except that they occur in the space of one half the total system
* memory. An update is a read-modify-write operation on a table of 64-bit words.
* An address is generated, the value at that address read from memory, modified
* by an integer operation (add, and, or, xor) with a literal value, and that
* new value is written back to memory.
*
* We are interested in knowing the GUPS performance of both entire systems and
* system subcomponents --- e.g., the GUPS rating of a distributed memory
* multiprocessor the GUPS rating of an SMP node, and the GUPS rating of a
* single processor. While there is typically a scaling of FLOPS with processor
* count, a similar phenomenon may not always occur for GUPS.
*
* For additional information on the GUPS metric, the HPCchallenge RandomAccess
* Benchmark,and the rules to run RandomAccess or modify it to optimize
* performance -- see http://icl.cs.utk.edu/hpcc/
*
*/
/*
* This file contains the computational core of the single cpu version
* of GUPS. The inner loop should easily be vectorized by compilers
* with such support.
*
* This core is used by both the single_cpu and star_single_cpu tests.
*/
#include "RandomAccess.h"
/* Number of updates to table (suggested: 4x number of table entries) */
#define NUPDATE (4 * TableSize)
/* Utility routine to start LCG random number generator at Nth step */
static uint64_t HPCC_starts_LCG(int64_t n)
{
uint64_t mul_k, add_k, ran, un;
mul_k = LCG_MUL64;
add_k = LCG_ADD64;
ran = 1;
for (un = (uint64_t)n; un; un >>= 1) {
if (un & 1)
ran = mul_k * ran + add_k;
add_k *= (mul_k + 1);
mul_k *= mul_k;
}
return ran;
}
static void RandomAccessUpdate_LCG(uint64_t TableSize, uint64_t *Table)
{
uint64_t i;
uint64_t ran[128]; /* Current random numbers */
int j, logTableSize;
/* Perform updates to main table. The scalar equivalent is:
*
* uint64_t ran;
* ran = 1;
* for (i=0; i<NUPDATE; i++) {
* ran = LCG_MUL64 * ran + LCG_ADD64;
* table[ran >> (64 - logTableSize)] ^= ran;
* }
*/
for (j = 0; j < 128; j++)
ran[j] = HPCC_starts_LCG((NUPDATE / 128) * j);
logTableSize = 0;
for (i = 1; i < TableSize; i <<= 1)
logTableSize += 1;
for (i = 0; i < NUPDATE / 128; i++) {
/* #pragma ivdep */
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j = 0; j < 128; j++) {
ran[j] = LCG_MUL64 * ran[j] + LCG_ADD64;
Table[ran[j] >> (64 - logTableSize)] ^= ran[j];
}
}
}
int HPCC_RandomAccess_LCG(HPCC_Params *params,
int doIO,
double *GUPs,
int *failure)
{
uint64_t i;
uint64_t temp;
double totalMem;
uint64_t *Table;
uint64_t logTableSize, TableSize;
/* calculate local memory per node for the update table */
totalMem = params->HPLMaxProcMem;
totalMem /= sizeof(uint64_t);
/* calculate the size of update array (must be a power of 2) */
for (totalMem *= 0.5, logTableSize = 0, TableSize = 1; totalMem >= 1.0;
totalMem *= 0.5, logTableSize++, TableSize <<= 1)
; /* EMPTY */
Table = HPCC_malloc(sizeof(uint64_t) * TableSize, params->TableAlignment);
if (!Table) {
printf("could not allocate table");
return 1;
}
params->RandomAccess_N = (int64_t) TableSize;
/* Print parameters for run */
printf("# GUPSLGC: Main table (@%p)size = 2^%" PRIu64 " = %" PRIu64 " words\n", Table,
logTableSize, TableSize);
printf("# GUPSLGC: Number of updates = %" PRIu64 "\n", NUPDATE);
printf("# GUPSLGC: Starting GUPS benchmark with %" PRIu32 " runs\n", params->NumReps);
bench_ctl_t *bench = bench_ctl_init(BENCH_MODE_FIXEDRUNS, 1, params->NumReps);
cycles_t t_diff;
do {
/* Initialize main table for each run */
for (i = 0; i < TableSize; i++) {
Table[i] = i;
}
/* Begin timing here */
#ifdef BARRELFISH
cycles_t t_start = bench_tsc();
#else
cycles_t t_start = get_timems();
#endif
RandomAccessUpdate_LCG(TableSize, Table);
/* End timed section */
#ifdef BARRELFISH
cycles_t t_end = bench_tsc();
t_diff = bench_tsc_to_ms(bench_time_diff(t_start, t_end));
#else
cycles_t t_end = get_timems();
t_diff = bench_time_diff(t_start, t_end);
#endif
printf("# GUPSLGC: Round: %" PRIu64 "ms\n", t_diff);
} while (!bench_ctl_add_run(bench, &t_diff));
cycles_t *bench_data = bench->data;
cycles_t avg;
cycles_t stddev;
bench_stddev(bench_data, bench->result_count, 0, &avg, &stddev);
double t_elapsed = ((double) avg) / 1000.0;
double t_err = ((double) stddev) / 1000000.0;
/* make sure no division by zero */
*GUPs = (t_elapsed > 0.0 ? 1.0 / t_elapsed : -1.0);
*GUPs *= 1e-9 * NUPDATE;
/* Print timing results */
printf("GUPSLGC: CPU time used = %.6f seconds (LCG)\n", t_elapsed);
printf("GUPSLGC: %.9f Billion(10^9) (s=%.9f) Updates per second [GUP/s] using %" PRIu64
" pages (LCG)\n",
*GUPs, t_err, params->TableAlignment);
/* Verification of results (in serial or "safe" mode; optional) */
temp = 0x1;
for (i = 0; i < NUPDATE; i++) {
temp = LCG_MUL64 * temp + LCG_ADD64;
Table[temp >> (64 - (int) logTableSize)] ^= temp;
}
temp = 0;
for (i = 0; i < TableSize; i++) {
if (Table[i] != i) {
temp++;
}
}
printf("Found %" PRIu64 " errors in %" PRIu64 " locations (%s).\n", temp,
TableSize, (temp <= 0.01 * TableSize) ? "passed" : "failed");
if (temp <= 0.01 * TableSize) {
*failure = 0;
} else {
*failure = 1;
}
bench_ctl_destroy(bench);
HPCC_free(Table);
return 0;
}
|
omp_workshare1.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 */
}
|
arm_device.h | #ifndef ANAKIN2_SABER_ARM_DEVICES_H
#define ANAKIN2_SABER_ARM_DEVICES_H
#include <stdio.h>
#include <vector>
#include "device.h"
#ifdef PLATFORM_ANDROID
#include <sys/syscall.h>
#include <unistd.h>
#define __NCPUBITS__ (8 * sizeof (unsigned long))
#define __CPU_SET(cpu, cpusetp) \
((cpusetp)->mask_bits[(cpu) / __NCPUBITS__] |= (1UL << ((cpu) % __NCPUBITS__)))
#define __CPU_ZERO(cpusetp) \
memset((cpusetp), 0, sizeof(cpu_set_t))
#endif
#if __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/machine.h>
#define __IOS__
#endif
#endif
#ifdef USE_ARM_PLACE
static int arm_get_cpucount()
{
#ifdef PLATFORM_ANDROID
// get cpu count from /proc/cpuinfo
FILE* fp = fopen("/proc/cpuinfo", "rb");
if (!fp) {
return 1;
}
int count = 0;
char line[1024];
while (!feof(fp))
{
char* s = fgets(line, 1024, fp);
if (!s) {
break;
}
if (memcmp(line, "processor", 9) == 0) {
count++;
}
}
fclose(fp);
if (count < 1) {
count = 1;
}
return count;
#elif __IOS__
int count = 0;
size_t len = sizeof(count);
sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
if (count < 1) {
count = 1;
}
return count;
#else
return 1;
#endif
}
static int arm_get_meminfo()
{
#ifdef PLATFORM_ANDROID
// get cpu count from /proc/cpuinfo
FILE* fp = fopen("/proc/meminfo", "rb");
if (!fp) {
return 1;
}
int memsize = 0;
char line[1024];
while (!feof(fp))
{
char* s = fgets(line, 1024, fp);
if (!s) {
break;
}
sscanf(s, "MemTotal: %d kB", &memsize);
}
fclose(fp);
return memsize;
#elif __IOS__
// to be implemented
return 0;
#endif
}
#ifdef PLATFORM_ANDROID
static int get_max_freq_khz(int cpuid)
{
// first try, for all possible cpu
char path[256];
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state",\
cpuid);
FILE* fp = fopen(path, "rb");
if (!fp)
{
// second try, for online cpu
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/cpufreq/stats/time_in_state",\
cpuid);
fp = fopen(path, "rb");
if (!fp)
{
// third try, for online cpu
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq",\
cpuid);
fp = fopen(path, "rb");
if (!fp) {
return -1;
}
int max_freq_khz = -1;
fscanf(fp, "%d", &max_freq_khz);
fclose(fp);
return max_freq_khz;
}
}
int max_freq_khz = 0;
while (!feof(fp))
{
int freq_khz = 0;
int nscan = fscanf(fp, "%d %*d", &freq_khz);
if (nscan != 1) {
break;
}
if (freq_khz > max_freq_khz) {
max_freq_khz = freq_khz;
}
}
fclose(fp);
return max_freq_khz;
}
static int arm_sort_cpuid_by_max_frequency(int cpu_count, std::vector<int>& cpuids, \
std::vector<int>& cpu_freq, std::vector<int>& cluster_ids) {
//const int cpu_count = cpuids.size();
if (cpu_count == 0) {
return 0;
}
//std::vector<int> cpu_max_freq_khz;
cpuids.resize(cpu_count);
cpu_freq.resize(cpu_count);
cluster_ids.resize(cpu_count);
for (int i = 0; i < cpu_count; i++)
{
int max_freq_khz = get_max_freq_khz(i);
//printf("%d max freq = %d khz\n", i, max_freq_khz);
cpuids[i] = i;
cpu_freq[i] = max_freq_khz / 1000;
}
// sort cpuid as big core first
// simple bubble sort
/*
for (int i = 0; i < cpu_count; i++)
{
for (int j = i+1; j < cpu_count; j++)
{
if (cpu_freq[i] < cpu_freq[j])
{
// swap
int tmp = cpuids[i];
cpuids[i] = cpuids[j];
cpuids[j] = tmp;
tmp = cpu_freq[i];
cpu_freq[i] = cpu_freq[j];
cpu_freq[j] = tmp;
}
}
}*/
// SMP
int mid_max_freq_khz = (cpu_freq.front() + cpu_freq.back()) / 2;
//if (mid_max_freq_khz == cpu_freq.back())
// return 0;
for (int i = 0; i < cpu_count; i++)
{
if (cpu_freq[i] >= mid_max_freq_khz) {
cluster_ids[i] = 0;
}
else{
cluster_ids[i] = 1;
}
}
return 0;
}
#endif // __ANDROID__
#ifdef __IOS__
static int sort_cpuid_by_max_frequency(int cpu_count, std::vector<int>& cpuids, \
std::vector<int>& cpu_freq, std::vector<int>& cluster_ids){
if (cpu_count == 0) {
return 0;
}
cpuids.resize(cpu_count);
cpu_freq.resize(cpu_count);
cluster_ids.resize(cpu_count);
for (int i = 0; i < cpu_count; ++i) {
cpuids[i] = i;
cpu_freq[i] = 1000;
cluster_ids[i] = 0;
}
}
#endif
#ifdef PLATFORM_ANDROID
static int set_sched_affinity(const std::vector<int>& cpuids)
{
// cpu_set_t definition
// ref http://stackoverflow.com/questions/16319725/android-set-thread-affinity
typedef struct
{
unsigned long mask_bits[1024 / __NCPUBITS__];
}cpu_set_t;
// set affinity for thread
pid_t pid = gettid();
cpu_set_t mask;
__CPU_ZERO(&mask);
for (int i = 0; i < (int)cpuids.size(); i++)
{
__CPU_SET(cpuids[i], &mask);
}
int syscallret = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
if (syscallret)
{
LOG(ERROR) << "syscall error " << syscallret;
return -1;
}
return 0;
}
void SetThreadAffinity(cpu_set_t mask) {
#if defined(__ANDROID__)
pid_t pid = gettid();
#else
pid_t pid = syscall(SYS_gettid);
#endif
int err = sched_setaffinity(pid, sizeof(mask), &mask);
if (err != 0) {
LOG(ERROR) << "set affinity error: " << strerror(errno);
}
}
static int set_cpu_affinity(const std::vector<int>& cpuids){
#ifdef USE_OPENMP
int num_threads = cpuids.size();
//omp_set_dynamic(0);
omp_set_num_threads(num_threads);
#if 0
// compute mask
cpu_set_t mask;
CPU_ZERO(&mask);
for (auto cpu_id : cpuids) {
CPU_SET(cpu_id, &mask);
}
#pragma omp parallel for
for (int i = 0; i < num_threads; ++i) {
SetThreadAffinity(mask);
LOG(INFO) << "Set affinity for OpenMP thread " << omp_get_thread_num()
<< "/" << omp_get_num_threads();
}
#else
std::vector<int> ssarets(num_threads, 0);
#pragma omp parallel for
for (int i = 0; i < num_threads; i++)
{
ssarets[i] = set_sched_affinity(cpuids);
}
for (int i = 0; i < num_threads; i++)
{
if (ssarets[i] != 0)
{
LOG(ERROR)<<"set cpu affinity failed, cpuID: " << cpuids[i];
return -1;
}
}
#endif
#else
std::vector<int> cpuid1;
cpuid1.push_back(cpuids[0]);
int ssaret = set_sched_affinity(cpuid1);
if (ssaret != 0)
{
LOG(ERROR)<<"set cpu affinity failed, cpuID: " << cpuids[0];
return -1;
}
#endif
return 0;
}
#endif //PLATFORN_ANDROID
#endif //USE_ARM_PLACE
#endif //ANAKIN2_SABER_ARM_DEVICES_H
|
affinuma.c | #include "affinuma.h"
struct numa_node_bw * numa_node_list = NULL;
struct numa_node_bw * numa_list_head = NULL;
int mem_types;
int max_node;
int numt;
int total_numa_nodes = 0;
int * numa_node_ids;
struct bitmask * numa_nodes;
char ** mem_tech;
long double * means;
int * cluster_sizes;
char classes[3][8] = {"fast", "slow", "slowest"};
char * cpu_range;
void label_mem(){
struct numa_node_bw * bw_it = numa_list_head;
struct numa_node_bw * next_bw_it = bw_it->next;
int i = 0;
bw_it->mem_type = classes[i];
while(next_bw_it != NULL){
long double diff = bw_it->owtr_avg - next_bw_it->owtr_avg;
long double perct = 0.2*bw_it->owtr_avg;
if((diff > perct)&&((i+1)<3)){
i++;
}
next_bw_it->mem_type = classes[i];
bw_it = next_bw_it;
next_bw_it= bw_it->next;
}
}
void sort_list(struct numa_node_bw * new_node){
struct numa_node_bw * bw_it = numa_list_head;
struct numa_node_bw * prev_bw_it = NULL;
while(bw_it != NULL){
if((bw_it->owtr_avg < new_node->owtr_avg)){
if(prev_bw_it == NULL){
new_node->next = bw_it;
numa_list_head = new_node;
}else{
prev_bw_it->next = new_node;
new_node->next = bw_it;
}
return;
}
prev_bw_it = bw_it;
bw_it = bw_it->next;
}
prev_bw_it->next = new_node;
return;
}
void write_config_file(){
FILE * conf;
char fname[50];
strcpy(fname, "numa_class");
conf = fopen(fname, "w");
struct numa_node_bw * bw_it = numa_list_head;
printf("CPU ID\tNUMA ID\tType\tInit(Mb/s)\tTriad(Mb/s)\n");
while(bw_it != NULL){
fprintf(conf, "%d %s %Lf\n", bw_it->numa_id, bw_it->mem_type, bw_it->owtr_avg);
printf("%s\t%d\t%s\t%LF\t%Lf\n", cpu_range, bw_it->numa_id, bw_it->mem_type, bw_it->wr_only_avg, bw_it->owtr_avg);
bw_it = bw_it->next;
}
fclose(conf);
}
void numatest(int argc, char ** argv){
cpu_range=argv[1];
max_node = numa_max_node() + 1;
int cpu_count = numa_num_possible_cpus();
numa_node_ids = (int*)malloc(sizeof(int)*max_node);
struct bitmask * numa_nodes = numa_get_membind();
int i = 0;
while(i < numa_nodes->size){
if(numa_bitmask_isbitset(numa_nodes, i)){
numa_node_ids[total_numa_nodes] = i;
total_numa_nodes++;
}
i++;
}
int mbs = 64;
size_t size = mbs*1024*1024;
int r_size = 16*32768;
int c_size = 16*32768;
double *a, *b, *c;
clock_t start, end;
struct timespec begin, stop;
srand(clock());
//sleep(5);
i = 0;
while(i < total_numa_nodes){
int iters = 0;
int stride;
long double wr_only_avg=0.0;
long double owtr_avg=0.0;
long double accum;
for( iters = 0; iters < 10; iters++){
int j = 0;
int k = 0;
a = (double*)numa_alloc_onnode(size, numa_node_ids[i]);
b = (double*)numa_alloc_onnode(size, numa_node_ids[i]);
c = (double*)numa_alloc_onnode(size, numa_node_ids[i]);
long double empty=0.0;
long double empty2=0.0;
redo1:
clock_gettime( CLOCK_MONOTONIC, &begin);
#pragma omp parallel for
for(j = 0;j < (size/sizeof(double));j++){
a[j] = 1.0;
b[j] = 2.0;
c[j] = 3.0;
}
clock_gettime( CLOCK_MONOTONIC, &stop);
accum = ( stop.tv_sec - begin.tv_sec ) + (long double)( stop.tv_nsec - begin.tv_nsec ) / (long double)BILLION;
if(accum <= empty){
goto redo1;
}
wr_only_avg += ((8*size*1.0E-06)/(long double)(accum - empty));
redo3:
clock_gettime( CLOCK_MONOTONIC, &begin);
#pragma omp parallel for
for(j =0; j < (size/sizeof(double)); j++){
a[j] = c[j] + b[j];
}
clock_gettime( CLOCK_MONOTONIC, &stop);
accum = ( stop.tv_sec - begin.tv_sec ) + (long double)( stop.tv_nsec - begin.tv_nsec ) / (long double)BILLION;
if(accum <= empty){
goto redo3;
}
owtr_avg += ((3*size*1.0E-06)/(long double)(accum - empty));
numa_free(a, size);
numa_free(b, size);
numa_free(c, size);
}
struct numa_node_bw * node_bw = (struct numa_node_bw *)malloc(sizeof(struct numa_node_bw));
node_bw->numa_id = numa_node_ids[i];
node_bw->wr_only_avg = wr_only_avg/10;
node_bw->owtr_avg = owtr_avg/10;
node_bw->next = NULL;
if(numa_node_list == NULL){
numa_node_list = node_bw;
numa_list_head = numa_node_list;
}
else{
sort_list(node_bw);
}
i++;
}
label_mem();
write_config_file();
}
|
wino_conv_kernel_x86.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2021, OPEN AI LAB
* Author: haoluo@openailab.com
*/
#include "wino_conv_kernel_x86.h"
#include "graph/tensor.h"
#include "graph/node.h"
#include "graph/graph.h"
#include "utility/sys_port.h"
#include "utility/float.h"
#include "utility/log.h"
#include "device/cpu/cpu_node.h"
#include "device/cpu/cpu_graph.h"
#include "device/cpu/cpu_module.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define TILE 4
#define ELEM_SIZE ((TILE + 2) * (TILE + 2))
#define WINO_MAX(a, b) ((a) > (b) ? (a) : (b))
#define WINO_MIN(a, b) ((a) < (b) ? (a) : (b))
static void relu(float* data, int size, int activation)
{
for (int i = 0; i < size; i++)
{
data[i] = WINO_MAX(data[i], (float)0);
if (activation > 0)
{
data[i] = WINO_MIN(data[i], (float)activation);
}
}
}
static int get_private_mem_size(struct tensor* filter, struct conv_param* param)
{
int output_c = filter->dims[0];
int input_c = filter->dims[1];
int trans_ker_size = (unsigned long)output_c * input_c * ELEM_SIZE * sizeof(float);
return trans_ker_size + 128; // caution
}
static void pad_0_align_2D(float* dst, float* src, int m, int n, int m_align, int n_align, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, (unsigned long)m * n * sizeof(float));
return;
}
for (i = 0; i < m; ++i)
{
memcpy(dst + (i + pad_h) * n_align + pad_w, src + i * n, n * sizeof(float));
}
}
// pad 0 in right and down side on 3D
static void pad_0_align_3D(float* dst, float* src, int m, int n, int m_align, int n_align, int c, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, (unsigned long)c * m * n * sizeof(float));
return;
}
for (i = 0; i < c; ++i)
{
pad_0_align_2D(dst + i * m_align * n_align, src + i * m * n, m, n, m_align, n_align, pad_h, pad_w);
}
}
static void delete_0_2D(float* dst, float* src, int m_align, int n_align, int m, int n, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, (unsigned long)m * n * sizeof(float));
return;
}
for (i = 0; i < m; ++i)
{
memcpy(dst + i * n, src + (i + pad_h) * n_align + pad_w, n * sizeof(float));
}
}
// pad 0 in right and down side on 3D
static void delete_0_3D(float* dst, float* src, int m_align, int n_align, int m, int n, int c, int pad_h, int pad_w)
{
int i;
if (n >= n_align && m >= m_align)
{
memcpy(dst, src, (unsigned long)c * m * n * sizeof(float));
return;
}
for (i = 0; i < c; ++i)
{
delete_0_2D(dst + i * m * n, src + i * m_align * n_align, m_align, n_align, m, n, pad_h, pad_w);
}
}
void conv3x3s1_winograd43_sse(float* bottom_blob, float* top_blob, float* kernel_tm_test, float* dot_block,
float* transform_input, float* output_bordered, float* _bias, int w, int h, int inch,
int outw, int outh, int outch, int num_thread)
{
size_t elemsize = sizeof(float);
const float* bias = _bias;
// pad to 4n+2, winograd F(4,3)
float* bottom_blob_bordered = bottom_blob;
int outw_align = (outw + 3) / 4 * 4;
int outh_align = (outh + 3) / 4 * 4;
w = outw_align + 2;
h = outh_align + 2;
// BEGIN transform input
float* bottom_blob_tm = NULL;
{
int w_tm = outw_align / 4 * 6;
int h_tm = outh_align / 4 * 6;
int nColBlocks = h_tm / 6; // may be the block num in Feathercnn
int nRowBlocks = w_tm / 6;
const int tiles = nColBlocks * nRowBlocks;
const int tiles_n = 4 * inch * tiles;
bottom_blob_tm = transform_input;
// BT
// const float itm[4][4] = {
// {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f},
// {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f},
// {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f},
// {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f}
// };
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
#if __AVX__
__m256 _1_n = _mm256_set1_ps(-1);
__m256 _2_p = _mm256_set1_ps(2);
__m256 _2_n = _mm256_set1_ps(-2);
__m256 _4_p = _mm256_set1_ps(4);
__m256 _4_n = _mm256_set1_ps(-4);
__m256 _5_n = _mm256_set1_ps(-5);
#endif
#pragma omp parallel for num_threads(num_thread)
for (int q = 0; q < inch; q++)
{
const float* img = bottom_blob_bordered + q * w * h;
for (int j = 0; j < nColBlocks; j++)
{
const float* r0 = img + w * j * 4;
const float* r1 = r0 + w;
const float* r2 = r1 + w;
const float* r3 = r2 + w;
const float* r4 = r3 + w;
const float* r5 = r4 + w;
for (int i = 0; i < nRowBlocks; i++)
{
float* out_tm0 = bottom_blob_tm + 4 * inch * (j * nRowBlocks + i) + 4 * q;
float* out_tm1 = out_tm0 + tiles_n;
float* out_tm2 = out_tm0 + 2 * tiles_n;
float* out_tm3 = out_tm0 + 3 * tiles_n;
float* out_tm4 = out_tm0 + 4 * tiles_n;
float* out_tm5 = out_tm0 + 5 * tiles_n;
float* out_tm6 = out_tm0 + 6 * tiles_n;
float* out_tm7 = out_tm0 + 7 * tiles_n;
float* out_tm8 = out_tm0 + 8 * tiles_n;
#if __AVX__
__m256 _d0, _d1, _d2, _d3, _d4, _d5;
__m256 _w0, _w1, _w2, _w3, _w4, _w5;
__m256 _t0, _t1, _t2, _t3, _t4, _t5;
__m256 _n0, _n1, _n2, _n3, _n4, _n5;
// load
_d0 = _mm256_loadu_ps(r0);
_d1 = _mm256_loadu_ps(r1);
_d2 = _mm256_loadu_ps(r2);
_d3 = _mm256_loadu_ps(r3);
_d4 = _mm256_loadu_ps(r4);
_d5 = _mm256_loadu_ps(r5);
// w = B_t * d
_w0 = _mm256_mul_ps(_d0, _4_p);
_w0 = _mm256_fmadd_ps(_d2, _5_n, _w0);
_w0 = _mm256_add_ps(_w0, _d4);
_w1 = _mm256_mul_ps(_d1, _4_n);
_w1 = _mm256_fmadd_ps(_d2, _4_n, _w1);
_w1 = _mm256_add_ps(_w1, _d3);
_w1 = _mm256_add_ps(_w1, _d4);
_w2 = _mm256_mul_ps(_d1, _4_p);
_w2 = _mm256_fmadd_ps(_d2, _4_n, _w2);
_w2 = _mm256_fmadd_ps(_d3, _1_n, _w2);
_w2 = _mm256_add_ps(_w2, _d4);
_w3 = _mm256_mul_ps(_d1, _2_n);
_w3 = _mm256_fmadd_ps(_d2, _1_n, _w3);
_w3 = _mm256_fmadd_ps(_d3, _2_p, _w3);
_w3 = _mm256_add_ps(_w3, _d4);
_w4 = _mm256_mul_ps(_d1, _2_p);
_w4 = _mm256_fmadd_ps(_d2, _1_n, _w4);
_w4 = _mm256_fmadd_ps(_d3, _2_n, _w4);
_w4 = _mm256_add_ps(_w4, _d4);
_w5 = _mm256_mul_ps(_d1, _4_p);
_w5 = _mm256_fmadd_ps(_d3, _5_n, _w5);
_w5 = _mm256_add_ps(_w5, _d5);
// transpose d to d_t
#ifdef _WIN32
{
_t0.m256_f32[0] = _w0.m256_f32[0];
_t1.m256_f32[0] = _w0.m256_f32[1];
_t2.m256_f32[0] = _w0.m256_f32[2];
_t3.m256_f32[0] = _w0.m256_f32[3];
_t4.m256_f32[0] = _w0.m256_f32[4];
_t5.m256_f32[0] = _w0.m256_f32[5];
_t0.m256_f32[1] = _w1.m256_f32[0];
_t1.m256_f32[1] = _w1.m256_f32[1];
_t2.m256_f32[1] = _w1.m256_f32[2];
_t3.m256_f32[1] = _w1.m256_f32[3];
_t4.m256_f32[1] = _w1.m256_f32[4];
_t5.m256_f32[1] = _w1.m256_f32[5];
_t0.m256_f32[2] = _w2.m256_f32[0];
_t1.m256_f32[2] = _w2.m256_f32[1];
_t2.m256_f32[2] = _w2.m256_f32[2];
_t3.m256_f32[2] = _w2.m256_f32[3];
_t4.m256_f32[2] = _w2.m256_f32[4];
_t5.m256_f32[2] = _w2.m256_f32[5];
_t0.m256_f32[3] = _w3.m256_f32[0];
_t1.m256_f32[3] = _w3.m256_f32[1];
_t2.m256_f32[3] = _w3.m256_f32[2];
_t3.m256_f32[3] = _w3.m256_f32[3];
_t4.m256_f32[3] = _w3.m256_f32[4];
_t5.m256_f32[3] = _w3.m256_f32[5];
_t0.m256_f32[4] = _w4.m256_f32[0];
_t1.m256_f32[4] = _w4.m256_f32[1];
_t2.m256_f32[4] = _w4.m256_f32[2];
_t3.m256_f32[4] = _w4.m256_f32[3];
_t4.m256_f32[4] = _w4.m256_f32[4];
_t5.m256_f32[4] = _w4.m256_f32[5];
_t0.m256_f32[5] = _w5.m256_f32[0];
_t1.m256_f32[5] = _w5.m256_f32[1];
_t2.m256_f32[5] = _w5.m256_f32[2];
_t3.m256_f32[5] = _w5.m256_f32[3];
_t4.m256_f32[5] = _w5.m256_f32[4];
_t5.m256_f32[5] = _w5.m256_f32[5];
}
#else
{
_t0[0] = _w0[0];
_t1[0] = _w0[1];
_t2[0] = _w0[2];
_t3[0] = _w0[3];
_t4[0] = _w0[4];
_t5[0] = _w0[5];
_t0[1] = _w1[0];
_t1[1] = _w1[1];
_t2[1] = _w1[2];
_t3[1] = _w1[3];
_t4[1] = _w1[4];
_t5[1] = _w1[5];
_t0[2] = _w2[0];
_t1[2] = _w2[1];
_t2[2] = _w2[2];
_t3[2] = _w2[3];
_t4[2] = _w2[4];
_t5[2] = _w2[5];
_t0[3] = _w3[0];
_t1[3] = _w3[1];
_t2[3] = _w3[2];
_t3[3] = _w3[3];
_t4[3] = _w3[4];
_t5[3] = _w3[5];
_t0[4] = _w4[0];
_t1[4] = _w4[1];
_t2[4] = _w4[2];
_t3[4] = _w4[3];
_t4[4] = _w4[4];
_t5[4] = _w4[5];
_t0[5] = _w5[0];
_t1[5] = _w5[1];
_t2[5] = _w5[2];
_t3[5] = _w5[3];
_t4[5] = _w5[4];
_t5[5] = _w5[5];
}
#endif
// d = B_t * d_t
_n0 = _mm256_mul_ps(_t0, _4_p);
_n0 = _mm256_fmadd_ps(_t2, _5_n, _n0);
_n0 = _mm256_add_ps(_n0, _t4);
_n1 = _mm256_mul_ps(_t1, _4_n);
_n1 = _mm256_fmadd_ps(_t2, _4_n, _n1);
_n1 = _mm256_add_ps(_n1, _t3);
_n1 = _mm256_add_ps(_n1, _t4);
_n2 = _mm256_mul_ps(_t1, _4_p);
_n2 = _mm256_fmadd_ps(_t2, _4_n, _n2);
_n2 = _mm256_fmadd_ps(_t3, _1_n, _n2);
_n2 = _mm256_add_ps(_n2, _t4);
_n3 = _mm256_mul_ps(_t1, _2_n);
_n3 = _mm256_fmadd_ps(_t2, _1_n, _n3);
_n3 = _mm256_fmadd_ps(_t3, _2_p, _n3);
_n3 = _mm256_add_ps(_n3, _t4);
_n4 = _mm256_mul_ps(_t1, _2_p);
_n4 = _mm256_fmadd_ps(_t2, _1_n, _n4);
_n4 = _mm256_fmadd_ps(_t3, _2_n, _n4);
_n4 = _mm256_add_ps(_n4, _t4);
_n5 = _mm256_mul_ps(_t1, _4_p);
_n5 = _mm256_fmadd_ps(_t3, _5_n, _n5);
_n5 = _mm256_add_ps(_n5, _t5);
// save to out_tm
float output_n0[8] = {0.f};
_mm256_storeu_ps(output_n0, _n0);
float output_n1[8] = {0.f};
_mm256_storeu_ps(output_n1, _n1);
float output_n2[8] = {0.f};
_mm256_storeu_ps(output_n2, _n2);
float output_n3[8] = {0.f};
_mm256_storeu_ps(output_n3, _n3);
float output_n4[8] = {0.f};
_mm256_storeu_ps(output_n4, _n4);
float output_n5[8] = {0.f};
_mm256_storeu_ps(output_n5, _n5);
out_tm0[0] = output_n0[0];
out_tm0[1] = output_n0[1];
out_tm0[2] = output_n0[2];
out_tm0[3] = output_n0[3];
out_tm1[0] = output_n0[4];
out_tm1[1] = output_n0[5];
out_tm1[2] = output_n1[0];
out_tm1[3] = output_n1[1];
out_tm2[0] = output_n1[2];
out_tm2[1] = output_n1[3];
out_tm2[2] = output_n1[4];
out_tm2[3] = output_n1[5];
out_tm3[0] = output_n2[0];
out_tm3[1] = output_n2[1];
out_tm3[2] = output_n2[2];
out_tm3[3] = output_n2[3];
out_tm4[0] = output_n2[4];
out_tm4[1] = output_n2[5];
out_tm4[2] = output_n3[0];
out_tm4[3] = output_n3[1];
out_tm5[0] = output_n3[2];
out_tm5[1] = output_n3[3];
out_tm5[2] = output_n3[4];
out_tm5[3] = output_n3[5];
out_tm6[0] = output_n4[0];
out_tm6[1] = output_n4[1];
out_tm6[2] = output_n4[2];
out_tm6[3] = output_n4[3];
out_tm7[0] = output_n4[4];
out_tm7[1] = output_n4[5];
out_tm7[2] = output_n5[0];
out_tm7[3] = output_n5[1];
out_tm8[0] = output_n5[2];
out_tm8[1] = output_n5[3];
out_tm8[2] = output_n5[4];
out_tm8[3] = output_n5[5];
#else
float d0[6], d1[6], d2[6], d3[6], d4[6], d5[6];
float w0[6], w1[6], w2[6], w3[6], w4[6], w5[6];
float t0[6], t1[6], t2[6], t3[6], t4[6], t5[6];
// load
for (int n = 0; n < 6; n++)
{
d0[n] = r0[n];
d1[n] = r1[n];
d2[n] = r2[n];
d3[n] = r3[n];
d4[n] = r4[n];
d5[n] = r5[n];
}
// w = B_t * d
for (int n = 0; n < 6; n++)
{
w0[n] = 4 * d0[n] - 5 * d2[n] + d4[n];
w1[n] = -4 * d1[n] - 4 * d2[n] + d3[n] + d4[n];
w2[n] = 4 * d1[n] - 4 * d2[n] - d3[n] + d4[n];
w3[n] = -2 * d1[n] - d2[n] + 2 * d3[n] + d4[n];
w4[n] = 2 * d1[n] - d2[n] - 2 * d3[n] + d4[n];
w5[n] = 4 * d1[n] - 5 * d3[n] + d5[n];
}
// transpose d to d_t
{
t0[0] = w0[0];
t1[0] = w0[1];
t2[0] = w0[2];
t3[0] = w0[3];
t4[0] = w0[4];
t5[0] = w0[5];
t0[1] = w1[0];
t1[1] = w1[1];
t2[1] = w1[2];
t3[1] = w1[3];
t4[1] = w1[4];
t5[1] = w1[5];
t0[2] = w2[0];
t1[2] = w2[1];
t2[2] = w2[2];
t3[2] = w2[3];
t4[2] = w2[4];
t5[2] = w2[5];
t0[3] = w3[0];
t1[3] = w3[1];
t2[3] = w3[2];
t3[3] = w3[3];
t4[3] = w3[4];
t5[3] = w3[5];
t0[4] = w4[0];
t1[4] = w4[1];
t2[4] = w4[2];
t3[4] = w4[3];
t4[4] = w4[4];
t5[4] = w4[5];
t0[5] = w5[0];
t1[5] = w5[1];
t2[5] = w5[2];
t3[5] = w5[3];
t4[5] = w5[4];
t5[5] = w5[5];
}
// d = B_t * d_t
for (int n = 0; n < 6; n++)
{
d0[n] = 4 * t0[n] - 5 * t2[n] + t4[n];
d1[n] = -4 * t1[n] - 4 * t2[n] + t3[n] + t4[n];
d2[n] = 4 * t1[n] - 4 * t2[n] - t3[n] + t4[n];
d3[n] = -2 * t1[n] - t2[n] + 2 * t3[n] + t4[n];
d4[n] = 2 * t1[n] - t2[n] - 2 * t3[n] + t4[n];
d5[n] = 4 * t1[n] - 5 * t3[n] + t5[n];
}
// save to out_tm
{
out_tm0[0] = d0[0];
out_tm0[1] = d0[1];
out_tm0[2] = d0[2];
out_tm0[3] = d0[3];
out_tm1[0] = d0[4];
out_tm1[1] = d0[5];
out_tm1[2] = d1[0];
out_tm1[3] = d1[1];
out_tm2[0] = d1[2];
out_tm2[1] = d1[3];
out_tm2[2] = d1[4];
out_tm2[3] = d1[5];
out_tm3[0] = d2[0];
out_tm3[1] = d2[1];
out_tm3[2] = d2[2];
out_tm3[3] = d2[3];
out_tm4[0] = d2[4];
out_tm4[1] = d2[5];
out_tm4[2] = d3[0];
out_tm4[3] = d3[1];
out_tm5[0] = d3[2];
out_tm5[1] = d3[3];
out_tm5[2] = d3[4];
out_tm5[3] = d3[5];
out_tm6[0] = d4[0];
out_tm6[1] = d4[1];
out_tm6[2] = d4[2];
out_tm6[3] = d4[3];
out_tm7[0] = d4[4];
out_tm7[1] = d4[5];
out_tm7[2] = d5[0];
out_tm7[3] = d5[1];
out_tm8[0] = d5[2];
out_tm8[1] = d5[3];
out_tm8[2] = d5[4];
out_tm8[3] = d5[5];
}
#endif // __AVX__
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
r5 += 4;
}
}
}
}
// BEGIN dot
float* top_blob_tm = NULL;
{
int w_tm = outw_align / 4 * 6;
int h_tm = outh_align / 4 * 6;
int nColBlocks = h_tm / 6; // may be the block num in Feathercnn
int nRowBlocks = w_tm / 6;
const int tiles = nColBlocks * nRowBlocks;
const int tiles_n = 36 * tiles;
top_blob_tm = dot_block;
#pragma omp parallel for num_threads(num_thread)
for (int r = 0; r < 9; r++)
{
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp << 3;
float* output0_tm = top_blob_tm + tiles_n * p;
float* output1_tm = top_blob_tm + tiles_n * (p + 1);
float* output2_tm = top_blob_tm + tiles_n * (p + 2);
float* output3_tm = top_blob_tm + tiles_n * (p + 3);
float* output4_tm = top_blob_tm + tiles_n * (p + 4);
float* output5_tm = top_blob_tm + tiles_n * (p + 5);
float* output6_tm = top_blob_tm + tiles_n * (p + 6);
float* output7_tm = top_blob_tm + tiles_n * (p + 7);
output0_tm = output0_tm + r * 4;
output1_tm = output1_tm + r * 4;
output2_tm = output2_tm + r * 4;
output3_tm = output3_tm + r * 4;
output4_tm = output4_tm + r * 4;
output5_tm = output5_tm + r * 4;
output6_tm = output6_tm + r * 4;
output7_tm = output7_tm + r * 4;
for (int i = 0; i < tiles; i++)
{
const float* kptr = kernel_tm_test + 4 * r * inch * outch + p / 8 * inch * 32;
const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i);
#if __AVX__ || __SSE__
#if __AVX__
float zero_val = 0.f;
__m128 _sum0 = _mm_broadcast_ss(&zero_val);
__m128 _sum1 = _mm_broadcast_ss(&zero_val);
__m128 _sum2 = _mm_broadcast_ss(&zero_val);
__m128 _sum3 = _mm_broadcast_ss(&zero_val);
__m128 _sum4 = _mm_broadcast_ss(&zero_val);
__m128 _sum5 = _mm_broadcast_ss(&zero_val);
__m128 _sum6 = _mm_broadcast_ss(&zero_val);
__m128 _sum7 = _mm_broadcast_ss(&zero_val);
#else
__m128 _sum0 = _mm_set1_ps(0.f);
__m128 _sum1 = _mm_set1_ps(0.f);
__m128 _sum2 = _mm_set1_ps(0.f);
__m128 _sum3 = _mm_set1_ps(0.f);
__m128 _sum4 = _mm_set1_ps(0.f);
__m128 _sum5 = _mm_set1_ps(0.f);
__m128 _sum6 = _mm_set1_ps(0.f);
__m128 _sum7 = _mm_set1_ps(0.f);
#endif
int q = 0;
for (; q + 3 < inch; q = q + 4)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _r1 = _mm_loadu_ps(r0 + 4);
__m128 _r2 = _mm_loadu_ps(r0 + 8);
__m128 _r3 = _mm_loadu_ps(r0 + 12);
__m128 _k0 = _mm_loadu_ps(kptr);
__m128 _k1 = _mm_loadu_ps(kptr + 4);
__m128 _k2 = _mm_loadu_ps(kptr + 8);
__m128 _k3 = _mm_loadu_ps(kptr + 12);
__m128 _k4 = _mm_loadu_ps(kptr + 16);
__m128 _k5 = _mm_loadu_ps(kptr + 20);
__m128 _k6 = _mm_loadu_ps(kptr + 24);
__m128 _k7 = _mm_loadu_ps(kptr + 28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r0, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r0, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r0, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r0, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r0, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r0, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r0, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7));
#endif
kptr += 32;
_k0 = _mm_loadu_ps(kptr);
_k1 = _mm_loadu_ps(kptr + 4);
_k2 = _mm_loadu_ps(kptr + 8);
_k3 = _mm_loadu_ps(kptr + 12);
_k4 = _mm_loadu_ps(kptr + 16);
_k5 = _mm_loadu_ps(kptr + 20);
_k6 = _mm_loadu_ps(kptr + 24);
_k7 = _mm_loadu_ps(kptr + 28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r1, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r1, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r1, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r1, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r1, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r1, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r1, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r1, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r1, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r1, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r1, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r1, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r1, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r1, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r1, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r1, _k7));
#endif
kptr += 32;
_k0 = _mm_loadu_ps(kptr);
_k1 = _mm_loadu_ps(kptr + 4);
_k2 = _mm_loadu_ps(kptr + 8);
_k3 = _mm_loadu_ps(kptr + 12);
_k4 = _mm_loadu_ps(kptr + 16);
_k5 = _mm_loadu_ps(kptr + 20);
_k6 = _mm_loadu_ps(kptr + 24);
_k7 = _mm_loadu_ps(kptr + 28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r2, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r2, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r2, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r2, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r2, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r2, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r2, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r2, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r2, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r2, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r2, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r2, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r2, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r2, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r2, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r2, _k7));
#endif
kptr += 32;
_k0 = _mm_loadu_ps(kptr);
_k1 = _mm_loadu_ps(kptr + 4);
_k2 = _mm_loadu_ps(kptr + 8);
_k3 = _mm_loadu_ps(kptr + 12);
_k4 = _mm_loadu_ps(kptr + 16);
_k5 = _mm_loadu_ps(kptr + 20);
_k6 = _mm_loadu_ps(kptr + 24);
_k7 = _mm_loadu_ps(kptr + 28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r3, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r3, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r3, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r3, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r3, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r3, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r3, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r3, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r3, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r3, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r3, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r3, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r3, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r3, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r3, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r3, _k7));
#endif
kptr += 32;
r0 += 16;
}
for (; q < inch; q++)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _k0 = _mm_loadu_ps(kptr);
__m128 _k1 = _mm_loadu_ps(kptr + 4);
__m128 _k2 = _mm_loadu_ps(kptr + 8);
__m128 _k3 = _mm_loadu_ps(kptr + 12);
__m128 _k4 = _mm_loadu_ps(kptr + 16);
__m128 _k5 = _mm_loadu_ps(kptr + 20);
__m128 _k6 = _mm_loadu_ps(kptr + 24);
__m128 _k7 = _mm_loadu_ps(kptr + 28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r0, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r0, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r0, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r0, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r0, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r0, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r0, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7));
#endif
kptr += 32;
r0 += 4;
}
_mm_storeu_ps(output0_tm, _sum0);
_mm_storeu_ps(output1_tm, _sum1);
_mm_storeu_ps(output2_tm, _sum2);
_mm_storeu_ps(output3_tm, _sum3);
_mm_storeu_ps(output4_tm, _sum4);
_mm_storeu_ps(output5_tm, _sum5);
_mm_storeu_ps(output6_tm, _sum6);
_mm_storeu_ps(output7_tm, _sum7);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
float sum4[4] = {0};
float sum5[4] = {0};
float sum6[4] = {0};
float sum7[4] = {0};
for (int q = 0; q < inch; q++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += r0[n] * kptr[n];
sum1[n] += r0[n] * kptr[n + 4];
sum2[n] += r0[n] * kptr[n + 8];
sum3[n] += r0[n] * kptr[n + 12];
sum4[n] += r0[n] * kptr[n + 16];
sum5[n] += r0[n] * kptr[n + 20];
sum6[n] += r0[n] * kptr[n + 24];
sum7[n] += r0[n] * kptr[n + 28];
}
kptr += 32;
r0 += 4;
}
for (int n = 0; n < 4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
output4_tm[n] = sum4[n];
output5_tm[n] = sum5[n];
output6_tm[n] = sum6[n];
output7_tm[n] = sum7[n];
}
#endif // __AVX__
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
output4_tm += 36;
output5_tm += 36;
output6_tm += 36;
output7_tm += 36;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
float* output0_tm = top_blob_tm + tiles_n * p;
float* output1_tm = top_blob_tm + tiles_n * (p + 1);
float* output2_tm = top_blob_tm + tiles_n * (p + 2);
float* output3_tm = top_blob_tm + tiles_n * (p + 3);
output0_tm = output0_tm + r * 4;
output1_tm = output1_tm + r * 4;
output2_tm = output2_tm + r * 4;
output3_tm = output3_tm + r * 4;
for (int i = 0; i < tiles; i++)
{
const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4) * inch * 16;
const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i);
#if __AVX__ || __SSE__
#if __AVX__
float zero_val = 0.f;
__m128 _sum0 = _mm_broadcast_ss(&zero_val);
__m128 _sum1 = _mm_broadcast_ss(&zero_val);
__m128 _sum2 = _mm_broadcast_ss(&zero_val);
__m128 _sum3 = _mm_broadcast_ss(&zero_val);
#else
__m128 _sum0 = _mm_set1_ps(0.f);
__m128 _sum1 = _mm_set1_ps(0.f);
__m128 _sum2 = _mm_set1_ps(0.f);
__m128 _sum3 = _mm_set1_ps(0.f);
#endif
for (int q = 0; q < inch; q++)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _k0 = _mm_loadu_ps(kptr);
__m128 _k1 = _mm_loadu_ps(kptr + 4);
__m128 _k2 = _mm_loadu_ps(kptr + 8);
__m128 _k3 = _mm_loadu_ps(kptr + 12);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r0, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r0, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r0, _k3, _sum3);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3));
#endif
kptr += 16;
r0 += 4;
}
_mm_storeu_ps(output0_tm, _sum0);
_mm_storeu_ps(output1_tm, _sum1);
_mm_storeu_ps(output2_tm, _sum2);
_mm_storeu_ps(output3_tm, _sum3);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
for (int q = 0; q < inch; q++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += r0[n] * kptr[n];
sum1[n] += r0[n] * kptr[n + 4];
sum2[n] += r0[n] * kptr[n + 8];
sum3[n] += r0[n] * kptr[n + 12];
}
kptr += 16;
r0 += 4;
}
for (int n = 0; n < 4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif // __AVX__
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
}
}
remain_outch_start += nn_outch << 2;
for (int p = remain_outch_start; p < outch; p++)
{
float* output0_tm = top_blob_tm + 36 * tiles * p;
output0_tm = output0_tm + r * 4;
for (int i = 0; i < tiles; i++)
{
const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4 + p % 4) * inch * 4;
const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i);
#if __AVX__ || __SSE__
#if __AVX__
float zero_val = 0.f;
__m128 _sum0 = _mm_broadcast_ss(&zero_val);
#else
__m128 _sum0 = _mm_set1_ps(0.f);
#endif
for (int q = 0; q < inch; q++)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _k0 = _mm_loadu_ps(kptr);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
#endif
kptr += 4;
r0 += 4;
}
_mm_storeu_ps(output0_tm, _sum0);
#else
float sum0[4] = {0};
for (int q = 0; q < inch; q++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += r0[n] * kptr[n];
}
kptr += 4;
r0 += 4;
}
for (int n = 0; n < 4; n++)
{
output0_tm[n] = sum0[n];
}
#endif // __AVX__ || __SSE__
output0_tm += 36;
}
}
}
}
// END dot
// BEGIN transform output
float* top_blob_bordered = NULL;
if (outw_align == outw && outh_align == outh)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered = output_bordered;
}
{
// AT
// const float itm[4][6] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f}
// };
// 0 = r00 + r01 + r02 + r03 + r04
// 1 = r01 - r02 + 2 * (r03 - r04)
// 2 = r01 + r02 + 4 * (r03 + r04)
// 3 = r01 - r02 + 8 * (r03 - r04) + r05
int w_tm = outw_align / 4 * 6;
int h_tm = outh_align / 4 * 6;
int nColBlocks = h_tm / 6; // may be the block num in Feathercnn
int nRowBlocks = w_tm / 6;
const int tiles = nColBlocks * nRowBlocks;
#pragma omp parallel for num_threads(num_thread)
for (int p = 0; p < outch; p++)
{
float* out_tile = top_blob_tm + 36 * tiles * p;
float* outRow0 = top_blob_bordered + outw_align * outh_align * p;
float* outRow1 = outRow0 + outw_align;
float* outRow2 = outRow0 + outw_align * 2;
float* outRow3 = outRow0 + outw_align * 3;
const float bias0 = bias ? bias[p] : 0.f;
for (int j = 0; j < nColBlocks; j++)
{
for (int i = 0; i < nRowBlocks; i++)
{
// TODO AVX2
float s0[6], s1[6], s2[6], s3[6], s4[6], s5[6];
float w0[6], w1[6], w2[6], w3[6];
float d0[4], d1[4], d2[4], d3[4], d4[4], d5[4];
float o0[4], o1[4], o2[4], o3[4];
// load
for (int n = 0; n < 6; n++)
{
s0[n] = out_tile[n];
s1[n] = out_tile[n + 6];
s2[n] = out_tile[n + 12];
s3[n] = out_tile[n + 18];
s4[n] = out_tile[n + 24];
s5[n] = out_tile[n + 30];
}
// w = A_T * W
for (int n = 0; n < 6; n++)
{
w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n];
w1[n] = s1[n] - s2[n] + 2 * s3[n] - 2 * s4[n];
w2[n] = s1[n] + s2[n] + 4 * s3[n] + 4 * s4[n];
w3[n] = s1[n] - s2[n] + 8 * s3[n] - 8 * s4[n] + s5[n];
}
// transpose w to w_t
{
d0[0] = w0[0];
d0[1] = w1[0];
d0[2] = w2[0];
d0[3] = w3[0];
d1[0] = w0[1];
d1[1] = w1[1];
d1[2] = w2[1];
d1[3] = w3[1];
d2[0] = w0[2];
d2[1] = w1[2];
d2[2] = w2[2];
d2[3] = w3[2];
d3[0] = w0[3];
d3[1] = w1[3];
d3[2] = w2[3];
d3[3] = w3[3];
d4[0] = w0[4];
d4[1] = w1[4];
d4[2] = w2[4];
d4[3] = w3[4];
d5[0] = w0[5];
d5[1] = w1[5];
d5[2] = w2[5];
d5[3] = w3[5];
}
// Y = A_T * w_t
for (int n = 0; n < 4; n++)
{
o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n];
o1[n] = d1[n] - d2[n] + 2 * d3[n] - 2 * d4[n];
o2[n] = d1[n] + d2[n] + 4 * d3[n] + 4 * d4[n];
o3[n] = d1[n] - d2[n] + 8 * d3[n] - 8 * d4[n] + d5[n];
}
// save to top blob tm
for (int n = 0; n < 4; n++)
{
outRow0[n] = o0[n] + bias0;
outRow1[n] = o1[n] + bias0;
outRow2[n] = o2[n] + bias0;
outRow3[n] = o3[n] + bias0;
}
out_tile += 36;
outRow0 += 4;
outRow1 += 4;
outRow2 += 4;
outRow3 += 4;
}
outRow0 += outw_align * 3;
outRow1 += outw_align * 3;
outRow2 += outw_align * 3;
outRow3 += outw_align * 3;
}
}
}
// END transform output
if (outw_align != outw || outh_align != outw)
{
delete_0_3D(top_blob, top_blob_bordered, outh_align, outw_align, outh, outw, outch, 0, 0);
}
}
void conv3x3s1_winograd43_transform_kernel_sse(const float* kernel, float* kernel_wino, int inch, int outch)
{
float* kernel_tm = (float*)sys_malloc((unsigned long)6 * 6 * inch * outch * sizeof(float));
// G
const float ktm[6][3] = {
{1.0f / 4, 0.0f, 0.0f}, {-1.0f / 6, -1.0f / 6, -1.0f / 6}, {-1.0f / 6, 1.0f / 6, -1.0f / 6}, {1.0f / 24, 1.0f / 12, 1.0f / 6}, {1.0f / 24, -1.0f / 12, 1.0f / 6}, {0.0f, 0.0f, 1.0f}};
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
const float* kernel0 = kernel + p * inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm + p * inch * 36 + q * 36;
// transform kernel
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[6][3] = {0};
for (int i = 0; i < 6; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j = 0; j < 6; j++)
{
float* tmpp = &tmp[j][0];
for (int i = 0; i < 6; i++)
{
kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
float* kernel_tm_test = kernel_wino;
for (int r = 0; r < 9; r++)
{
int p = 0;
for (; p + 7 < outch; p += 8)
{
const float* kernel0 = (const float*)kernel_tm + p * inch * 36;
const float* kernel1 = (const float*)kernel_tm + (p + 1) * inch * 36;
const float* kernel2 = (const float*)kernel_tm + (p + 2) * inch * 36;
const float* kernel3 = (const float*)kernel_tm + (p + 3) * inch * 36;
const float* kernel4 = (const float*)kernel_tm + (p + 4) * inch * 36;
const float* kernel5 = (const float*)kernel_tm + (p + 5) * inch * 36;
const float* kernel6 = (const float*)kernel_tm + (p + 6) * inch * 36;
const float* kernel7 = (const float*)kernel_tm + (p + 7) * inch * 36;
float* ktmp = kernel_tm_test + p / 8 * inch * 32;
for (int q = 0; q < inch; q++)
{
ktmp[0] = kernel0[r * 4 + 0];
ktmp[1] = kernel0[r * 4 + 1];
ktmp[2] = kernel0[r * 4 + 2];
ktmp[3] = kernel0[r * 4 + 3];
ktmp[4] = kernel1[r * 4 + 0];
ktmp[5] = kernel1[r * 4 + 1];
ktmp[6] = kernel1[r * 4 + 2];
ktmp[7] = kernel1[r * 4 + 3];
ktmp[8] = kernel2[r * 4 + 0];
ktmp[9] = kernel2[r * 4 + 1];
ktmp[10] = kernel2[r * 4 + 2];
ktmp[11] = kernel2[r * 4 + 3];
ktmp[12] = kernel3[r * 4 + 0];
ktmp[13] = kernel3[r * 4 + 1];
ktmp[14] = kernel3[r * 4 + 2];
ktmp[15] = kernel3[r * 4 + 3];
ktmp[16] = kernel4[r * 4 + 0];
ktmp[17] = kernel4[r * 4 + 1];
ktmp[18] = kernel4[r * 4 + 2];
ktmp[19] = kernel4[r * 4 + 3];
ktmp[20] = kernel5[r * 4 + 0];
ktmp[21] = kernel5[r * 4 + 1];
ktmp[22] = kernel5[r * 4 + 2];
ktmp[23] = kernel5[r * 4 + 3];
ktmp[24] = kernel6[r * 4 + 0];
ktmp[25] = kernel6[r * 4 + 1];
ktmp[26] = kernel6[r * 4 + 2];
ktmp[27] = kernel6[r * 4 + 3];
ktmp[28] = kernel7[r * 4 + 0];
ktmp[29] = kernel7[r * 4 + 1];
ktmp[30] = kernel7[r * 4 + 2];
ktmp[31] = kernel7[r * 4 + 3];
ktmp += 32;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
kernel4 += 36;
kernel5 += 36;
kernel6 += 36;
kernel7 += 36;
}
}
for (; p + 3 < outch; p += 4)
{
const float* kernel0 = (const float*)kernel_tm + p * inch * 36;
const float* kernel1 = (const float*)kernel_tm + (p + 1) * inch * 36;
const float* kernel2 = (const float*)kernel_tm + (p + 2) * inch * 36;
const float* kernel3 = (const float*)kernel_tm + (p + 3) * inch * 36;
float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4) * inch * 16;
for (int q = 0; q < inch; q++)
{
ktmp[0] = kernel0[r * 4 + 0];
ktmp[1] = kernel0[r * 4 + 1];
ktmp[2] = kernel0[r * 4 + 2];
ktmp[3] = kernel0[r * 4 + 3];
ktmp[4] = kernel1[r * 4 + 0];
ktmp[5] = kernel1[r * 4 + 1];
ktmp[6] = kernel1[r * 4 + 2];
ktmp[7] = kernel1[r * 4 + 3];
ktmp[8] = kernel2[r * 4 + 0];
ktmp[9] = kernel2[r * 4 + 1];
ktmp[10] = kernel2[r * 4 + 2];
ktmp[11] = kernel2[r * 4 + 3];
ktmp[12] = kernel3[r * 4 + 0];
ktmp[13] = kernel3[r * 4 + 1];
ktmp[14] = kernel3[r * 4 + 2];
ktmp[15] = kernel3[r * 4 + 3];
ktmp += 16;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
}
}
for (; p < outch; p++)
{
const float* kernel0 = (const float*)kernel_tm + p * inch * 36;
float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4 + p % 4) * inch * 4;
for (int q = 0; q < inch; q++)
{
ktmp[0] = kernel0[r * 4 + 0];
ktmp[1] = kernel0[r * 4 + 1];
ktmp[2] = kernel0[r * 4 + 2];
ktmp[3] = kernel0[r * 4 + 3];
ktmp += 4;
kernel0 += 36;
}
}
kernel_tm_test += 4 * inch * outch;
}
free(kernel_tm);
}
int wino_conv_hcl_prerun(struct tensor* input_tensor, struct tensor* filter_tensor,
struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param)
{
int batch = input_tensor->dims[0];
int input_c = input_tensor->dims[1];
int input_h = input_tensor->dims[2];
int input_w = input_tensor->dims[3];
int output_c = output_tensor->dims[1];
int output_h = output_tensor->dims[2];
int output_w = output_tensor->dims[3];
int pad_h = param->pad_h0;
int pad_w = param->pad_w0;
float* kernel = (float*)filter_tensor->data;
if (!priv_info->external_interleave_mem)
{
int mem_size = get_private_mem_size(filter_tensor, param);
void* mem = sys_malloc(mem_size);
priv_info->interleave_buffer = mem;
priv_info->interleave_buffer_size = mem_size;
}
int block_h = (output_h + TILE - 1) / TILE;
int block_w = (output_w + TILE - 1) / TILE;
int block = block_h * block_w;
int padded_inh = TILE * block_h + 2;
int padded_inw = TILE * block_w + 2;
int pad_inhw = padded_inh * padded_inw;
int outw = block_w * TILE;
int outh = block_h * TILE;
priv_info->input_pad = (float*)sys_malloc((unsigned long)batch * input_c * pad_inhw * sizeof(float));
memset(priv_info->input_pad, 0, (unsigned long)batch * input_c * pad_inhw * sizeof(float));
priv_info->dot_block = (float*)sys_malloc(ELEM_SIZE * (unsigned long)block * output_c * sizeof(float));
priv_info->transform_input = (float*)sys_malloc(ELEM_SIZE * (unsigned long)block * input_c * sizeof(float));
priv_info->output_bordered = NULL;
if (outw != output_w || outh != output_h)
{
priv_info->output_bordered = (float*)sys_malloc((unsigned long)outw * outh * output_c * sizeof(float));
}
conv3x3s1_winograd43_transform_kernel_sse(kernel, (float*)priv_info->interleave_buffer, input_c, output_c);
return 0;
}
int wino_conv_hcl_postrun(struct conv_priv_info* priv_info)
{
if (!priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL)
{
sys_free(priv_info->interleave_buffer);
priv_info->interleave_buffer = NULL;
}
if (priv_info->input_pad)
{
sys_free(priv_info->input_pad);
priv_info->input_pad = NULL;
}
if (priv_info->dot_block)
{
sys_free(priv_info->dot_block);
priv_info->dot_block = NULL;
}
if (priv_info->transform_input)
{
sys_free(priv_info->transform_input);
priv_info->transform_input = NULL;
}
if (priv_info->output_bordered)
{
sys_free(priv_info->output_bordered);
priv_info->output_bordered = NULL;
}
return 0;
}
int wino_conv_hcl_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor,
struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param,
int num_thread, int cpu_affinity)
{
/* param */
int kernel_h = param->kernel_h;
int kernel_w = param->kernel_w;
int stride_h = param->stride_h;
int stride_w = param->stride_w;
int dilation_h = param->dilation_h;
int dilation_w = param->dilation_w;
int pad_h0 = param->pad_h0;
int pad_w0 = param->pad_w0;
int act_type = param->activation;
int group = param->group;
int batch = input_tensor->dims[0];
int in_c = input_tensor->dims[1];
int in_c_g = input_tensor->dims[1] / group;
int in_h = input_tensor->dims[2];
int in_w = input_tensor->dims[3];
int input_size = in_c * in_h * in_w;
int input_size_g = in_c_g * in_h * in_w;
int kernel_size = in_c * kernel_h * kernel_w;
int out_c = output_tensor->dims[1];
int out_h = output_tensor->dims[2];
int out_w = output_tensor->dims[3];
int out_hw = out_h * out_w;
int output_size = out_c * out_h * out_w;
int out_c_align = ((out_c + 3) & -4);
/* wino param */
int block_h = (out_h + TILE - 1) / TILE;
int block_w = (out_w + TILE - 1) / TILE;
int block_hw = block_h * block_w;
int padded_in_h = block_h * TILE + 2;
int padded_in_w = block_w * TILE + 2;
int padded_in_hw = padded_in_h * padded_in_w;
/* buffer addr */
float* input = (float*)input_tensor->data;
float* output = (float*)output_tensor->data;
float* biases = NULL;
if (bias_tensor != NULL)
biases = (float*)bias_tensor->data;
for (int i = 0; i < batch; i++)
{
for (int g = 0; g < group; g++)
{
pad_0_align_3D((float*)priv_info->input_pad + i * in_c * padded_in_h * padded_in_w, input + i * in_c * in_h * in_w,
in_h, in_w, padded_in_h, padded_in_w, in_c, pad_h0, pad_w0);
conv3x3s1_winograd43_sse((float*)priv_info->input_pad + i * in_c * padded_in_h * padded_in_w + g * input_size_g,
output + i * out_c * out_h * out_w, (float*)priv_info->interleave_buffer, (float*)priv_info->dot_block,
(float*)priv_info->transform_input, (float*)priv_info->output_bordered,
biases, padded_in_w, padded_in_h, in_c, out_w, out_h, out_c, num_thread);
}
}
if (act_type >= 0)
{
relu(output, batch * output_size, act_type);
}
return 0;
} |
GB_unop__log1p_fc64_fc64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__log1p_fc64_fc64)
// op(A') function: GB (_unop_tran__log1p_fc64_fc64)
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// cast: GxB_FC64_t cij = aij
// unaryop: cij = GB_clog1p (aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_clog1p (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = aij ; \
Cx [pC] = GB_clog1p (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LOG1P || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__log1p_fc64_fc64)
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = GB_clog1p (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = GB_clog1p (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__log1p_fc64_fc64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
initialize.c | //-------------------------------------------------------------------------//
// //
// This benchmark is a serial C version of the NPB BT code. This C //
// version is developed by the Center for Manycore Programming at Seoul //
// National University and derived from the serial Fortran versions in //
// "NPB3.3-SER" developed by NAS. //
// //
// Permission to use, copy, distribute and modify this software for any //
// purpose with or without fee is hereby granted. This software is //
// provided "as is" without express or implied warranty. //
// //
// Information on NPB 3.3, including the technical report, the original //
// specifications, source code, results and information on how to submit //
// new results, is available at: //
// //
// http://www.nas.nasa.gov/Software/NPB/ //
// //
// Send comments or suggestions for this C version to cmp@aces.snu.ac.kr //
// //
// Center for Manycore Programming //
// School of Computer Science and Engineering //
// Seoul National University //
// Seoul 151-744, Korea //
// //
// E-mail: cmp@aces.snu.ac.kr //
// //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
// Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, //
// and Jaejin Lee //
//-------------------------------------------------------------------------//
#include "header.h"
//---------------------------------------------------------------------
// This subroutine initializes the field variable u using
// tri-linear transfinite interpolation of the boundary values
//---------------------------------------------------------------------
void initialize()
{
int i, j, k, m, ix, iy, iz;
double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5];
//---------------------------------------------------------------------
// Later (in compute_rhs) we compute 1/u for every element. A few of
// the corner elements are not used, but it convenient (and faster)
// to compute the whole thing with a simple loop. Make sure those
// values are nonzero by initializing the whole thing here.
//---------------------------------------------------------------------
for (k = 0; k <= grid_points[2]-1; k++) {
for (j = 0; j <= grid_points[1]-1; j++) {
for (i = 0; i <= grid_points[0]-1; i++) {
for (m = 0; m < 5; m++) {
u[k][j][i][m] = 1.0;
}
}
}
}
//---------------------------------------------------------------------
// first store the "interpolated" values everywhere on the grid
//---------------------------------------------------------------------
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)(k) * dnzm1;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)(j) * dnym1;
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)(i) * dnxm1;
for (ix = 0; ix < 2; ix++) {
exact_solution((double)ix, eta, zeta, &Pface[ix][0][0]);
}
for (iy = 0; iy < 2; iy++) {
exact_solution(xi, (double)iy , zeta, &Pface[iy][1][0]);
}
for (iz = 0; iz < 2; iz++) {
exact_solution(xi, eta, (double)iz, &Pface[iz][2][0]);
}
for (m = 0; m < 5; m++) {
Pxi = xi * Pface[1][0][m] + (1.0-xi) * Pface[0][0][m];
Peta = eta * Pface[1][1][m] + (1.0-eta) * Pface[0][1][m];
Pzeta = zeta * Pface[1][2][m] + (1.0-zeta) * Pface[0][2][m];
u[k][j][i][m] = Pxi + Peta + Pzeta -
Pxi*Peta - Pxi*Pzeta - Peta*Pzeta +
Pxi*Peta*Pzeta;
}
}
}
}
//---------------------------------------------------------------------
// now store the exact values on the boundaries
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// west face
//---------------------------------------------------------------------
i = 0;
xi = 0.0;
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)(k) * dnzm1;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)(j) * dnym1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// east face
//---------------------------------------------------------------------
i = grid_points[0]-1;
xi = 1.0;
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)(k) * dnzm1;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)(j) * dnym1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// south face
//---------------------------------------------------------------------
j = 0;
eta = 0.0;
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)(k) * dnzm1;
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)(i) * dnxm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// north face
//---------------------------------------------------------------------
j = grid_points[1]-1;
eta = 1.0;
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)(k) * dnzm1;
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)(i) * dnxm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// bottom face
//---------------------------------------------------------------------
k = 0;
zeta = 0.0;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)(j) * dnym1;
for (i =0; i <= grid_points[0]-1; i++) {
xi = (double)(i) *dnxm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
//---------------------------------------------------------------------
// top face
//---------------------------------------------------------------------
k = grid_points[2]-1;
zeta = 1.0;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)(j) * dnym1;
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)(i) * dnxm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[k][j][i][m] = temp[m];
}
}
}
#pragma omp target update to(u)
}
void lhsinit(double lhs[][3][5][5], int size)
{
int i, m, n;
i = size;
//---------------------------------------------------------------------
// zero the whole left hand side for starters
//---------------------------------------------------------------------
for (n = 0; n < 5; n++) {
for (m = 0; m < 5; m++) {
lhs[0][0][n][m] = 0.0;
lhs[0][1][n][m] = 0.0;
lhs[0][2][n][m] = 0.0;
lhs[i][0][n][m] = 0.0;
lhs[i][1][n][m] = 0.0;
lhs[i][2][n][m] = 0.0;
}
}
//---------------------------------------------------------------------
// next, set all diagonal values to 1. This is overkill, but convenient
//---------------------------------------------------------------------
for (m = 0; m < 5; m++) {
lhs[0][1][m][m] = 1.0;
lhs[i][1][m][m] = 1.0;
}
}
|
symm.c | /**
* This version is stamped on May 10, 2016
*
* Contact:
* Louis-Noel Pouchet <pouchet.ohio-state.edu>
* Tomofumi Yuki <tomofumi.yuki.fr>
*
* Web address: http://polybench.sourceforge.net
*/
/* symm.c: this file is part of PolyBench/C */
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
#include "symm.h"
/* Array initialization. */
static
void init_array(int m, int n,
DATA_TYPE *alpha,
DATA_TYPE *beta,
DATA_TYPE POLYBENCH_2D(C, M, N, m, n),
DATA_TYPE POLYBENCH_2D(A, M, M, m, m),
DATA_TYPE POLYBENCH_2D(B, M, N, m, n))
{
int i, j;
*alpha = 1.5;
*beta = 1.2;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
{
C[i][j] = (DATA_TYPE) ((i + j) % 100) / m ;
B[i][j] = (DATA_TYPE) ((n + i - j) % 100) / m ;
}
for (i = 0; i < m; i++)
{
for (j = 0; j <= i; j++)
A[i][j] = (DATA_TYPE) ((i + j) % 100) / m ;
for (j = i + 1; j < m; j++)
A[i][j] = -999; //regions of arrays that should not be used
}
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int m, int n,
DATA_TYPE POLYBENCH_2D(C, M, N, m, n))
{
int i, j;
POLYBENCH_DUMP_START;
POLYBENCH_DUMP_BEGIN("C");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
{
if ((i * m + j) % 20 == 0) fprintf (POLYBENCH_DUMP_TARGET, "\n");
fprintf (POLYBENCH_DUMP_TARGET, DATA_PRINTF_MODIFIER, C[i][j]);
}
POLYBENCH_DUMP_END("C");
POLYBENCH_DUMP_FINISH;
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_symm(int m, int n,
DATA_TYPE alpha,
DATA_TYPE beta,
DATA_TYPE POLYBENCH_2D(C, M, N, m, n),
DATA_TYPE POLYBENCH_2D(A, M, M, m, m),
DATA_TYPE POLYBENCH_2D(B, M, N, m, n))
{
int i, j, k;
DATA_TYPE temp2;
for (i = 0; i < _PB_M; i++)
{
#pragma omp parallel for default(shared) private(j, k, temp2) firstprivate(n, i, alpha, beta, B, A)
for (j = 0; j < _PB_N; j++ )
{
temp2 = 0;
for (k = 0; k < i; k++)
{
C[k][j] += alpha * B[i][j] * A[i][k];
temp2 += B[k][j] * A[i][k];
}
C[i][j] = beta * C[i][j] + alpha * B[i][j] * A[i][i] + alpha * temp2;
}
}
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int m = M;
int n = N;
/* Variable declaration/allocation. */
DATA_TYPE alpha;
DATA_TYPE beta;
POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, M, N, m, n);
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, M, M, m, m);
POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, M, N, m, n);
/* Initialize array(s). */
init_array (m, n, &alpha, &beta,
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_symm (m, n,
alpha, beta,
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(m, n, POLYBENCH_ARRAY(C)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(C);
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
return 0;
}
|
GB_unop__ceil_fp32_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__ceil_fp32_fp32)
// op(A') function: GB (_unop_tran__ceil_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = ceilf (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = ceilf (x) ;
// casting
#define GB_CAST(z, aij) \
float z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = aij ; \
Cx [pC] = ceilf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_CEIL || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__ceil_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = ceilf (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = ceilf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__ceil_fp32_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
zsymm.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> s d c
*
**/
#include "plasma.h"
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_types.h"
#include "plasma_workspace.h"
/***************************************************************************//**
*
* @ingroup plasma_symm
*
* Performs one of the matrix-matrix operations
*
* \f[ C = \alpha \times A \times B + \beta \times C \f]
* or
* \f[ C = \alpha \times B \times A + \beta \times C \f]
*
* where alpha and beta are scalars, A is a symmetric matrix and B and
* C are m-by-n matrices.
*
*******************************************************************************
*
* @param[in] side
* Specifies whether the symmetric matrix A appears on the
* left or right in the operation as follows:
* - PlasmaLeft: \f[ C = \alpha \times A \times B + \beta \times C \f]
* - PlasmaRight: \f[ C = \alpha \times B \times A + \beta \times C \f]
*
* @param[in] uplo
* Specifies whether the upper or lower triangular part of
* the symmetric matrix A is to be referenced as follows:
* - PlasmaLower: Only the lower triangular part of the
* symmetric matrix A is to be referenced.
* - PlasmaUpper: Only the upper triangular part of the
* symmetric matrix A is to be referenced.
*
* @param[in] m
* The number of rows of the matrix C. m >= 0.
*
* @param[in] n
* The number of columns of the matrix C. n >= 0.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] pA
* A is an lda-by-ka matrix, where ka is m when side = PlasmaLeft,
* and is n otherwise. Only the uplo triangular part is referenced.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,ka).
*
* @param[in] pB
* B is an ldb-by-n matrix, where the leading m-by-n part of
* the array B must contain the matrix B.
*
* @param[in] ldb
* The leading dimension of the array B. ldb >= max(1,m).
*
* @param[in] beta
* The scalar beta.
*
* @param[in,out] pC
* C is an ldc-by-n matrix.
* On exit, the array is overwritten by the m-by-n updated matrix.
*
* @param[in] ldc
* The leading dimension of the array C. ldc >= max(1,m).
*
*******************************************************************************
*
* @retval PlasmaSuccess successful exit
*
*******************************************************************************
*
* @sa plasma_omp_zsymm
* @sa plasma_csymm
* @sa plasma_dsymm
* @sa plasma_ssymm
*
******************************************************************************/
int plasma_zsymm(plasma_enum_t side, plasma_enum_t
uplo, int m, int n,
plasma_complex64_t alpha, plasma_complex64_t *pA, int lda,
plasma_complex64_t *pB, int ldb,
plasma_complex64_t beta, plasma_complex64_t *pC, int ldc)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if ((side != PlasmaLeft) && (side != PlasmaRight)) {
plasma_error("illegal value of side");
return -1;
}
if ((uplo != PlasmaLower) && (uplo != PlasmaUpper)) {
plasma_error("illegal value of uplo");
return -2;
}
if (m < 0) {
plasma_error("illegal value of m");
return -3;
}
if (n < 0) {
plasma_error("illegal value of n");
return -4;
}
int am;
if (side == PlasmaLeft)
am = m;
else
am = n;
if (lda < imax(1, am)) {
plasma_error("illegal value of lda");
return -7;
}
if (ldb < imax(1, m)) {
plasma_error("illegal value of ldb");
return -9;
}
if (ldc < imax(1, m)) {
plasma_error("illegal value of ldc");
return -12;
}
// quick return
if (m == 0 || n == 0 || (alpha == 0.0 && beta == 1.0))
return PlasmaSuccess;
// Set tiling parameters.
int nb = plasma->nb;
// Create tile matrices.
plasma_desc_t A;
plasma_desc_t B;
plasma_desc_t C;
int retval;
retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb,
am, am, 0, 0, am, am, &A);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
return retval;
}
retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb,
m, n, 0, 0, m, n, &B);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
plasma_desc_destroy(&A);
return retval;
}
retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb,
m, n, 0, 0, m, n, &C);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
plasma_desc_destroy(&A);
plasma_desc_destroy(&B);
return retval;
}
// Create sequence.
plasma_sequence_t *sequence = NULL;
retval = plasma_sequence_create(&sequence);
if (retval != PlasmaSuccess) {
plasma_error("plasma_sequence_create() failed");
return retval;
}
// Initialize request.
plasma_request_t request = PlasmaRequestInitializer;
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate to tile layout.
plasma_omp_zge2desc(pA, lda, A, sequence, &request);
plasma_omp_zge2desc(pB, ldb, B, sequence, &request);
plasma_omp_zge2desc(pC, ldc, C, sequence, &request);
// Call the tile async function.
plasma_omp_zsymm(side, uplo,
alpha, A,
B,
beta, C,
sequence, &request);
// Translate back to LAPACK layout.
plasma_omp_zdesc2ge(C, pC, ldc, sequence, &request);
}
// implicit synchronization
// Free matrices in tile layout.
plasma_desc_destroy(&A);
plasma_desc_destroy(&B);
plasma_desc_destroy(&C);
// Return status.
int status = sequence->status;
plasma_sequence_destroy(sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup plasma_symm
*
* Performs symmetric matrix multiplication.
* Non-blocking tile version of plasma_zsymm().
* May return before the computation is finished.
* Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] side
* Specifies whether the symmetric matrix A appears on the
* left or right in the operation as follows:
* - PlasmaLeft: \f[ C = \alpha \times A \times B + \beta \times C \f]
* - PlasmaRight: \f[ C = \alpha \times B \times A + \beta \times C \f]
*
* @param[in] uplo
* Specifies whether the upper or lower triangular part of
* the symmetric matrix A is to be referenced as follows:
* - PlasmaLower: Only the lower triangular part of the
* symmetric matrix A is to be referenced.
* - PlasmaUpper: Only the upper triangular part of the
* symmetric matrix A is to be referenced.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] A
* Descriptor of matrix A.
*
* @param[in] B
* Descriptor of matrix B.
*
* @param[in] beta
* The scalar beta.
*
* @param[in,out] C
* Descriptor of matrix C.
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
*******************************************************************************
*
* @sa plasma_zsymm
* @sa plasma_omp_csymm
* @sa plasma_omp_dsymm
* @sa plasma_omp_ssymm
*
******************************************************************************/
void plasma_omp_zsymm(plasma_enum_t side, plasma_enum_t uplo,
plasma_complex64_t alpha, plasma_desc_t A,
plasma_desc_t B,
plasma_complex64_t beta, plasma_desc_t C,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// Check input arguments.
if ((side != PlasmaLeft) &&
(side != PlasmaRight)) {
plasma_error("illegal value of side");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if ((uplo != PlasmaLower) &&
(uplo != PlasmaUpper)) {
plasma_error("illegal value of uplo");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(A) != PlasmaSuccess) {
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
plasma_error("invalid A");
return;
}
if (plasma_desc_check(B) != PlasmaSuccess) {
plasma_error("invalid B");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(C) != PlasmaSuccess) {
plasma_error("invalid C");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (sequence == NULL) {
plasma_error("NULL sequence");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (request == NULL) {
plasma_error("NULL request");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// quick return
if (C.m == 0 || C.n == 0 || ((alpha == 0.0 || A.n == 0) && beta == 1.0))
return;
// Call the parallel function.
plasma_pzsymm(side, uplo,
alpha, A,
B,
beta, C,
sequence, request);
}
|
check_impl.c | /*
Copyright 2021 Tim Jammer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "correctness-checking-partitioned-impl.h"
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#define SIZE 16
#define PARTITIONS 16
#define TAG 42
void correct_usage() {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
MPIX_Psend_init(buffer, PARTITIONS, SIZE, MPI_INT, 1, TAG, MPI_COMM_WORLD,
MPI_INFO_NULL, &r);
MPIX_Start(&r);
#pragma omp parallel for
for (int i = 0; i < PARTITIONS; ++i) {
for (int j = i * SIZE; j < i * SIZE + SIZE; ++j) {
buffer[j] = i;
}
MPIX_Pready(i, &r);
}
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
void correct_usage_with_false_positives() {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
int sum = 0;
MPIX_Psend_init(buffer, PARTITIONS, SIZE, MPI_INT, 1, TAG, MPI_COMM_WORLD,
MPI_INFO_NULL, &r);
MPIX_Start(&r);
#pragma omp parallel for reduction(+ : sum)
for (int i = 0; i < PARTITIONS; ++i) {
for (int j = i * SIZE; j < i * SIZE + SIZE; ++j) {
buffer[j] = i;
}
MPIX_Pready(i, &r);
for (int j = i * SIZE; j < i * SIZE + SIZE; ++j) {
// reading is allowed
sum += buffer[j];
}
}
printf("%d\n", sum);
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
void error_usage() {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
MPIX_Psend_init(buffer, PARTITIONS, SIZE, MPI_INT, 1, TAG, MPI_COMM_WORLD,
MPI_INFO_NULL, &r);
MPIX_Start(&r);
// likely to fail
#pragma omp parallel for
for (int i = 0; i < PARTITIONS * 2; ++i) {
if (i < PARTITIONS) {
for (int j = i * SIZE; j < i * SIZE + SIZE / 2; ++j) {
buffer[j] = i;
}
MPIX_Pready(i, &r);
} else {
for (int j = (i - PARTITIONS) * SIZE + SIZE / 2;
j < (i - PARTITIONS) * SIZE + SIZE; ++j) {
buffer[j] = i;
}
}
}
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
int main(int argc, char **argv) {
MPI_Init(&argc, &argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
// correct_usage();
correct_usage_with_false_positives();
error_usage();
} else if (rank == 1) {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
MPIX_Precv_init(buffer, 1, (PARTITIONS * SIZE), MPI_INT, 0, TAG,
MPI_COMM_WORLD, MPI_INFO_NULL, &r);
MPIX_Start(&r);
MPIX_Pready(0, &r);
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Start(&r);
MPIX_Pready(0, &r);
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
MPI_Finalize();
}
|
matmul_int.c | /*
* Square matrix multiplication
* A[N][N] * B[N][N] = C[N][N]
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/timeb.h>
#include <malloc.h>
#define N 1024
//#define N 16
// read timer in second
double read_timer() {
struct timeb tm;
ftime(&tm);
return (double) tm.time + (double) tm.millitm / 1000.0;
}
void init(int **A) {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
A[i][j] = (int)rand()/(int)(RAND_MAX/10.0);
}
}
}
void matmul_simd(int **A, int **B, int **C) {
int i,j,k;
int temp;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
temp = 0;
#pragma omp simd reduction(+:temp)
for (k = 0; k < N; k++) {
temp += A[i][k] * B[j][k];
}
C[i][j] = temp;
}
}
}
// Debug functions
void print_matrix(int **matrix) {
for (int i = 0; i<8; i++) {
printf("[");
for (int j = 0; j<8; j++) {
printf("%d ", matrix[i][j]);
}
puts("]");
}
puts("");
}
void matmul_serial(int **A, int **B, int **C) {
int i,j,k;
int temp;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
temp = 0;
for (k = 0; k < N; k++) {
temp += A[i][k] * B[j][k];
}
C[i][j] = temp;
}
}
}
int check(int **A, int **B){
int difference = 0;
for(int i = 0;i<N; i++){
for (int j = 0; j<N; j++)
{ difference += A[i][j]- B[i][j];}
}
return difference;
}
// Main
int main(int argc, char *argv[]) {
//Set everything up
int **A = malloc(sizeof(int*)*N);
int **B = malloc(sizeof(int*)*N);
int **C_simd = malloc(sizeof(int*)*N);
int **C_serial = malloc(sizeof(int*)*N);
int **BT = malloc(sizeof(int*)*N);
for (int i = 0; i<N; i++) {
A[i] = malloc(sizeof(int)*N);
B[i] = malloc(sizeof(int)*N);
C_simd[i] = malloc(sizeof(int)*N);
C_serial[i] = malloc(sizeof(int)*N);
BT[i] = malloc(sizeof(int)*N);
}
srand(time(NULL));
init(A);
init(B);
for(int line = 0; line<N; line++){
for(int col = 0; col<N; col++){
BT[line][col] = B[col][line];
}
}
int i;
int num_runs = 20;
//Warming up
matmul_simd(A, BT, C_simd);
matmul_serial(A, BT, C_serial);
double elapsed = 0;
double elapsed1 = read_timer();
for (i=0; i<num_runs; i++)
matmul_simd(A, BT, C_simd);
elapsed += (read_timer() - elapsed1);
double elapsed_serial = 0;
double elapsed_serial1 = read_timer();
for (i=0; i<num_runs; i++)
matmul_serial(A, BT, C_serial);
elapsed_serial += (read_timer() - elapsed_serial1);
print_matrix(A);
print_matrix(BT);
puts("=\n");
print_matrix(C_simd);
puts("---------------------------------");
print_matrix(C_serial);
double gflops_omp = ((((2.0 * N) * N) * N * num_runs) / (1.0e9 * elapsed));
double gflops_serial = ((((2.0 * N) * N) * N * num_runs) / (1.0e9 * elapsed_serial));
printf("======================================================================================================\n");
printf("\tMatrix Multiplication: A[N][N] * B[N][N] = C[N][N], N=%d\n", N);
printf("------------------------------------------------------------------------------------------------------\n");
printf("Performance:\t\tRuntime (s)\t GFLOPS\n");
printf("------------------------------------------------------------------------------------------------------\n");
printf("matmul_omp:\t\t%4f\t%4f\n", elapsed/num_runs, gflops_omp);
printf("matmul_serial:\t\t%4f\t%4f\n", elapsed_serial/num_runs, gflops_serial);
printf("Correctness check: %d\n", check(C_simd,C_serial));
return 0;
}
|
Perft.h | // JAGLAVAK CHESS ENGINE (c) 2019 Stuart Riffle
#pragma once
const int MAX_PARALLEL_DEPTH = 5;
static void GatherPerftParallelPositions( const Position& pos, int depth, vector< Position >* dest )
{
MoveList valid;
valid.FindMoves( pos );
for( int i = 0; i < valid._Count; i++ )
{
Position next = pos;
next.Step( valid._Move[i] );
if( depth == (MAX_PARALLEL_DEPTH + 1) )
dest->push_back( next );
else
GatherPerftParallelPositions( next, depth - 1, dest );
}
}
static u64 CalcPerftParallel( const Position& pos, int depth );
static u64 CalcPerftInternal( const Position& pos, int depth )
{
if( (depth > MAX_PARALLEL_DEPTH) && (depth <= MAX_PARALLEL_DEPTH + 3) )
{
return( CalcPerftParallel( pos, depth ) );
}
MoveList valid;
valid.FindMoves( pos );
u64 total = 0;
for( int i = 0; i < valid._Count; i++ )
{
Position next = pos;
next.Step( valid._Move[i] );
if( depth == 2 )
{
MoveList dummy;
total += dummy.FindMoves( next );
}
else
{
total += CalcPerftInternal( next, depth - 1 );
}
}
return( total );
}
static u64 CalcPerftParallel( const Position& pos, int depth )
{
vector< Position > positions( 16384 );
GatherPerftParallelPositions( pos, depth, &positions );
u64 total = 0;
#pragma omp parallel for reduction(+: total) schedule(dynamic)
for( int i = 0; i < ( int) positions.size(); i++ )
{
u64 subtotal = CalcPerftInternal( positions[i], MAX_PARALLEL_DEPTH );
total = total + subtotal;
}
return(total);
}
static u64 CalcPerft( const Position& pos, int depth )
{
if( depth < 2 )
{
MoveList dummy;
return( dummy.FindMoves( pos ) );
}
return( CalcPerftInternal( pos, depth ) );
}
static map< MoveSpec, u64 > DividePerft( const Position& pos, int depth )
{
MoveList valid;
valid.FindMoves( pos );
map< MoveSpec, u64 > result;
for( int i = 0; i < valid._Count; i++ )
{
Position next = pos;
next.Step( valid._Move[i] );
u64 count = (depth > 1)? CalcPerft( next, depth - 1 ) : 1;
result[valid._Move[i]] = count;
}
return result;
}
|
masterConstruct.c | int main() {
int x = 1;
#pragma omp parallel
{
int localX = 2;
#pragma omp master
{
localX = x;
}
localX = 20;
}
}
|
absgradMEX.c | /**************************************************************************
MEX function to compute the approximate gradient of the absolute value
Author: R. Marc Lebel
Contact: mlebel@gmail.com
Date: 11/2010
Useage: wc2 = absgradMEX(wc,smooth)
Input:
wc: numeric array (single/double; real/complex)
smooth: small smoothing factor to prevent Inf
Output:
wc2: numeric array
**************************************************************************/
#include "mex.h"
#include <math.h>
#include <string.h>
#include "fast_mxArray_setup.c"
#ifdef __GNU__
#include <omp.h>
#endif
#ifndef MAXCORES
#define MAXCORES 1
#endif
void mexFunction(int nlhs, mxArray *left[], int nrhs, const mxArray *right[]) {
/* Declare variables */
mwSize nD, elem, cmplx, *size2;
long long i;
mxClassID precision;
const mwSize *size;
mxComplexity cmplx2;
mxArray *X, *Y;
double *pXr, *pXi, *pYi, *pYr, *pS, Sd, denom;
float *pXrf, *pXif, *pYif, *pYrf, *pSf, Sf, denomf;
/* Get size */
nD = mxGetNumberOfDimensions(right[0]);
size = mxGetDimensions(right[0]);
elem = mxGetNumberOfElements(right[0]);
/*mexPrintf("nD: %i\n",nD);
mexPrintf("size: %i\n",size[0]);
mexPrintf("elem: %i\n",elem);*/
/* Perform strange memory copy to replicate the size (needed for create_array_d/f) */
size2 = (mwSize *)mxMalloc(nD*sizeof(mwSize));
memcpy(size2,size,nD*sizeof(mwSize));
/* Test for complex and obtain data class */
cmplx = mxIsComplex(right[0]);
precision = mxGetClassID(right[0]);
cmplx2 = cmplx ? mxCOMPLEX:mxREAL;
/* Test to ensure smoothing factor is real */
if (mxIsComplex(right[1]))
mexErrMsgTxt("Inputs 1 is complex");
/* Get pointers to input array and create output */
if (precision == mxDOUBLE_CLASS) {
pXr = mxGetPr(right[0]);
if (cmplx)
pXi = mxGetPi(right[0]);
/* Create output and assign pointers */
create_array_d(&(left[0]), &pYr, &pYi, nD, size2, cmplx2, 0);
}
else {
pXrf = mxGetData(right[0]);
if (cmplx)
pXif = mxGetImagData(right[0]);
/* Create output and assign pointers */
create_array_f(&(left[0]), &pYrf, &pYif, nD, size2, cmplx2, 0);
}
/* Get pointer to input scalar */
if (mxGetClassID(right[1]) == mxDOUBLE_CLASS)
pS = mxGetData(right[1]);
else
pSf = mxGetData(right[1]);
/* Convert smoothing factor to appropriate class */
if (precision == mxDOUBLE_CLASS) {
if (mxGetClassID(right[1]) == mxDOUBLE_CLASS)
Sd = pS[0];
else
Sd = (double) pSf[0];
}
else {
if (mxGetClassID(right[1]) == mxDOUBLE_CLASS)
Sf = (float) pS[0];
else
Sf = pSf[0];
}
#ifdef __GNU__
/* Set number of threads */
omp_set_num_threads(MAXCORES);
#endif
/* Loop through and compute the gradient of the absolute value */
if (precision == mxDOUBLE_CLASS) {
if (cmplx) {
#pragma omp parallel for private(i,denom)
for (i=0; i<elem; i++) {
denom = 1.0/sqrt(pXr[i]*pXr[i] + pXi[i]*pXi[i] + Sd);
pYr[i] = pXr[i] * denom;
pYi[i] = pXi[i] * denom;
}
}
else {
#pragma omp parallel for private(i)
for (i=0; i<elem; i++) {
pYr[i] = pXr[i]/sqrt(pXr[i]*pXr[i] + Sd);
}
}
}
else {
if (cmplx) {
#pragma omp parallel for private(i,denomf)
for (i=0; i<elem; i++) {
/*denomf = Q_rsqrt(pXrf[i]*pXrf[i] + pXif[i]*pXif[i] + Sf);*/ /* Not working on ubuntu?! */
denomf = 1.0/sqrtf(pXrf[i]*pXrf[i] + pXif[i]*pXif[i] + Sf);
pYrf[i] = pXrf[i] * denomf;
pYif[i] = pXif[i] * denomf;
}
}
else {
#pragma omp parallel for private(i)
for (i=0; i<elem; i++) {
pYrf[i] = pXrf[i]/sqrtf(pXrf[i]*pXrf[i] + Sf);
/*denomf = Q_rsqrt(pXrf[i]*pXrf[i] + Sf); */
/*pYrf[i] = pXrf[i] * denomf;*/ /* Not working on ubuntu?! */
}
}
}
/* Free memory */
mxFree(size2);
}
|
replacement_filter_impl.h | /* The MIT License (MIT)
*
* (c) Jürgen Simon 2014 (juergen.simon@uni-bonn.de)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef M3D_REPLACEMENT_FILTER_IMPL_H
#define M3D_REPLACEMENT_FILTER_IMPL_H
#include <meanie3D/utils.h>
#include <meanie3D/index.h>
#include "replacement_filter.h"
#include <vector>
namespace m3D {
using namespace std;
template<typename T>
ReplacementFilter<T>::ReplacementFilter(const ReplacementMode mode,
const size_t variable_index,
const std::vector<T> &bandwidth,
const float percentage,
bool show_progress)
: FeatureSpaceFilter<T>(show_progress),
m_replacement_mode(mode),
m_variable_index(variable_index),
m_bandwidth(bandwidth),
m_percentage(percentage) {};
template<typename T>
void ReplacementFilter<T>::apply(FeatureSpace <T> *fs) {
// Create a spatial index for the copied feature space
PointIndex<T> *index = PointIndex<T>::create(fs->get_points(), fs->rank());
SearchParameters *params = new RangeSearchParams<T>(m_bandwidth);
size_t value_index = fs->spatial_rank() + m_variable_index;
vector<T> filteredValues;
filteredValues.resize(fs->size());
typename Point<T>::list points;
#if WITH_OPENMP
#pragma omp parallel for schedule(dynamic)
#endif
for (size_t i = 0; i < fs->size(); i++) {
// Get the values around the point (original index)
T result = fs->points[i]->values[value_index];
typename Point<T>::list *neighbours = NULL;
#if WITH_OPENMP
#pragma omp critical
{
#endif
neighbours = index->search(fs->points[i]->coordinate, params);
#if WITH_OPENMP
}
#endif
if (!(neighbours == NULL || neighbours->size() == 0)) {
vector<T> values;
for (size_t n = 0; n < neighbours->size(); n++) {
values.push_back(neighbours->at(n)->values[value_index]);
}
switch (m_replacement_mode) {
case ReplaceWithLowest:
case ReplaceWithMedian:
// sort the data in ascending order
std::sort(values.begin(), values.end());
break;
case ReplaceWithHighest:
// sort the data in descending order
std::sort(values.begin(), values.end(), std::greater<int>());
break;
}
// calculate the number of values that make up
// the required percentage
int num_values = round(values.size() * m_percentage);
if (m_replacement_mode == ReplaceWithMedian) {
result = values[num_values / 2];
} else {
// obtain the average of the last num_values values
T sum = 0.0;
for (int i = 0; i < num_values; i++)
sum += values[i];
result = sum / ((T) num_values);
}
}
filteredValues[i] = result;
}
// Replace the values in the featurespace's points
for (size_t i = 0; i < fs->size(); i++) {
fs->points[i]->values[value_index] = filteredValues[i];
}
delete index;
delete params;
}
}
#endif
|
compute_dem_face_load_utility.h | /*
* Author: Salva Latorre and Ignasi Pouplana
*
* latorre@cimne.upc.edu
* ipouplana@cimne.upc.edu
*/
#ifndef COMPUTE_DEM_FACE_LOAD_UTILITY_H
#define COMPUTE_DEM_FACE_LOAD_UTILITY_H
#include "includes/variables.h"
#include <limits>
#include <iostream>
#include <iomanip>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "includes/define.h"
#include "includes/condition.h"
#include "includes/model_part.h"
#include "dem_structures_coupling_application_variables.h"
namespace Kratos {
class ComputeDEMFaceLoadUtility {
public:
typedef ModelPart::NodesContainerType::ContainerType::iterator NodesIteratorType;
KRATOS_CLASS_POINTER_DEFINITION(ComputeDEMFaceLoadUtility);
ComputeDEMFaceLoadUtility() {}
virtual ~ComputeDEMFaceLoadUtility() {}
void ClearDEMFaceLoads(ModelPart& r_structural_skin_model_part) {
KRATOS_TRY
#pragma omp parallel for
for (int i=0; i<(int)r_structural_skin_model_part.Nodes().size(); i++) {
auto node_it = r_structural_skin_model_part.NodesBegin() + i;
array_1d<double, 3>& node_rhs = node_it->FastGetSolutionStepValue(DEM_SURFACE_LOAD);
node_rhs = ZeroVector(3);
}
KRATOS_CATCH("")
}
void CalculateDEMFaceLoads(ModelPart& r_structural_skin_model_part, const double DEM_delta_time, const double FEM_delta_time) {
KRATOS_TRY
static bool nodal_area_already_computed = false;
if (!nodal_area_already_computed) {
#pragma omp parallel for
for (int i=0; i<(int)r_structural_skin_model_part.Nodes().size(); i++) {
auto node_it = r_structural_skin_model_part.NodesBegin() + i;
double& node_area = node_it->GetSolutionStepValue(DEM_NODAL_AREA);
node_area = 0.0;
}
ModelPart::ConditionsContainerType& source_conditions = r_structural_skin_model_part.Conditions();
const double one_third = 1.0/3.0;
for (unsigned int i = 0; i < source_conditions.size(); i++) {
ModelPart::ConditionsContainerType::iterator it = r_structural_skin_model_part.ConditionsBegin() + i;
Condition::GeometryType& geometry = it->GetGeometry();
double condition_area = geometry.Area();
for (unsigned int i = 0; i < geometry.size(); i++) { //talking about each of the three nodes of the condition
double& node_area = geometry[i].FastGetSolutionStepValue(DEM_NODAL_AREA);
node_area += one_third * condition_area; //TODO: ONLY FOR TRIANGLE... Generalize for 3 or 4 nodes
}
}
nodal_area_already_computed = true;
}
#pragma omp parallel for
for (int i=0; i<(int)r_structural_skin_model_part.Nodes().size(); i++) {
auto node_it = r_structural_skin_model_part.NodesBegin() + i;
double& nodal_area = node_it->FastGetSolutionStepValue(DEM_NODAL_AREA);
if (nodal_area && FEM_delta_time) {
node_it->FastGetSolutionStepValue(DEM_SURFACE_LOAD) += node_it->FastGetSolutionStepValue(CONTACT_FORCES) * DEM_delta_time / (nodal_area * FEM_delta_time);
}
}
KRATOS_CATCH("")
}
virtual std::string Info() const { return "";}
virtual void PrintInfo(std::ostream& rOStream) const {}
virtual void PrintData(std::ostream& rOStream) const {}
private:
ComputeDEMFaceLoadUtility& operator= (ComputeDEMFaceLoadUtility const& rOther);
}; // class ComputeDEMFaceLoadUtility
} // namespace Kratos
#endif // COMPUTE_DEM_FACE_LOAD_UTILITY_H
|
GB_unop__abs_fp64_fp64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__abs_fp64_fp64)
// op(A') function: GB (_unop_tran__abs_fp64_fp64)
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = fabs (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 = fabs (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] = fabs (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__abs_fp64_fp64)
(
double *Cx, // Cx and Ax may be aliased
const double *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = fabs (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = fabs (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__abs_fp64_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
critical.c | /* Copyright (C) 2005-2015 Free Software Foundation, Inc.
Contributed by Richard Henderson <rth@redhat.com>.
This file is part of the GNU Offloading and Multi Processing Library
(libgomp).
Libgomp is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/* This file handles the CRITICAL construct. */
#include "libgomp.h"
#include <stdlib.h>
static gomp_mutex_t default_lock;
void
GOMP_critical_start (void)
{
/* There is an implicit flush on entry to a critical region. */
__atomic_thread_fence (MEMMODEL_RELEASE);
gomp_mutex_lock (&default_lock);
}
void
GOMP_critical_end (void)
{
gomp_mutex_unlock (&default_lock);
}
#ifndef HAVE_SYNC_BUILTINS
static gomp_mutex_t create_lock_lock;
#endif
void
GOMP_critical_name_start (void **pptr)
{
gomp_mutex_t *plock;
/* If a mutex fits within the space for a pointer, and is zero initialized,
then use the pointer space directly. */
if (GOMP_MUTEX_INIT_0
&& sizeof (gomp_mutex_t) <= sizeof (void *)
&& __alignof (gomp_mutex_t) <= sizeof (void *))
plock = (gomp_mutex_t *)pptr;
/* Otherwise we have to be prepared to malloc storage. */
else
{
plock = *pptr;
if (plock == NULL)
{
#ifdef HAVE_SYNC_BUILTINS
gomp_mutex_t *nlock = gomp_malloc (sizeof (gomp_mutex_t));
gomp_mutex_init (nlock);
plock = __sync_val_compare_and_swap (pptr, NULL, nlock);
if (plock != NULL)
{
gomp_mutex_destroy (nlock);
free (nlock);
}
else
plock = nlock;
#else
gomp_mutex_lock (&create_lock_lock);
plock = *pptr;
if (plock == NULL)
{
plock = gomp_malloc (sizeof (gomp_mutex_t));
gomp_mutex_init (plock);
__sync_synchronize ();
*pptr = plock;
}
gomp_mutex_unlock (&create_lock_lock);
#endif
}
}
gomp_mutex_lock (plock);
}
void
GOMP_critical_name_end (void **pptr)
{
gomp_mutex_t *plock;
/* If a mutex fits within the space for a pointer, and is zero initialized,
then use the pointer space directly. */
if (GOMP_MUTEX_INIT_0
&& sizeof (gomp_mutex_t) <= sizeof (void *)
&& __alignof (gomp_mutex_t) <= sizeof (void *))
plock = (gomp_mutex_t *)pptr;
else
plock = *pptr;
gomp_mutex_unlock (plock);
}
/* This mutex is used when atomic operations don't exist for the target
in the mode requested. The result is not globally atomic, but works so
long as all parallel references are within #pragma omp atomic directives.
According to responses received from omp@openmp.org, appears to be within
spec. Which makes sense, since that's how several other compilers
handle this situation as well. */
static gomp_mutex_t atomic_lock;
void
GOMP_atomic_start (void)
{
gomp_mutex_lock (&atomic_lock);
}
void
GOMP_atomic_end (void)
{
gomp_mutex_unlock (&atomic_lock);
}
#if !GOMP_MUTEX_INIT_0
static void __attribute__((constructor))
initialize_critical (void)
{
gomp_mutex_init (&default_lock);
gomp_mutex_init (&atomic_lock);
#ifndef HAVE_SYNC_BUILTINS
gomp_mutex_init (&create_lock_lock);
#endif
}
#endif
|
GB_unaryop__identity_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__identity_int8_int64
// op(A') function: GB_tran__identity_int8_int64
// C type: int8_t
// A type: int64_t
// cast: int8_t cij = (int8_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_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_IDENTITY || GxB_NO_INT8 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_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__identity_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
|
ej2.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <unistd.h>
#define TAM 40
void rellenarArray(float *M){
for(int i=0;i<TAM;++i)
*(M+i)=5.0f;
}
int main() {
double start;int numthreads=4;
float *a = (float *)malloc(sizeof(float)*TAM);
float *b = (float *)malloc(sizeof(float)*TAM);
float *c = (float *)malloc(sizeof(float)*TAM);
rellenarArray(a);rellenarArray(b);
start = omp_get_wtime();
#pragma omp parallel for schedule(static) num_threads(numthreads)
for(int i=0;i<TAM;++i)
*(c+i)=*(a+i)+*(b+i);
printf("\n-------------------------------------------\nTiempo de ejecucion del programa con %i hilos y schedule STATIC, %lfs\n-------------------------------------------\n",numthreads,omp_get_wtime()-start);
start = omp_get_wtime();
#pragma omp parallel for schedule(dynamic) num_threads(numthreads)
for(int i=0;i<TAM;++i)
*(c+i)=*(a+i)+*(b+i);
printf("\n-------------------------------------------\nTiempo de ejecucion del programa con %i hilos y schedule DYNAMIC, %lfs\n-------------------------------------------\n",numthreads,omp_get_wtime()-start);
start = omp_get_wtime();
#pragma omp parallel for schedule(guided) num_threads(numthreads)
for(int i=0;i<TAM;++i)
*(c+i)=*(a+i)+*(b+i);
printf("\n-------------------------------------------\nTiempo de ejecucion del programa con %i hilos y schedule GUIDED, %lfs\n-------------------------------------------\n",numthreads,omp_get_wtime()-start);
return 0;
}
|
GB_binop__isgt_fp32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__isgt_fp32)
// A.*B function (eWiseMult): GB (_AemultB_08__isgt_fp32)
// A.*B function (eWiseMult): GB (_AemultB_02__isgt_fp32)
// A.*B function (eWiseMult): GB (_AemultB_04__isgt_fp32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__isgt_fp32)
// A*D function (colscale): GB (_AxD__isgt_fp32)
// D*A function (rowscale): GB (_DxB__isgt_fp32)
// C+=B function (dense accum): GB (_Cdense_accumB__isgt_fp32)
// C+=b function (dense accum): GB (_Cdense_accumb__isgt_fp32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isgt_fp32)
// C=scalar+B GB (_bind1st__isgt_fp32)
// C=scalar+B' GB (_bind1st_tran__isgt_fp32)
// C=A+scalar GB (_bind2nd__isgt_fp32)
// C=A'+scalar GB (_bind2nd_tran__isgt_fp32)
// C type: float
// A type: float
// A pattern? 0
// B type: float
// B pattern? 0
// BinaryOp: cij = (aij > bij)
#define GB_ATYPE \
float
#define GB_BTYPE \
float
#define GB_CTYPE \
float
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
float aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
float bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
float t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x > y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISGT || GxB_NO_FP32 || GxB_NO_ISGT_FP32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__isgt_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__isgt_fp32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__isgt_fp32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type float
float bwork = (*((float *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__isgt_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *restrict Cx = (float *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__isgt_fp32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *restrict Cx = (float *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__isgt_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
float alpha_scalar ;
float beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((float *) alpha_scalar_in)) ;
beta_scalar = (*((float *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__isgt_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__isgt_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__isgt_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__isgt_fp32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__isgt_fp32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *Cx = (float *) Cx_output ;
float x = (*((float *) x_input)) ;
float *Bx = (float *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
float bij = GBX (Bx, p, false) ;
Cx [p] = (x > bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__isgt_fp32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
float *Cx = (float *) Cx_output ;
float *Ax = (float *) Ax_input ;
float y = (*((float *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
float aij = GBX (Ax, p, false) ;
Cx [p] = (aij > y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x > aij) ; \
}
GrB_Info GB (_bind1st_tran__isgt_fp32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
float
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float x = (*((const float *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
float
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij > y) ; \
}
GrB_Info GB (_bind2nd_tran__isgt_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float y = (*((const float *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
stopgp32.c | /* Copyright © 2018-2019 Jakub Wilk <jwilk@jwilk.net>
* SPDX-License-Identifier: MIT
*/
#include <arpa/inet.h>
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <openssl/bn.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#define PROGRAM_NAME "stopgp32"
#define DEFAULT_USER "<user@example.org>"
static const int rsa_bits = 1024;
static const uint32_t ts_min = 1136073600; /* 2006-01-01 */
static const uint32_t ts_max = 1609459200; /* 2021-01-01 */
static size_t bignum2mpi(const BIGNUM *n, unsigned char *to)
{
int nbits = BN_num_bits(n);
assert(nbits <= 0xFFFF);
to[0] = nbits >> 8;
to[1] = nbits & 0xFF;
size_t size = 2 + BN_bn2bin(n, to + 2);
return size;
}
struct openpgp_packet
{
unsigned char data[0x10000];
};
#if OPENSSL_VERSION_NUMBER < 0x10100000
static void RSA_get0_key(const RSA *rsa, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
{
if (n != NULL)
*n = rsa->n;
if (e != NULL)
*e = rsa->e;
if (d != NULL)
*d = rsa->d;
}
#endif
static void openpgp_from_rsa(struct openpgp_packet *pkt, const RSA *rsa)
{
unsigned char *data = pkt->data;
data[0] = 0x99;
data[3] = 0x04;
data[8] = 0x01;
const BIGNUM *n, *e;
RSA_get0_key(rsa, &n, &e, NULL);
size_t size = 9;
size += bignum2mpi(n, data + size);
size += bignum2mpi(e, data + size);
assert(size <= 0xFFFF);
uint16_t len = htons(size - 3);
memcpy(data + 1, &len, sizeof len);
}
static void openpgp_set_timestamp(struct openpgp_packet *pkt, uint32_t timestamp)
{
timestamp = htonl(timestamp);
memcpy(pkt->data + 4, ×tamp, sizeof timestamp);
}
static void openpgp_fingerprint(const struct openpgp_packet *pkt, unsigned char *sha)
{
size_t size = 3 + (pkt->data[1] << 8) + pkt->data[2];
SHA1(pkt->data, size, sha);
}
static void posix_error(const char *context)
{
int orig_errno = errno;
fprintf(stderr, "%s: ", PROGRAM_NAME);
errno = orig_errno;
perror(context);
exit(EXIT_FAILURE);
}
static void fprintsh(FILE *fp, const char *s)
{
bool escape = true;
for (const char *p = s; *p; p++) {
char c = *p;
if (c >= 'a' && c <= 'z')
escape = false;
else if (c >= 'A' && c <= 'Z')
escape = false;
else if (c >= '0' && c <= '9')
escape = false;
else if (c == '/' || c == '.' || c == ',' || c == '+' || c == '-' || c == '_')
escape = false;
else {
escape = true;
break;
}
}
if (!escape) {
fprintf(fp, "%s", s);
return;
}
fprintf(fp, "'");
for (const char *p = s; *p; p++)
if (*p == '\'')
fprintf(fp, "'\\''");
else
putc(*p, fp);
fprintf(fp, "'");
}
static void printsh(const char *s)
{
fprintsh(stdout, s);
}
struct cache_dir
{
char path[PATH_MAX];
const char *home_path;
DIR *handle;
int fd;
};
static void cache_dir_init(struct cache_dir *o, const char *path, bool real)
{
const char *home = getenv("HOME");
const char *cache_home = getenv("XDG_CACHE_HOME");
if (cache_home && cache_home[0] != '/')
cache_home = NULL;
o->home_path = NULL;
if (path != NULL) {
size_t size = strnlen(path, sizeof o->path);
if (size >= sizeof o->path) {
errno = ENAMETOOLONG;
posix_error(path);
}
strcpy(o->path, path);
} else if (cache_home) {
int size = snprintf(o->path, sizeof o->path, "%s/" PROGRAM_NAME, cache_home);
if (size < 0)
posix_error(NULL);
if ((size_t) size >= sizeof o->path) {
errno = ENAMETOOLONG;
posix_error("$XDG_CACHE_HOME/" PROGRAM_NAME);
}
} else {
if ((home == NULL) || (*home == '\0')) {
errno = ENOTDIR;
posix_error("$HOME");
}
int size = snprintf(o->path, sizeof o->path, "%s/.cache/" PROGRAM_NAME, home);
if (size < 0)
posix_error(NULL);
if ((size_t) size >= sizeof o->path) {
errno = ENAMETOOLONG;
posix_error("$HOME/.cache/" PROGRAM_NAME);
}
}
if ((home != NULL) && (*home != '\0')) {
size_t home_len = strlen(home);
if ((strncmp(o->path, home, home_len) == 0) && (o->path[home_len] == '/'))
o->home_path = o->path + home_len + 1;
}
if (!real) {
o->handle = NULL;
o->fd = -1;
return;
}
if (path == NULL) {
char *p = strrchr(o->path, '/');
assert(p != NULL);
*p = '\0';
int rc = mkdir(o->path, 0700);
if (rc < 0 && errno != EEXIST)
posix_error(o->path);
*p = '/';
}
int rc = mkdir(o->path, 0700);
if (rc < 0 && errno != EEXIST)
posix_error(o->path);
o->handle = opendir(o->path);
if (o->handle == NULL)
posix_error(o->path);
o->fd = dirfd(o->handle);
if (o->fd < 0)
posix_error(o->path);
rc = flock(o->fd, LOCK_EX | LOCK_NB);
if (rc < 0)
posix_error(o->path);
}
static void cache_dir_close(struct cache_dir *o)
{
o->path[0] = '\0';
o->home_path = NULL;
if (o->handle != NULL) {
int rc = closedir(o->handle);
if (rc < 0)
posix_error(o->path);
o->handle = NULL;
o->fd = -1;
}
}
static void openssl_error()
{
fprintf(stderr, "%s: ", PROGRAM_NAME);
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
static int genrsa_callback(int a, int b, BN_GENCB *cb)
{
(void) a; (void) b; (void) cb;
fprintf(stderr, ".");
return 1;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000
static BN_GENCB *BN_GENCB_new(void)
{
BN_GENCB *cb = malloc(sizeof (BN_GENCB));
if (cb == NULL)
perror(NULL);
return cb;
}
static void BN_GENCB_free(BN_GENCB *cb)
{
free(cb);
}
#endif
static void get_rsa_name(RSA *rsa, char *name)
{
static const char alphabet[] = "ybndrfg8ejkmcpqxot1uwisza345h769";
unsigned char sha[SHA_DIGEST_LENGTH];
struct openpgp_packet pkt;
openpgp_from_rsa(&pkt, rsa);
openpgp_set_timestamp(&pkt, 0);
openpgp_fingerprint(&pkt, sha);
uint64_t rsaid;
memcpy(&rsaid, sha, sizeof rsaid);
strcpy(name, "rsa-");
for (int i = 0; i < 8; i++) {
name[i + 4] = alphabet[rsaid % 32];
rsaid /= 32;
}
strcpy(name + 12, ".pem");
}
static void retrieve_key(struct openpgp_packet *pkt, struct cache_dir *cache_dir, char *name)
{
BIO *io = NULL;
RSA *rsa = NULL;
errno = 0;
struct dirent *ent;
while (true) {
errno = 0;
ent = readdir(cache_dir->handle);
if (ent == NULL)
break;
size_t len = strlen(ent->d_name);
if (len < 5)
continue;
if (strcmp(ent->d_name + (len - 4), ".pem") == 0)
break;
else
continue;
}
if (ent) {
strcpy(name, ent->d_name);
fprintf(stderr, "%s: retrieving RSA key ", PROGRAM_NAME);
fprintsh(stderr, name);
fprintf(stderr, " from cache\n");
int fd = openat(cache_dir->fd, name, O_RDONLY);
if (fd < 0)
posix_error(name);
FILE *fp = fdopen(fd, "r");
if (fp == NULL)
posix_error(name);
io = BIO_new_fp(fp, BIO_CLOSE);
if (io == NULL)
openssl_error();
EVP_PKEY *pkey = PEM_read_bio_PrivateKey(io, NULL, NULL, NULL);
if (pkey == NULL)
openssl_error();
rsa = EVP_PKEY_get1_RSA(pkey);
if (rsa == NULL)
openssl_error();
EVP_PKEY_free(pkey);
} else if (errno == 0) {
fprintf(stderr, "%s: generating new RSA key: ", PROGRAM_NAME);
rsa = RSA_new();
if (rsa == NULL)
openssl_error();
BIGNUM *exp = BN_new();
if (exp == NULL)
openssl_error();
if (!BN_set_word(exp, 0x10001))
openssl_error();
BN_GENCB *cb = BN_GENCB_new();
if (cb == NULL)
openssl_error();
BN_GENCB_set(cb, genrsa_callback, NULL);
if (!RSA_generate_key_ex(rsa, rsa_bits, exp, cb))
openssl_error();
BN_GENCB_free(cb);
BN_free(exp);
get_rsa_name(rsa, name);
fprintf(stderr, " ");
fprintsh(stderr, name);
fprintf(stderr, "\n");
int fd = openat(cache_dir->fd, name, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0)
posix_error(name);
FILE *fp = fdopen(fd, "w");
if (fp == NULL)
posix_error(name);
io = BIO_new_fp(fp, BIO_CLOSE);
if (io == NULL)
openssl_error();
if (!PEM_write_bio_RSAPrivateKey(io, rsa, NULL, NULL, 0, NULL, NULL))
openssl_error();
} else
posix_error(cache_dir->path);
assert(rsa != NULL);
openpgp_from_rsa(pkt, rsa);
RSA_free(rsa);
BIO_free_all(io);
}
static double xtime()
{
struct timespec ts;
int rc = clock_gettime(CLOCK_MONOTONIC, &ts);
if (rc < 0)
posix_error("clock_gettime()");
return ts.tv_sec + ts.tv_nsec * 1E-9;
}
struct progress
{
double time;
uint64_t count;
};
static void progress_start(struct progress *obj)
{
obj->time = xtime();
obj->count = 0;
fprintf(stderr, "%s: searching...", PROGRAM_NAME);
}
static void progress_update(struct progress *obj)
{
double t0 = obj->time;
double t = xtime();
if (t > t0) {
double v = obj->count / 1.0E6 / (t - t0);
fprintf(stderr, "\r\033[2K%s: searching... %.2f Mkeys/s", PROGRAM_NAME, v);
}
}
static void progress_stop(struct progress *obj)
{
fprintf(stderr, "\r\033[2K%s: searching...", PROGRAM_NAME);
double t0 = obj->time;
double t = xtime();
if (t > t0) {
double v = obj->count / 1.0E6 / (t - t0);
fprintf(stderr, " %.2f Mkeys/s", v);
}
fprintf(stderr, "\n");
}
static void show_usage(FILE *fp)
{
fprintf(fp, "Usage: %s [-u USERID] [-p] [-d DIR] [-j N] KEYID [KEYID...]\n", PROGRAM_NAME);
if (fp != stdout)
return;
char *cd_path = NULL;
struct cache_dir cd;
cache_dir_init(&cd, NULL, false);
if (cd.home_path != NULL) {
assert(cd.home_path >= cd.path + 2);
cd_path = cd.path + (cd.home_path - cd.path) - 2;
cd_path[0] = '~';
cd_path[1] = '/';
} else
cd_path = cd.path;
fprintf(fp,
"\n"
"Options:\n"
" -u USERID add this user ID (default: " DEFAULT_USER ")\n"
" -p only print pem2openpgp(1) commands; don't run them\n"
" -d DIR cache RSA keys in DIR (default: %s)\n"
" -j N use N threads (default: 1)\n"
" -j auto use as many threads as possible\n"
" -h, --help show this help message and exit\n",
cd_path
);
cache_dir_close(&cd);
}
struct keyidlist
{
size_t len;
size_t count;
uint32_t *keys;
char *found;
};
static struct keyidlist kil_new(size_t len)
{
struct keyidlist obj;
obj.len = obj.count = len;
obj.keys = calloc(len, sizeof (uint32_t));
if (obj.keys == NULL)
posix_error(NULL);
obj.found = calloc(len, 1);
if (obj.found == NULL)
posix_error(NULL);
return obj;
}
static bool kil_crude_check(const struct keyidlist *obj, uint32_t keyid)
{
for (size_t i = 0; i < obj->len; i++)
if (obj->keys[i] == keyid)
return true;
return false;
}
static bool kil_pop(struct keyidlist *obj, uint32_t keyid)
{
for (size_t i = 0; i < obj->len; i++)
if (obj->keys[i] == keyid && obj->found[i] == 0) {
obj->found[i] = 1;
obj->count--;
return true;
}
return false;
}
static void kil_free(struct keyidlist *obj)
{
obj->len = obj->count = 0;
free(obj->keys);
obj->keys = NULL;
free(obj->found);
obj->found = NULL;
}
static void pem2openpgp_print(uint32_t keyid, uint32_t ts, const char *user, const struct cache_dir *cache_dir, const char *pem_name)
{
printf("PEM2OPENPGP_TIMESTAMP=%" PRIu32 " pem2openpgp ", ts);
printsh(user);
printf(" < ");
if (cache_dir->home_path) {
printf("~/");
printsh(cache_dir->home_path);
} else
printsh(cache_dir->path);
printf("/");
printsh(pem_name);
printf(" > %08" PRIX32 ".pgp\n", keyid);
int rc;
if (ferror(stdout)) {
errno = EIO;
rc = EOF;
} else
rc = fflush(stdout);
if (rc == EOF)
posix_error("/dev/stdout");
}
static void xpipe(int pipefd[2])
{
int rc = pipe(pipefd);
if (rc < 0)
posix_error("pipe()");
for (int i = 0; i < 2; i++) {
int flags = fcntl(pipefd[i], F_GETFD);
if (flags < 0)
posix_error("fcntl(..., F_GETFD)");
flags |= FD_CLOEXEC;
int rc = fcntl(pipefd[i], F_SETFD, flags);
if (rc < 0)
posix_error("fcntl(..., F_SETFD, ...)");
}
}
static void serialize_error(int fd, const char *context)
{
int xerrno = errno;
ssize_t n = write(fd, &xerrno, sizeof xerrno);
if (n < 0)
return;
if ((size_t) n != sizeof xerrno)
return;
assert(context != NULL);
n = write(fd, context, strlen(context));
(void) n;
}
static int deserialize_error(int fd, char context[BUFSIZ])
{
int xerrno = 0;
ssize_t n = read(fd, &xerrno, sizeof xerrno);
if (n < 0)
posix_error("read()");
if ((n > 0) && (size_t) n != sizeof xerrno) {
errno = EIO;
posix_error("read()");
}
n = read(fd, context, BUFSIZ - 1);
if (n < 0)
posix_error("read()");
context[n] = '\0';
return xerrno;
}
static void pem2openpgp_exec(uint32_t keyid, uint32_t ts, const char *user, const struct cache_dir *cache_dir, const char *pem_name)
{
bool dry_run = (pem_name == NULL);
char * const argv[] = { "pem2openpgp", (char*) user, (char*) NULL };
int in_fd;
if (dry_run)
in_fd = open("/dev/null", O_RDONLY);
else
in_fd = openat(cache_dir->fd, pem_name, O_RDONLY);
if (in_fd < 0)
posix_error(pem_name);
char tmp_path[13], path[13];
int size = sprintf(tmp_path, "%08" PRIX32 ".tmp", keyid);
if (size < 0)
posix_error(NULL);
size = sprintf(path, "%08" PRIX32 ".pgp", keyid);
if (size < 0)
posix_error(NULL);
if (dry_run) {
strcpy(tmp_path, "/dev/null");
strcpy(path, "/dev/null");
}
int out_fd = open(tmp_path, O_WRONLY | O_TRUNC | O_CREAT, 0600);
if (out_fd < 0)
posix_error(path);
char ts_str[11];
size = sprintf(ts_str, "%" PRIu32, ts);
if (size < 0)
posix_error(NULL);
int rc = setenv("PEM2OPENPGP_TIMESTAMP", ts_str, true);
if (rc < 0)
posix_error("setenv()");
int pipefd[2];
xpipe(pipefd);
pid_t pid = fork();
if (pid < 0)
posix_error("fork()");
if (pid == 0) {
/* child: */
int fd = dup2(in_fd, STDIN_FILENO);
if (fd < 0) {
serialize_error(pipefd[1], "dup2()");
abort();
}
close(in_fd);
fd = dup2(out_fd, STDOUT_FILENO);
if (fd < 0) {
serialize_error(pipefd[1], "dup2()");
abort();
}
if (dry_run) {
fd = dup2(out_fd, STDERR_FILENO);
if (fd < 0) {
serialize_error(pipefd[1], "dup2()");
abort();
}
}
close(out_fd);
execvp(argv[0], argv);
serialize_error(pipefd[1], argv[0]);
abort();
}
/* parent: */
rc = unsetenv("PEM2OPENPGP_TIMESTAMP");
if (rc < 0)
posix_error("unsetenv()");
rc = close(in_fd);
if (rc < 0)
posix_error("close()");
rc = close(out_fd);
if (rc < 0)
posix_error("close()");
rc = close(pipefd[1]);
if (rc < 0)
posix_error("close()");
int wstatus;
pid = wait(&wstatus);
if (pid < 0)
posix_error("wait()");
char context[BUFSIZ];
int xerrno = deserialize_error(pipefd[0], context);
rc = close(pipefd[0]);
if (rc < 0)
posix_error("close");
if (dry_run && WIFEXITED(wstatus) && (WEXITSTATUS(wstatus) != 0))
return;
else if (!dry_run && WIFEXITED(wstatus) && (WEXITSTATUS(wstatus) == 0)) {
rc = rename(tmp_path, path);
if (rc < 0)
posix_error("rename");
} else if (xerrno == 0) {
if (WIFEXITED(wstatus)) {
int status = WEXITSTATUS(wstatus);
fprintf(stderr, "%s: %s exited with status %d\n", PROGRAM_NAME, argv[0], status);
} else if (WIFSIGNALED(wstatus)) {
int signo = WTERMSIG(wstatus);
fprintf(stderr, "%s: %s was terminated with signal %d (%s)\n", PROGRAM_NAME, argv[0], signo, strsignal(signo));
} else
assert("unexpected wait(2) status" == NULL);
exit(EXIT_FAILURE);
} else {
errno = xerrno;
posix_error(context);
}
}
int main(int argc, char **argv)
{
const char *user = DEFAULT_USER;
const char *cache_path = NULL;
int num_threads = 1;
bool only_print = false;
int opt;
while ((opt = getopt(argc, argv, "u:pd:j:h-:")) != -1)
switch (opt) {
case 'u':
user = optarg;
break;
case 'p':
only_print = true;
break;
case 'd':
cache_path = optarg;
break;
case 'j':
if (strcmp(optarg, "auto") == 0)
num_threads = -1;
else {
char *endarg;
long int l = strtol(optarg, &endarg, 10);
if (*endarg != '\0') {
errno = EINVAL;
posix_error("-j");
}
if (l <= 0 || l >= INT_MAX) {
errno = ERANGE;
posix_error("-j");
}
num_threads = (int) l;
}
break;
case 'h':
show_usage(stdout);
exit(EXIT_SUCCESS);
break;
case '-':
if (strcmp(optarg, "help") == 0) {
show_usage(stdout);
exit(EXIT_SUCCESS);
}
/* fall through */
default:
show_usage(stderr);
exit(EXIT_FAILURE);
}
if (optind >= argc) {
show_usage(stderr);
exit(EXIT_FAILURE);
}
argc -= optind;
argv += optind;
#ifdef _OPENMP
if (num_threads >= 1)
omp_set_num_threads(num_threads);
#else
if (num_threads != 1) {
errno = ENOSYS;
posix_error("-j");
}
#endif
struct keyidlist keyidlist = kil_new(argc);
for (size_t i = 0; i < keyidlist.len; i++) {
const char *arg = argv[i];
for (size_t j = 0; j < 8; j++) {
uint32_t d = arg[j];
if (d >= '0' && d <= '9') {
d -= '0';
} else if (d >= 'a' && d <= 'f') {
d -= 'a' - 10;
} else if (d >= 'A' && d <= 'F') {
d -= 'A' - 10;
} else if (d == '\0') {
fprintf(stderr, "%s: key ID too short: %s\n", PROGRAM_NAME, arg);
exit(EXIT_FAILURE);
} else {
fprintf(stderr, "%s: bad key ID: %s\n", PROGRAM_NAME, arg);
exit(EXIT_FAILURE);
}
keyidlist.keys[i] |= d << ((7 - j) * 4);
}
if (arg[8] != '\0') {
fprintf(stderr, "%s: key ID too long: %s\n", PROGRAM_NAME, arg);
exit(EXIT_FAILURE);
}
}
struct cache_dir cache_dir;
cache_dir_init(&cache_dir, cache_path, true);
if (!only_print)
pem2openpgp_exec(0, 0, "dummy", NULL, NULL);
struct openpgp_packet pkt;
while (true) {
char pem_name[NAME_MAX + 1];
retrieve_key(&pkt, &cache_dir, pem_name);
struct progress progress;
progress_start(&progress);
unsigned int lcount = 0;
#pragma omp parallel for firstprivate(pkt, lcount)
for (uint32_t ts = ts_min; ts < ts_max; ts++) {
lcount++;
unsigned char sha[SHA_DIGEST_LENGTH];
openpgp_set_timestamp(&pkt, ts);
openpgp_fingerprint(&pkt, sha);
uint32_t keyid;
memcpy(&keyid, sha + SHA_DIGEST_LENGTH - sizeof keyid, sizeof keyid);
keyid = ntohl(keyid);
if (kil_crude_check(&keyidlist, keyid))
#pragma omp critical
if (kil_pop(&keyidlist, keyid)) {
progress_stop(&progress);
if (only_print)
pem2openpgp_print(keyid, ts, user, &cache_dir, pem_name);
else {
fprintf(stderr, "%s: found %08" PRIX32 "\n", PROGRAM_NAME, keyid);
pem2openpgp_exec(keyid, ts, user, &cache_dir, pem_name);
}
if (keyidlist.count == 0) {
cache_dir_close(&cache_dir);
kil_free(&keyidlist);
exit(EXIT_SUCCESS);
}
/* FIXME: we should set lcount=0 in all threads */
progress_start(&progress);
}
if (lcount == 0xFFFF) {
/* FIXME: all threads may want to update progress at roughly the same time */
#pragma omp critical
{
progress.count += lcount;
progress_update(&progress);
}
lcount = 0;
}
}
progress_stop(&progress);
}
abort(); /* unreachable */
}
/* vim:set ts=4 sw=4 sts=4 et:*/
|
quantize.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
% Q Q U U A A NN N T I ZZ E %
% Q Q U U AAAAA N N N T I ZZZ EEEEE %
% Q QQ U U A A N NN T I ZZ E %
% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
% %
% %
% MagickCore Methods to Reduce the Number of Unique Colors in an Image %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Realism in computer graphics typically requires using 24 bits/pixel to
% generate an image. Yet many graphic display devices do not contain the
% amount of memory necessary to match the spatial and color resolution of
% the human eye. The Quantize methods takes a 24 bit image and reduces
% the number of colors so it can be displayed on raster device with less
% bits per pixel. In most instances, the quantized image closely
% resembles the original reference image.
%
% A reduction of colors in an image is also desirable for image
% transmission and real-time animation.
%
% QuantizeImage() takes a standard RGB or monochrome images and quantizes
% them down to some fixed number of colors.
%
% For purposes of color allocation, an image is a set of n pixels, where
% each pixel is a point in RGB space. RGB space is a 3-dimensional
% vector space, and each pixel, Pi, is defined by an ordered triple of
% red, green, and blue coordinates, (Ri, Gi, Bi).
%
% Each primary color component (red, green, or blue) represents an
% intensity which varies linearly from 0 to a maximum value, Cmax, which
% corresponds to full saturation of that color. Color allocation is
% defined over a domain consisting of the cube in RGB space with opposite
% vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
% 255.
%
% The algorithm maps this domain onto a tree in which each node
% represents a cube within that domain. In the following discussion
% these cubes are defined by the coordinate of two opposite vertices (vertex
% nearest the origin in RGB space and the vertex farthest from the origin).
%
% The tree's root node represents the entire domain, (0,0,0) through
% (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
% subdividing one node's cube into eight smaller cubes of equal size.
% This corresponds to bisecting the parent cube with planes passing
% through the midpoints of each edge.
%
% The basic algorithm operates in three phases: Classification,
% Reduction, and Assignment. Classification builds a color description
% tree for the image. Reduction collapses the tree until the number it
% represents, at most, the number of colors desired in the output image.
% Assignment defines the output image's color map and sets each pixel's
% color by restorage_class in the reduced tree. Our goal is to minimize
% the numerical discrepancies between the original colors and quantized
% colors (quantization error).
%
% Classification begins by initializing a color description tree of
% sufficient depth to represent each possible input color in a leaf.
% However, it is impractical to generate a fully-formed color description
% tree in the storage_class phase for realistic values of Cmax. If
% colors components in the input image are quantized to k-bit precision,
% so that Cmax= 2k-1, the tree would need k levels below the root node to
% allow representing each possible input color in a leaf. This becomes
% prohibitive because the tree's total number of nodes is 1 +
% sum(i=1, k, 8k).
%
% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
% Initializes data structures for nodes only as they are needed; (2)
% Chooses a maximum depth for the tree as a function of the desired
% number of colors in the output image (currently log2(colormap size)).
%
% For each pixel in the input image, storage_class scans downward from
% the root of the color description tree. At each level of the tree it
% identifies the single node which represents a cube in RGB space
% containing the pixel's color. It updates the following data for each
% such node:
%
% n1: Number of pixels whose color is contained in the RGB cube which
% this node represents;
%
% n2: Number of pixels whose color is not represented in a node at
% lower depth in the tree; initially, n2 = 0 for all nodes except
% leaves of the tree.
%
% Sr, Sg, Sb: Sums of the red, green, and blue component values for all
% pixels not classified at a lower depth. The combination of these sums
% and n2 will ultimately characterize the mean color of a set of
% pixels represented by this node.
%
% E: the distance squared in RGB space between each pixel contained
% within a node and the nodes' center. This represents the
% quantization error for a node.
%
% Reduction repeatedly prunes the tree until the number of nodes with n2
% > 0 is less than or equal to the maximum number of colors allowed in
% the output image. On any given iteration over the tree, it selects
% those nodes whose E count is minimal for pruning and merges their color
% statistics upward. It uses a pruning threshold, Ep, to govern node
% selection as follows:
%
% Ep = 0
% while number of nodes with (n2 > 0) > required maximum number of colors
% prune all nodes such that E <= Ep
% Set Ep to minimum E in remaining nodes
%
% This has the effect of minimizing any quantization error when merging
% two nodes together.
%
% When a node to be pruned has offspring, the pruning procedure invokes
% itself recursively in order to prune the tree from the leaves upward.
% n2, Sr, Sg, and Sb in a node being pruned are always added to the
% corresponding data in that node's parent. This retains the pruned
% node's color characteristics for later averaging.
%
% For each node, n2 pixels exist for which that node represents the
% smallest volume in RGB space containing those pixel's colors. When n2
% > 0 the node will uniquely define a color in the output image. At the
% beginning of reduction, n2 = 0 for all nodes except a the leaves of
% the tree which represent colors present in the input image.
%
% The other pixel count, n1, indicates the total number of colors within
% the cubic volume which the node represents. This includes n1 - n2
% pixels whose colors should be defined by nodes at a lower level in the
% tree.
%
% Assignment generates the output image from the pruned tree. The output
% image consists of two parts: (1) A color map, which is an array of
% color descriptions (RGB triples) for each color present in the output
% image; (2) A pixel array, which represents each pixel as an index
% into the color map array.
%
% First, the assignment phase makes one pass over the pruned color
% description tree to establish the image's color map. For each node
% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
% color of all pixels that classify no lower than this node. Each of
% these colors becomes an entry in the color map.
%
% Finally, the assignment phase reclassifies each pixel in the pruned
% tree to identify the deepest node containing the pixel's color. The
% pixel's value in the pixel array becomes the index of this node's mean
% color in the color map.
%
% This method is based on a similar algorithm written by Paul Raveling.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
/*
Define declarations.
*/
#if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
#define CacheShift 2
#else
#define CacheShift 3
#endif
#define ErrorQueueLength 16
#define MaxNodes 266817
#define MaxTreeDepth 8
#define NodesInAList 1920
/*
Typdef declarations.
*/
typedef struct _RealPixelInfo
{
double
red,
green,
blue,
alpha;
} RealPixelInfo;
typedef struct _NodeInfo
{
struct _NodeInfo
*parent,
*child[16];
MagickSizeType
number_unique;
RealPixelInfo
total_color;
double
quantize_error;
size_t
color_number,
id,
level;
} NodeInfo;
typedef struct _Nodes
{
NodeInfo
*nodes;
struct _Nodes
*next;
} Nodes;
typedef struct _CubeInfo
{
NodeInfo
*root;
size_t
colors,
maximum_colors;
ssize_t
transparent_index;
MagickSizeType
transparent_pixels;
RealPixelInfo
target;
double
distance,
pruning_threshold,
next_threshold;
size_t
nodes,
free_nodes,
color_number;
NodeInfo
*next_node;
Nodes
*node_queue;
MemoryInfo
*memory_info;
ssize_t
*cache;
RealPixelInfo
error[ErrorQueueLength];
double
weights[ErrorQueueLength];
QuantizeInfo
*quantize_info;
MagickBooleanType
associate_alpha;
ssize_t
x,
y;
size_t
depth;
MagickOffsetType
offset;
MagickSizeType
span;
} CubeInfo;
/*
Method prototypes.
*/
static CubeInfo
*GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
static NodeInfo
*GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
static MagickBooleanType
AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
DitherImage(Image *,CubeInfo *,ExceptionInfo *),
SetGrayscaleImage(Image *,ExceptionInfo *);
static size_t
DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
static void
ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
DestroyCubeInfo(CubeInfo *),
PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
ReduceImageColors(const Image *,CubeInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireQuantizeInfo() allocates the QuantizeInfo structure.
%
% The format of the AcquireQuantizeInfo method is:
%
% QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
{
QuantizeInfo
*quantize_info;
quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
if (quantize_info == (QuantizeInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetQuantizeInfo(quantize_info);
if (image_info != (ImageInfo *) NULL)
{
const char
*option;
quantize_info->dither_method=image_info->dither == MagickFalse ?
NoDitherMethod : RiemersmaDitherMethod;
option=GetImageOption(image_info,"dither");
if (option != (const char *) NULL)
quantize_info->dither_method=(DitherMethod) ParseCommandOption(
MagickDitherOptions,MagickFalse,option);
quantize_info->measure_error=image_info->verbose;
}
return(quantize_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A s s i g n I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AssignImageColors() generates the output image from the pruned tree. The
% output image consists of two parts: (1) A color map, which is an array
% of color descriptions (RGB triples) for each color present in the
% output image; (2) A pixel array, which represents each pixel as an
% index into the color map array.
%
% First, the assignment phase makes one pass over the pruned color
% description tree to establish the image's color map. For each node
% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
% color of all pixels that classify no lower than this node. Each of
% these colors becomes an entry in the color map.
%
% Finally, the assignment phase reclassifies each pixel in the pruned
% tree to identify the deepest node containing the pixel's color. The
% pixel's value in the pixel array becomes the index of this node's mean
% color in the color map.
%
% The format of the AssignImageColors() method is:
%
% MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
*/
static inline void AssociateAlphaPixel(const Image *image,
const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
{
double
alpha;
if ((cube_info->associate_alpha == MagickFalse) ||
(GetPixelAlpha(image,pixel)== OpaqueAlpha))
{
alpha_pixel->red=(double) GetPixelRed(image,pixel);
alpha_pixel->green=(double) GetPixelGreen(image,pixel);
alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
return;
}
alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
alpha_pixel->red=alpha*GetPixelRed(image,pixel);
alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
}
static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
const PixelInfo *pixel,RealPixelInfo *alpha_pixel)
{
double
alpha;
if ((cube_info->associate_alpha == MagickFalse) ||
(pixel->alpha == OpaqueAlpha))
{
alpha_pixel->red=(double) pixel->red;
alpha_pixel->green=(double) pixel->green;
alpha_pixel->blue=(double) pixel->blue;
alpha_pixel->alpha=(double) pixel->alpha;
return;
}
alpha=(double) (QuantumScale*pixel->alpha);
alpha_pixel->red=alpha*pixel->red;
alpha_pixel->green=alpha*pixel->green;
alpha_pixel->blue=alpha*pixel->blue;
alpha_pixel->alpha=(double) pixel->alpha;
}
static inline Quantum ClampPixel(const MagickRealType value)
{
if (value < 0.0f)
return(0);
if (value >= (MagickRealType) QuantumRange)
return((Quantum) QuantumRange);
#if !defined(MAGICKCORE_HDRI_SUPPORT)
return((Quantum) (value+0.5f));
#else
return(value);
#endif
}
static inline size_t ColorToNodeId(const CubeInfo *cube_info,
const RealPixelInfo *pixel,size_t index)
{
size_t
id;
id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
if (cube_info->associate_alpha != MagickFalse)
id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
return(id);
}
static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
ExceptionInfo *exception)
{
#define AssignImageTag "Assign/Image"
ssize_t
y;
/*
Allocate image colormap.
*/
if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
(cube_info->quantize_info->colorspace != CMYKColorspace))
(void) TransformImageColorspace((Image *) image,
cube_info->quantize_info->colorspace,exception);
else
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
image->colors=0;
cube_info->transparent_pixels=0;
cube_info->transparent_index=(-1);
(void) DefineImageColormap(image,cube_info,cube_info->root);
/*
Create a reduced color image.
*/
if (cube_info->quantize_info->dither_method != NoDitherMethod)
(void) DitherImage(image,cube_info,exception);
else
{
CacheView
*image_view;
MagickBooleanType
status;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CubeInfo
cube;
register Quantum
*restrict q;
register ssize_t
x;
ssize_t
count;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
cube=(*cube_info);
for (x=0; x < (ssize_t) image->columns; x+=count)
{
RealPixelInfo
pixel;
register const NodeInfo
*node_info;
register ssize_t
i;
size_t
id,
index;
/*
Identify the deepest node containing the pixel's color.
*/
for (count=1; (x+count) < (ssize_t) image->columns; count++)
{
PixelInfo
packet;
GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
break;
}
AssociateAlphaPixel(image,&cube,q,&pixel);
node_info=cube.root;
for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
{
id=ColorToNodeId(&cube,&pixel,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
cube.target=pixel;
cube.distance=(double) (4.0*(QuantumRange+1.0)*
(QuantumRange+1.0)+1.0);
ClosestColor(image,&cube,node_info->parent);
index=cube.color_number;
for (i=0; i < (ssize_t) count; i++)
{
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) index,q);
if (cube.quantize_info->measure_error == MagickFalse)
{
SetPixelRed(image,ClampToQuantum(
image->colormap[index].red),q);
SetPixelGreen(image,ClampToQuantum(
image->colormap[index].green),q);
SetPixelBlue(image,ClampToQuantum(
image->colormap[index].blue),q);
if (cube.associate_alpha != MagickFalse)
SetPixelAlpha(image,ClampToQuantum(
image->colormap[index].alpha),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_AssignImageColors)
#endif
proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
}
if (cube_info->quantize_info->measure_error != MagickFalse)
(void) GetImageQuantizeError(image,exception);
if ((cube_info->quantize_info->number_colors == 2) &&
(cube_info->quantize_info->colorspace == GRAYColorspace))
{
double
intensity;
register PixelInfo
*restrict q;
register ssize_t
i;
/*
Monochrome image.
*/
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
QuantumRange);
q->red=intensity;
q->green=intensity;
q->blue=intensity;
q++;
}
}
(void) SyncImage(image,exception);
if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
(cube_info->quantize_info->colorspace != CMYKColorspace))
(void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l a s s i f y I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClassifyImageColors() begins by initializing a color description tree
% of sufficient depth to represent each possible input color in a leaf.
% However, it is impractical to generate a fully-formed color
% description tree in the storage_class phase for realistic values of
% Cmax. If colors components in the input image are quantized to k-bit
% precision, so that Cmax= 2k-1, the tree would need k levels below the
% root node to allow representing each possible input color in a leaf.
% This becomes prohibitive because the tree's total number of nodes is
% 1 + sum(i=1,k,8k).
%
% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
% Initializes data structures for nodes only as they are needed; (2)
% Chooses a maximum depth for the tree as a function of the desired
% number of colors in the output image (currently log2(colormap size)).
%
% For each pixel in the input image, storage_class scans downward from
% the root of the color description tree. At each level of the tree it
% identifies the single node which represents a cube in RGB space
% containing It updates the following data for each such node:
%
% n1 : Number of pixels whose color is contained in the RGB cube
% which this node represents;
%
% n2 : Number of pixels whose color is not represented in a node at
% lower depth in the tree; initially, n2 = 0 for all nodes except
% leaves of the tree.
%
% Sr, Sg, Sb : Sums of the red, green, and blue component values for
% all pixels not classified at a lower depth. The combination of
% these sums and n2 will ultimately characterize the mean color of a
% set of pixels represented by this node.
%
% E: the distance squared in RGB space between each pixel contained
% within a node and the nodes' center. This represents the quantization
% error for a node.
%
% The format of the ClassifyImageColors() method is:
%
% MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
% const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o image: the image.
%
*/
static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
{
MagickBooleanType
associate_alpha;
associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
MagickFalse;
if ((cube_info->quantize_info->number_colors == 2) &&
(cube_info->quantize_info->colorspace == GRAYColorspace))
associate_alpha=MagickFalse;
cube_info->associate_alpha=associate_alpha;
}
static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
const Image *image,ExceptionInfo *exception)
{
#define ClassifyImageTag "Classify/Image"
CacheView
*image_view;
MagickBooleanType
proceed;
double
bisect;
NodeInfo
*node_info;
RealPixelInfo
error,
mid,
midpoint,
pixel;
size_t
count,
id,
index,
level;
ssize_t
y;
/*
Classify the first cube_info->maximum_colors colors to a tree depth of 8.
*/
SetAssociatedAlpha(image,cube_info);
if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
(cube_info->quantize_info->colorspace != CMYKColorspace))
(void) TransformImageColorspace((Image *) image,
cube_info->quantize_info->colorspace,exception);
else
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
midpoint.red=(double) QuantumRange/2.0;
midpoint.green=(double) QuantumRange/2.0;
midpoint.blue=(double) QuantumRange/2.0;
midpoint.alpha=(double) QuantumRange/2.0;
error.alpha=0.0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (cube_info->nodes > MaxNodes)
{
/*
Prune one level if the color tree is too large.
*/
PruneLevel(image,cube_info,cube_info->root);
cube_info->depth--;
}
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
{
/*
Start at the root and descend the color cube tree.
*/
for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
{
PixelInfo
packet;
GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
break;
}
AssociateAlphaPixel(image,cube_info,p,&pixel);
index=MaxTreeDepth-1;
bisect=((double) QuantumRange+1.0)/2.0;
mid=midpoint;
node_info=cube_info->root;
for (level=1; level <= MaxTreeDepth; level++)
{
double
distance;
bisect*=0.5;
id=ColorToNodeId(cube_info,&pixel,index);
mid.red+=(id & 1) != 0 ? bisect : -bisect;
mid.green+=(id & 2) != 0 ? bisect : -bisect;
mid.blue+=(id & 4) != 0 ? bisect : -bisect;
mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
if (node_info->child[id] == (NodeInfo *) NULL)
{
/*
Set colors of new node to contain pixel.
*/
node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
if (node_info->child[id] == (NodeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
continue;
}
if (level == MaxTreeDepth)
cube_info->colors++;
}
/*
Approximate the quantization error represented by this node.
*/
node_info=node_info->child[id];
error.red=QuantumScale*(pixel.red-mid.red);
error.green=QuantumScale*(pixel.green-mid.green);
error.blue=QuantumScale*(pixel.blue-mid.blue);
if (cube_info->associate_alpha != MagickFalse)
error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
distance=(double) (error.red*error.red+error.green*error.green+
error.blue*error.blue+error.alpha*error.alpha);
if (IsNaN(distance) != MagickFalse)
distance=0.0;
node_info->quantize_error+=count*sqrt(distance);
cube_info->root->quantize_error+=node_info->quantize_error;
index--;
}
/*
Sum RGB for this leaf for later derivation of the mean cube color.
*/
node_info->number_unique+=count;
node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
if (cube_info->associate_alpha != MagickFalse)
node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
pixel.alpha);
p+=count*GetPixelChannels(image);
}
if (cube_info->colors > cube_info->maximum_colors)
{
PruneToCubeDepth(image,cube_info,cube_info->root);
break;
}
proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
break;
}
for (y++; y < (ssize_t) image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (cube_info->nodes > MaxNodes)
{
/*
Prune one level if the color tree is too large.
*/
PruneLevel(image,cube_info,cube_info->root);
cube_info->depth--;
}
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
{
/*
Start at the root and descend the color cube tree.
*/
for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
{
PixelInfo
packet;
GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
break;
}
AssociateAlphaPixel(image,cube_info,p,&pixel);
index=MaxTreeDepth-1;
bisect=((double) QuantumRange+1.0)/2.0;
mid=midpoint;
node_info=cube_info->root;
for (level=1; level <= cube_info->depth; level++)
{
double
distance;
bisect*=0.5;
id=ColorToNodeId(cube_info,&pixel,index);
mid.red+=(id & 1) != 0 ? bisect : -bisect;
mid.green+=(id & 2) != 0 ? bisect : -bisect;
mid.blue+=(id & 4) != 0 ? bisect : -bisect;
mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
if (node_info->child[id] == (NodeInfo *) NULL)
{
/*
Set colors of new node to contain pixel.
*/
node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
if (node_info->child[id] == (NodeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","%s",
image->filename);
continue;
}
if (level == cube_info->depth)
cube_info->colors++;
}
/*
Approximate the quantization error represented by this node.
*/
node_info=node_info->child[id];
error.red=QuantumScale*(pixel.red-mid.red);
error.green=QuantumScale*(pixel.green-mid.green);
error.blue=QuantumScale*(pixel.blue-mid.blue);
if (cube_info->associate_alpha != MagickFalse)
error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
distance=(double) (error.red*error.red+error.green*error.green+
error.blue*error.blue+error.alpha*error.alpha);
if (IsNaN(distance) != MagickFalse)
distance=0.0;
node_info->quantize_error+=count*sqrt(distance);
cube_info->root->quantize_error+=node_info->quantize_error;
index--;
}
/*
Sum RGB for this leaf for later derivation of the mean cube color.
*/
node_info->number_unique+=count;
node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
if (cube_info->associate_alpha != MagickFalse)
node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
pixel.alpha);
p+=count*GetPixelChannels(image);
}
proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
(cube_info->quantize_info->colorspace != CMYKColorspace))
(void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
% or if quantize info is NULL, a new one.
%
% The format of the CloneQuantizeInfo method is:
%
% QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
% quantize info, or if image info is NULL a new one.
%
% o quantize_info: a structure of type info.
%
*/
MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
{
QuantizeInfo
*clone_info;
clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
if (clone_info == (QuantizeInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
GetQuantizeInfo(clone_info);
if (quantize_info == (QuantizeInfo *) NULL)
return(clone_info);
clone_info->number_colors=quantize_info->number_colors;
clone_info->tree_depth=quantize_info->tree_depth;
clone_info->dither_method=quantize_info->dither_method;
clone_info->colorspace=quantize_info->colorspace;
clone_info->measure_error=quantize_info->measure_error;
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o s e s t C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClosestColor() traverses the color cube tree at a particular node and
% determines which colormap entry best represents the input color.
%
% The format of the ClosestColor method is:
%
% void ClosestColor(const Image *image,CubeInfo *cube_info,
% const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: the address of a structure of type NodeInfo which points to a
% node in the color cube tree that is to be pruned.
%
*/
static void ClosestColor(const Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
ClosestColor(image,cube_info,node_info->child[i]);
if (node_info->number_unique != 0)
{
double
pixel;
register double
alpha,
beta,
distance;
register PixelInfo
*restrict p;
register RealPixelInfo
*restrict q;
/*
Determine if this color is "closest".
*/
p=image->colormap+node_info->color_number;
q=(&cube_info->target);
alpha=1.0;
beta=1.0;
if (cube_info->associate_alpha != MagickFalse)
{
alpha=(double) (QuantumScale*p->alpha);
beta=(double) (QuantumScale*q->alpha);
}
pixel=alpha*p->red-beta*q->red;
distance=pixel*pixel;
if (distance <= cube_info->distance)
{
pixel=alpha*p->green-beta*q->green;
distance+=pixel*pixel;
if (distance <= cube_info->distance)
{
pixel=alpha*p->blue-beta*q->blue;
distance+=pixel*pixel;
if (distance <= cube_info->distance)
{
pixel=alpha-beta;
distance+=pixel*pixel;
if (distance <= cube_info->distance)
{
cube_info->distance=distance;
cube_info->color_number=node_info->color_number;
}
}
}
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p r e s s I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompressImageColormap() compresses an image colormap by removing any
% duplicate or unused color entries.
%
% The format of the CompressImageColormap method is:
%
% MagickBooleanType CompressImageColormap(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType CompressImageColormap(Image *image,
ExceptionInfo *exception)
{
QuantizeInfo
quantize_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsPaletteImage(image,exception) == MagickFalse)
return(MagickFalse);
GetQuantizeInfo(&quantize_info);
quantize_info.number_colors=image->colors;
quantize_info.tree_depth=MaxTreeDepth;
return(QuantizeImage(&quantize_info,image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f i n e I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineImageColormap() traverses the color cube tree and notes each colormap
% entry. A colormap entry is any node in the color cube tree where the
% of unique colors is not zero. DefineImageColormap() returns the number of
% colors in the image colormap.
%
% The format of the DefineImageColormap method is:
%
% size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
% NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: the address of a structure of type NodeInfo which points to a
% node in the color cube tree that is to be pruned.
%
*/
static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
(void) DefineImageColormap(image,cube_info,node_info->child[i]);
if (node_info->number_unique != 0)
{
register double
alpha;
register PixelInfo
*restrict q;
/*
Colormap entry is defined by the mean color in this cube.
*/
q=image->colormap+image->colors;
alpha=(double) ((MagickOffsetType) node_info->number_unique);
alpha=PerceptibleReciprocal(alpha);
if (cube_info->associate_alpha == MagickFalse)
{
q->red=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.red);
q->green=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.green);
q->blue=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.blue);
q->alpha=(double) OpaqueAlpha;
}
else
{
double
opacity;
opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
q->alpha=(double) ClampToQuantum((opacity));
if (q->alpha == OpaqueAlpha)
{
q->red=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.red);
q->green=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.green);
q->blue=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.blue);
}
else
{
double
gamma;
gamma=(double) (QuantumScale*q->alpha);
gamma=PerceptibleReciprocal(gamma);
q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
node_info->total_color.red);
q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
node_info->total_color.green);
q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
node_info->total_color.blue);
if (node_info->number_unique > cube_info->transparent_pixels)
{
cube_info->transparent_pixels=node_info->number_unique;
cube_info->transparent_index=(ssize_t) image->colors;
}
}
}
node_info->color_number=image->colors++;
}
return(image->colors);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y C u b e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyCubeInfo() deallocates memory associated with an image.
%
% The format of the DestroyCubeInfo method is:
%
% DestroyCubeInfo(CubeInfo *cube_info)
%
% A description of each parameter follows:
%
% o cube_info: the address of a structure of type CubeInfo.
%
*/
static void DestroyCubeInfo(CubeInfo *cube_info)
{
register Nodes
*nodes;
/*
Release color cube tree storage.
*/
do
{
nodes=cube_info->node_queue->next;
cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
cube_info->node_queue->nodes);
cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
cube_info->node_queue);
cube_info->node_queue=nodes;
} while (cube_info->node_queue != (Nodes *) NULL);
if (cube_info->memory_info != (MemoryInfo *) NULL)
cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
% structure.
%
% The format of the DestroyQuantizeInfo method is:
%
% QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
*/
MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(quantize_info != (QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickSignature);
quantize_info->signature=(~MagickSignature);
quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
return(quantize_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DitherImage() distributes the difference between an original image and
% the corresponding color reduced algorithm to neighboring pixels using
% serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
% MagickTrue if the image is dithered otherwise MagickFalse.
%
% The format of the DitherImage method is:
%
% MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
{
register ssize_t
i;
assert(pixels != (RealPixelInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (RealPixelInfo *) NULL)
pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
return(pixels);
}
static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
{
RealPixelInfo
**pixels;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (RealPixelInfo **) NULL)
return((RealPixelInfo **) NULL);
(void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
if (pixels[i] == (RealPixelInfo *) NULL)
return(DestroyPixelThreadSet(pixels));
}
return(pixels);
}
static inline ssize_t CacheOffset(CubeInfo *cube_info,
const RealPixelInfo *pixel)
{
#define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
#define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
#define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
#define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
ssize_t
offset;
offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
if (cube_info->associate_alpha != MagickFalse)
offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
return(offset);
}
static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
MagickBooleanType
status;
RealPixelInfo
**pixels;
ssize_t
y;
/*
Distribute quantization error using Floyd-Steinberg.
*/
pixels=AcquirePixelThreadSet(image->columns);
if (pixels == (RealPixelInfo **) NULL)
return(MagickFalse);
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
CubeInfo
cube;
RealPixelInfo
*current,
*previous;
register Quantum
*restrict q;
register ssize_t
x;
size_t
index;
ssize_t
v;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
q+=(y & 0x01)*image->columns*GetPixelChannels(image);
cube=(*cube_info);
current=pixels[id]+(y & 0x01)*image->columns;
previous=pixels[id]+((y+1) & 0x01)*image->columns;
v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
for (x=0; x < (ssize_t) image->columns; x++)
{
RealPixelInfo
color,
pixel;
register ssize_t
i;
ssize_t
u;
q-=(y & 0x01)*GetPixelChannels(image);
u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
AssociateAlphaPixel(image,&cube,q,&pixel);
if (x > 0)
{
pixel.red+=7*current[u-v].red/16;
pixel.green+=7*current[u-v].green/16;
pixel.blue+=7*current[u-v].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=7*current[u-v].alpha/16;
}
if (y > 0)
{
if (x < (ssize_t) (image->columns-1))
{
pixel.red+=previous[u+v].red/16;
pixel.green+=previous[u+v].green/16;
pixel.blue+=previous[u+v].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=previous[u+v].alpha/16;
}
pixel.red+=5*previous[u].red/16;
pixel.green+=5*previous[u].green/16;
pixel.blue+=5*previous[u].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=5*previous[u].alpha/16;
if (x > 0)
{
pixel.red+=3*previous[u-v].red/16;
pixel.green+=3*previous[u-v].green/16;
pixel.blue+=3*previous[u-v].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=3*previous[u-v].alpha/16;
}
}
pixel.red=(double) ClampPixel(pixel.red);
pixel.green=(double) ClampPixel(pixel.green);
pixel.blue=(double) ClampPixel(pixel.blue);
if (cube.associate_alpha != MagickFalse)
pixel.alpha=(double) ClampPixel(pixel.alpha);
i=CacheOffset(&cube,&pixel);
if (cube.cache[i] < 0)
{
register NodeInfo
*node_info;
register size_t
id;
/*
Identify the deepest node containing the pixel's color.
*/
node_info=cube.root;
for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
{
id=ColorToNodeId(&cube,&pixel,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
cube.target=pixel;
cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1.0);
ClosestColor(image,&cube,node_info->parent);
cube.cache[i]=(ssize_t) cube.color_number;
}
/*
Assign pixel to closest colormap entry.
*/
index=(size_t) cube.cache[i];
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) index,q);
if (cube.quantize_info->measure_error == MagickFalse)
{
SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
if (cube.associate_alpha != MagickFalse)
SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
/*
Store the error.
*/
AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
current[u].red=pixel.red-color.red;
current[u].green=pixel.green-color.green;
current[u].blue=pixel.blue-color.blue;
if (cube.associate_alpha != MagickFalse)
current[u].alpha=pixel.alpha-color.alpha;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
q+=((y+1) & 0x01)*GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
pixels=DestroyPixelThreadSet(pixels);
return(MagickTrue);
}
static MagickBooleanType
RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
ExceptionInfo *exception);
static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
const size_t level,const unsigned int direction,ExceptionInfo *exception)
{
if (level == 1)
switch (direction)
{
case WestGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
break;
}
case EastGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
break;
}
case NorthGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
break;
}
case SouthGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
break;
}
default:
break;
}
else
switch (direction)
{
case WestGravity:
{
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
break;
}
case EastGravity:
{
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
break;
}
case NorthGravity:
{
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
break;
}
case SouthGravity:
{
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
break;
}
default:
break;
}
}
static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
MagickBooleanType
proceed;
RealPixelInfo
color,
pixel;
register CubeInfo
*p;
size_t
index;
p=cube_info;
if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
(p->y >= 0) && (p->y < (ssize_t) image->rows))
{
register Quantum
*restrict q;
register ssize_t
i;
/*
Distribute error.
*/
q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
AssociateAlphaPixel(image,cube_info,q,&pixel);
for (i=0; i < ErrorQueueLength; i++)
{
pixel.red+=p->weights[i]*p->error[i].red;
pixel.green+=p->weights[i]*p->error[i].green;
pixel.blue+=p->weights[i]*p->error[i].blue;
if (cube_info->associate_alpha != MagickFalse)
pixel.alpha+=p->weights[i]*p->error[i].alpha;
}
pixel.red=(double) ClampPixel(pixel.red);
pixel.green=(double) ClampPixel(pixel.green);
pixel.blue=(double) ClampPixel(pixel.blue);
if (cube_info->associate_alpha != MagickFalse)
pixel.alpha=(double) ClampPixel(pixel.alpha);
i=CacheOffset(cube_info,&pixel);
if (p->cache[i] < 0)
{
register NodeInfo
*node_info;
register size_t
id;
/*
Identify the deepest node containing the pixel's color.
*/
node_info=p->root;
for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
{
id=ColorToNodeId(cube_info,&pixel,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
p->target=pixel;
p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
QuantumRange+1.0)+1.0);
ClosestColor(image,p,node_info->parent);
p->cache[i]=(ssize_t) p->color_number;
}
/*
Assign pixel to closest colormap entry.
*/
index=(size_t) p->cache[i];
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) index,q);
if (cube_info->quantize_info->measure_error == MagickFalse)
{
SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
if (cube_info->associate_alpha != MagickFalse)
SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
return(MagickFalse);
/*
Propagate the error as the last entry of the error queue.
*/
(void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
sizeof(p->error[0]));
AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
p->error[ErrorQueueLength-1].red=pixel.red-color.red;
p->error[ErrorQueueLength-1].green=pixel.green-color.green;
p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
if (cube_info->associate_alpha != MagickFalse)
p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
if (proceed == MagickFalse)
return(MagickFalse);
p->offset++;
}
switch (direction)
{
case WestGravity: p->x--; break;
case EastGravity: p->x++; break;
case NorthGravity: p->y--; break;
case SouthGravity: p->y++; break;
}
return(MagickTrue);
}
static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
{
if (x > y)
return(x);
return(y);
}
static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
{
if (x < y)
return(x);
return(y);
}
static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
register ssize_t
i;
size_t
depth;
if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
return(FloydSteinbergDither(image,cube_info,exception));
/*
Distribute quantization error along a Hilbert curve.
*/
(void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
sizeof(*cube_info->error));
cube_info->x=0;
cube_info->y=0;
i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
for (depth=1; i != 0; depth++)
i>>=1;
if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
depth++;
cube_info->offset=0;
cube_info->span=(MagickSizeType) image->columns*image->rows;
image_view=AcquireAuthenticCacheView(image,exception);
if (depth > 1)
Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t C u b e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetCubeInfo() initialize the Cube data structure.
%
% The format of the GetCubeInfo method is:
%
% CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
% const size_t depth,const size_t maximum_colors)
%
% A description of each parameter follows.
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o depth: Normally, this integer value is zero or one. A zero or
% one tells Quantize to choose a optimal tree depth of Log4(number_colors).
% A tree of this depth generally allows the best representation of the
% reference image with the least amount of memory and the fastest
% computational speed. In some cases, such as an image with low color
% dispersion (a few number of colors), a value other than
% Log4(number_colors) is required. To expand the color tree completely,
% use a value of 8.
%
% o maximum_colors: maximum colors.
%
*/
static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
const size_t depth,const size_t maximum_colors)
{
CubeInfo
*cube_info;
double
sum,
weight;
register ssize_t
i;
size_t
length;
/*
Initialize tree to describe color cube_info.
*/
cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
if (cube_info == (CubeInfo *) NULL)
return((CubeInfo *) NULL);
(void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
cube_info->depth=depth;
if (cube_info->depth > MaxTreeDepth)
cube_info->depth=MaxTreeDepth;
if (cube_info->depth < 2)
cube_info->depth=2;
cube_info->maximum_colors=maximum_colors;
/*
Initialize root node.
*/
cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
if (cube_info->root == (NodeInfo *) NULL)
return((CubeInfo *) NULL);
cube_info->root->parent=cube_info->root;
cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
if (cube_info->quantize_info->dither_method == NoDitherMethod)
return(cube_info);
/*
Initialize dither resources.
*/
length=(size_t) (1UL << (4*(8-CacheShift)));
cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
if (cube_info->memory_info == (MemoryInfo *) NULL)
return((CubeInfo *) NULL);
cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
/*
Initialize color cache.
*/
for (i=0; i < (ssize_t) length; i++)
cube_info->cache[i]=(-1);
/*
Distribute weights along a curve of exponential decay.
*/
weight=1.0;
for (i=0; i < ErrorQueueLength; i++)
{
cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
}
/*
Normalize the weighting factors.
*/
weight=0.0;
for (i=0; i < ErrorQueueLength; i++)
weight+=cube_info->weights[i];
sum=0.0;
for (i=0; i < ErrorQueueLength; i++)
{
cube_info->weights[i]/=weight;
sum+=cube_info->weights[i];
}
cube_info->weights[0]+=1.0-sum;
return(cube_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t N o d e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNodeInfo() allocates memory for a new node in the color cube tree and
% presets all fields to zero.
%
% The format of the GetNodeInfo method is:
%
% NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
% const size_t level,NodeInfo *parent)
%
% A description of each parameter follows.
%
% o node: The GetNodeInfo method returns a pointer to a queue of nodes.
%
% o id: Specifies the child number of the node.
%
% o level: Specifies the level in the storage_class the node resides.
%
*/
static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
const size_t level,NodeInfo *parent)
{
NodeInfo
*node_info;
if (cube_info->free_nodes == 0)
{
Nodes
*nodes;
/*
Allocate a new queue of nodes.
*/
nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
if (nodes == (Nodes *) NULL)
return((NodeInfo *) NULL);
nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
sizeof(*nodes->nodes));
if (nodes->nodes == (NodeInfo *) NULL)
return((NodeInfo *) NULL);
nodes->next=cube_info->node_queue;
cube_info->node_queue=nodes;
cube_info->next_node=nodes->nodes;
cube_info->free_nodes=NodesInAList;
}
cube_info->nodes++;
cube_info->free_nodes--;
node_info=cube_info->next_node++;
(void) ResetMagickMemory(node_info,0,sizeof(*node_info));
node_info->parent=parent;
node_info->id=id;
node_info->level=level;
return(node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e Q u a n t i z e E r r o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageQuantizeError() measures the difference between the original
% and quantized images. This difference is the total quantization error.
% The error is computed by summing over all pixels in an image the distance
% squared in RGB space between each reference pixel value and its quantized
% value. These values are computed:
%
% o mean_error_per_pixel: This value is the mean error for any single
% pixel in the image.
%
% o normalized_mean_square_error: This value is the normalized mean
% quantization error for any single pixel in the image. This distance
% measure is normalized to a range between 0 and 1. It is independent
% of the range of red, green, and blue values in the image.
%
% o normalized_maximum_square_error: Thsi value is the normalized
% maximum quantization error for any single pixel in the image. This
% distance measure is normalized to a range between 0 and 1. It is
% independent of the range of red, green, and blue values in your image.
%
% The format of the GetImageQuantizeError method is:
%
% MagickBooleanType GetImageQuantizeError(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
double
alpha,
area,
beta,
distance,
maximum_error,
mean_error,
mean_error_per_pixel;
size_t
index;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
(void) ResetMagickMemory(&image->error,0,sizeof(image->error));
if (image->storage_class == DirectClass)
return(MagickTrue);
alpha=1.0;
beta=1.0;
area=3.0*image->columns*image->rows;
maximum_error=0.0;
mean_error_per_pixel=0.0;
mean_error=0.0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=1UL*GetPixelIndex(image,p);
if (image->alpha_trait == BlendPixelTrait)
{
alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
beta=(double) (QuantumScale*image->colormap[index].alpha);
}
distance=fabs(alpha*GetPixelRed(image,p)-beta*
image->colormap[index].red);
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
distance=fabs(alpha*GetPixelGreen(image,p)-beta*
image->colormap[index].green);
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
distance=fabs(alpha*GetPixelBlue(image,p)-beta*
image->colormap[index].blue);
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
mean_error/area;
image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantizeInfo() initializes the QuantizeInfo structure.
%
% The format of the GetQuantizeInfo method is:
%
% GetQuantizeInfo(QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to a QuantizeInfo structure.
%
*/
MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(quantize_info != (QuantizeInfo *) NULL);
(void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
quantize_info->number_colors=256;
quantize_info->dither_method=RiemersmaDitherMethod;
quantize_info->colorspace=UndefinedColorspace;
quantize_info->measure_error=MagickFalse;
quantize_info->signature=MagickSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o s t e r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PosterizeImage() reduces the image to a limited number of colors for a
% "poster" effect.
%
% The format of the PosterizeImage method is:
%
% MagickBooleanType PosterizeImage(Image *image,const size_t levels,
% const DitherMethod dither_method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Specifies a pointer to an Image structure.
%
% o levels: Number of color levels allowed in each channel. Very low values
% (2, 3, or 4) have the most visible effect.
%
% o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
% RiemersmaDitherMethod, FloydSteinbergDitherMethod.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
const DitherMethod dither_method,ExceptionInfo *exception)
{
#define PosterizeImageTag "Posterize/Image"
#define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
QuantizeInfo
*quantize_info;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,1,1)
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Posterize colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double)
PosterizePixel(image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double)
PosterizePixel(image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double)
PosterizePixel(image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double)
PosterizePixel(image->colormap[i].alpha);
}
/*
Posterize image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait == BlendPixelTrait))
SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),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_PosterizeImage)
#endif
proceed=SetImageProgress(image,PosterizeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
levels,MaxColormapSize+1);
quantize_info->dither_method=dither_method;
quantize_info->tree_depth=MaxTreeDepth;
status=QuantizeImage(quantize_info,image,exception);
quantize_info=DestroyQuantizeInfo(quantize_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e C h i l d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneChild() deletes the given node and merges its statistics into its
% parent.
%
% The format of the PruneSubtree method is:
%
% PruneChild(const Image *image,CubeInfo *cube_info,
% const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void PruneChild(const Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
NodeInfo
*parent;
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
PruneChild(image,cube_info,node_info->child[i]);
/*
Merge color statistics into parent.
*/
parent=node_info->parent;
parent->number_unique+=node_info->number_unique;
parent->total_color.red+=node_info->total_color.red;
parent->total_color.green+=node_info->total_color.green;
parent->total_color.blue+=node_info->total_color.blue;
parent->total_color.alpha+=node_info->total_color.alpha;
parent->child[node_info->id]=(NodeInfo *) NULL;
cube_info->nodes--;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e L e v e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneLevel() deletes all nodes at the bottom level of the color tree merging
% their color statistics into their parent node.
%
% The format of the PruneLevel method is:
%
% PruneLevel(const Image *image,CubeInfo *cube_info,
% const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void PruneLevel(const Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
PruneLevel(image,cube_info,node_info->child[i]);
if (node_info->level == cube_info->depth)
PruneChild(image,cube_info,node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e T o C u b e D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneToCubeDepth() deletes any nodes at a depth greater than
% cube_info->depth while merging their color statistics into their parent
% node.
%
% The format of the PruneToCubeDepth method is:
%
% PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
% const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
PruneToCubeDepth(image,cube_info,node_info->child[i]);
if (node_info->level > cube_info->depth)
PruneChild(image,cube_info,node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u a n t i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeImage() analyzes the colors within a reference image and chooses a
% fixed number of colors to represent the image. The goal of the algorithm
% is to minimize the color difference between the input and output image while
% minimizing the processing time.
%
% The format of the QuantizeImage method is:
%
% MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType DirectToColormapImage(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
register ssize_t
i;
size_t
number_colors;
ssize_t
y;
status=MagickTrue;
number_colors=(size_t) (image->columns*image->rows);
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->colors != number_colors)
return(MagickFalse);
i=0;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
proceed;
register Quantum
*restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
image->colormap[i].red=(double) GetPixelRed(image,q);
image->colormap[i].green=(double) GetPixelGreen(image,q);
image->colormap[i].blue=(double) GetPixelBlue(image,q);
image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
SetPixelIndex(image,(Quantum) i,q);
i++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
break;
proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
Image *image,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
MagickBooleanType
status;
size_t
depth,
maximum_colors;
assert(quantize_info != (const QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
maximum_colors=quantize_info->number_colors;
if (maximum_colors == 0)
maximum_colors=MaxColormapSize;
if (maximum_colors > MaxColormapSize)
maximum_colors=MaxColormapSize;
if (image->alpha_trait != BlendPixelTrait)
{
if ((image->columns*image->rows) <= maximum_colors)
(void) DirectToColormapImage(image,exception);
if (IsImageGray(image,exception) != MagickFalse)
(void) SetGrayscaleImage(image,exception);
}
if ((image->storage_class == PseudoClass) &&
(image->colors <= maximum_colors))
return(MagickTrue);
depth=quantize_info->tree_depth;
if (depth == 0)
{
size_t
colors;
/*
Depth of color tree is: Log4(colormap size)+2.
*/
colors=maximum_colors;
for (depth=1; colors != 0; depth++)
colors>>=2;
if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
depth--;
if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
depth--;
if (IsImageGray(image,exception) != MagickFalse)
depth=MaxTreeDepth;
}
/*
Initialize color cube.
*/
cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ClassifyImageColors(cube_info,image,exception);
if (status != MagickFalse)
{
/*
Reduce the number of colors in the image.
*/
ReduceImageColors(image,cube_info);
status=AssignImageColors(image,cube_info,exception);
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u a n t i z e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeImages() analyzes the colors within a set of reference images and
% chooses a fixed number of colors to represent the set. The goal of the
% algorithm is to minimize the color difference between the input and output
% images while minimizing the processing time.
%
% The format of the QuantizeImages method is:
%
% MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
% Image *images,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o images: Specifies a pointer to a list of Image structures.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
Image *images,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
Image
*image;
MagickBooleanType
proceed,
status;
MagickProgressMonitor
progress_monitor;
register ssize_t
i;
size_t
depth,
maximum_colors,
number_images;
assert(quantize_info != (const QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickSignature);
assert(images != (Image *) NULL);
assert(images->signature == MagickSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
if (GetNextImageInList(images) == (Image *) NULL)
{
/*
Handle a single image with QuantizeImage.
*/
status=QuantizeImage(quantize_info,images,exception);
return(status);
}
status=MagickFalse;
maximum_colors=quantize_info->number_colors;
if (maximum_colors == 0)
maximum_colors=MaxColormapSize;
if (maximum_colors > MaxColormapSize)
maximum_colors=MaxColormapSize;
depth=quantize_info->tree_depth;
if (depth == 0)
{
size_t
colors;
/*
Depth of color tree is: Log4(colormap size)+2.
*/
colors=maximum_colors;
for (depth=1; colors != 0; depth++)
colors>>=2;
if (quantize_info->dither_method != NoDitherMethod)
depth--;
}
/*
Initialize color cube.
*/
cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
if (cube_info == (CubeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return(MagickFalse);
}
number_images=GetImageListLength(images);
image=images;
for (i=0; image != (Image *) NULL; i++)
{
progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
image->client_data);
status=ClassifyImageColors(cube_info,image,exception);
if (status == MagickFalse)
break;
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
number_images);
if (proceed == MagickFalse)
break;
image=GetNextImageInList(image);
}
if (status != MagickFalse)
{
/*
Reduce the number of colors in an image sequence.
*/
ReduceImageColors(images,cube_info);
image=images;
for (i=0; image != (Image *) NULL; i++)
{
progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
NULL,image->client_data);
status=AssignImageColors(image,cube_info,exception);
if (status == MagickFalse)
break;
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
number_images);
if (proceed == MagickFalse)
break;
image=GetNextImageInList(image);
}
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Q u a n t i z e E r r o r F l a t t e n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeErrorFlatten() traverses the color cube and flattens the quantization
% error into a sorted 1D array. This accelerates the color reduction process.
%
% Contributed by Yoya.
%
% The format of the QuantizeImages method is:
%
% size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
% const NodeInfo *node_info,const ssize_t offset,
% MagickRealType *quantize_error)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is current pointer.
%
% o offset: quantize error offset.
%
% o quantize_error: the quantization error vector.
%
*/
static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
{
register ssize_t
i;
size_t
n,
number_children;
if (offset >= (ssize_t) cube_info->nodes)
return(0);
quantize_error[offset]=node_info->quantize_error;
n=1;
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children ; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
quantize_error);
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e d u c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Reduce() traverses the color cube tree and prunes any node whose
% quantization error falls below a particular threshold.
%
% The format of the Reduce method is:
%
% Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void Reduce(const Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
Reduce(image,cube_info,node_info->child[i]);
if (node_info->quantize_error <= cube_info->pruning_threshold)
PruneChild(image,cube_info,node_info);
else
{
/*
Find minimum pruning threshold.
*/
if (node_info->number_unique > 0)
cube_info->colors++;
if (node_info->quantize_error < cube_info->next_threshold)
cube_info->next_threshold=node_info->quantize_error;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e d u c e I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReduceImageColors() repeatedly prunes the tree until the number of nodes
% with n2 > 0 is less than or equal to the maximum number of colors allowed
% in the output image. On any given iteration over the tree, it selects
% those nodes whose E value is minimal for pruning and merges their
% color statistics upward. It uses a pruning threshold, Ep, to govern
% node selection as follows:
%
% Ep = 0
% while number of nodes with (n2 > 0) > required maximum number of colors
% prune all nodes such that E <= Ep
% Set Ep to minimum E in remaining nodes
%
% This has the effect of minimizing any quantization error when merging
% two nodes together.
%
% When a node to be pruned has offspring, the pruning procedure invokes
% itself recursively in order to prune the tree from the leaves upward.
% n2, Sr, Sg, and Sb in a node being pruned are always added to the
% corresponding data in that node's parent. This retains the pruned
% node's color characteristics for later averaging.
%
% For each node, n2 pixels exist for which that node represents the
% smallest volume in RGB space containing those pixel's colors. When n2
% > 0 the node will uniquely define a color in the output image. At the
% beginning of reduction, n2 = 0 for all nodes except a the leaves of
% the tree which represent colors present in the input image.
%
% The other pixel count, n1, indicates the total number of colors
% within the cubic volume which the node represents. This includes n1 -
% n2 pixels whose colors should be defined by nodes at a lower level in
% the tree.
%
% The format of the ReduceImageColors method is:
%
% ReduceImageColors(const Image *image,CubeInfo *cube_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
*/
static int MagickRealTypeCompare(const void *error_p,const void *error_q)
{
MagickRealType
*p,
*q;
p=(MagickRealType *) error_p;
q=(MagickRealType *) error_q;
if (*p > *q)
return(1);
if (fabs((double) (*q-*p)) <= MagickEpsilon)
return(0);
return(-1);
}
static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
{
#define ReduceImageTag "Reduce/Image"
MagickBooleanType
proceed;
MagickOffsetType
offset;
size_t
span;
cube_info->next_threshold=0.0;
if ((cube_info->colors > cube_info->maximum_colors) &&
(cube_info->nodes > 128))
{
MagickRealType
*quantize_error;
/*
Enable rapid reduction of the number of unique colors.
*/
quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
sizeof(*quantize_error));
if (quantize_error != (MagickRealType *) NULL)
{
(void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
quantize_error);
qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
MagickRealTypeCompare);
cube_info->next_threshold=quantize_error[MagickMax((ssize_t)
cube_info->nodes-110*(cube_info->maximum_colors+1)/100,0)];
quantize_error=(MagickRealType *) RelinquishMagickMemory(
quantize_error);
}
}
for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
{
cube_info->pruning_threshold=cube_info->next_threshold;
cube_info->next_threshold=cube_info->root->quantize_error-1;
cube_info->colors=0;
Reduce(image,cube_info,cube_info->root);
offset=(MagickOffsetType) span-cube_info->colors;
proceed=SetImageProgress(image,ReduceImageTag,offset,span-
cube_info->maximum_colors+1);
if (proceed == MagickFalse)
break;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m a p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemapImage() replaces the colors of an image with a dither of the colors
% provided.
%
% The format of the RemapImage method is:
%
% MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
% Image *image,const Image *remap_image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o image: the image.
%
% o remap_image: the reference image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
Image *image,const Image *remap_image,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
MagickBooleanType
status;
/*
Initialize color cube.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(remap_image != (Image *) NULL);
assert(remap_image->signature == MagickSignature);
cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
quantize_info->number_colors);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ClassifyImageColors(cube_info,remap_image,exception);
if (status != MagickFalse)
{
/*
Classify image colors from the reference image.
*/
cube_info->quantize_info->number_colors=cube_info->colors;
status=AssignImageColors(image,cube_info,exception);
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m a p I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemapImages() replaces the colors of a sequence of images with the
% closest color from a reference image.
%
% The format of the RemapImage method is:
%
% MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
% Image *images,Image *remap_image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o images: the image sequence.
%
% o remap_image: the reference image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
Image *images,const Image *remap_image,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
Image
*image;
MagickBooleanType
status;
assert(images != (Image *) NULL);
assert(images->signature == MagickSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
image=images;
if (remap_image == (Image *) NULL)
{
/*
Create a global colormap for an image sequence.
*/
status=QuantizeImages(quantize_info,images,exception);
return(status);
}
/*
Classify image colors from the reference image.
*/
cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
quantize_info->number_colors);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ClassifyImageColors(cube_info,remap_image,exception);
if (status != MagickFalse)
{
/*
Classify image colors from the reference image.
*/
cube_info->quantize_info->number_colors=cube_info->colors;
image=images;
for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
{
status=AssignImageColors(image,cube_info,exception);
if (status == MagickFalse)
break;
}
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t G r a y s c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
%
% The format of the SetGrayscaleImage method is:
%
% MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int IntensityCompare(const void *x,const void *y)
{
PixelInfo
*color_1,
*color_2;
ssize_t
intensity;
color_1=(PixelInfo *) x;
color_2=(PixelInfo *) y;
intensity=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
GetPixelInfoIntensity(color_2));
return((int) intensity);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickBooleanType SetGrayscaleImage(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace,exception);
colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
for (i=0; i <= (ssize_t) MaxMap; i++)
colormap_index[i]=(-1);
if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
image->colors=0;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(image,q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=(double)
GetPixelRed(image,q);
image->colormap[image->colors].green=(double)
GetPixelGreen(image,q);
image->colormap[image->colors].blue=(double)
GetPixelBlue(image,q);
image->colors++;
}
}
SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].alpha=(double) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
IntensityCompare);
colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
if (colormap == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].alpha]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
GetPixelIndex(image,q))],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (IsImageMonochrome(image,exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
|
GeneralMatrixMatrix.h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#ifndef EIGEN_GENERAL_MATRIX_MATRIX_H
#define EIGEN_GENERAL_MATRIX_MATRIX_H
template<typename _LhsScalar, typename _RhsScalar> class ei_level3_blocking;
/* Specialization for a row-major destination matrix => simple transposition of the product */
template<
typename Scalar, typename Index,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs>
struct ei_general_matrix_matrix_product<Scalar,Index,LhsStorageOrder,ConjugateLhs,RhsStorageOrder,ConjugateRhs,RowMajor>
{
static EIGEN_STRONG_INLINE void run(
Index rows, Index cols, Index depth,
const Scalar* lhs, Index lhsStride,
const Scalar* rhs, Index rhsStride,
Scalar* res, Index resStride,
Scalar alpha,
ei_level3_blocking<Scalar,Scalar>& blocking,
GemmParallelInfo<Index>* info = 0)
{
// transpose the product such that the result is column major
ei_general_matrix_matrix_product<Scalar, Index,
RhsStorageOrder==RowMajor ? ColMajor : RowMajor,
ConjugateRhs,
LhsStorageOrder==RowMajor ? ColMajor : RowMajor,
ConjugateLhs,
ColMajor>
::run(cols,rows,depth,rhs,rhsStride,lhs,lhsStride,res,resStride,alpha,blocking,info);
}
};
/* Specialization for a col-major destination matrix
* => Blocking algorithm following Goto's paper */
template<
typename Scalar, typename Index,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs>
struct ei_general_matrix_matrix_product<Scalar,Index,LhsStorageOrder,ConjugateLhs,RhsStorageOrder,ConjugateRhs,ColMajor>
{
static void run(Index rows, Index cols, Index depth,
const Scalar* _lhs, Index lhsStride,
const Scalar* _rhs, Index rhsStride,
Scalar* res, Index resStride,
Scalar alpha,
ei_level3_blocking<Scalar,Scalar>& blocking,
GemmParallelInfo<Index>* info = 0)
{
ei_const_blas_data_mapper<Scalar, Index, LhsStorageOrder> lhs(_lhs,lhsStride);
ei_const_blas_data_mapper<Scalar, Index, RhsStorageOrder> rhs(_rhs,rhsStride);
if (ConjugateRhs)
alpha = ei_conj(alpha);
typedef typename ei_packet_traits<Scalar>::type PacketType;
typedef ei_product_blocking_traits<Scalar> Blocking;
Index kc = blocking.kc(); // cache block size along the K direction
Index mc = std::min(rows,blocking.mc()); // cache block size along the M direction
//Index nc = blocking.nc(); // cache block size along the N direction
ei_gemm_pack_rhs<Scalar, Index, Blocking::nr, RhsStorageOrder> pack_rhs;
ei_gemm_pack_lhs<Scalar, Index, Blocking::mr, LhsStorageOrder> pack_lhs;
ei_gebp_kernel<Scalar, Index, Blocking::mr, Blocking::nr, ei_conj_helper<ConjugateLhs,ConjugateRhs> > gebp;
#ifdef EIGEN_HAS_OPENMP
if(info)
{
// this is the parallel version!
Index tid = omp_get_thread_num();
Index threads = omp_get_num_threads();
Scalar* blockA = ei_aligned_stack_new(Scalar, kc*mc);
std::size_t sizeW = kc*Blocking::PacketSize*Blocking::nr*8;
Scalar* w = ei_aligned_stack_new(Scalar, sizeW);
Scalar* blockB = blocking.blockB();
ei_internal_assert(blockB!=0);
// For each horizontal panel of the rhs, and corresponding vertical panel of the lhs...
for(Index k=0; k<depth; k+=kc)
{
const Index actual_kc = std::min(k+kc,depth)-k; // => rows of B', and cols of the A'
// In order to reduce the chance that a thread has to wait for the other,
// let's start by packing A'.
pack_lhs(blockA, &lhs(0,k), lhsStride, actual_kc, mc);
// Pack B_k to B' in a parallel fashion:
// each thread packs the sub block B_k,j to B'_j where j is the thread id.
// However, before copying to B'_j, we have to make sure that no other thread is still using it,
// i.e., we test that info[tid].users equals 0.
// Then, we set info[tid].users to the number of threads to mark that all other threads are going to use it.
while(info[tid].users!=0) {}
info[tid].users += threads;
pack_rhs(blockB+info[tid].rhs_start*kc, &rhs(k,info[tid].rhs_start), rhsStride, alpha, actual_kc, info[tid].rhs_length);
// Notify the other threads that the part B'_j is ready to go.
info[tid].sync = k;
// Computes C_i += A' * B' per B'_j
for(Index shift=0; shift<threads; ++shift)
{
Index j = (tid+shift)%threads;
// At this point we have to make sure that B'_j has been updated by the thread j,
// we use testAndSetOrdered to mimic a volatile access.
// However, no need to wait for the B' part which has been updated by the current thread!
if(shift>0)
while(info[j].sync!=k) {}
gebp(res+info[j].rhs_start*resStride, resStride, blockA, blockB+info[j].rhs_start*kc, mc, actual_kc, info[j].rhs_length, -1,-1,0,0, w);
}
// Then keep going as usual with the remaining A'
for(Index i=mc; i<rows; i+=mc)
{
const Index actual_mc = std::min(i+mc,rows)-i;
// pack A_i,k to A'
pack_lhs(blockA, &lhs(i,k), lhsStride, actual_kc, actual_mc);
// C_i += A' * B'
gebp(res+i, resStride, blockA, blockB, actual_mc, actual_kc, cols, -1,-1,0,0, w);
}
// Release all the sub blocks B'_j of B' for the current thread,
// i.e., we simply decrement the number of users by 1
for(Index j=0; j<threads; ++j)
#pragma omp atomic
--(info[j].users);
}
ei_aligned_stack_delete(Scalar, blockA, kc*mc);
ei_aligned_stack_delete(Scalar, w, sizeW);
}
else
#endif // EIGEN_HAS_OPENMP
{
EIGEN_UNUSED_VARIABLE(info);
// this is the sequential version!
std::size_t sizeA = kc*mc;
std::size_t sizeB = kc*cols;
std::size_t sizeW = kc*Blocking::PacketSize*Blocking::nr;
Scalar *blockA = blocking.blockA()==0 ? ei_aligned_stack_new(Scalar, sizeA) : blocking.blockA();
Scalar *blockB = blocking.blockB()==0 ? ei_aligned_stack_new(Scalar, sizeB) : blocking.blockB();
Scalar *blockW = blocking.blockW()==0 ? ei_aligned_stack_new(Scalar, sizeW) : blocking.blockW();
// For each horizontal panel of the rhs, and corresponding panel of the lhs...
// (==GEMM_VAR1)
for(Index k2=0; k2<depth; k2+=kc)
{
const Index actual_kc = std::min(k2+kc,depth)-k2;
// OK, here we have selected one horizontal panel of rhs and one vertical panel of lhs.
// => Pack rhs's panel into a sequential chunk of memory (L2 caching)
// Note that this panel will be read as many times as the number of blocks in the lhs's
// vertical panel which is, in practice, a very low number.
pack_rhs(blockB, &rhs(k2,0), rhsStride, alpha, actual_kc, cols);
// For each mc x kc block of the lhs's vertical panel...
// (==GEPP_VAR1)
for(Index i2=0; i2<rows; i2+=mc)
{
const Index actual_mc = std::min(i2+mc,rows)-i2;
// We pack the lhs's block into a sequential chunk of memory (L1 caching)
// Note that this block will be read a very high number of times, which is equal to the number of
// micro vertical panel of the large rhs's panel (e.g., cols/4 times).
pack_lhs(blockA, &lhs(i2,k2), lhsStride, actual_kc, actual_mc);
// Everything is packed, we can now call the block * panel kernel:
gebp(res+i2, resStride, blockA, blockB, actual_mc, actual_kc, cols, -1, -1, 0, 0, blockW);
}
}
if(blocking.blockA()==0) ei_aligned_stack_delete(Scalar, blockA, kc*mc);
if(blocking.blockB()==0) ei_aligned_stack_delete(Scalar, blockB, sizeB);
if(blocking.blockW()==0) ei_aligned_stack_delete(Scalar, blockW, sizeW);
}
}
};
/*********************************************************************************
* Specialization of GeneralProduct<> for "large" GEMM, i.e.,
* implementation of the high level wrapper to ei_general_matrix_matrix_product
**********************************************************************************/
template<typename Lhs, typename Rhs>
struct ei_traits<GeneralProduct<Lhs,Rhs,GemmProduct> >
: ei_traits<ProductBase<GeneralProduct<Lhs,Rhs,GemmProduct>, Lhs, Rhs> >
{};
template<typename Scalar, typename Index, typename Gemm, typename Lhs, typename Rhs, typename Dest, typename BlockingType>
struct ei_gemm_functor
{
ei_gemm_functor(const Lhs& lhs, const Rhs& rhs, Dest& dest, Scalar actualAlpha,
BlockingType& blocking)
: m_lhs(lhs), m_rhs(rhs), m_dest(dest), m_actualAlpha(actualAlpha), m_blocking(blocking)
{}
void initParallelSession() const
{
m_blocking.allocateB();
}
void operator() (Index row, Index rows, Index col=0, Index cols=-1, GemmParallelInfo<Index>* info=0) const
{
if(cols==-1)
cols = m_rhs.cols();
Gemm::run(rows, cols, m_lhs.cols(),
(const Scalar*)&(m_lhs.const_cast_derived().coeffRef(row,0)), m_lhs.outerStride(),
(const Scalar*)&(m_rhs.const_cast_derived().coeffRef(0,col)), m_rhs.outerStride(),
(Scalar*)&(m_dest.coeffRef(row,col)), m_dest.outerStride(),
m_actualAlpha, m_blocking, info);
}
protected:
const Lhs& m_lhs;
const Rhs& m_rhs;
Dest& m_dest;
Scalar m_actualAlpha;
BlockingType& m_blocking;
};
template<int StorageOrder, typename LhsScalar, typename RhsScalar, int MaxRows, int MaxCols, int MaxDepth,
bool FiniteAtCompileTime = MaxRows!=Dynamic && MaxCols!=Dynamic && MaxDepth != Dynamic> class ei_gemm_blocking_space;
template<typename _LhsScalar, typename _RhsScalar>
class ei_level3_blocking
{
typedef _LhsScalar LhsScalar;
typedef _RhsScalar RhsScalar;
protected:
LhsScalar* m_blockA;
RhsScalar* m_blockB;
RhsScalar* m_blockW;
DenseIndex m_mc;
DenseIndex m_nc;
DenseIndex m_kc;
public:
ei_level3_blocking()
: m_blockA(0), m_blockB(0), m_blockW(0), m_mc(0), m_nc(0), m_kc(0)
{}
inline DenseIndex mc() const { return m_mc; }
inline DenseIndex nc() const { return m_nc; }
inline DenseIndex kc() const { return m_kc; }
inline LhsScalar* blockA() { return m_blockA; }
inline RhsScalar* blockB() { return m_blockB; }
inline RhsScalar* blockW() { return m_blockW; }
};
template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth>
class ei_gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, true>
: public ei_level3_blocking<
typename ei_meta_if<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::ret,
typename ei_meta_if<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::ret>
{
enum {
Transpose = StorageOrder==RowMajor,
ActualRows = Transpose ? MaxCols : MaxRows,
ActualCols = Transpose ? MaxRows : MaxCols
};
typedef typename ei_meta_if<Transpose,_RhsScalar,_LhsScalar>::ret LhsScalar;
typedef typename ei_meta_if<Transpose,_LhsScalar,_RhsScalar>::ret RhsScalar;
typedef ei_product_blocking_traits<RhsScalar> Blocking;
enum {
SizeA = ActualRows * MaxDepth,
SizeB = ActualCols * MaxDepth,
SizeW = MaxDepth * Blocking::nr * ei_packet_traits<RhsScalar>::size
};
EIGEN_ALIGN16 LhsScalar m_staticA[SizeA];
EIGEN_ALIGN16 RhsScalar m_staticB[SizeB];
EIGEN_ALIGN16 RhsScalar m_staticW[SizeW];
public:
ei_gemm_blocking_space(DenseIndex /*rows*/, DenseIndex /*cols*/, DenseIndex /*depth*/)
{
this->m_mc = ActualRows;
this->m_nc = ActualCols;
this->m_kc = MaxDepth;
this->m_blockA = m_staticA;
this->m_blockB = m_staticB;
this->m_blockW = m_staticW;
}
inline void allocateA() {}
inline void allocateB() {}
inline void allocateW() {}
inline void allocateAll() {}
};
template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth>
class ei_gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, false>
: public ei_level3_blocking<
typename ei_meta_if<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::ret,
typename ei_meta_if<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::ret>
{
enum {
Transpose = StorageOrder==RowMajor
};
typedef typename ei_meta_if<Transpose,_RhsScalar,_LhsScalar>::ret LhsScalar;
typedef typename ei_meta_if<Transpose,_LhsScalar,_RhsScalar>::ret RhsScalar;
typedef ei_product_blocking_traits<RhsScalar> Blocking;
DenseIndex m_sizeA;
DenseIndex m_sizeB;
DenseIndex m_sizeW;
public:
ei_gemm_blocking_space(DenseIndex rows, DenseIndex cols, DenseIndex depth)
{
this->m_mc = Transpose ? cols : rows;
this->m_nc = Transpose ? rows : cols;
this->m_kc = depth;
computeProductBlockingSizes<LhsScalar,RhsScalar>(this->m_kc, this->m_mc, this->m_nc);
m_sizeA = this->m_mc * this->m_kc;
m_sizeB = this->m_kc * this->m_nc;
m_sizeW = this->m_kc*ei_packet_traits<RhsScalar>::size*Blocking::nr;
}
void allocateA()
{
if(this->m_blockA==0)
this->m_blockA = ei_aligned_new<LhsScalar>(m_sizeA);
}
void allocateB()
{
if(this->m_blockB==0)
this->m_blockB = ei_aligned_new<RhsScalar>(m_sizeB);
}
void allocateW()
{
if(this->m_blockW==0)
this->m_blockW = ei_aligned_new<RhsScalar>(m_sizeW);
}
void allocateAll()
{
allocateA();
allocateB();
allocateW();
}
~ei_gemm_blocking_space()
{
ei_aligned_delete(this->m_blockA, m_sizeA);
ei_aligned_delete(this->m_blockB, m_sizeB);
ei_aligned_delete(this->m_blockW, m_sizeW);
}
};
template<typename Lhs, typename Rhs>
class GeneralProduct<Lhs, Rhs, GemmProduct>
: public ProductBase<GeneralProduct<Lhs,Rhs,GemmProduct>, Lhs, Rhs>
{
enum {
MaxDepthAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(Lhs::MaxColsAtCompileTime,Rhs::MaxRowsAtCompileTime)
};
public:
EIGEN_PRODUCT_PUBLIC_INTERFACE(GeneralProduct)
GeneralProduct(const Lhs& lhs, const Rhs& rhs) : Base(lhs,rhs)
{
EIGEN_STATIC_ASSERT((ei_is_same_type<typename Lhs::Scalar, typename Rhs::Scalar>::ret),
YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
}
template<typename Dest> void scaleAndAddTo(Dest& dst, Scalar alpha) const
{
ei_assert(dst.rows()==m_lhs.rows() && dst.cols()==m_rhs.cols());
const ActualLhsType lhs = LhsBlasTraits::extract(m_lhs);
const ActualRhsType rhs = RhsBlasTraits::extract(m_rhs);
Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(m_lhs)
* RhsBlasTraits::extractScalarFactor(m_rhs);
typedef ei_gemm_blocking_space<(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor,Scalar,Scalar,
Dest::MaxRowsAtCompileTime,Dest::MaxColsAtCompileTime,MaxDepthAtCompileTime> BlockingType;
typedef ei_gemm_functor<
Scalar, Index,
ei_general_matrix_matrix_product<
Scalar, Index,
(_ActualLhsType::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(LhsBlasTraits::NeedToConjugate),
(_ActualRhsType::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(RhsBlasTraits::NeedToConjugate),
(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor>,
_ActualLhsType, _ActualRhsType, Dest, BlockingType> GemmFunctor;
BlockingType blocking(dst.rows(), dst.cols(), lhs.cols());
ei_parallelize_gemm<(Dest::MaxRowsAtCompileTime>32 || Dest::MaxRowsAtCompileTime==Dynamic)>(GemmFunctor(lhs, rhs, dst, actualAlpha, blocking), this->rows(), this->cols(), Dest::Flags&RowMajorBit);
}
};
#endif // EIGEN_GENERAL_MATRIX_MATRIX_H
|
DRB026-targetparallelfor-orig-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 due to anti-dependence within a loop offloaded to accelerators.
Data race pair: a[i]@64:5 vs. a[i+1]@64:10
*/
int main(int argc, char* argv[])
{
int i;
int len = 1000;
int a[1000];
#pragma omp parallel for private(i )
for (i=0; i<len; i++)
a[i]= i;
for (i=0;i< len -1 ;i++)
a[i]=a[i+1]+1;
for (i=0; i<len; i++)
printf("%d\n", a[i]);
return 0;
}
|
GB_binop__bxor_int64.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__bxor_int64)
// A.*B function (eWiseMult): GB (_AemultB_08__bxor_int64)
// A.*B function (eWiseMult): GB (_AemultB_02__bxor_int64)
// A.*B function (eWiseMult): GB (_AemultB_04__bxor_int64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bxor_int64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bxor_int64)
// C+=b function (dense accum): GB (_Cdense_accumb__bxor_int64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bxor_int64)
// C=scalar+B GB (_bind1st__bxor_int64)
// C=scalar+B' GB (_bind1st_tran__bxor_int64)
// C=A+scalar GB (_bind2nd__bxor_int64)
// C=A'+scalar GB (_bind2nd_tran__bxor_int64)
// C type: int64_t
// A type: int64_t
// B,b type: int64_t
// BinaryOp: cij = (aij) ^ (bij)
#define GB_ATYPE \
int64_t
#define GB_BTYPE \
int64_t
#define GB_CTYPE \
int64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int64_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int64_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x) ^ (y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BXOR || GxB_NO_INT64 || GxB_NO_BXOR_INT64)
//------------------------------------------------------------------------------
// 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__bxor_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__bxor_int64)
(
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__bxor_int64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int64_t
int64_t bwork = (*((int64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bxor_int64)
(
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__bxor_int64)
(
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__bxor_int64)
(
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__bxor_int64)
(
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__bxor_int64)
(
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__bxor_int64)
(
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
int64_t *Cx = (int64_t *) Cx_output ;
int64_t x = (*((int64_t *) x_input)) ;
int64_t *Bx = (int64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int64_t bij = GBX (Bx, p, false) ;
Cx [p] = (x) ^ (bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bxor_int64)
(
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 ;
int64_t *Cx = (int64_t *) Cx_output ;
int64_t *Ax = (int64_t *) Ax_input ;
int64_t y = (*((int64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int64_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij) ^ (y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x) ^ (aij) ; \
}
GrB_Info GB (_bind1st_tran__bxor_int64)
(
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 \
int64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t x = (*((const int64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij) ^ (y) ; \
}
GrB_Info GB (_bind2nd_tran__bxor_int64)
(
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
int64_t y = (*((const int64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
cmontecarlo.c |
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#ifdef WITHOPENMP
#include <omp.h>
#endif
#include "io.h"
#include "abbrev.h"
#include "status.h"
#include "rpacket.h"
#include "cmontecarlo.h"
/** Look for a place to insert a value in an inversely sorted float array.
*
* @param x an inversely (largest to lowest) sorted float array
* @param x_insert a value to insert
* @param imin lower bound
* @param imax upper bound
*
* @return index of the next boundary to the left
*/
tardis_error_t
reverse_binary_search (const double *x, double x_insert,
int64_t imin, int64_t imax, int64_t * result)
{
/*
Have in mind that *x points to a reverse sorted array.
That is large values will have small indices and small ones
will have large indices.
*/
tardis_error_t ret_val = TARDIS_ERROR_OK;
if (x_insert > x[imin] || x_insert < x[imax])
{
ret_val = TARDIS_ERROR_BOUNDS_ERROR;
}
else
{
int imid = (imin + imax) >> 1;
while (imax - imin > 2)
{
if (x[imid] < x_insert)
{
imax = imid + 1;
}
else
{
imin = imid;
}
imid = (imin + imax) >> 1;
}
if (imax - imin == 2 && x_insert < x[imin + 1])
{
*result = imin + 1;
}
else
{
*result = imin;
}
}
return ret_val;
}
/** Insert a value in to an array of line frequencies
*
* @param nu array of line frequencies
* @param nu_insert value of nu key
* @param number_of_lines number of lines in the line list
*
* @return index of the next line ot the red. If the key value is redder than the reddest line returns number_of_lines.
*/
tardis_error_t
line_search (const double *nu, double nu_insert, int64_t number_of_lines,
int64_t * result)
{
tardis_error_t ret_val = TARDIS_ERROR_OK;
int64_t imin = 0;
int64_t imax = number_of_lines - 1;
if (nu_insert > nu[imin])
{
*result = imin;
}
else if (nu_insert < nu[imax])
{
*result = imax + 1;
}
else
{
ret_val = reverse_binary_search (nu, nu_insert, imin, imax, result);
*result = *result + 1;
}
return ret_val;
}
tardis_error_t
binary_search (const double *x, double x_insert, int64_t imin,
int64_t imax, int64_t * result)
{
/*
Have in mind that *x points to a sorted array.
Like [1,2,3,4,5,...]
*/
int imid;
tardis_error_t ret_val = TARDIS_ERROR_OK;
if (x_insert < x[imin] || x_insert > x[imax])
{
ret_val = TARDIS_ERROR_BOUNDS_ERROR;
}
else
{
while (imax >= imin)
{
imid = (imin + imax) / 2;
if (x[imid] == x_insert)
{
*result = imid;
break;
}
else if (x[imid] < x_insert)
{
imin = imid + 1;
}
else
{
imax = imid - 1;
}
}
if (imax - imid == 2 && x_insert < x[imin + 1])
{
*result = imin;
}
else
{
*result = imin;
}
}
return ret_val;
}
void
angle_aberration_CMF_to_LF (rpacket_t *packet, const storage_model_t *storage)
{
if (storage->full_relativity)
{
double beta = rpacket_get_r (packet) * storage->inverse_time_explosion * INVERSE_C;
double mu_0 = rpacket_get_mu (packet);
rpacket_set_mu (packet, (mu_0 + beta) / (1.0 + beta * mu_0));
}
}
/** Transform the lab frame direction cosine to the CMF
*
* @param packet
* @param storage
* @param mu lab frame direction cosine
*
* @return CMF direction cosine
*/
double
angle_aberration_LF_to_CMF (rpacket_t *packet, const storage_model_t *storage, double mu)
{
double beta = rpacket_get_r (packet) * storage->inverse_time_explosion * INVERSE_C;
return (mu - beta) / (1.0 - beta * mu);
}
double
rpacket_doppler_factor (const rpacket_t *packet, const storage_model_t *storage)
{
double beta = rpacket_get_r (packet) * storage->inverse_time_explosion * INVERSE_C;
if (!storage->full_relativity)
{
return 1.0 - rpacket_get_mu (packet) * beta;
}
else
{
return (1.0 - rpacket_get_mu (packet) * beta) / sqrt (1 - beta * beta);
}
}
double
rpacket_inverse_doppler_factor (const rpacket_t *packet, const storage_model_t *storage)
{
double beta = rpacket_get_r (packet) * storage->inverse_time_explosion * INVERSE_C;
if (!storage->full_relativity)
{
return 1.0 / (1.0 - rpacket_get_mu (packet) * beta);
}
else
{
return (1.0 + rpacket_get_mu (packet) * beta) / sqrt (1 - beta * beta);
}
}
double
bf_cross_section (const storage_model_t * storage, int64_t continuum_id, double comov_nu)
{
double bf_xsect;
double *x_sect = storage->photo_xsect[continuum_id]->x_sect;
double *nu = storage->photo_xsect[continuum_id]->nu;
switch (storage->bf_treatment)
{
case LIN_INTERPOLATION:
{
int64_t result;
tardis_error_t error = binary_search (nu, comov_nu, 0,
storage->photo_xsect[continuum_id]->no_of_points - 1, &result);
if (error == TARDIS_ERROR_BOUNDS_ERROR)
{
bf_xsect = 0.0;
}
else
{
bf_xsect = x_sect[result-1] + (comov_nu - nu[result-1]) / (nu[result] - nu[result-1])
* (x_sect[result] - x_sect[result-1]);
}
break;
}
case HYDROGENIC:
{
double nu_ratio = nu[0] / comov_nu;
bf_xsect = x_sect[0] * nu_ratio * nu_ratio * nu_ratio;
break;
}
default:
fprintf (stderr, "(%d) is not a valid bound-free cross section treatment.\n", storage->bf_treatment);
exit(1);
}
return bf_xsect;
}
void calculate_chi_bf (rpacket_t * packet, storage_model_t * storage)
{
double doppler_factor = rpacket_doppler_factor (packet, storage);
double comov_nu = rpacket_get_nu (packet) * doppler_factor;
int64_t no_of_continuum_edges = storage->no_of_edges;
int64_t current_continuum_id;
line_search(storage->continuum_list_nu, comov_nu, no_of_continuum_edges, ¤t_continuum_id);
rpacket_set_current_continuum_id (packet, current_continuum_id);
int64_t shell_id = rpacket_get_current_shell_id (packet);
double T = storage->t_electrons[shell_id];
double boltzmann_factor = exp (-(H * comov_nu) / (KB * T));
double bf_helper = 0;
for(int64_t i = current_continuum_id; i < no_of_continuum_edges; i++)
{
// get the level population for the level ijk in the current shell:
double l_pop = storage->l_pop[shell_id * no_of_continuum_edges + i];
// get the level population ratio \frac{n_{0,j+1,k}}{n_{i,j,k}} \frac{n_{i,j,k}}{n_{0,j+1,k}}^{*}:
double l_pop_r = storage->l_pop_r[shell_id * no_of_continuum_edges + i];
double bf_x_sect = bf_cross_section (storage, i, comov_nu);
if (bf_x_sect == 0.0)
{
break;
}
bf_helper += l_pop * bf_x_sect * (1.0 - l_pop_r * boltzmann_factor) * doppler_factor;
packet->chi_bf_tmp_partial[i] = bf_helper;
}
rpacket_set_chi_boundfree (packet, bf_helper);
}
void calculate_chi_ff (rpacket_t * packet, const storage_model_t * storage)
{
double doppler_factor = rpacket_doppler_factor (packet, storage);
double comov_nu = rpacket_get_nu (packet) * doppler_factor;
int64_t shell_id = rpacket_get_current_shell_id (packet);
double T = storage->t_electrons[shell_id];
double boltzmann_factor = exp (-(H * comov_nu) / KB / T);
double chi_ff_factor = storage->chi_ff_factor[shell_id];
double chi_ff = chi_ff_factor * (1 - boltzmann_factor) * pow (comov_nu, -3);
rpacket_set_chi_freefree (packet, chi_ff * doppler_factor);
}
void
compute_distance2boundary (rpacket_t * packet, const storage_model_t * storage)
{
double r = rpacket_get_r (packet);
double mu = rpacket_get_mu (packet);
double r_outer = storage->r_outer[rpacket_get_current_shell_id (packet)];
double r_inner = storage->r_inner[rpacket_get_current_shell_id (packet)];
double check, distance;
if (mu > 0.0)
{ // direction outward
rpacket_set_next_shell_id (packet, 1);
distance = sqrt (r_outer * r_outer + ((mu * mu - 1.0) * r * r)) - (r * mu);
}
else
{ // going inward
if ( (check = r_inner * r_inner + (r * r * (mu * mu - 1.0)) )>= 0.0)
{ // hit inner boundary
rpacket_set_next_shell_id (packet, -1);
distance = - r * mu - sqrt (check);
}
else
{ // miss inner boundary
rpacket_set_next_shell_id (packet, 1);
distance = sqrt (r_outer * r_outer + ((mu * mu - 1.0) * r * r)) - (r * mu);
}
}
rpacket_set_d_boundary (packet, distance);
}
tardis_error_t
compute_distance2line (rpacket_t * packet, const storage_model_t * storage)
{
if (!rpacket_get_last_line (packet))
{
double r = rpacket_get_r (packet);
double mu = rpacket_get_mu (packet);
double nu = rpacket_get_nu (packet);
double nu_line = rpacket_get_nu_line (packet);
double distance, nu_diff;
double ct = storage->time_explosion * C;
double doppler_factor = rpacket_doppler_factor (packet, storage);
double comov_nu = nu * doppler_factor;
if ( (nu_diff = comov_nu - nu_line) >= 0)
{
if (!storage->full_relativity)
{
distance = (nu_diff / nu) * ct;
}
else
{
double nu_r = nu_line / nu;
distance = - mu * r + (ct - nu_r * nu_r * sqrt(ct * ct -
(1 + r * r * (1 - mu * mu) * (1 + pow (nu_r, -2))))) / (1 + nu_r * nu_r);
}
rpacket_set_d_line (packet, distance);
return TARDIS_ERROR_OK;
}
else
{
if (rpacket_get_next_line_id (packet) == storage->no_of_lines - 1)
{
fprintf (stderr, "last_line = %f\n",
storage->
line_list_nu[rpacket_get_next_line_id (packet) - 1]);
fprintf (stderr, "Last line in line list reached!");
}
else if (rpacket_get_next_line_id (packet) == 0)
{
fprintf (stderr, "First line in line list!");
fprintf (stderr, "next_line = %f\n",
storage->
line_list_nu[rpacket_get_next_line_id (packet) + 1]);
}
else
{
fprintf (stderr, "last_line = %f\n",
storage->
line_list_nu[rpacket_get_next_line_id (packet) - 1]);
fprintf (stderr, "next_line = %f\n",
storage->
line_list_nu[rpacket_get_next_line_id (packet) + 1]);
}
fprintf (stderr, "ERROR: Comoving nu less than nu_line!\n");
fprintf (stderr, "comov_nu = %f\n", comov_nu);
fprintf (stderr, "nu_line = %f\n", nu_line);
fprintf (stderr, "(comov_nu - nu_line) / nu_line = %f\n",
(comov_nu - nu_line) / nu_line);
fprintf (stderr, "r = %f\n", r);
fprintf (stderr, "mu = %f\n", mu);
fprintf (stderr, "nu = %f\n", nu);
fprintf (stderr, "doppler_factor = %f\n", doppler_factor);
fprintf (stderr, "cur_zone_id = %" PRIi64 "\n", rpacket_get_current_shell_id (packet));
return TARDIS_ERROR_COMOV_NU_LESS_THAN_NU_LINE;
}
}
else
{
rpacket_set_d_line (packet, MISS_DISTANCE);
return TARDIS_ERROR_OK;
}
}
void
compute_distance2continuum (rpacket_t * packet, storage_model_t * storage)
{
double chi_continuum, d_continuum;
double chi_electron = storage->electron_densities[rpacket_get_current_shell_id(packet)] *
storage->sigma_thomson;
if (storage->full_relativity)
{
chi_electron *= rpacket_doppler_factor (packet, storage);
}
if (storage->cont_status == CONTINUUM_ON)
{
if (packet->compute_chi_bf)
{
calculate_chi_bf (packet, storage);
calculate_chi_ff (packet, storage);
}
else
{
packet->compute_chi_bf=true;
}
chi_continuum = rpacket_get_chi_boundfree (packet) + rpacket_get_chi_freefree (packet) + chi_electron;
d_continuum = rpacket_get_tau_event (packet) / chi_continuum;
}
else
{
chi_continuum = chi_electron;
d_continuum = storage->inverse_electron_densities[rpacket_get_current_shell_id (packet)] *
storage->inverse_sigma_thomson * rpacket_get_tau_event (packet);
}
if (rpacket_get_virtual_packet(packet) > 0)
{
//Set all continuum distances to MISS_DISTANCE in case of an virtual_packet
d_continuum = MISS_DISTANCE;
packet->compute_chi_bf = false;
}
else
{
// fprintf(stderr, "--------\n");
// fprintf(stderr, "nu = %e \n", rpacket_get_nu(packet));
// fprintf(stderr, "chi_electron = %e\n", chi_electron);
// fprintf(stderr, "chi_boundfree = %e\n", calculate_chi_bf(packet, storage));
// fprintf(stderr, "chi_line = %e \n", rpacket_get_tau_event(packet) / rpacket_get_d_line(packet));
// fprintf(stderr, "--------\n");
//rpacket_set_chi_freefree(packet, chi_freefree);
rpacket_set_chi_electron (packet, chi_electron);
}
rpacket_set_chi_continuum (packet, chi_continuum);
rpacket_set_d_continuum (packet, d_continuum);
}
void
macro_atom (rpacket_t * packet, const storage_model_t * storage, rk_state *mt_state)
{
int emit = 0, i = 0, offset = -1;
uint64_t activate_level = rpacket_get_macro_atom_activation_level (packet);
while (emit >= 0)
{
double event_random = rk_double (mt_state);
i = storage->macro_block_references[activate_level] - 1;
double p = 0.0;
offset = storage->transition_probabilities_nd *
rpacket_get_current_shell_id (packet);
do
{
++i;
p += storage->transition_probabilities[offset + i];
}
while (p <= event_random);
emit = storage->transition_type[i];
activate_level = storage->destination_level_id[i];
}
switch (emit)
{
case BB_EMISSION:
line_emission (packet, storage, storage->transition_line_id[i], mt_state);
break;
case BF_EMISSION:
rpacket_set_current_continuum_id (packet, storage->transition_line_id[i]);
storage->last_line_interaction_out_id[rpacket_get_id (packet)] =
rpacket_get_current_continuum_id (packet);
continuum_emission (packet, storage, mt_state, sample_nu_free_bound, 3);
break;
case FF_EMISSION:
continuum_emission (packet, storage, mt_state, sample_nu_free_free, 4);
break;
case ADIABATIC_COOLING:
storage->last_interaction_type[rpacket_get_id (packet)] = 5;
rpacket_set_status (packet, TARDIS_PACKET_STATUS_REABSORBED);
break;
default:
fprintf (stderr, "This process for macro-atom deactivation should not exist! (emit = %d)\n", emit);
exit(1);
}
}
void
move_packet (rpacket_t * packet, storage_model_t * storage, double distance)
{
double doppler_factor = rpacket_doppler_factor (packet, storage);
if (distance > 0.0)
{
double r = rpacket_get_r (packet);
double new_r =
sqrt (r * r + distance * distance +
2.0 * r * distance * rpacket_get_mu (packet));
rpacket_set_mu (packet,
(rpacket_get_mu (packet) * r + distance) / new_r);
rpacket_set_r (packet, new_r);
if (rpacket_get_virtual_packet (packet) <= 0)
{
double comov_energy = rpacket_get_energy (packet) * doppler_factor;
double comov_nu = rpacket_get_nu (packet) * doppler_factor;
if (storage->full_relativity)
{
distance *= doppler_factor;
}
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->js[rpacket_get_current_shell_id (packet)] +=
comov_energy * distance;
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->nubars[rpacket_get_current_shell_id (packet)] +=
comov_energy * distance * comov_nu;
if (storage->cont_status)
{
increment_continuum_estimators(packet, storage, distance, comov_nu, comov_energy);
}
}
}
}
void
increment_continuum_estimators (const rpacket_t * packet, storage_model_t * storage, double distance,
double comov_nu, double comov_energy)
{
int64_t current_continuum_id;
int64_t no_of_continuum_edges = storage->no_of_edges;
int64_t shell_id = rpacket_get_current_shell_id (packet);
line_search(storage->continuum_list_nu, comov_nu, no_of_continuum_edges, ¤t_continuum_id);
double T = storage->t_electrons[shell_id];
double boltzmann_factor = exp (-(H * comov_nu) / (KB * T));
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->ff_heating_estimator[shell_id] += comov_energy * distance * rpacket_get_chi_freefree (packet);
for(int64_t i = current_continuum_id; i < no_of_continuum_edges; i++)
{
double bf_xsect = bf_cross_section (storage, i, comov_nu);
int64_t photo_ion_idx = i * storage->no_of_shells + shell_id;
double photo_ion_estimator_helper = comov_energy * distance * bf_xsect / comov_nu;
double bf_heating_estimator_helper =
comov_energy * distance * bf_xsect * (1. - storage->continuum_list_nu[i] / comov_nu);
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->photo_ion_estimator[photo_ion_idx] += photo_ion_estimator_helper;
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->stim_recomb_estimator[photo_ion_idx] += photo_ion_estimator_helper * boltzmann_factor;
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->bf_heating_estimator[photo_ion_idx] += bf_heating_estimator_helper;
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->stim_recomb_cooling_estimator[photo_ion_idx] += bf_heating_estimator_helper * boltzmann_factor;
if (photo_ion_estimator_helper != 0.0)
{
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->photo_ion_estimator_statistics[photo_ion_idx] += 1;
}
else
{
break;
}
}
}
double
get_increment_j_blue_estimator_energy (const rpacket_t * packet,
const storage_model_t * storage,
double d_line)
{
double energy;
if (storage->full_relativity)
{
// Accurate up to a factor 1 / gamma
energy = rpacket_get_energy (packet);
}
else
{
double r = rpacket_get_r (packet);
double r_interaction = sqrt (r * r + d_line * d_line +
2.0 * r * d_line * rpacket_get_mu (packet));
double mu_interaction = (rpacket_get_mu (packet) * r + d_line) / r_interaction;
double doppler_factor = 1.0 - mu_interaction * r_interaction *
storage->inverse_time_explosion * INVERSE_C;
energy = rpacket_get_energy (packet) * doppler_factor;
}
return energy;
}
void
increment_j_blue_estimator (const rpacket_t * packet, storage_model_t * storage,
double d_line, int64_t j_blue_idx)
{
if (storage->line_lists_j_blues != NULL)
{
double energy = get_increment_j_blue_estimator_energy (packet, storage,
d_line);
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->line_lists_j_blues[j_blue_idx] +=
energy / rpacket_get_nu (packet);
}
}
void
increment_Edotlu_estimator (const rpacket_t * packet, storage_model_t * storage,
double d_line, int64_t line_idx)
{
if (storage->line_lists_Edotlu != NULL)
{
double energy = get_increment_j_blue_estimator_energy (packet, storage,
d_line);
#ifdef WITHOPENMP
#pragma omp atomic
#endif
storage->line_lists_Edotlu[line_idx] += energy;
}
}
int64_t
montecarlo_one_packet (storage_model_t * storage, rpacket_t * packet,
int64_t virtual_mode, rk_state *mt_state)
{
int64_t reabsorbed=-1;
if (virtual_mode == 0)
{
reabsorbed = montecarlo_one_packet_loop (storage, packet, 0, mt_state);
}
else
{
if ((rpacket_get_nu (packet) > storage->spectrum_virt_start_nu) && (rpacket_get_nu(packet) < storage->spectrum_virt_end_nu))
{
for (int64_t i = 0; i < rpacket_get_virtual_packet_flag (packet); i++)
{
double weight;
rpacket_t virt_packet = *packet;
double mu_min;
if (rpacket_get_r(&virt_packet) > storage->r_inner[0])
{
mu_min =
-1.0 * sqrt (1.0 -
(storage->r_inner[0] / rpacket_get_r(&virt_packet)) *
(storage->r_inner[0] / rpacket_get_r(&virt_packet)));
if (storage->full_relativity)
{
// Need to transform the angular size of the photosphere into the CMF
mu_min = angle_aberration_LF_to_CMF (&virt_packet, storage, mu_min);
}
}
else
{
mu_min = 0.0;
}
double mu_bin = (1.0 - mu_min) / rpacket_get_virtual_packet_flag (packet);
rpacket_set_mu(&virt_packet,mu_min + (i + rk_double (mt_state)) * mu_bin);
switch (virtual_mode)
{
case -2:
weight = 1.0 / rpacket_get_virtual_packet_flag (packet);
break;
case -1:
weight =
2.0 * rpacket_get_mu(&virt_packet) /
rpacket_get_virtual_packet_flag (packet);
break;
case 1:
weight =
(1.0 -
mu_min) / 2.0 / rpacket_get_virtual_packet_flag (packet);
break;
default:
fprintf (stderr, "Something has gone horribly wrong!\n");
// FIXME MR: we need to somehow signal an error here
// I'm adding an exit() here to inform the compiler about the impossible path
exit(1);
}
angle_aberration_CMF_to_LF (&virt_packet, storage);
double doppler_factor_ratio =
rpacket_doppler_factor (packet, storage) /
rpacket_doppler_factor (&virt_packet, storage);
rpacket_set_energy(&virt_packet,
rpacket_get_energy (packet) * doppler_factor_ratio);
rpacket_set_nu(&virt_packet,rpacket_get_nu (packet) * doppler_factor_ratio);
reabsorbed = montecarlo_one_packet_loop (storage, &virt_packet, 1, mt_state);
#ifdef WITH_VPACKET_LOGGING
#ifdef WITHOPENMP
#pragma omp critical
{
#endif // WITHOPENMP
if (storage->virt_packet_count >= storage->virt_array_size)
{
storage->virt_array_size *= 2;
storage->virt_packet_nus = safe_realloc(storage->virt_packet_nus, sizeof(double) * storage->virt_array_size);
storage->virt_packet_energies = safe_realloc(storage->virt_packet_energies, sizeof(double) * storage->virt_array_size);
storage->virt_packet_last_interaction_in_nu = safe_realloc(storage->virt_packet_last_interaction_in_nu, sizeof(double) * storage->virt_array_size);
storage->virt_packet_last_interaction_type = safe_realloc(storage->virt_packet_last_interaction_type, sizeof(int64_t) * storage->virt_array_size);
storage->virt_packet_last_line_interaction_in_id = safe_realloc(storage->virt_packet_last_line_interaction_in_id, sizeof(int64_t) * storage->virt_array_size);
storage->virt_packet_last_line_interaction_out_id = safe_realloc(storage->virt_packet_last_line_interaction_out_id, sizeof(int64_t) * storage->virt_array_size);
}
storage->virt_packet_nus[storage->virt_packet_count] = rpacket_get_nu(&virt_packet);
storage->virt_packet_energies[storage->virt_packet_count] = rpacket_get_energy(&virt_packet) * weight;
storage->virt_packet_last_interaction_in_nu[storage->virt_packet_count] = storage->last_interaction_in_nu[rpacket_get_id (packet)];
storage->virt_packet_last_interaction_type[storage->virt_packet_count] = storage->last_interaction_type[rpacket_get_id (packet)];
storage->virt_packet_last_line_interaction_in_id[storage->virt_packet_count] = storage->last_line_interaction_in_id[rpacket_get_id (packet)];
storage->virt_packet_last_line_interaction_out_id[storage->virt_packet_count] = storage->last_line_interaction_out_id[rpacket_get_id (packet)];
storage->virt_packet_count += 1;
#ifdef WITHOPENMP
}
#endif // WITHOPENMP
#endif // WITH_VPACKET_LOGGING
if ((rpacket_get_nu(&virt_packet) < storage->spectrum_end_nu) &&
(rpacket_get_nu(&virt_packet) > storage->spectrum_start_nu))
{
#ifdef WITHOPENMP
#pragma omp critical
{
#endif // WITHOPENMP
int64_t virt_id_nu =
floor ((rpacket_get_nu(&virt_packet) -
storage->spectrum_start_nu) /
storage->spectrum_delta_nu);
storage->spectrum_virt_nu[virt_id_nu] +=
rpacket_get_energy(&virt_packet) * weight;
#ifdef WITHOPENMP
}
#endif // WITHOPENMP
}
}
}
else
{
return 1;
}
}
return reabsorbed;
}
void
move_packet_across_shell_boundary (rpacket_t * packet,
storage_model_t * storage, double distance, rk_state *mt_state)
{
move_packet (packet, storage, distance);
if (rpacket_get_virtual_packet (packet) > 0)
{
double delta_tau_event = rpacket_get_chi_continuum(packet) * distance;
rpacket_set_tau_event (packet,
rpacket_get_tau_event (packet) +
delta_tau_event);
packet->compute_chi_bf = true;
}
else
{
rpacket_reset_tau_event (packet, mt_state);
}
if ((rpacket_get_current_shell_id (packet) < storage->no_of_shells - 1
&& rpacket_get_next_shell_id (packet) == 1)
|| (rpacket_get_current_shell_id (packet) > 0
&& rpacket_get_next_shell_id (packet) == -1))
{
rpacket_set_current_shell_id (packet,
rpacket_get_current_shell_id (packet) +
rpacket_get_next_shell_id (packet));
}
else if (rpacket_get_next_shell_id (packet) == 1)
{
rpacket_set_status (packet, TARDIS_PACKET_STATUS_EMITTED);
}
else if ((storage->reflective_inner_boundary == 0) ||
(rk_double (mt_state) > storage->inner_boundary_albedo))
{
rpacket_set_status (packet, TARDIS_PACKET_STATUS_REABSORBED);
}
else
{
double doppler_factor = rpacket_doppler_factor (packet, storage);
double comov_nu = rpacket_get_nu (packet) * doppler_factor;
double comov_energy = rpacket_get_energy (packet) * doppler_factor;
// TODO: correct
rpacket_set_mu (packet, rk_double (mt_state));
double inverse_doppler_factor = rpacket_inverse_doppler_factor (packet, storage);
rpacket_set_nu (packet, comov_nu * inverse_doppler_factor);
rpacket_set_energy (packet, comov_energy * inverse_doppler_factor);
if (rpacket_get_virtual_packet_flag (packet) > 0)
{
montecarlo_one_packet (storage, packet, -2, mt_state);
}
}
}
void
montecarlo_thomson_scatter (rpacket_t * packet, storage_model_t * storage,
double distance, rk_state *mt_state)
{
move_packet (packet, storage, distance);
double doppler_factor = rpacket_doppler_factor (packet, storage);
double comov_nu = rpacket_get_nu (packet) * doppler_factor;
double comov_energy = rpacket_get_energy (packet) * doppler_factor;
rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0);
double inverse_doppler_factor = rpacket_inverse_doppler_factor (packet, storage);
rpacket_set_nu (packet, comov_nu * inverse_doppler_factor);
rpacket_set_energy (packet, comov_energy * inverse_doppler_factor);
rpacket_reset_tau_event (packet, mt_state);
storage->last_interaction_type[rpacket_get_id (packet)] = 1;
angle_aberration_CMF_to_LF (packet, storage);
if (rpacket_get_virtual_packet_flag (packet) > 0)
{
montecarlo_one_packet (storage, packet, 1, mt_state);
}
}
void
montecarlo_bound_free_scatter (rpacket_t * packet, storage_model_t * storage, double distance, rk_state *mt_state)
{
// current position in list of continuum edges -> indicates which bound-free processes are possible
int64_t ccontinuum = rpacket_get_current_continuum_id (packet);
// Determine in which continuum the bf-absorption occurs
double chi_bf = rpacket_get_chi_boundfree (packet);
double zrand = rk_double (mt_state);
double zrand_x_chibf = zrand * chi_bf;
while ((ccontinuum < storage->no_of_edges - 1) && (packet->chi_bf_tmp_partial[ccontinuum] <= zrand_x_chibf))
{
ccontinuum++;
}
rpacket_set_current_continuum_id (packet, ccontinuum);
/* For consistency reasons the branching between ionization and thermal energy is determined using the
comoving frequency at the initial position instead of the frequency at the point of interaction */
double comov_nu = rpacket_get_nu (packet) * rpacket_doppler_factor (packet, storage);
/* Move the packet to the place of absorption, select a direction for re-emission and impose energy conservation
in the co-moving frame. */
move_packet (packet, storage, distance);
double old_doppler_factor = rpacket_doppler_factor (packet, storage);
rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0);
double inverse_doppler_factor = rpacket_inverse_doppler_factor (packet, storage);
double comov_energy = rpacket_get_energy (packet) * old_doppler_factor;
rpacket_set_energy (packet, comov_energy * inverse_doppler_factor);
storage->last_interaction_type[rpacket_get_id (packet)] = 3; // last interaction was a bf-absorption
storage->last_line_interaction_in_id[rpacket_get_id (packet)] = ccontinuum;
// Convert the rpacket to thermal or ionization energy
zrand = rk_double (mt_state);
int64_t activate_level = (zrand < storage->continuum_list_nu[ccontinuum] / comov_nu) ?
storage->cont_edge2macro_level[ccontinuum] : storage->kpacket2macro_level;
rpacket_set_macro_atom_activation_level (packet, activate_level);
macro_atom (packet, storage, mt_state);
}
void
montecarlo_free_free_scatter (rpacket_t * packet, storage_model_t * storage, double distance, rk_state *mt_state)
{
/* Move the packet to the place of absorption, select a direction for re-emission and impose energy conservation
in the co-moving frame. */
move_packet (packet, storage, distance);
double old_doppler_factor = rpacket_doppler_factor (packet, storage);
rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0);
double inverse_doppler_factor = rpacket_inverse_doppler_factor (packet, storage);
double comov_energy = rpacket_get_energy (packet) * old_doppler_factor;
rpacket_set_energy (packet, comov_energy * inverse_doppler_factor);
storage->last_interaction_type[rpacket_get_id (packet)] = 4; // last interaction was a ff-absorption
// Create a k-packet
rpacket_set_macro_atom_activation_level (packet, storage->kpacket2macro_level);
macro_atom (packet, storage, mt_state);
}
double
sample_nu_free_free (const rpacket_t * packet, const storage_model_t * storage, rk_state *mt_state)
{
int64_t shell_id = rpacket_get_current_shell_id (packet);
double T = storage->t_electrons[shell_id];
double zrand = rk_double (mt_state);
return -KB * T / H * log(zrand); // Lucy 2003 MC II Eq.41
}
double
sample_nu_free_bound (const rpacket_t * packet, const storage_model_t * storage, rk_state *mt_state)
{
int64_t continuum_id = rpacket_get_current_continuum_id (packet);
double th_frequency = storage->continuum_list_nu[continuum_id];
int64_t shell_id = rpacket_get_current_shell_id (packet);
double T = storage->t_electrons[shell_id];
double zrand = rk_double (mt_state);
return th_frequency * (1 - (KB * T / H / th_frequency * log(zrand))); // Lucy 2003 MC II Eq.26
}
void
montecarlo_line_scatter (rpacket_t * packet, storage_model_t * storage,
double distance, rk_state *mt_state)
{
uint64_t next_line_id = rpacket_get_next_line_id (packet);
uint64_t line2d_idx = next_line_id +
storage->no_of_lines * rpacket_get_current_shell_id (packet);
if (rpacket_get_virtual_packet (packet) == 0)
{
increment_j_blue_estimator (packet, storage, distance, line2d_idx);
increment_Edotlu_estimator (packet, storage, distance, line2d_idx);
}
double tau_line =
storage->line_lists_tau_sobolevs[line2d_idx];
double tau_continuum = rpacket_get_chi_continuum(packet) * distance;
double tau_combined = tau_line + tau_continuum;
//rpacket_set_next_line_id (packet, rpacket_get_next_line_id (packet) + 1);
if (next_line_id + 1 == storage->no_of_lines)
{
rpacket_set_last_line (packet, true);
}
if (rpacket_get_virtual_packet (packet) > 0)
{
rpacket_set_tau_event (packet,
rpacket_get_tau_event (packet) + tau_line);
rpacket_set_next_line_id (packet, next_line_id + 1);
test_for_close_line (packet, storage);
}
else if (rpacket_get_tau_event (packet) < tau_combined)
{ // Line absorption occurs
move_packet (packet, storage, distance);
double old_doppler_factor = rpacket_doppler_factor (packet, storage);
rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0);
double inverse_doppler_factor = rpacket_inverse_doppler_factor (packet, storage);
double comov_energy = rpacket_get_energy (packet) * old_doppler_factor;
rpacket_set_energy (packet, comov_energy * inverse_doppler_factor);
storage->last_interaction_in_nu[rpacket_get_id (packet)] =
rpacket_get_nu (packet);
storage->last_line_interaction_in_id[rpacket_get_id (packet)] =
next_line_id;
storage->last_line_interaction_shell_id[rpacket_get_id (packet)] =
rpacket_get_current_shell_id (packet);
storage->last_interaction_type[rpacket_get_id (packet)] = 2;
if (storage->line_interaction_id == 0)
{
line_emission (packet, storage, next_line_id, mt_state);
}
else if (storage->line_interaction_id >= 1)
{
rpacket_set_macro_atom_activation_level (packet,
storage->line2macro_level_upper[next_line_id]);
macro_atom (packet, storage, mt_state);
}
}
else
{ // Packet passes line without interacting
rpacket_set_tau_event (packet,
rpacket_get_tau_event (packet) - tau_line);
rpacket_set_next_line_id (packet, next_line_id + 1);
packet->compute_chi_bf = false;
test_for_close_line (packet, storage);
}
}
void
line_emission (rpacket_t * packet, storage_model_t * storage, int64_t emission_line_id, rk_state *mt_state)
{
double inverse_doppler_factor = rpacket_inverse_doppler_factor (packet, storage);
storage->last_line_interaction_out_id[rpacket_get_id (packet)] = emission_line_id;
if (storage->cont_status == CONTINUUM_ON)
{
storage->last_interaction_out_type[rpacket_get_id (packet)] = 2;
}
rpacket_set_nu (packet,
storage->line_list_nu[emission_line_id] * inverse_doppler_factor);
rpacket_set_nu_line (packet, storage->line_list_nu[emission_line_id]);
rpacket_set_next_line_id (packet, emission_line_id + 1);
rpacket_reset_tau_event (packet, mt_state);
angle_aberration_CMF_to_LF (packet, storage);
if (rpacket_get_virtual_packet_flag (packet) > 0)
{
bool virtual_close_line = false;
if (!rpacket_get_last_line (packet) &&
fabs (storage->line_list_nu[rpacket_get_next_line_id (packet)] -
rpacket_get_nu_line (packet)) <
(rpacket_get_nu_line (packet)* 1e-7))
{
virtual_close_line = true;
}
// QUESTIONABLE!!!
bool old_close_line = rpacket_get_close_line (packet);
rpacket_set_close_line (packet, virtual_close_line);
montecarlo_one_packet (storage, packet, 1, mt_state);
rpacket_set_close_line (packet, old_close_line);
virtual_close_line = false;
}
test_for_close_line (packet, storage);
}
void test_for_close_line (rpacket_t * packet, const storage_model_t * storage)
{
if (!rpacket_get_last_line (packet) &&
fabs (storage->line_list_nu[rpacket_get_next_line_id (packet)] -
rpacket_get_nu_line (packet)) < (rpacket_get_nu_line (packet)*
1e-7))
{
rpacket_set_close_line (packet, true);
}
}
void
continuum_emission (rpacket_t * packet, storage_model_t * storage, rk_state *mt_state,
pt2sample_nu sample_nu_continuum, int64_t emission_type_id)
{
double inverse_doppler_factor = rpacket_inverse_doppler_factor (packet, storage);
double nu_comov = sample_nu_continuum (packet, storage, mt_state);
rpacket_set_nu (packet, nu_comov * inverse_doppler_factor);
rpacket_reset_tau_event (packet, mt_state);
storage->last_interaction_out_type[rpacket_get_id (packet)] = emission_type_id;
// Have to find current position in line list
int64_t current_line_id;
line_search (storage->line_list_nu, nu_comov, storage->no_of_lines, ¤t_line_id);
bool last_line = (current_line_id == storage->no_of_lines);
rpacket_set_last_line (packet, last_line);
rpacket_set_next_line_id (packet, current_line_id);
angle_aberration_CMF_to_LF (packet, storage);
if (rpacket_get_virtual_packet_flag (packet) > 0)
{
montecarlo_one_packet (storage, packet, 1, mt_state);
}
}
static void
montecarlo_compute_distances (rpacket_t * packet, storage_model_t * storage)
{
// Check if the last line was the same nu as the current line.
if (rpacket_get_close_line (packet))
{
// If so set the distance to the line to 0.0
rpacket_set_d_line (packet, 0.0);
// Reset close_line.
rpacket_set_close_line (packet, false);
}
else
{
compute_distance2boundary (packet, storage);
compute_distance2line (packet, storage);
// FIXME MR: return status of compute_distance2line() is ignored
compute_distance2continuum (packet, storage);
}
}
montecarlo_event_handler_t
get_event_handler (rpacket_t * packet, storage_model_t * storage,
double *distance, rk_state *mt_state)
{
montecarlo_compute_distances (packet, storage);
double d_boundary = rpacket_get_d_boundary (packet);
double d_continuum = rpacket_get_d_continuum (packet);
double d_line = rpacket_get_d_line (packet);
montecarlo_event_handler_t handler;
if (d_line <= d_boundary && d_line <= d_continuum)
{
*distance = d_line;
handler = &montecarlo_line_scatter;
}
else if (d_boundary <= d_continuum)
{
*distance = d_boundary;
handler = &move_packet_across_shell_boundary;
}
else
{
*distance = d_continuum;
handler = montecarlo_continuum_event_handler (packet, storage, mt_state);
}
return handler;
}
montecarlo_event_handler_t
montecarlo_continuum_event_handler (rpacket_t * packet, storage_model_t * storage, rk_state *mt_state)
{
if (storage->cont_status)
{
double zrand_x_chi_cont = rk_double (mt_state) * rpacket_get_chi_continuum (packet);
double chi_th = rpacket_get_chi_electron (packet);
double chi_bf = rpacket_get_chi_boundfree (packet);
if (zrand_x_chi_cont < chi_th)
{
return &montecarlo_thomson_scatter;
}
else if (zrand_x_chi_cont < chi_th + chi_bf)
{
return &montecarlo_bound_free_scatter;
}
else
{
return &montecarlo_free_free_scatter;
}
}
else
{
return &montecarlo_thomson_scatter;
}
}
int64_t
montecarlo_one_packet_loop (storage_model_t * storage, rpacket_t * packet,
int64_t virtual_packet, rk_state *mt_state)
{
rpacket_set_tau_event (packet, 0.0);
rpacket_set_nu_line (packet, 0.0);
rpacket_set_virtual_packet (packet, virtual_packet);
rpacket_set_status (packet, TARDIS_PACKET_STATUS_IN_PROCESS);
// Initializing tau_event if it's a real packet.
if (virtual_packet == 0)
{
rpacket_reset_tau_event (packet,mt_state);
}
// For a virtual packet tau_event is the sum of all the tau's that the packet passes.
while (rpacket_get_status (packet) == TARDIS_PACKET_STATUS_IN_PROCESS)
{
// Check if we are at the end of line list.
if (!rpacket_get_last_line (packet))
{
rpacket_set_nu_line (packet,
storage->
line_list_nu[rpacket_get_next_line_id
(packet)]);
}
double distance;
get_event_handler (packet, storage, &distance, mt_state) (packet, storage,
distance, mt_state);
if (virtual_packet > 0 && rpacket_get_tau_event (packet) > storage->tau_russian)
{
double event_random = rk_double (mt_state);
if (event_random > storage->survival_probability)
{
rpacket_set_energy(packet, 0.0);
rpacket_set_status (packet, TARDIS_PACKET_STATUS_EMITTED);
}
else
{
rpacket_set_energy(packet,
rpacket_get_energy (packet) / storage->survival_probability *
exp (-1.0 * rpacket_get_tau_event (packet)));
rpacket_set_tau_event (packet, 0.0);
}
}
}
if (virtual_packet > 0)
{
rpacket_set_energy (packet,
rpacket_get_energy (packet) * exp (-1.0 *
rpacket_get_tau_event
(packet)));
}
return rpacket_get_status (packet) ==
TARDIS_PACKET_STATUS_REABSORBED ? 1 : 0;
}
void
montecarlo_main_loop(storage_model_t * storage, int64_t virtual_packet_flag, int nthreads, unsigned long seed)
{
int64_t finished_packets = 0;
storage->virt_packet_count = 0;
#ifdef WITH_VPACKET_LOGGING
storage->virt_packet_nus = (double *)safe_malloc(sizeof(double) * storage->no_of_packets);
storage->virt_packet_energies = (double *)safe_malloc(sizeof(double) * storage->no_of_packets);
storage->virt_packet_last_interaction_in_nu = (double *)safe_malloc(sizeof(double) * storage->no_of_packets);
storage->virt_packet_last_interaction_type = (int64_t *)safe_malloc(sizeof(int64_t) * storage->no_of_packets);
storage->virt_packet_last_line_interaction_in_id = (int64_t *)safe_malloc(sizeof(int64_t) * storage->no_of_packets);
storage->virt_packet_last_line_interaction_out_id = (int64_t *)safe_malloc(sizeof(int64_t) * storage->no_of_packets);
storage->virt_array_size = storage->no_of_packets;
#endif // WITH_VPACKET_LOGGING
#ifdef WITHOPENMP
omp_set_dynamic(0);
if (nthreads > 0)
{
omp_set_num_threads(nthreads);
}
#pragma omp parallel firstprivate(finished_packets)
{
rk_state mt_state;
rk_seed (seed + omp_get_thread_num(), &mt_state);
#pragma omp master
{
fprintf(stderr, "Running with OpenMP - %d threads\n", omp_get_num_threads());
print_progress(0, storage->no_of_packets);
}
#else
rk_state mt_state;
rk_seed (seed, &mt_state);
fprintf(stderr, "Running without OpenMP\n");
#endif
int64_t chi_bf_tmp_size = (storage->cont_status) ? storage->no_of_edges : 0;
double *chi_bf_tmp_partial = safe_malloc(sizeof(double) * chi_bf_tmp_size);
#pragma omp for
for (int64_t packet_index = 0; packet_index < storage->no_of_packets; ++packet_index)
{
int reabsorbed = 0;
rpacket_t packet;
rpacket_set_id(&packet, packet_index);
rpacket_init(&packet, storage, packet_index, virtual_packet_flag, chi_bf_tmp_partial);
if (virtual_packet_flag > 0)
{
reabsorbed = montecarlo_one_packet(storage, &packet, -1, &mt_state);
}
reabsorbed = montecarlo_one_packet(storage, &packet, 0, &mt_state);
storage->output_nus[packet_index] = rpacket_get_nu(&packet);
if (reabsorbed == 1)
{
storage->output_energies[packet_index] = -rpacket_get_energy(&packet);
}
else
{
storage->output_energies[packet_index] = rpacket_get_energy(&packet);
}
if ( ++finished_packets%100 == 0 )
{
#ifdef WITHOPENMP
// WARNING: This only works with a static sheduler and gives an approximation of progress.
// The alternative would be to have a shared variable but that could potentially decrease performance when using many threads.
if (omp_get_thread_num() == 0 )
print_progress(finished_packets * omp_get_num_threads(), storage->no_of_packets);
#else
print_progress(finished_packets, storage->no_of_packets);
#endif
}
}
free(chi_bf_tmp_partial);
#ifdef WITHOPENMP
}
#endif
print_progress(storage->no_of_packets, storage->no_of_packets);
fprintf(stderr,"\n");
}
|
GB_binop__plus_uint16.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__plus_uint16)
// A.*B function (eWiseMult): GB (_AemultB_08__plus_uint16)
// A.*B function (eWiseMult): GB (_AemultB_02__plus_uint16)
// A.*B function (eWiseMult): GB (_AemultB_04__plus_uint16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__plus_uint16)
// A*D function (colscale): GB (_AxD__plus_uint16)
// D*A function (rowscale): GB (_DxB__plus_uint16)
// C+=B function (dense accum): GB (_Cdense_accumB__plus_uint16)
// C+=b function (dense accum): GB (_Cdense_accumb__plus_uint16)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__plus_uint16)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__plus_uint16)
// C=scalar+B GB (_bind1st__plus_uint16)
// C=scalar+B' GB (_bind1st_tran__plus_uint16)
// C=A+scalar GB (_bind2nd__plus_uint16)
// C=A'+scalar GB (_bind2nd_tran__plus_uint16)
// C type: uint16_t
// A type: uint16_t
// A pattern? 0
// B type: uint16_t
// B pattern? 0
// BinaryOp: cij = (aij + bij)
#define GB_ATYPE \
uint16_t
#define GB_BTYPE \
uint16_t
#define GB_CTYPE \
uint16_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) \
uint16_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) \
uint16_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) \
uint16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x + y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_PLUS || GxB_NO_UINT16 || GxB_NO_PLUS_UINT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__plus_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__plus_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__plus_uint16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__plus_uint16)
(
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 uint16_t
uint16_t bwork = (*((uint16_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__plus_uint16)
(
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
uint16_t *restrict Cx = (uint16_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__plus_uint16)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t *restrict Cx = (uint16_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__plus_uint16)
(
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) ;
uint16_t alpha_scalar ;
uint16_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint16_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__plus_uint16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__plus_uint16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__plus_uint16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__plus_uint16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__plus_uint16)
(
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
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t x = (*((uint16_t *) x_input)) ;
uint16_t *Bx = (uint16_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 ;
uint16_t bij = GBX (Bx, p, false) ;
Cx [p] = (x + bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__plus_uint16)
(
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 ;
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t *Ax = (uint16_t *) Ax_input ;
uint16_t y = (*((uint16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint16_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij + y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x + aij) ; \
}
GrB_Info GB (_bind1st_tran__plus_uint16)
(
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 \
uint16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t x = (*((const uint16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint16_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) \
{ \
uint16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij + y) ; \
}
GrB_Info GB (_bind2nd_tran__plus_uint16)
(
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
uint16_t y = (*((const uint16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
Interp1PrimFifthOrderHCWENO.c | /*! @file Interp1PrimFifthOrderHCWENO.c
@author Debojyoti Ghosh
@brief hybrid compact-WENO5 Scheme (Component-wise application to vectors)
*/
#include <stdio.h>
#include <basic.h>
#include <arrayfunctions.h>
#include <mathfunctions.h>
#include <interpolation.h>
#include <tridiagLU.h>
#include <mpivars.h>
#include <hypar.h>
#ifdef with_omp
#include <omp.h>
#endif
#undef _MINIMUM_GHOSTS_
/*! \def _MINIMUM_GHOSTS_
* Minimum number of ghost points required for this interpolation
* method.
*/
#define _MINIMUM_GHOSTS_ 3
/*! @brief 5th order hybrid compact-WENO reconstruction (component-wise) on a uniform grid
Computes the interpolated values of the first primitive of a function \f${\bf f}\left({\bf u}\right)\f$
at the interfaces from the cell-centered values of the function using the fifth order hybrid compact-WENO scheme on a
uniform grid. The tridiagonal system is solved using tridiagLU() (see also #TridiagLU, tridiagLU.h). See references
below for a complete description of the method implemented here.
\b Implementation \b Notes:
+ This method assumes a uniform grid in the spatial dimension corresponding to the interpolation.
+ The scalar interpolation method is applied to the vector function in a component-wise manner.
+ The WENO weights are computed in WENOFifthOrderCalculateWeights().
+ The function computes the interpolant for the entire grid in one call. It loops over all the grid lines along the interpolation direction
and carries out the 1D interpolation along these grid lines.
+ Location of cell-centers and cell interfaces along the spatial dimension of the interpolation is shown in the following figure:
@image html chap1_1Ddomain.png
@image latex chap1_1Ddomain.eps width=0.9\textwidth
\b Function \b arguments:
Argument | Type | Explanation
--------- | --------- | ---------------------------------------------
fI | double* | Array to hold the computed interpolant at the grid interfaces. This array must have the same layout as the solution, but with \b no \b ghost \b points. Its size should be the same as u in all dimensions, except dir (the dimension along which to interpolate) along which it should be larger by 1 (number of interfaces is 1 more than the number of interior cell centers).
fC | double* | Array with the cell-centered values of the flux function \f${\bf f}\left({\bf u}\right)\f$. This array must have the same layout and size as the solution, \b with \b ghost \b points.
u | double* | The solution array \f${\bf u}\f$ (with ghost points). If the interpolation is characteristic based, this is needed to compute the eigendecomposition. For a multidimensional problem, the layout is as follows: u is a contiguous 1D array of size (nvars*dim[0]*dim[1]*...*dim[D-1]) corresponding to the multi-dimensional solution, with the following ordering - nvars, dim[0], dim[1], ..., dim[D-1], where nvars is the number of solution components (#HyPar::nvars), dim is the local size (#HyPar::dim_local), D is the number of spatial dimensions.
x | double* | The grid array (with ghost points). This is used only by non-uniform-grid interpolation methods. For multidimensional problems, the layout is as follows: x is a contiguous 1D array of size (dim[0]+dim[1]+...+dim[D-1]), with the spatial coordinates along dim[0] stored from 0,...,dim[0]-1, the spatial coordinates along dim[1] stored along dim[0],...,dim[0]+dim[1]-1, and so forth.
upw | int | Upwinding direction: if positive, a left-biased interpolant will be computed; if negative, a right-biased interpolant will be computed. If the interpolation method is central, then this has no effect.
dir | int | Spatial dimension along which to interpolate (eg: 0 for 1D; 0 or 1 for 2D; 0,1 or 2 for 3D)
s | void* | Solver object of type #HyPar: the following variables are needed - #HyPar::ghosts, #HyPar::ndims, #HyPar::nvars, #HyPar::dim_local.
m | void* | MPI object of type #MPIVariables: this is needed only by compact interpolation method that need to solve a global implicit system across MPI ranks.
uflag | int | A flag indicating if the function being interpolated \f${\bf f}\f$ is the solution itself \f${\bf u}\f$ (if 1, \f${\bf f}\left({\bf u}\right) \equiv {\bf u}\f$).
\b Reference:
+ Pirozzoli, S., Conservative Hybrid Compact-WENO Schemes for Shock-Turbulence Interaction, J. Comput. Phys., 178 (1), 2002, pp. 81-117, http://dx.doi.org/10.1006/jcph.2002.7021
+ Ren, Y.-X., Liu, M., Zhang, H., A characteristic-wise hybrid compact-WENO scheme for solving hyperbolic conservation laws, J. Comput. Phys., 192 (2), 2003, pp. 365-386,
http://dx.doi.org/10.1016/j.jcp.2003.07.006
*/
int Interp1PrimFifthOrderHCWENO(
double *fI, /*!< Array of interpolated function values at the interfaces */
double *fC, /*!< Array of cell-centered values of the function \f${\bf f}\left({\bf u}\right)\f$ */
double *u, /*!< Array of cell-centered values of the solution \f${\bf u}\f$ */
double *x, /*!< Grid coordinates */
int upw, /*!< Upwind direction (left or right biased) */
int dir, /*!< Spatial dimension along which to interpolation */
void *s, /*!< Object of type #HyPar containing solver-related variables */
void *m, /*!< Object of type #MPIVariables containing MPI-related variables */
int uflag /*!< Flag to indicate if \f$f(u) \equiv u\f$, i.e, if the solution is being reconstructed */
)
{
HyPar *solver = (HyPar*) s;
MPIVariables *mpi = (MPIVariables*) m;
CompactScheme *compact= (CompactScheme*) solver->compact;
WENOParameters *weno = (WENOParameters*) solver->interp;
TridiagLU *lu = (TridiagLU*) solver->lusolver;
int sys,Nsys,d;
_DECLARE_IERR_;
int ghosts = solver->ghosts;
int ndims = solver->ndims;
int nvars = solver->nvars;
int *dim = solver->dim_local;
/* define some constants */
static const double one_half = 1.0/2.0;
static const double one_third = 1.0/3.0;
static const double one_sixth = 1.0/6.0;
double *ww1, *ww2, *ww3;
ww1 = weno->w1 + (upw < 0 ? 2*weno->size : 0) + (uflag ? weno->size : 0) + weno->offset[dir];
ww2 = weno->w2 + (upw < 0 ? 2*weno->size : 0) + (uflag ? weno->size : 0) + weno->offset[dir];
ww3 = weno->w3 + (upw < 0 ? 2*weno->size : 0) + (uflag ? weno->size : 0) + weno->offset[dir];
/* create index and bounds for the outer loop, i.e., to loop over all 1D lines along
dimension "dir" */
int indexC[ndims], indexI[ndims], index_outer[ndims], bounds_outer[ndims], bounds_inter[ndims];
_ArrayCopy1D_(dim,bounds_outer,ndims); bounds_outer[dir] = 1;
_ArrayCopy1D_(dim,bounds_inter,ndims); bounds_inter[dir] += 1;
int N_outer; _ArrayProduct1D_(bounds_outer,ndims,N_outer);
/* calculate total number of tridiagonal systems to solve */
_ArrayProduct1D_(bounds_outer,ndims,Nsys); Nsys *= nvars;
/* Allocate arrays for tridiagonal system */
double *A = compact->A;
double *B = compact->B;
double *C = compact->C;
double *R = compact->R;
#pragma omp parallel for schedule(auto) default(shared) private(sys,d,index_outer,indexC,indexI)
for (sys=0; sys < N_outer; sys++) {
_ArrayIndexnD_(ndims,sys,bounds_outer,index_outer,0);
_ArrayCopy1D_(index_outer,indexC,ndims);
_ArrayCopy1D_(index_outer,indexI,ndims);
for (indexI[dir] = 0; indexI[dir] < dim[dir]+1; indexI[dir]++) {
int qm1,qm2,qm3,qp1,qp2,p;
_ArrayIndex1D_(ndims,bounds_inter,indexI,0,p);
if (upw > 0) {
indexC[dir] = indexI[dir]-3; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm3);
indexC[dir] = indexI[dir]-2; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm2);
indexC[dir] = indexI[dir]-1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm1);
indexC[dir] = indexI[dir] ; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp1);
indexC[dir] = indexI[dir]+1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp2);
} else {
indexC[dir] = indexI[dir]+2; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm3);
indexC[dir] = indexI[dir]+1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm2);
indexC[dir] = indexI[dir] ; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm1);
indexC[dir] = indexI[dir]-1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp1);
indexC[dir] = indexI[dir]-2; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp2);
}
int v;
for (v=0; v<nvars; v++) {
/* Defining stencil points */
double fm3, fm2, fm1, fp1, fp2;
fm3 = fC[qm3*nvars+v];
fm2 = fC[qm2*nvars+v];
fm1 = fC[qm1*nvars+v];
fp1 = fC[qp1*nvars+v];
fp2 = fC[qp2*nvars+v];
/* Candidate stencils and their optimal weights*/
double f1, f2, f3;
f1 = (2*one_sixth)*fm3 - (7.0*one_sixth)*fm2 + (11.0*one_sixth)*fm1;
f2 = (-one_sixth)*fm2 + (5.0*one_sixth)*fm1 + (2*one_sixth)*fp1;
f3 = (2*one_sixth)*fm1 + (5*one_sixth)*fp1 - (one_sixth)*fp2;
/* calculate WENO weights */
double w1,w2,w3;
w1 = *(ww1+p*nvars+v);
w2 = *(ww2+p*nvars+v);
w3 = *(ww3+p*nvars+v);
/* calculate the hybridization parameter */
double sigma;
if ( ((mpi->ip[dir] == 0 ) && (indexI[dir] == 0 ))
|| ((mpi->ip[dir] == mpi->iproc[dir]-1) && (indexI[dir] == dim[dir])) ) {
/* Standard WENO at physical boundaries */
sigma = 0.0;
} else {
double cuckoo, df_jm12, df_jp12, df_jp32, r_j, r_jp1, r_int;
cuckoo = (0.9*weno->rc / (1.0-0.9*weno->rc)) * weno->xi * weno->xi;
df_jm12 = fm1 - fm2;
df_jp12 = fp1 - fm1;
df_jp32 = fp2 - fp1;
r_j = (absolute(2*df_jp12*df_jm12)+cuckoo)/(df_jp12*df_jp12+df_jm12*df_jm12+cuckoo);
r_jp1 = (absolute(2*df_jp32*df_jp12)+cuckoo)/(df_jp32*df_jp32+df_jp12*df_jp12+cuckoo);
r_int = min(r_j, r_jp1);
sigma = min((r_int/weno->rc), 1.0);
}
if (upw > 0) {
A[sys*nvars+v+Nsys*indexI[dir]] = one_half * sigma;
B[sys*nvars+v+Nsys*indexI[dir]] = 1.0;
C[sys*nvars+v+Nsys*indexI[dir]] = one_sixth * sigma;
} else {
C[sys*nvars+v+Nsys*indexI[dir]] = one_half * sigma;
B[sys*nvars+v+Nsys*indexI[dir]] = 1.0;
A[sys*nvars+v+Nsys*indexI[dir]] = one_sixth * sigma;
}
double fWENO, fCompact;
fWENO = w1*f1 + w2*f2 + w3*f3;
fCompact = one_sixth * (one_third*fm2 + 19.0*one_third*fm1 + 10.0*one_third*fp1);
R[sys*nvars+v+Nsys*indexI[dir]] = sigma*fCompact + (1.0-sigma)*fWENO;
}
}
}
#ifdef serial
/* Solve the tridiagonal system */
IERR tridiagLU(A,B,C,R,dim[dir]+1,Nsys,lu,NULL); CHECKERR(ierr);
#else
/* Solve the tridiagonal system */
/* all processes except the last will solve without the last interface to avoid overlap */
if (mpi->ip[dir] != mpi->iproc[dir]-1) { IERR tridiagLU(A,B,C,R,dim[dir] ,Nsys,lu,&mpi->comm[dir]); CHECKERR(ierr); }
else { IERR tridiagLU(A,B,C,R,dim[dir]+1,Nsys,lu,&mpi->comm[dir]); CHECKERR(ierr); }
/* Now get the solution to the last interface from the next proc */
double *sendbuf = compact->sendbuf;
double *recvbuf = compact->recvbuf;
MPI_Request req[2] = {MPI_REQUEST_NULL,MPI_REQUEST_NULL};
if (mpi->ip[dir]) for (d=0; d<Nsys; d++) sendbuf[d] = R[d];
if (mpi->ip[dir] != mpi->iproc[dir]-1) MPI_Irecv(recvbuf,Nsys,MPI_DOUBLE,mpi->ip[dir]+1,214,mpi->comm[dir],&req[0]);
if (mpi->ip[dir]) MPI_Isend(sendbuf,Nsys,MPI_DOUBLE,mpi->ip[dir]-1,214,mpi->comm[dir],&req[1]);
MPI_Waitall(2,&req[0],MPI_STATUS_IGNORE);
if (mpi->ip[dir] != mpi->iproc[dir]-1) for (d=0; d<Nsys; d++) R[d+Nsys*dim[dir]] = recvbuf[d];
#endif
/* save the solution to fI */
#pragma omp parallel for schedule(auto) default(shared) private(sys,d,index_outer,indexC,indexI)
for (sys=0; sys < N_outer; sys++) {
_ArrayIndexnD_(ndims,sys,bounds_outer,index_outer,0);
_ArrayCopy1D_(index_outer,indexI,ndims);
for (indexI[dir] = 0; indexI[dir] < dim[dir]+1; indexI[dir]++) {
int p; _ArrayIndex1D_(ndims,bounds_inter,indexI,0,p);
_ArrayCopy1D_((R+sys*nvars+Nsys*indexI[dir]),(fI+nvars*p),nvars);
}
}
return(0);
}
|
helloworld.c | #include <stdio.h>
#include <omp.h>
int main()
{
#pragma omp parallel
{
printf("Hello World !\n");
}
return 0;
}
|
bug_nested_proxy_task.c | // RUN: %libomp-compile -lpthread && %libomp-run
// The runtime currently does not get dependency information from GCC.
// UNSUPPORTED: gcc
#include <stdio.h>
#include <omp.h>
#include <pthread.h>
#include "omp_my_sleep.h"
/*
With task dependencies one can generate proxy tasks from an explicit task
being executed by a serial task team. The OpenMP runtime library didn't
expect that and tries to free the explicit task that is the parent of the
proxy task still working in background. It therefore has incomplete children
which triggers a debugging assertion.
*/
// Compiler-generated code (emulation)
typedef long kmp_intptr_t;
typedef int kmp_int32;
typedef char bool;
typedef struct ident {
kmp_int32 reserved_1; /**< might be used in Fortran; see above */
kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags; KMP_IDENT_KMPC identifies this union member */
kmp_int32 reserved_2; /**< not really used in Fortran any more; see above */
#if USE_ITT_BUILD
/* but currently used for storing region-specific ITT */
/* contextual information. */
#endif /* USE_ITT_BUILD */
kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for C++ */
char const *psource; /**< String describing the source location.
The string is composed of semi-colon separated fields which describe the source file,
the function and a pair of line numbers that delimit the construct.
*/
} ident_t;
typedef struct kmp_depend_info {
kmp_intptr_t base_addr;
size_t len;
struct {
bool in:1;
bool out:1;
} flags;
} kmp_depend_info_t;
struct kmp_task;
typedef kmp_int32 (* kmp_routine_entry_t)( kmp_int32, struct kmp_task * );
typedef struct kmp_task { /* GEH: Shouldn't this be aligned somehow? */
void * shareds; /**< pointer to block of pointers to shared vars */
kmp_routine_entry_t routine; /**< pointer to routine to call for executing task */
kmp_int32 part_id; /**< part id for the task */
} kmp_task_t;
#ifdef __cplusplus
extern "C" {
#endif
kmp_int32 __kmpc_global_thread_num ( ident_t * );
kmp_task_t*
__kmpc_omp_task_alloc( ident_t *loc_ref, kmp_int32 gtid, kmp_int32 flags,
size_t sizeof_kmp_task_t, size_t sizeof_shareds,
kmp_routine_entry_t task_entry );
void __kmpc_proxy_task_completed_ooo ( kmp_task_t *ptask );
kmp_int32 __kmpc_omp_task_with_deps ( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * new_task,
kmp_int32 ndeps, kmp_depend_info_t *dep_list,
kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list );
kmp_int32
__kmpc_omp_task( ident_t *loc_ref, kmp_int32 gtid, kmp_task_t * new_task );
#ifdef __cplusplus
}
#endif
void *target(void *task)
{
my_sleep( 0.1 );
__kmpc_proxy_task_completed_ooo((kmp_task_t*) task);
return NULL;
}
pthread_t target_thread;
// User's code
int task_entry(kmp_int32 gtid, kmp_task_t *task)
{
pthread_create(&target_thread, NULL, &target, task);
return 0;
}
int main()
{
int dep;
#pragma omp taskgroup
{
/*
* Corresponds to:
#pragma omp target nowait depend(out: dep)
{
my_sleep( 0.1 );
}
*/
kmp_depend_info_t dep_info;
dep_info.base_addr = (long) &dep;
dep_info.len = sizeof(int);
// out = inout per spec and runtime expects this
dep_info.flags.in = 1;
dep_info.flags.out = 1;
kmp_int32 gtid = __kmpc_global_thread_num(NULL);
kmp_task_t *proxy_task = __kmpc_omp_task_alloc(NULL,gtid,17,sizeof(kmp_task_t),0,&task_entry);
__kmpc_omp_task_with_deps(NULL,gtid,proxy_task,1,&dep_info,0,NULL);
#pragma omp task depend(in: dep)
{
/*
* Corresponds to:
#pragma omp target nowait depend(out: dep)
{
my_sleep( 0.1 );
}
*/
kmp_task_t *nested_proxy_task = __kmpc_omp_task_alloc(NULL,gtid,17,sizeof(kmp_task_t),0,&task_entry);
__kmpc_omp_task(NULL,gtid,nested_proxy_task);
}
}
// only check that it didn't crash
return 0;
}
|
mergesort.c | #include <assert.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define BENCHMARK(name, block)\
do {\
clock_t t1, t2;\
t1 = clock();\
{\
block\
}\
t2 = clock();\
int duration_ms = (((double)t2 - t1) / CLOCKS_PER_SEC) * 1000;\
printf("%s - duration: %d ms\n", name, duration_ms);\
} while(0);
#define BENCHMARK_PARALL(name, block)\
do {\
double t1, t2;\
t1 = omp_get_wtime();\
{\
block\
}\
t2 = omp_get_wtime();\
double duration_ms = (t2 - t1) * 1000;\
printf("%s - duration: %lf ms\n", name, duration_ms);\
} while(0);
int is_ordered(const int *v, int n);
void print_array(int *v, int n);
void populate_array_seq(int *v, int n);
void populate_array_parall(int *v, int n);
void populate_array_parall_better(int *v, int n);
void mergesort_seq(int *v, int a, int b);
void mergesort_parall(int *v, int a, int b, int threads);
void merge(int *v, int a, int b);
#ifdef DEBUG
void test_is_ordered();
void test_merge();
void test_mergesort_seq();
void test_mergesort_parall();
void test_all();
#endif
void merge(int *v, int a, int b) {
/* halves: [a, m) and [m, b) */
int m = a + (b - a)/2;
int n = b - a;
int *tmp = (int*) malloc(n * sizeof(int));
int ti = 0, ai = a, bi = m;
while(ai < m && bi < b) {
tmp[ti++] = (v[ai] < v[bi]) ? v[ai++] : v[bi++];
}
// lower half
while(ai < m) {
tmp[ti++] = v[ai++];
}
// upper half
while(bi < b) {
tmp[ti++] = v[bi++];
}
memcpy(v + a, tmp, n * sizeof(int));
free(tmp);
}
void mergesort_seq(int *v, int a, int b) {
if(b - a <= 1)
return;
int m = a + (b - a)/2;
mergesort_seq(v, a, m);
mergesort_seq(v, m, b);
merge(v, a, b);
}
void mergesort_parall(int *v, int a, int b, int threads) {
if(b - a <= 1)
return;
int m = a + (b - a)/2;
if(threads > 1) {
#pragma omp parallel sections
{
#pragma omp section
mergesort_parall(v, a, m, threads / 2);
#pragma omp section
mergesort_parall(v, m, b, threads - threads / 2);
}
}
else {
mergesort_seq(v, a, m);
mergesort_seq(v, m, b);
}
merge(v, a, b);
}
/* Returns 1 if the n-element array v is ordered, or 0 otherwise. */
int is_ordered(const int *v, int n) {
for(int i = 0; i < n - 1; ++i) {
if(v[i] > v[i+1])
return 0;
}
return 1;
}
void print_array(int *v, int n) {
for(int i = 0; i < n; ++i) {
printf("%d ", v[i]);
}
puts("");
}
void populate_array_seq(int *v, int n) {
for(int i = 0; i < n; ++i) {
v[i] = rand() % n;
}
}
void populate_array_parall(int *v, int n) {
#pragma omp parallel for
for(int i = 0; i < n; ++i) {
v[i] = rand() % n;
}
}
void populate_array_parall_better(int *v, int n) {
unsigned seed;
#pragma omp parallel private(seed)
{
// Those constants were chosen arbitrarily.
seed = 25234 + 17 * omp_get_thread_num();
#pragma omp for
for(int i = 0; i < n; ++i) {
v[i] = rand_r(&seed) % n;
}
}
}
int main(int argc, char *argv[]) {
#ifdef DEBUG
test_all();
#endif
if(argc < 2) {
printf("Usage: %s <k>\n", argv[0]);
printf("Example: %s %d\n", argv[0], 28);
exit(0);
}
/* Size of the sequence: n = 2^k */
const int k = atoi(argv[1]);
const int n = 1 << k;
int *v = (int*) malloc(n * sizeof(int));
srand(time(NULL));
int num_threads;
#pragma omp parallel
{
#pragma omp single
num_threads = omp_get_num_threads();
}
printf("Running with %d threads\n", num_threads);
/*
* Just comment/uncomment the section you don't want/want.
* There are two benchmarks in each one.
*/
/*
* SERIAL VERSION.
*
*/
/*
BENCHMARK("populate_array_seq",
populate_array_seq(v, n);
);
BENCHMARK("megesort_seq",
mergesort_seq(v, 0, n);
);
*/
/*
* PARALLEL VERSION.
*
*/
BENCHMARK_PARALL("populate_array_parall_better",
populate_array_parall_better(v, n);
);
BENCHMARK_PARALL("mergesort_parall",
mergesort_parall(v, 0, n, num_threads);
);
assert(is_ordered(v, n));
free(v);
return 0;
}
#ifdef DEBUG
void test_is_ordered() {
puts("test_is_ordered");
int v[] = {1, 2, 3, 4};
assert(is_ordered(v, 4));
int w[] = {1, 2, 4, 3};
assert(!is_ordered(w, 4));
}
void test_merge() {
puts("test_merge");
int v[] = {3, 4, 1, 2};
merge(v, 0, 4);
assert(is_ordered(v, 4));
int w[] = {1, 2, 3, 4};
merge(w, 0, 4);
assert(is_ordered(w, 4));
}
void test_mergesort_seq() {
puts("test_mergesort_seq");
int v[] = {5, 4, 3, 2, 1};
mergesort_seq(v, 0, 5);
assert(is_ordered(v, 5));
int w[] = {4, 3, 2, 1};
mergesort_seq(w, 0, 4);
assert(is_ordered(w, 4));
int x[] = {1, 2, 3};
mergesort_seq(x, 0, 3);
assert(is_ordered(x, 3));
}
void test_mergesort_parall() {
puts("test_mergesort_parall");
int v[] = {5, 4, 3, 2, 1};
mergesort_parall(v, 0, 5);
assert(is_ordered(v, 5));
int w[] = {4, 3, 2, 1};
mergesort_parall(w, 0, 4);
assert(is_ordered(w, 4));
int x[] = {1, 2, 3};
mergesort_parall(x, 0, 3);
assert(is_ordered(x, 3));
}
void test_all() {
puts("test");
test_is_ordered();
test_merge();
test_mergesort_seq();
test_mergesort_parall();
}
#endif
|
matmul_double.c | /*
* Square matrix multiplication
* A[N][N] * B[N][N] = C[N][N]
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/timeb.h>
#include <malloc.h>
#define N 1024
//#define N 16
// read timer in second
double read_timer() {
struct timeb tm;
ftime(&tm);
return (double) tm.time + (double) tm.millitm / 1000.0;
}
void init(double **A) {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
A[i][j] = (double)rand()/(double)(RAND_MAX/10.0);
}
}
}
void matmul_simd(double **A, double **B, double **C) {
int i,j,k;
double temp;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
temp = 0;
#pragma omp simd reduction(+:temp)
for (k = 0; k < N; k++) {
temp += A[i][k] * B[j][k];
}
C[i][j] = temp;
}
}
}
// Debug functions
void print_matrix(double **matrix) {
for (int i = 0; i<8; i++) {
printf("[");
for (int j = 0; j<8; j++) {
printf("%.2f ", matrix[i][j]);
}
puts("]");
}
puts("");
}
void matmul_serial(double **A, double **B, double **C) {
int i,j,k;
double temp;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
temp = 0;
for (k = 0; k < N; k++) {
temp += A[i][k] * B[j][k];
}
C[i][j] = temp;
}
}
}
double check(double **A, double **B){
double difference = 0;
for(int i = 0;i<N; i++){
for (int j = 0; j<N; j++)
{ difference += A[i][j]- B[i][j];}
}
return difference;
}
// Main
int main(int argc, char *argv[]) {
//Set everything up
double **A = malloc(sizeof(double*)*N);
double **B = malloc(sizeof(double*)*N);
double **C_simd = malloc(sizeof(double*)*N);
double **C_serial = malloc(sizeof(double*)*N);
double **BT = malloc(sizeof(double*)*N);
for (int i = 0; i<N; i++) {
A[i] = malloc(sizeof(double)*N);
B[i] = malloc(sizeof(double)*N);
C_simd[i] = malloc(sizeof(double)*N);
C_serial[i] = malloc(sizeof(double)*N);
BT[i] = malloc(sizeof(double)*N);
}
srand(time(NULL));
init(A);
init(B);
for(int line = 0; line<N; line++){
for(int col = 0; col<N; col++){
BT[line][col] = B[col][line];
}
}
int i;
int num_runs = 20;
//Warming up
matmul_simd(A, BT, C_simd);
matmul_serial(A, BT, C_serial);
double elapsed = 0;
double elapsed1 = read_timer();
for (i=0; i<num_runs; i++)
matmul_simd(A, BT, C_simd);
elapsed += (read_timer() - elapsed1);
double elapsed_serial = 0;
double elapsed_serial1 = read_timer();
for (i=0; i<num_runs; i++)
matmul_serial(A, BT, C_serial);
elapsed_serial += (read_timer() - elapsed_serial1);
print_matrix(A);
print_matrix(BT);
puts("=\n");
print_matrix(C_simd);
puts("---------------------------------");
print_matrix(C_serial);
double gflops_omp = ((((2.0 * N) * N) * N * num_runs) / (1.0e9 * elapsed));
double gflops_serial = ((((2.0 * N) * N) * N * num_runs) / (1.0e9 * elapsed_serial));
printf("======================================================================================================\n");
printf("\tMatrix Multiplication: A[N][N] * B[N][N] = C[N][N], N=%d\n", N);
printf("------------------------------------------------------------------------------------------------------\n");
printf("Performance:\t\tRuntime (s)\t GFLOPS\n");
printf("------------------------------------------------------------------------------------------------------\n");
printf("matmul_omp:\t\t%4f\t%4f\n", elapsed/num_runs, gflops_omp);
printf("matmul_serial:\t\t%4f\t%4f\n", elapsed_serial/num_runs, gflops_serial);
printf("Correctness check: %f\n", check(C_simd,C_serial));
return 0;
}
|
raytracer.h | #pragma once
#include "resource.h"
#include <iostream>
#include <linalg.h>
#include <memory>
#include <omp.h>
#include <random>
using namespace linalg::aliases;
namespace cg::renderer
{
struct ray
{
ray(float3 position, float3 direction) : position(position)
{
this->direction = normalize(direction);
}
float3 position;
float3 direction;
};
struct payload
{
float t;
float3 bary;
cg::color color;
};
template<typename VB>
struct triangle
{
triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c);
float3 a;
float3 b;
float3 c;
float3 ba;
float3 ca;
float3 na;
float3 nb;
float3 nc;
float3 ambient;
float3 diffuse;
float3 emissive;
};
template<typename VB>
inline triangle<VB>::triangle(
const VB& vertex_a, const VB& vertex_b, const VB& vertex_c)
{
a = float3{vertex_a.x, vertex_a.y, vertex_a.z};
b = float3{vertex_b.x, vertex_b.y, vertex_b.z};
c = float3{vertex_c.x, vertex_c.y, vertex_c.z};
ba = b - a;
ca = c - a;
na = float3{vertex_a.nx, vertex_a.ny, vertex_a.nz};
nb = float3{vertex_b.nx, vertex_b.ny, vertex_b.nz};
nc = float3{vertex_c.nx, vertex_c.ny, vertex_c.nz};
ambient = {vertex_a.ambient_r, vertex_a.ambient_g, vertex_a.ambient_b};
diffuse = {vertex_a.diffuse_r, vertex_a.diffuse_g, vertex_a.diffuse_b};
emissive = {vertex_a.emissive_r, vertex_a.emissive_g, vertex_a.emissive_b};
}
template<typename VB>
class aabb
{
public:
void add_triangle(const triangle<VB> triangle);
const std::vector<triangle<VB>>& get_triangles() const;
bool aabb_test(const ray& ray) const;
protected:
std::vector<triangle<VB>> triangles;
float3 aabb_min;
float3 aabb_max;
};
struct light
{
float3 position;
float3 color;
};
template<typename VB, typename RT>
class raytracer
{
public:
raytracer(){};
~raytracer(){};
void set_render_target(std::shared_ptr<resource<RT>> in_render_target);
void clear_render_target(const RT& in_clear_value);
void set_viewport(size_t in_width, size_t in_height);
void set_vertex_buffers(std::vector<std::shared_ptr<cg::resource<VB>>> in_vertex_buffers);
void set_index_buffers(std::vector<std::shared_ptr<cg::resource<unsigned int>>> in_index_buffers);
void build_acceleration_structure();
std::vector<aabb<VB>> acceleration_structures;
void ray_generation(float3 position, float3 direction, float3 right, float3 up, size_t depth, size_t accumulation_num);
payload trace_ray(const ray& ray, size_t depth, float max_t = 1000.f, float min_t = 0.001f) const;
payload intersection_shader(const triangle<VB>& triangle, const ray& ray) const;
std::function<payload(const ray& ray)> miss_shader = nullptr;
std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle, size_t depth)>
closest_hit_shader = nullptr;
std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> any_hit_shader =
nullptr;
float2 get_jitter(int frame_id);
protected:
std::shared_ptr<cg::resource<RT>> render_target;
std::shared_ptr<cg::resource<float3>> history;
std::vector<std::shared_ptr<cg::resource<unsigned int>>> index_buffers;
std::vector<std::shared_ptr<cg::resource<VB>>> vertex_buffers;
size_t width = 1920;
size_t height = 1080;
};
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_render_target(
std::shared_ptr<resource<RT>> in_render_target)
{
render_target = in_render_target;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::clear_render_target(const RT& in_clear_value)
{
for (size_t i = 0; i < width * height; ++i) {
render_target->item(i) = in_clear_value;
if (history) {
history->item(i) = float3{0.0f, 0.0f, 0.0f};// AMGOUS.
}
}
}
template<typename VB, typename RT>
void raytracer<VB, RT>::set_index_buffers(std::vector<std::shared_ptr<cg::resource<unsigned int>>> in_index_buffers)
{
index_buffers = in_index_buffers;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_vertex_buffers(std::vector<std::shared_ptr<cg::resource<VB>>> in_vertex_buffers)
{
vertex_buffers = in_vertex_buffers;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::build_acceleration_structure()
{
for (size_t shape_id = 0; shape_id < index_buffers.size(); ++shape_id) {
auto& index_buffer = index_buffers[shape_id];
auto& vertex_buffer = vertex_buffers[shape_id];
size_t index_id = 0;
aabb<VB> aabb;
while (index_id < index_buffer->get_number_of_elements()) {
triangle<VB> triangle(
vertex_buffer->item(index_buffer->item(index_id++)),
vertex_buffer->item(index_buffer->item(index_id++)),
vertex_buffer->item(index_buffer->item(index_id++)));
aabb.add_triangle(triangle);
}
acceleration_structures.push_back(aabb);
}
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_viewport(size_t in_width, size_t in_height)
{
width = in_width;
height = in_height;
history = std::make_shared<cg::resource<float3>>(width, height);
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::ray_generation(
float3 position, float3 direction,
float3 right, float3 up,
size_t depth, size_t accumulation_num)
{
float frame_weight = 1.0f / static_cast<float>(accumulation_num);
for (size_t frame_id = 0; frame_id < accumulation_num; ++frame_id) {
float2 jitter = get_jitter(static_cast<int>(frame_id));
for (int x = 0; x < static_cast<int>(width); ++x) {
#pragma omp parallel for
for (int y = 0; y < static_cast<int>(height); ++y) {
float u = (2.0f * x + jitter.x) / static_cast<float>(width - 1) - 1.0f;
float v = (2.0f * y + jitter.y) / static_cast<float>(height - 1) - 1.0f;
u *= static_cast<float>(width) / static_cast<float>(height);
float3 ray_direction = direction + u * right - v * up;
ray ray(position, ray_direction);
payload payload = trace_ray(ray, depth);
auto& history_pixel = history->item(x, y);
history_pixel += sqrt(frame_weight * float3{
payload.color.r,
payload.color.g,
payload.color.b,
});
render_target->item(x, y) = RT::from_float3(history_pixel);
}
}
}
}
template<typename VB, typename RT>
inline payload raytracer<VB, RT>::trace_ray(
const ray& ray, size_t depth, float max_t, float min_t) const
{
if (depth == 0) {
return miss_shader(ray);
}
--depth;
payload closest_hit_payload = {};
closest_hit_payload.t = max_t;
const triangle<VB>* closest_triangle = nullptr;
for (auto& aabb: acceleration_structures) {
if (!aabb.aabb_test(ray)) {
continue;
}
for (auto& triangle: aabb.get_triangles()) {
payload payload = intersection_shader(triangle, ray);
if (payload.t > min_t && payload.t < closest_hit_payload.t) {
closest_hit_payload = payload;
closest_triangle = ▵
if (any_hit_shader) {
return any_hit_shader(ray, payload, triangle);
}
}
}
}
if ((closest_hit_payload.t < max_t) && closest_hit_shader) {
return closest_hit_shader(
ray, closest_hit_payload, *closest_triangle, depth);
}
return miss_shader(ray);
}
template<typename VB, typename RT>
inline payload raytracer<VB, RT>::intersection_shader(
const triangle<VB>& triangle, const ray& ray) const
{
payload payload{};
payload.t = -1.0f;
float3 pvec = cross(ray.direction, triangle.ca);
float det = dot(triangle.ba, pvec);
if (-1e-8 < det && det < 1e-8) {
return payload;
}
float inv_det = 1.0f / det;
float3 tvec = ray.position - triangle.a;
float u = dot(tvec, pvec) * inv_det;
if (u < 0.0f || u > 1.0f) {
return payload;
}
float3 qvec = cross(tvec, triangle.ba);
float v = dot(ray.direction, qvec) * inv_det;
if (v < 0.0f || u + v > 1.0f) {
return payload;
}
payload.t = dot(triangle.ca, qvec) * inv_det;
payload.bary = float3{1.0f - u - v, u, v};
return payload;
}
template<typename VB, typename RT>
float2 raytracer<VB, RT>::get_jitter(int frame_id)
{
float2 result{0.0f, 0.0f};
constexpr int base_x = 2;
constexpr float inverted_base_x = 1.0f / base_x;
int index_x = frame_id + 1;
float fraction_x = inverted_base_x;
while (index_x > 0) {
result.x += (index_x % base_x) * fraction_x;
index_x /= base_x;
fraction_x *= inverted_base_x;
}
constexpr int base_y = 3;
constexpr float inverted_base_y = 1.0f / base_y;
int index_y = frame_id + 1;
float fraction_y = inverted_base_y;
while (index_y > 0) {
result.y += (index_y % base_y) * fraction_y;
index_y /= base_y;
fraction_y *= inverted_base_y;
}
return result - 0.5f;
}
template<typename VB>
inline void aabb<VB>::add_triangle(const triangle<VB> triangle)
{
if (triangles.empty()) {
aabb_max = triangle.a;
aabb_min = triangle.a;
}
triangles.push_back(triangle);
aabb_min = min(aabb_min, triangle.a);
aabb_min = min(aabb_min, triangle.b);
aabb_min = min(aabb_min, triangle.c);
aabb_max = max(aabb_max, triangle.a);
aabb_max = max(aabb_max, triangle.b);
aabb_max = max(aabb_max, triangle.c);
}
template<typename VB>
inline const std::vector<triangle<VB>>& aabb<VB>::get_triangles() const
{
return triangles;
}
template<typename VB>
inline bool aabb<VB>::aabb_test(const ray& ray) const
{
float3 inverted_ray_direction = float3(1.0f) / ray.direction;
float3 t0 = (aabb_max - ray.position) * inverted_ray_direction;
float3 t1 = (aabb_min - ray.position) * inverted_ray_direction;
float3 tmax = max(t0, t1);
float3 tmin = min(t0, t1);
return maxelem(tmin) <= minelem(tmax);
}
}// namespace cg::renderer |
stream_omp.c | #include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <sys/time.h>
#include <assert.h>
#include <stdlib.h>
#include <shmem.h>
#ifdef _OPENMP
#include <omp.h>
#endif
// This program will require setting OMP_LIMIT_THREADS for
// correct functioning
#define SHMALIGN 64
#define NTHREADS 2
/*-----------------------------------------------------------------------
* INSTRUCTIONS:
*
* 1) STREAM requires different amounts of memory to run on different
* systems, depending on both the system cache size(s) and the
* granularity of the system timer.
* You should adjust the value of 'STREAM_ARRAY_SIZE' (below)
* to meet *both* of the following criteria:
* (a) Each array must be at least 4 times the size of the
* available cache memory. I don't worry about the difference
* between 10^6 and 2^20, so in practice the minimum array size
* is about 3.8 times the cache size.
* Example 1: One Xeon E3 with 8 MB L3 cache
* STREAM_ARRAY_SIZE should be >= 4 million, giving
* an array size of 30.5 MB and a total memory requirement
* of 91.5 MB.
* Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP)
* STREAM_ARRAY_SIZE should be >= 20 million, giving
* an array size of 153 MB and a total memory requirement
* of 458 MB.
* (b) The size should be large enough so that the 'timing calibration'
* output by the program is at least 20 clock-ticks.
* Example: most versions of Windows have a 10 millisecond timer
* granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds.
* If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec.
* This means the each array must be at least 1 GB, or 128M elements.
* CULLED change reports...SEE ABOVE
*/
#ifndef STREAM_ARRAY_SIZE
//#define STREAM_ARRAY_SIZE 10000000
#define STREAM_ARRAY_SIZE 8388608
#endif
#ifndef MIN
#define MIN(x,y) ((x)<(y)?(x):(y))
#endif
#ifndef MAX
#define MAX(x,y) ((x)>(y)?(x):(y))
#endif
/* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result
* for any iteration after the first, therefore the minimum value
* for NTIMES is 2.
* There are no rules on maximum allowable values for NTIMES, but
* values larger than the default are unlikely to noticeably
* increase the reported performance.
* NTIMES can also be set on the compile line without changing the source
* code using, for example, "-DNTIMES=7".
*/
#ifdef NTIMES
#if NTIMES<=1
#define NTIMES 10
#endif
#endif
#ifndef NTIMES
#define NTIMES 10
#endif
/* Users are allowed to modify the "OFFSET" variable, which *may* change the
* relative alignment of the arrays (though compilers may change the
* effective offset by making the arrays non-contiguous on some systems).
* Use of non-zero values for OFFSET can be especially helpful if the
* STREAM_ARRAY_SIZE is set to a value close to a large power of 2.
* OFFSET can also be set on the compile line without changing the source
* code using, for example, "-DOFFSET=56".
*/
#ifndef OFFSET
#define OFFSET 0
#endif
/*
* 3) Compile the code with optimization. Many compilers generate
* unreasonably bad code before the optimizer tightens things up.
* If the results are unreasonably good, on the other hand, the
* optimizer might be too smart for me!
*
* For a simple single-core version, try compiling with:
* cc -O stream.c -o stream
* This is known to work on many, many systems....
*
* To use multiple cores, you need to tell the compiler to obey the OpenMP
* directives in the code. This varies by compiler, but a common example is
* gcc -O -fopenmp stream.c -o stream_omp
* The environment variable OMP_NUM_THREADS allows runtime control of the
* number of threads/cores used when the resulting "stream_omp" program
* is executed.
*
* To run with single-precision variables and arithmetic, simply add
* -DSTREAM_TYPE=float
* to the compile line.
* Note that this changes the minimum array sizes required --- see (1) above.
*
* The preprocessor directive "TUNED" does not do much -- it simply causes the
* code to call separate functions to execute each kernel. Trivial versions
* of these functions are provided, but they are *not* tuned -- they just
* provide predefined interfaces to be replaced with tuned code.
*
*
* 4) Optional: Mail the results to mccalpin@cs.virginia.edu
* Be sure to include info that will help me understand:
* a) the computer hardware configuration (e.g., processor model, memory type)
* b) the compiler name/version and compilation flags
* c) any run-time information (such as OMP_NUM_THREADS)
* d) all of the output from the test case.
*
* Thanks!
*
*-----------------------------------------------------------------------*/
#define HLINE "-------------------------------------------------------------\n"
#ifndef STREAM_TYPE
#define STREAM_TYPE double
#endif
/* SHMEM global variables */
int _world_rank, _world_size;
long pSync0[_SHMEM_COLLECT_SYNC_SIZE], pSync1[_SHMEM_COLLECT_SYNC_SIZE],
pSync2[_SHMEM_COLLECT_SYNC_SIZE];
double pWrk0[_SHMEM_REDUCE_MIN_WRKDATA_SIZE],
pWrk1[_SHMEM_REDUCE_MIN_WRKDATA_SIZE],
pWrk2[_SHMEM_REDUCE_MIN_WRKDATA_SIZE];
double time_start, time_end, total_clock_time, max_clock_time, min_clock_time,
clock_time_PE;
// global counter, perform fadd against this var
int gcounter = 0;
// process local counters
int count_p = 0, next_p = 0;
#define ROOT 1 // root rank, typically used as FOP target
/* SHMEM global variables */
// we shmalloc the arrays because shmem_ptr implementation
// in openshmem is incomplete
//static STREAM_TYPE a[STREAM_ARRAY_SIZE + OFFSET],
// b[STREAM_ARRAY_SIZE + OFFSET], c[STREAM_ARRAY_SIZE + OFFSET];
/*
* PE start, stride, size is assumed to be 0,0 and
* world_size is power of 2
*/
#define REDUCE_ADD(source, target) target += source
#define REDUCE_MAX(source, target) MAX(target, source)
#define REDUCE_MIN(source, target) MIN(target, source)
// we know there will be overlap, so hardcoding
// check shmem_x_reduce under openshmem/reduce
#if 0
void
flat_tree (STREAM_TYPE * target, STREAM_TYPE * source, int nreduce)
{
STREAM_TYPE *tmptrg;
STREAM_TYPE *write_to;
/* use temp target in case source/target overlap/same */
tmptrg = (STREAM_TYPE *) malloc (nreduce * sizeof (STREAM_TYPE));
write_to = tmptrg;
for (int j = 0; j < nreduce; j += 1)
{
write_to[j] = source[j];
}
shmem_barrier_all ();
// only one PE needs to access this section
if (_world_rank == 0)
{
/* First, finish gathering */
for (int n = 0; n < _world_size; n++)
{
shmem_getmem (tmptrg, source, nreduce * sizeof (STREAM_TYPE), n);
/* Compute max */
for (int k = 0; k < nreduce; k++)
{
write_to[k] = REDUCE_MAX (write_to[k], source[k]);
}
}
/* Then, broadcast results */
for (int n = 0; n < _world_size; n++)
{
shmem_putmem (target, tmptrg, nreduce * sizeof (STREAM_TYPE), n);
}
}
shmem_barrier_all ();
free (tmptrg);
tmptrg = NULL;
return;
}
#endif //first working version
#if 0
void
flat_tree (STREAM_TYPE * target, STREAM_TYPE * source, int nreduce)
{
STREAM_TYPE *tmptrg;
tmptrg = (STREAM_TYPE *) malloc (nreduce * sizeof (STREAM_TYPE));
// only one PE needs to access this section
if (_world_rank == 0)
{
/* First, finish gathering */
for (int n = 0; n < _world_size; n++)
{
shmem_getmem (tmptrg, source, nreduce * sizeof (STREAM_TYPE), n);
/* Compute max */
for (int k = 0; k < nreduce; k++)
{
tmptrg[k] = REDUCE_MAX (tmptrg[k], source[k]);
}
}
/* Then, broadcast results */
for (int n = 0; n < _world_size; n++)
{
shmem_putmem (target, tmptrg, nreduce * sizeof (STREAM_TYPE), n);
}
}
shmem_barrier_all ();
free (tmptrg);
return;
}
#endif //second working version
void
flat_tree (STREAM_TYPE * target, STREAM_TYPE * source, int nreduce)
{
/* Consider the root to be PE #0 */
if (_world_rank == 0)
{
/* First, finish gathering */
for (int n = 0; n < _world_size; n++)
{
STREAM_TYPE *ptr = (STREAM_TYPE *) shmem_ptr (source, n);
/* Compute max */
#ifdef __INTEL_COMPILER
#pragma vector aligned
#pragma ivdep
#endif
for (int k = 0; k < nreduce; k++)
{
source[k] = REDUCE_MAX (ptr[k], source[k]);
}
}
/* Then, broadcast results */
#ifdef __INTEL_COMPILER
#pragma vector aligned
#pragma ivdep
#endif
for (int n = 0; n < _world_size; n++)
{
STREAM_TYPE *ptr = (STREAM_TYPE *) shmem_ptr (target, n);
for (int k = 0; k < nreduce; k++)
{
ptr[k] = source[k];
}
}
}
shmem_barrier_all ();
return;
}
double times[4][NTIMES];
static double avgtime[4] = { 0 }, maxtime[4] =
{
0}, mintime[4] =
{
FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX};
static char *label[4] = { "Copy: ", "Scale: ",
"Add: ", "Triad: "
};
static double bytes[4] = {
2 * sizeof (STREAM_TYPE) * STREAM_ARRAY_SIZE,
2 * sizeof (STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof (STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof (STREAM_TYPE) * STREAM_ARRAY_SIZE
};
//static STREAM_TYPE a[STREAM_ARRAY_SIZE + OFFSET],
// b[STREAM_ARRAY_SIZE + OFFSET], c[STREAM_ARRAY_SIZE + OFFSET];
extern void checkSTREAMresults (STREAM_TYPE * a, STREAM_TYPE * b,
STREAM_TYPE * c);
extern double mysecond ();
int
main ()
{
int quantum = -1, checktick ();
int BytesPerWord;
int k;
ssize_t j, i;
STREAM_TYPE scalar;
/* --- SETUP --- determine precision and check timing --- */
printf (HLINE);
printf ("STREAM version $Revision: 5.10 $\n");
printf (HLINE);
BytesPerWord = sizeof (STREAM_TYPE);
printf ("This system uses %d bytes per array element.\n", BytesPerWord);
/* SHMEM initialize */
start_pes (0);
_world_size = _num_pes ();
_world_rank = _my_pe ();
STREAM_TYPE *a =
(STREAM_TYPE *) shmemalign (SHMALIGN, (STREAM_ARRAY_SIZE + OFFSET) *
sizeof (STREAM_TYPE));
STREAM_TYPE *b =
(STREAM_TYPE *) shmemalign (SHMALIGN, (STREAM_ARRAY_SIZE + OFFSET) *
sizeof (STREAM_TYPE));
STREAM_TYPE *c =
(STREAM_TYPE *) shmemalign (SHMALIGN, (STREAM_ARRAY_SIZE + OFFSET) *
sizeof (STREAM_TYPE));
/* wait for user to input runtime params */
for (int j = 0; j < _SHMEM_BARRIER_SYNC_SIZE; j++)
{
pSync0[j] = pSync1[j] = pSync2[j] = _SHMEM_SYNC_VALUE;
}
int size = _world_size;
if (!(size == 0) && !(size & (size - 1)))
;
else
{
printf ("Program only works for a PE size of power-of-2\n");
exit (-1);
}
if (_world_rank == 0)
{
printf (HLINE);
#ifdef N
printf ("***** WARNING: ******\n");
printf
(" It appears that you set the preprocessor variable N when compiling this code.\n");
printf
(" This version of the code uses the preprocesor variable STREAM_ARRAY_SIZE to control the array size\n");
printf (" Reverting to default value of STREAM_ARRAY_SIZE=%llu\n",
(unsigned long long) STREAM_ARRAY_SIZE);
printf ("***** WARNING: ******\n");
#endif
printf ("Array size = %llu (elements), Offset = %d (elements)\n",
(unsigned long long) STREAM_ARRAY_SIZE, OFFSET);
printf ("Memory per array = %.1f MiB (= %.1f GiB).\n",
BytesPerWord * ((double) STREAM_ARRAY_SIZE / 1024.0 / 1024.0),
BytesPerWord * ((double) STREAM_ARRAY_SIZE / 1024.0 / 1024.0 /
1024.0));
printf ("Total memory required = %.1f MiB (= %.1f GiB).\n",
(3.0 * BytesPerWord) * ((double) STREAM_ARRAY_SIZE / 1024.0 /
1024.),
(3.0 * BytesPerWord) * ((double) STREAM_ARRAY_SIZE / 1024.0 /
1024. / 1024.));
printf ("Each kernel will be executed %d times.\n", NTIMES);
printf
(" The *best* time for each kernel (excluding the first iteration)\n");
printf (" will be used to compute the reported bandwidth.\n");
printf ("Number of SHMEM PEs requested = %i\n", _world_size);
}
//int blocksize = 10000;
//int blocksize = 8192;
int blocksize = 16384;
assert (STREAM_ARRAY_SIZE % blocksize == 0);
// do something really minor
/* Get initial value for system clock. */
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
{
a[j] = 1.0;
b[j] = 2.0;
c[j] = 0.0;
}
printf (HLINE);
if (_world_rank == 0)
{
if ((quantum = checktick ()) >= 1)
printf ("Your clock granularity/precision appears to be "
"%d microseconds.\n", quantum);
else
{
printf ("Your clock granularity appears to be "
"less than one microsecond.\n");
quantum = 1;
}
}
shmem_barrier_all ();
// assign fixed iterations per PE
// since we know default STREAM array size
// we are hardcoding this, but if the value
// changes, then this blocking factor must
// also change
// basically, each PE works on this block
// size at a time
time_start = mysecond ();
/* Initialize */
next_p = shmem_int_fadd (&gcounter, 1, ROOT);
for (j = 0; j < STREAM_ARRAY_SIZE; j += blocksize)
{
if (next_p == count_p)
{
for (i = j; i < (j + blocksize); i++)
{
a[i] = 2.0E0 * a[i];
}
next_p = shmem_int_fadd (&gcounter, 1, ROOT);
}
count_p++;
}
time_end = mysecond ();
clock_time_PE = time_end - time_start;
shmem_double_sum_to_all (&total_clock_time, &clock_time_PE, 1,
0, 0, _world_size, pWrk0, pSync0);
if (_world_rank == 0)
{
printf ("Each test below will take on the order"
" of %d microseconds.\n", (int) (total_clock_time * 1.0E6));
printf (" (= %d clock ticks)\n",
(int) ((1.0E6 * total_clock_time) / quantum));
printf ("Increase the size of the arrays if this shows that\n");
printf ("you are not getting at least 20 clock ticks per test.\n");
printf (HLINE);
printf ("WARNING -- The above is only a rough guideline.\n");
printf ("For best results, please be sure you know the\n");
printf ("precision of your system timer.\n");
printf (HLINE);
}
/* --- MAIN LOOP --- repeat test cases NTIMES times --- */
// reduction required, as each PE only fills a,b,c partially
scalar = 3.0;
for (k = 0; k < NTIMES; k++)
{
#ifdef __INTEL_COMPILER
__assume (blocksize % 64 == 0);
__assume (j % 64 == 0);
#endif
#ifdef __INTEL_COMPILER
#pragma novector
#endif
for (j = 0; j < STREAM_ARRAY_SIZE; j += blocksize)
{
if (next_p == count_p)
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(NTHREADS)
#endif
#ifdef __INTEL_COMPILER
#pragma vector aligned
#pragma ivdep
#endif
for (i = j; i < (j + blocksize); i++)
{
a[i] = 1.0;
b[i] = 2.0;
c[i] = 0.0;
a[i] = 2.0E0 * a[i];
}
next_p = shmem_int_fadd (&gcounter, 1, ROOT);
}
count_p++;
//shmem_double_max_to_all (a + j, a + j, blocksize, 0,
// 0, _world_size, pWrk1, pSync1);
shmem_barrier_all ();
flat_tree (a + j, a + j, blocksize);
}
shmem_barrier_all ();
time_start = mysecond ();
#ifdef __INTEL_COMPILER
#pragma novector
#endif
for (j = 0; j < STREAM_ARRAY_SIZE; j += blocksize)
{
if (next_p == count_p)
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(NTHREADS)
#endif
#ifdef __INTEL_COMPILER
#pragma vector aligned
#pragma ivdep
#endif
for (i = j; i < (j + blocksize); i++)
{
c[i] = a[i];
}
next_p = shmem_int_fadd (&gcounter, 1, ROOT);
}
count_p++;
//shmem_double_max_to_all (c + j, c + j, blocksize, 0,
// 0, _world_size, pWrk1, pSync1);
shmem_barrier_all ();
flat_tree (c + j, c + j, blocksize);
}
time_end = mysecond () - time_start;
shmem_double_max_to_all (×[0][k], &time_end, 1,
0, 0, _world_size, pWrk0, pSync0);
time_start = mysecond ();
#ifdef __INTEL_COMPILER
#pragma novector
#endif
for (j = 0; j < STREAM_ARRAY_SIZE; j += blocksize)
{
if (next_p == count_p)
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(NTHREADS)
#endif
#ifdef __INTEL_COMPILER
#pragma vector aligned
#pragma ivdep
#endif
for (i = j; i < (j + blocksize); i++)
{
b[i] = scalar * c[i];
}
next_p = shmem_int_fadd (&gcounter, 1, ROOT);
}
count_p++;
//shmem_double_max_to_all (b + j, b + j, blocksize, 0,
// 0, _world_size, pWrk1, pSync1);
shmem_barrier_all ();
flat_tree (b + j, b + j, blocksize);
}
time_end = mysecond () - time_start;
shmem_double_sum_to_all (×[1][k], &time_end, 1,
0, 0, _world_size, pWrk0, pSync0);
time_start = mysecond ();
#ifdef __INTEL_COMPILER
#pragma novector
#endif
for (j = 0; j < STREAM_ARRAY_SIZE; j += blocksize)
{
if (next_p == count_p)
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(NTHREADS)
#endif
#ifdef __INTEL_COMPILER
#pragma vector aligned
#pragma ivdep
#endif
for (i = j; i < (j + blocksize); i++)
{
c[i] = a[i] + b[i];
}
next_p = shmem_int_fadd (&gcounter, 1, ROOT);
}
count_p++;
//shmem_double_max_to_all (c + j, c + j, blocksize, 0,
// 0, _world_size, pWrk1, pSync1);
shmem_barrier_all ();
flat_tree (c + j, c + j, blocksize);
}
time_end = mysecond () - time_start;
shmem_double_sum_to_all (×[2][k], &time_end, 1,
0, 0, _world_size, pWrk0, pSync0);
time_start = mysecond ();
#ifdef __INTEL_COMPILER
#pragma novector
#endif
for (j = 0; j < STREAM_ARRAY_SIZE; j += blocksize)
{
if (next_p == count_p)
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(NTHREADS)
#endif
#ifdef __INTEL_COMPILER
#pragma vector aligned
#pragma ivdep
#endif
for (i = j; i < (j + blocksize); i++)
{
a[i] = b[i] + scalar * c[i];
}
next_p = shmem_int_fadd (&gcounter, 1, ROOT);
}
count_p++;
//shmem_double_max_to_all (a + j, a + j, blocksize, 0,
// 0, _world_size, pWrk1, pSync1);
shmem_barrier_all ();
flat_tree (a + j, a + j, blocksize);
}
time_end = mysecond () - time_start;
shmem_double_sum_to_all (×[3][k], &time_end, 1,
0, 0, _world_size, pWrk0, pSync0);
} // end of NTIMES iteration
shmem_barrier_all ();
/* --- SUMMARY --- */
for (k = 1; k < NTIMES; k++) /* note -- skip first iteration */
{
for (j = 0; j < 4; j++)
{
avgtime[j] = avgtime[j] + times[j][k];
mintime[j] = MIN (mintime[j], times[j][k]);
maxtime[j] = MAX (maxtime[j], times[j][k]);
}
}
if (_world_rank == 0)
{
printf
("Function Best Rate MB/s Avg time Min time Max time\n");
for (j = 0; j < 4; j++)
{
avgtime[j] = avgtime[j] / (double) (NTIMES - 1);
printf ("%s%12.1f %11.6f %11.6f %11.6f\n", label[j],
1.0E-06 * bytes[j] / mintime[j],
avgtime[j], mintime[j], maxtime[j]);
}
printf (HLINE);
}
/* --- Check Results --- */
if (_world_rank == 0)
{
checkSTREAMresults (a, b, c);
printf (HLINE);
}
shfree (a);
shfree (b);
shfree (c);
return 0;
}
#define M 20
int
checktick ()
{
int i, minDelta, Delta;
double t1, t2, timesfound[M];
/* Collect a sequence of M unique time values from the system. */
for (i = 0; i < M; i++)
{
t1 = mysecond ();
while (((t2 = mysecond ()) - t1) < 1.0E-6)
;
timesfound[i] = t1 = t2;
}
/*
* Determine the minimum difference between these M values.
* This result will be our estimate (in microseconds) for the
* clock granularity.
*/
minDelta = 1000000;
for (i = 1; i < M; i++)
{
Delta = (int) (1.0E6 * (timesfound[i] - timesfound[i - 1]));
minDelta = MIN (minDelta, MAX (Delta, 0));
}
return (minDelta);
}
/* A gettimeofday routine to give access to the wall
clock timer on most UNIX-like systems. */
#include <sys/time.h>
double
mysecond ()
{
struct timeval tp;
gettimeofday (&tp, NULL);
return ((double) tp.tv_sec + (double) tp.tv_usec * 1.e-6);
}
#ifndef abs
#define abs(a) ((a) >= 0 ? (a) : -(a))
#endif
void
checkSTREAMresults (STREAM_TYPE * a, STREAM_TYPE * b, STREAM_TYPE * c)
{
STREAM_TYPE aj, bj, cj, scalar;
STREAM_TYPE aSumErr, bSumErr, cSumErr;
STREAM_TYPE aAvgErr, bAvgErr, cAvgErr;
double epsilon;
ssize_t j;
int k, ierr, err;
/* reproduce initialization */
aj = 1.0;
bj = 2.0;
cj = 0.0;
/* a[] is modified during timing check */
aj = 2.0E0 * aj;
/* now execute timing loop */
scalar = 3.0;
for (k = 0; k < NTIMES; k++)
{
cj = aj;
bj = scalar * cj;
cj = aj + bj;
aj = bj + scalar * cj;
}
/* accumulate deltas between observed and expected results */
aSumErr = 0.0;
bSumErr = 0.0;
cSumErr = 0.0;
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
{
aSumErr += abs (a[j] - aj);
bSumErr += abs (b[j] - bj);
cSumErr += abs (c[j] - cj);
// if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN
}
aAvgErr = aSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
bAvgErr = bSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
cAvgErr = cSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
if (sizeof (STREAM_TYPE) == 4)
{
epsilon = 1.e-6;
}
else if (sizeof (STREAM_TYPE) == 8)
{
epsilon = 1.e-13;
}
else
{
printf ("WEIRD: sizeof(STREAM_TYPE) = %lu\n", sizeof (STREAM_TYPE));
epsilon = 1.e-6;
}
err = 0;
if (abs (aAvgErr / aj) > epsilon)
{
err++;
printf
("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",
epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",
aj, aAvgErr, abs (aAvgErr) / aj);
ierr = 0;
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
{
if (abs (a[j] / aj - 1.0) > epsilon)
{
ierr++;
#ifdef VERBOSE
if (ierr < 10)
{
printf
(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j, aj, a[j], abs ((aj - a[j]) / aAvgErr));
}
#endif
}
}
printf (" For array a[], %d errors were found.\n", ierr);
}
if (abs (bAvgErr / bj) > epsilon)
{
err++;
printf
("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",
epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",
bj, bAvgErr, abs (bAvgErr) / bj);
printf (" AvgRelAbsErr > Epsilon (%e)\n", epsilon);
ierr = 0;
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
{
if (abs (b[j] / bj - 1.0) > epsilon)
{
ierr++;
#ifdef VERBOSE
if (ierr < 10)
{
printf
(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j, bj, b[j], abs ((bj - b[j]) / bAvgErr));
}
#endif
}
}
printf (" For array b[], %d errors were found.\n", ierr);
}
if (abs (cAvgErr / cj) > epsilon)
{
err++;
printf
("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",
epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",
cj, cAvgErr, abs (cAvgErr) / cj);
printf (" AvgRelAbsErr > Epsilon (%e)\n", epsilon);
ierr = 0;
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
{
if (abs (c[j] / cj - 1.0) > epsilon)
{
ierr++;
#ifdef VERBOSE
if (ierr < 10)
{
printf
(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j, cj, c[j], abs ((cj - c[j]) / cAvgErr));
}
#endif
}
}
printf (" For array c[], %d errors were found.\n", ierr);
}
if (err == 0)
{
printf
("Solution Validates: avg error less than %e on all three arrays\n",
epsilon);
}
#ifdef VERBOSE
printf ("Results Validation Verbose Results: \n");
printf (" Expected a(1), b(1), c(1): %f %f %f \n", aj, bj, cj);
printf (" Observed a(1), b(1), c(1): %f %f %f \n", a[1], b[1], c[1]);
printf (" Rel Errors on a, b, c: %e %e %e \n", abs (aAvgErr / aj),
abs (bAvgErr / bj), abs (cAvgErr / cj));
#endif
}
|
A_comp.c |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "MBIRModularDefs.h"
#include "MBIRModularUtils.h"
#include "allocate.h"
#include "initialize.h"
#include "A_comp.h"
#ifndef MSVC /* not included in MS Visual C++ */
#include <sys/time.h>
#endif
/* Pixel profile params */
#define WIDE_BEAM /* Finite element analysis of detector channel, accounts for sensitivity variation across its aperture */
#define LEN_PIX 511 /* determines the spatial resolution for Detector-Pixel computation. Higher LEN_PIX, higher resolution */
/* In this implementation, spatial resolution is : [2*PixelDimension/LEN_PIX]^(-1) */
#define LEN_DET 101 /* Each detector channel is "split" into LEN_DET sub-elements ... */
/* to account for detector sensitivity variation across its aperture */
/******************************************************************/
/* Compute line segment lengths through a pixel for the given set */
/* of sinogram angles and for multiple displacements (LEN_PIX) */
/******************************************************************/
/* Fill profiles of pixels from all angles
ONLY FOR SQUARE PIXELS NOW
Each profile assumed 2 pixels wide
This is used to speed calculation (too many to store) of the
entries of the projection matrix.
Values are scaled by "scale"
*/
/* The System matrix does not vary with slice for 3-D Parallel Geometry */
/* So, the method of compuatation is same as that of 2-D Parallel Geometry */
float **ComputePixelProfile3DParallel(
struct SinoParams3DParallel *sinoparams,
struct ImageParams3D *imgparams)
{
int i, j;
float pi, ang, d1, d2, t, t_1, t_2, t_3, t_4, maxval, rc;
float **pix_prof ; /* Detector-pixel profile, indexed by view angle and detector-pixel displacement */
pix_prof = (float **)get_img(LEN_PIX, sinoparams->NViews, sizeof(float));
pi = PI;
rc = sin(pi/4.0);
/* Compute 3 parameters of the profile function */
/* Here the corresponding parameters are : maxval, d1 and d2 */
for (i = 0; i < sinoparams->NViews; i++)
{
ang = sinoparams->ViewAngles[i];
while(ang >= pi/2.0)
ang -= pi/2.0;
while(ang < 0.0)
ang += pi/2.0;
if (ang <= pi/4.0)
maxval = imgparams->Deltaxy/cos(ang);
else
maxval = imgparams->Deltaxy/cos(pi/2.0-ang);
d1 = rc*cos(pi/4.0-ang);
d2 = rc*fabs(sin(pi/4.0-ang));
t_1 = 1.0 - d1;
t_2 = 1.0 - d2;
t_3 = 1.0 + d2;
t_4 = 1.0 + d1;
/* Profile is a trapezoidal function of detector-pixel displacement*/
for (j = 0; j < LEN_PIX; j++)
{
t = 2.0*j/(float)LEN_PIX;
if(t <= t_1 || t > t_4)
pix_prof[i][j] = 0.0;
else if(t <= t_2)
pix_prof[i][j] = maxval*(t-t_1)/(t_2-t_1);
else if(t <= t_3)
pix_prof[i][j] = maxval;
else
pix_prof[i][j] = maxval*(t_4-t)/(t_4-t_3);
}
}
return pix_prof;
}
/* Compute the System Matrix column for a given pixel */
void A_comp_ij(
int im_row,
int im_col,
struct SinoParams3DParallel *sinoparams,
struct ImageParams3D *imgparams,
float **pix_prof,
struct ACol *A_col,float *A_Values)
{
static int first_call=1;
static float dprof[LEN_DET];
float t_0, x_0, y_0;
int i, k, pr, ind_min, ind_max, pix_prof_ind, proj_count;
float Aval, t_min, t_max, ang, x, y;
float t, const1, const2, const3, const4;
float Deltaxy = imgparams->Deltaxy;
int NChannels = sinoparams->NChannels;
float DeltaChannel = sinoparams->DeltaChannel;
if (first_call == 1)
{
first_call = 0;
/* delta profile */
/*
for(k=0;k<LEN_DET;k++)
dprof[k] =0;
dprof[(LEN_DET-1)/2]=1.0;
*/
/* square profile */
for (k = 0; k < LEN_DET; k++)
dprof[k] = 1.0/(LEN_DET);
/* triangular profile */
/*
float sum=0;
for(k=0;k<LEN_DET;k++)
{
if(k<=(LEN_DET-1)/2)
dprof[k]=2.0*k/(LEN_DET-1);
else
dprof[k]=2.0*(LEN_DET-1-k)/(LEN_DET-1);
sum += dprof[k];
}
for(k=0;k<LEN_DET;k++)
dprof[k] /= sum;
*/
}
/* WATCH THIS; ONLY FOR SQUARE PIXELS NOW */
t_0 = -(NChannels-1)*DeltaChannel/2.0 - sinoparams->CenterOffset * DeltaChannel;
x_0 = -(imgparams->Nx-1)*Deltaxy/2.0;
y_0 = -(imgparams->Ny-1)*Deltaxy/2.0;
y = y_0 + im_row*Deltaxy;
x = x_0 + im_col*Deltaxy;
proj_count = 0;
for (pr = 0; pr < sinoparams->NViews; pr++)
{
int countTemp=proj_count;
int write=1;
int minCount=0;
ang = sinoparams->ViewAngles[pr];
/* range for pixel profile. Need profile to contain 2 pixel widths */
t_min = y*cos(ang) - x*sin(ang) - Deltaxy;
t_max = t_min + 2.0*Deltaxy;
/* Relevant detector indices */
ind_min = ceil((t_min-t_0)/DeltaChannel - 0.5);
ind_max= floor((t_max-t_0)/DeltaChannel + 0.5);
/* move on if voxel clearly out of range of detectors */
if(ind_max<0 || ind_min>NChannels-1)
{
A_col->countTheta[pr]=0;
A_col->minIndex[pr]=0;
continue;
}
/* Fix this 4/91 to prevent over-reach at ends */
ind_min = (ind_min<0) ? 0 : ind_min;
ind_max = (ind_max>=NChannels) ? NChannels-1 : ind_max;
const1 = t_0 - DeltaChannel/2.0;
const2 = DeltaChannel/(float)(LEN_DET-1);
const3 = Deltaxy - (y*cos(ang) - x*sin(ang));
const4 = (float)(LEN_PIX-1)/(2.0*Deltaxy);
for (i = ind_min; i <= ind_max; i++)
{
#ifdef WIDE_BEAM
/* step through values of detector profile, inner product with PIX prof */
Aval = 0;
for (k = 0; k < LEN_DET; k++)
{
t = const1 + (float)i*DeltaChannel + (float)k*const2;
pix_prof_ind = (t+const3)*const4 +0.5; /* +0.5 for rounding */
if (pix_prof_ind >= 0 && pix_prof_ind < LEN_PIX)
Aval += dprof[k]*pix_prof[pr][pix_prof_ind];
}
#else
/*** this block computes zero-beam-width projection model ****/
int prof_ind = LEN_PIX*(t_0+i*DeltaChannel+const3)/(2.0*Deltaxy);
if (prof_ind >= LEN_PIX || prof_ind < 0)
{
if (prof_ind == LEN_PIX)
prof_ind = LEN_PIX-1;
else if (prof_ind == -1)
prof_ind = 0;
else
{
fprintf(stderr,"A_comp_ij() Error: input parameters inconsistant\n");
exit(-1);
}
}
Aval = pix_prof[pr][prof_ind];
#endif
if (Aval > 0.0)
{
/*XW: record the starting position for each view. */
if(write==1) {
minCount=i;
write=0;
}
A_Values[proj_count] = Aval;
proj_count++;
}
}
/* data type of ACol.countTheta is typically unsigned char --check for overflow */
const int overflow_val = 1 << (8*sizeof(chanwidth_t));
if(proj_count-countTemp >= overflow_val) {
fprintf(stderr,"A_comp_ij() Error: overflow detected--check voxel/detector dimensions\n");
exit(-1);
}
A_col->countTheta[pr] = proj_count-countTemp;
A_col->minIndex[pr] = minCount;
}
A_col->n_index = proj_count;
}
void A_piecewise(
struct ACol **ACol_ptr,
struct AValues_char **AVal_ptr,
struct AValues_char **A_Padded_Map,
struct SVParams svpar,
struct SinoParams3DParallel *sinoparams,
struct ImageParams3D *imgparams)
{
int i,j,jj,p,t;
int Nx = imgparams->Nx;
int Ny = imgparams->Ny;
int NViews = sinoparams->NViews;
int NChannels = sinoparams->NChannels;
int SVLength = svpar.SVLength;
int pieceLength = svpar.pieceLength;
int NViewSets = NViews/svpar.pieceLength;
struct minStruct * bandMinMap = svpar.bandMinMap;
struct maxStruct * bandMaxMap = svpar.bandMaxMap;
int *order = (int *) mget_spc(svpar.Nsv,sizeof(int));
t=0;
for(i=0; i<Ny; i+=(SVLength*2-svpar.overlap))
for(j=0; j<Nx; j+=(SVLength*2-svpar.overlap)) {
order[t]=i*Nx+j; /* order is the first voxel coordinate, not the center */
t++;
}
for(jj=0; jj<svpar.Nsv; jj++)
for(i=0; i<(SVLength*2+1)*(SVLength*2+1); i++) {
A_Padded_Map[jj][i].val=NULL;
A_Padded_Map[jj][i].length=0;
}
for(i=0; i<Ny; i++)
for(j=0; j<Nx; j++)
if(ACol_ptr[i][j].n_index > 0)
for(p=0; p<NViews; p++)
{
if(ACol_ptr[i][j].minIndex[p]==0 && ACol_ptr[i][j].countTheta[p]==0)
{
if(p!=0)
ACol_ptr[i][j].minIndex[p] = ACol_ptr[i][j].minIndex[p-1];
else
{
t=0;
while(ACol_ptr[i][j].minIndex[t] == 0 && t<NViews-1)
t++;
ACol_ptr[i][j].minIndex[p] = ACol_ptr[i][j].minIndex[t];
}
}
}
/* Note this gets *slower* if running more than a few threads */
#pragma omp parallel private(i,j,p,t) num_threads(4)
{
int jx,jy,q,jx_new,jy_new;
channel_t *bandMin = (channel_t *) mget_spc(NViews,sizeof(channel_t));
channel_t *bandMax = (channel_t *) mget_spc(NViews,sizeof(channel_t));
channel_t *bandWidth=(channel_t *) mget_spc(NViews,sizeof(channel_t));
channel_t *bandWidthPW = (channel_t *) mget_spc(NViewSets,sizeof(channel_t));
int SVSize = (2*SVLength+1)*(2*SVLength+1);
channel_t **piecewiseMin = (channel_t **)multialloc(sizeof(channel_t),2,SVSize,NViewSets);
channel_t **piecewiseMax = (channel_t **)multialloc(sizeof(channel_t),2,SVSize,NViewSets);
channel_t **piecewiseWidth=(channel_t **)multialloc(sizeof(channel_t),2,SVSize,NViewSets);
int *jx_list = (int *) mget_spc(SVSize,sizeof(int));
int *jy_list = (int *) mget_spc(SVSize,sizeof(int));
int *totalSum = (int *) mget_spc(SVSize,sizeof(int));
#pragma omp for schedule(static)
for(jj=0; jj<svpar.Nsv; jj++)
{
jy = order[jj] / Nx;
jx = order[jj] % Nx;
SVSize = 0;
for(jy_new=jy; jy_new<=(jy+2*SVLength); jy_new++)
for(jx_new=jx; jx_new<=(jx+2*SVLength); jx_new++)
if(jy_new<Ny && jx_new<Nx) {
if(ACol_ptr[jy_new][jx_new].n_index >0) {
jy_list[SVSize] = jy_new;
jx_list[SVSize] = jx_new;
SVSize++;
}
}
//channel_t bandMin[NViews]__attribute__((aligned(64)));
//channel_t bandMax[NViews]__attribute__((aligned(64)));
for(p=0; p< NViews; p++)
bandMin[p] = NChannels;
for(i=0; i<SVSize; i++)
{
jy_new = jy_list[i];
jx_new = jx_list[i];
for(p=0; p< NViews; p++)
{
if(ACol_ptr[jy_new][jx_new].minIndex[p] < bandMin[p])
bandMin[p] = ACol_ptr[jy_new][jx_new].minIndex[p];
}
}
for(p=0; p< NViews; p++)
bandMax[p]=bandMin[p];
for(i=0; i<SVSize; i++)
{
jy_new = jy_list[i];
jx_new = jx_list[i];
for(p=0; p< NViews; p++) {
if((ACol_ptr[jy_new][jx_new].minIndex[p] + ACol_ptr[jy_new][jx_new].countTheta[p]) > bandMax[p])
bandMax[p] = ACol_ptr[jy_new][jx_new].minIndex[p] + ACol_ptr[jy_new][jx_new].countTheta[p];
}
}
//channel_t bandWidth[NViews]__attribute__((aligned(64)));
//channel_t bandWidthPW[NViewSets]__attribute__((aligned(64)));
//#pragma vector aligned
for(p=0; p< NViews; p++)
bandWidth[p] = bandMax[p]-bandMin[p];
for (p=0; p < NViewSets; p++)
{
int bandWidthMax = bandWidth[p*pieceLength];
for(t=0; t<pieceLength; t++) {
if(bandWidth[p*pieceLength+t] > bandWidthMax) {
bandWidthMax = bandWidth[p*pieceLength+t];
}
}
bandWidthPW[p] = bandWidthMax;
}
//#pragma vector aligned
for(p=0; p< NViews; p++) {
if((bandMin[p]+bandWidthPW[p/pieceLength]) >= NChannels)
bandMin[p] = NChannels - bandWidthPW[p/pieceLength];
}
memcpy(&bandMinMap[jj].bandMin[0],&bandMin[0],sizeof(channel_t)*NViews);
memcpy(&bandMaxMap[jj].bandMax[0],&bandMax[0],sizeof(channel_t)*NViews);
//int totalSum[SVSize]__attribute__((aligned(64)));
for(i=0; i<SVSize; i++)
{
jy_new = jy_list[i];
jx_new = jx_list[i];
for (p=0; p < NViewSets; p++)
{
int pwMin = (int)ACol_ptr[jy_new][jx_new].minIndex[p*pieceLength]-(int)bandMin[p*pieceLength];
int pwMax = pwMin + ACol_ptr[jy_new][jx_new].countTheta[p*pieceLength];
for(t=0; t<pieceLength; t++)
{
int idx0 = (int)ACol_ptr[jy_new][jx_new].minIndex[p*pieceLength+t]-(int)bandMin[p*pieceLength+t];
int idx1 = idx0 + ACol_ptr[jy_new][jx_new].countTheta[p*pieceLength+t];
if(idx0 < pwMin)
pwMin = idx0;
if(pwMax < idx1)
pwMax = idx1;
}
piecewiseMin[i][p] = pwMin;
piecewiseMax[i][p] = pwMax;
piecewiseWidth[i][p] = (pwMax - pwMin);
}
}
for(i=0; i<SVSize; i++)
{
totalSum[i]=0;
//#pragma vector aligned
for (p = 0; p < NViewSets; p++)
totalSum[i] += piecewiseWidth[i][p] * pieceLength;
}
unsigned char **AMatrixPadded= (unsigned char **) mget_spc(SVSize,sizeof(unsigned char *));
unsigned char **AMatrixPaddedTranspose=(unsigned char **) mget_spc(SVSize,sizeof(unsigned char *));
for(i=0;i<SVSize;i++) {
AMatrixPadded[i] = (unsigned char *) mget_spc(totalSum[i],sizeof(unsigned char));
AMatrixPaddedTranspose[i] = (unsigned char *) mget_spc(totalSum[i],sizeof(unsigned char));
}
for(i=0; i<SVSize; i++)
{
jy_new = jy_list[i];
jx_new = jx_list[i];
unsigned char * A_padded_pointer = &AMatrixPadded[i][0];
unsigned char * newProjectionValueArrayPointer = &AVal_ptr[jy_new][jx_new].val[0];
for (p=0; p < NViews; p++)
{
int n_pad;
n_pad=(int)ACol_ptr[jy_new][jx_new].minIndex[p]-(int)piecewiseMin[i][p/pieceLength]-(int)bandMin[p];
#pragma vector aligned
for(t=0; t<n_pad; t++) {
*A_padded_pointer = 0;
A_padded_pointer++;
}
#pragma vector aligned
for(t=0; t<ACol_ptr[jy_new][jx_new].countTheta[p]; t++) {
*A_padded_pointer = *newProjectionValueArrayPointer;
A_padded_pointer++;
newProjectionValueArrayPointer++;
}
n_pad=(int)piecewiseMax[i][p/pieceLength]-(int)ACol_ptr[jy_new][jx_new].minIndex[p]-(int)ACol_ptr[jy_new][jx_new].countTheta[p]+(int)bandMin[p];
#pragma vector aligned
for(t=0; t<n_pad; t++) {
*A_padded_pointer = 0;
A_padded_pointer++;
}
}
}
for(i=0; i<SVSize; i++)
{
unsigned char * A_padded_pointer = &AMatrixPadded[i][0];
unsigned char * A_padd_Tranpose_pointer = &AMatrixPaddedTranspose[i][0];
for (p=0; p < NViewSets; p++)
{
for(q=0; q<piecewiseWidth[i][p]; q++) {
for(t=0; t<pieceLength; t++) {
A_padd_Tranpose_pointer[q*pieceLength+t] = A_padded_pointer[t*piecewiseWidth[i][p]+q];
}
}
A_padded_pointer += piecewiseWidth[i][p]*pieceLength;
A_padd_Tranpose_pointer += piecewiseWidth[i][p]*pieceLength;
}
}
for(i=0;i<SVSize;i++)
{
jy_new = jy_list[i];
jx_new = jx_list[i];
int VoxelPosition = (jy_new-jy)*(2*SVLength+1)+(jx_new-jx);
A_Padded_Map[jj][VoxelPosition].val = (unsigned char *)get_spc(totalSum[i], sizeof(unsigned char));
A_Padded_Map[jj][VoxelPosition].pieceWiseMin = (channel_t *)get_spc(NViewSets,sizeof(channel_t));
A_Padded_Map[jj][VoxelPosition].pieceWiseWidth = (channel_t *)get_spc(NViewSets,sizeof(channel_t));
A_Padded_Map[jj][VoxelPosition].length = totalSum[i];
memcpy(&A_Padded_Map[jj][VoxelPosition].val[0],&AMatrixPaddedTranspose[i][0],sizeof(unsigned char)*totalSum[i]);
memcpy(&A_Padded_Map[jj][VoxelPosition].pieceWiseMin[0],&piecewiseMin[i][0],sizeof(channel_t)*NViewSets);
memcpy(&A_Padded_Map[jj][VoxelPosition].pieceWiseWidth[0],&piecewiseWidth[i][0],sizeof(channel_t)*NViewSets);
}
for(i=0;i<SVSize;i++) {
free((void *)AMatrixPadded[i]);
free((void *)AMatrixPaddedTranspose[i]);
}
free((void *)AMatrixPadded);
free((void *)AMatrixPaddedTranspose);
} //omp for block
multifree(piecewiseMin,2);
multifree(piecewiseMax,2);
multifree(piecewiseWidth,2);
free((void *) bandMin);
free((void *) bandMax);
free((void *) bandWidth);
free((void *) bandWidthPW);
free((void *) jx_list);
free((void *) jy_list);
free((void *) totalSum);
} //omp parallel block
free((void *) order);
} /*** END A_piecewise() ***/
/* Compute Entire System Matrix */
/* The System matrix does not vary with slice for 3-D Parallel Geometry */
/* So, the method of compuatation is same as that of 2-D Parallel Geometry */
void A_comp(
struct AValues_char **A_Padded_Map,
float *Aval_max_ptr,
struct SVParams svpar,
struct SinoParams3DParallel *sinoparams,
char *recon_mask,
struct ImageParams3D *imgparams)
{
int i,j,r;
struct ACol **ACol_arr;
struct AValues_char **AVal_arr;
int NViews = sinoparams->NViews;
int NChannels = sinoparams->NChannels;
int Nx = imgparams->Nx;
int Ny = imgparams->Ny;
ACol_arr = (struct ACol **)multialloc(sizeof(struct ACol), 2, Ny, Nx);
AVal_arr = (struct AValues_char **)multialloc(sizeof(struct AValues_char), 2, Ny, Nx);
float **pix_prof = ComputePixelProfile3DParallel(sinoparams,imgparams);
//struct timeval tm1,tm2;
//unsigned long long tdiff;
//gettimeofday(&tm1,NULL);
#pragma omp parallel private(j,r)
{
struct ACol A_col_sgl;
A_col_sgl.countTheta = (chanwidth_t *)get_spc(NViews,sizeof(chanwidth_t));
A_col_sgl.minIndex = (channel_t *)get_spc(NViews,sizeof(channel_t));
float *A_val_sgl = (float *)get_spc(NViews*NChannels, sizeof(float));
#pragma omp for schedule(static)
for (i=0; i<Ny; i++)
for (j=0; j<Nx; j++)
if(recon_mask[i*Nx+j])
{
A_comp_ij(i,j,sinoparams,imgparams,pix_prof,&A_col_sgl,A_val_sgl);
ACol_arr[i][j].n_index = A_col_sgl.n_index;
ACol_arr[i][j].countTheta = (chanwidth_t *) get_spc(NViews,sizeof(chanwidth_t));
ACol_arr[i][j].minIndex = (channel_t *) get_spc(NViews,sizeof(channel_t));
AVal_arr[i][j].val = (unsigned char *) get_spc(A_col_sgl.n_index, sizeof(unsigned char));
float maxval = A_val_sgl[0];
for (r = 0; r < A_col_sgl.n_index; r++) {
if(A_val_sgl[r]>maxval)
maxval = A_val_sgl[r];
}
Aval_max_ptr[i*Nx+j] = maxval;
for (r=0; r < A_col_sgl.n_index; r++)
AVal_arr[i][j].val[r] = (unsigned char)((A_val_sgl[r])/maxval*255+0.5);
for (r=0; r < NViews; r++) {
ACol_arr[i][j].countTheta[r] = A_col_sgl.countTheta[r];
ACol_arr[i][j].minIndex[r] = A_col_sgl.minIndex[r];
}
}
else
{
ACol_arr[i][j].n_index = 0;
Aval_max_ptr[i*Nx+j] = 0;
}
free((void *)A_val_sgl);
free((void *)A_col_sgl.countTheta);
free((void *)A_col_sgl.minIndex);
}
//gettimeofday(&tm2,NULL);
//tdiff = 1000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec) / 1000;
//fprintf(stdout,"matrix time 1 = %llu ms\n",tdiff);
//gettimeofday(&tm1,NULL);
A_piecewise(ACol_arr,AVal_arr,A_Padded_Map,svpar,sinoparams,imgparams);
//gettimeofday(&tm2,NULL);
//tdiff = 1000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec) / 1000;
//fprintf(stdout,"matrix time 2 = %llu ms\n",tdiff);
for (i=0; i<Ny; i++)
for (j=0; j<Nx; j++)
if(recon_mask[i*Nx+j]) {
free((void *)ACol_arr[i][j].countTheta);
free((void *)ACol_arr[i][j].minIndex);
free((void *)AVal_arr[i][j].val);
}
multifree(ACol_arr,2);
multifree(AVal_arr,2);
free_img((void **)pix_prof);
}
void readAmatrix(
char *fname,
struct AValues_char **A_Padded_Map,
float *Aval_max_ptr,
struct ImageParams3D *imgparams,
struct SinoParams3DParallel *sinoparams,
struct SVParams svpar)
{
FILE *fp;
int i,j;
int M_nonzero;
int Nxy = imgparams->Nx * imgparams->Ny;
int NViews = sinoparams->NViews;
int NViewSets = sinoparams->NViews/svpar.pieceLength;
if ((fp = fopen(fname, "rb")) == NULL) {
fprintf(stderr, "ERROR in readAmatrix: can't open file %s.\n", fname);
exit(-1);
}
for (i=0; i<svpar.Nsv ; i++)
{
if(fread(svpar.bandMinMap[i].bandMin,sizeof(channel_t),NViews,fp) < (size_t)NViews) {
fprintf(stderr, "ERROR in readAmatrix: %s terminated early.\n", fname);
exit(-1);
}
if(fread(svpar.bandMaxMap[i].bandMax,sizeof(channel_t),NViews,fp) < (size_t)NViews) {
fprintf(stderr, "ERROR in readAmatrix: %s terminated early.\n", fname);
exit(-1);
}
for (j=0; j< (svpar.SVLength*2+1)*(svpar.SVLength*2+1); j++)
{
if(fread(&M_nonzero, sizeof(int), 1, fp) < 1) {
fprintf(stderr, "ERROR in readAmatrix: %s terminated early.\n", fname);
exit(-1);
}
A_Padded_Map[i][j].length = M_nonzero;
if(M_nonzero > 0)
{
A_Padded_Map[i][j].val = (unsigned char *)get_spc(M_nonzero, sizeof(unsigned char));
A_Padded_Map[i][j].pieceWiseWidth = (channel_t *)get_spc(NViewSets,sizeof(channel_t));
A_Padded_Map[i][j].pieceWiseMin = (channel_t *)get_spc(NViewSets,sizeof(channel_t));
if(fread(A_Padded_Map[i][j].val, sizeof(unsigned char), M_nonzero, fp) < (size_t)M_nonzero) {
fprintf(stderr, "ERROR in readAmatrix: %s terminated early.\n", fname);
exit(-1);
}
if(fread(A_Padded_Map[i][j].pieceWiseMin,sizeof(channel_t),NViewSets,fp) < (size_t)NViewSets) {
fprintf(stderr, "ERROR in readAmatrix: %s terminated early.\n", fname);
exit(-1);
}
if(fread(A_Padded_Map[i][j].pieceWiseWidth,sizeof(channel_t),NViewSets,fp) < (size_t)NViewSets) {
fprintf(stderr, "ERROR in readAmatrix: %s terminated early.\n", fname);
exit(-1);
}
}
}
}
if(fread(&Aval_max_ptr[0],sizeof(float),Nxy,fp) < (size_t)Nxy) {
fprintf(stderr, "ERROR in readAmatrix: %s terminated early.\n", fname);
exit(-1);
}
fclose(fp);
}
void writeAmatrix(
char *fname,
struct AValues_char **A_Padded_Map,
float *Aval_max_ptr,
struct ImageParams3D *imgparams,
struct SinoParams3DParallel *sinoparams,
struct SVParams svpar)
{
FILE *fp;
int i,j;
int M_nonzero;
int NViewSets = sinoparams->NViews/svpar.pieceLength;
if ((fp = fopen(fname, "wb")) == NULL) {
fprintf(stderr, "ERROR in writeAmatrix: can't open file %s.\n", fname);
exit(-1);
}
for (i=0; i<svpar.Nsv; i++)
{
fwrite(svpar.bandMinMap[i].bandMin,sizeof(channel_t),sinoparams->NViews,fp);
fwrite(svpar.bandMaxMap[i].bandMax,sizeof(channel_t),sinoparams->NViews,fp);
for (j=0; j< (svpar.SVLength*2+1)*(svpar.SVLength*2+1); j++)
{
M_nonzero = A_Padded_Map[i][j].length;
fwrite(&M_nonzero, sizeof(int), 1, fp);
if(M_nonzero > 0) {
fwrite(A_Padded_Map[i][j].val, sizeof(unsigned char), M_nonzero, fp);
fwrite(A_Padded_Map[i][j].pieceWiseMin,sizeof(channel_t),NViewSets,fp);
fwrite(A_Padded_Map[i][j].pieceWiseWidth,sizeof(channel_t),NViewSets,fp);
}
}
}
fwrite(&Aval_max_ptr[0],sizeof(float),imgparams->Nx*imgparams->Ny,fp);
fclose(fp);
}
void AmatrixComputeToFile(
struct ImageParams3D imgparams,
struct SinoParams3DParallel sinoparams,
char *Amatrix_fname,
char verboseLevel)
{
struct SVParams svpar;
struct AValues_char **A_Padded_Map;
float *Aval_max_ptr;
char *ImageReconMask; /* Image reconstruction mask (determined by ROI) */
int i,j;
#ifndef MSVC /* not included in MS Visual C++ */
struct timeval tm1,tm2;
unsigned long long tdiff;
#endif
if(verboseLevel) {
fprintf(stdout,"Computing system matrix...\n");
#ifndef MSVC /* not included in MS Visual C++ */
gettimeofday(&tm1,NULL);
#endif
}
initSVParams(&svpar,imgparams,sinoparams); /* Initialize/allocate SV parameters */
int Nx = imgparams.Nx;
int Ny = imgparams.Ny;
int SVLength = svpar.SVLength;
int Nsv = svpar.Nsv;
/* Allocate and generate recon mask based on ROIRadius */
ImageReconMask = GenImageReconMask(&imgparams);
A_Padded_Map = (struct AValues_char **)multialloc(sizeof(struct AValues_char),2,Nsv,(2*SVLength+1)*(2*SVLength+1));
Aval_max_ptr = (float *) get_spc(Nx*Ny,sizeof(float));
A_comp(A_Padded_Map,Aval_max_ptr,svpar,&sinoparams,ImageReconMask,&imgparams);
if(verboseLevel>1) {
#ifndef MSVC /* not included in MS Visual C++ */
gettimeofday(&tm2,NULL);
tdiff = 1000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec) / 1000;
fprintf(stdout,"\tmatrix time = %llu ms\n",tdiff);
#endif
fprintf(stdout,"Writing system matrix %s\n",Amatrix_fname);
}
else if(verboseLevel)
fprintf(stdout,"Writing system matrix...\n");
writeAmatrix(Amatrix_fname,A_Padded_Map,Aval_max_ptr,&imgparams,&sinoparams,svpar);
/* Free memory */
for(i=0;i<Nsv;i++)
for(j=0;j<(2*SVLength+1)*(2*SVLength+1);j++)
if(A_Padded_Map[i][j].length>0)
{
free((void *)A_Padded_Map[i][j].val);
free((void *)A_Padded_Map[i][j].pieceWiseMin);
free((void *)A_Padded_Map[i][j].pieceWiseWidth);
}
multifree(A_Padded_Map,2);
free((void *)Aval_max_ptr);
free((void *)ImageReconMask);
}
|
ASTMatchers.h | //===- ASTMatchers.h - Structural query framework ---------------*- 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 implements matchers to be used together with the MatchFinder to
// match AST nodes.
//
// Matchers are created by generator functions, which can be combined in
// a functional in-language DSL to express queries over the C++ AST.
//
// For example, to match a class with a certain name, one would call:
// cxxRecordDecl(hasName("MyClass"))
// which returns a matcher that can be used to find all AST nodes that declare
// a class named 'MyClass'.
//
// For more complicated match expressions we're often interested in accessing
// multiple parts of the matched AST nodes once a match is found. In that case,
// call `.bind("name")` on match expressions that match the nodes you want to
// access.
//
// For example, when we're interested in child classes of a certain class, we
// would write:
// cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child")))
// When the match is found via the MatchFinder, a user provided callback will
// be called with a BoundNodes instance that contains a mapping from the
// strings that we provided for the `.bind()` calls to the nodes that were
// matched.
// In the given example, each time our matcher finds a match we get a callback
// where "child" is bound to the RecordDecl node of the matching child
// class declaration.
//
// See ASTMatchersInternal.h for a more in-depth explanation of the
// implementation details of the matcher framework.
//
// See ASTMatchFinder.h for how to use the generated matchers to run over
// an AST.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/LambdaCapture.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/ParentMapContext.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtOpenMP.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/ASTMatchers/ASTMatchersInternal.h"
#include "clang/ASTMatchers/ASTMatchersMacros.h"
#include "clang/Basic/AttrKinds.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TypeTraits.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Regex.h"
#include <cassert>
#include <cstddef>
#include <iterator>
#include <limits>
#include <string>
#include <utility>
#include <vector>
namespace clang {
namespace ast_matchers {
/// Maps string IDs to AST nodes matched by parts of a matcher.
///
/// The bound nodes are generated by calling \c bind("id") on the node matchers
/// of the nodes we want to access later.
///
/// The instances of BoundNodes are created by \c MatchFinder when the user's
/// callbacks are executed every time a match is found.
class BoundNodes {
public:
/// Returns the AST node bound to \c ID.
///
/// Returns NULL if there was no node bound to \c ID or if there is a node but
/// it cannot be converted to the specified type.
template <typename T>
const T *getNodeAs(StringRef ID) const {
return MyBoundNodes.getNodeAs<T>(ID);
}
/// Type of mapping from binding identifiers to bound nodes. This type
/// is an associative container with a key type of \c std::string and a value
/// type of \c clang::DynTypedNode
using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
/// Retrieve mapping from binding identifiers to bound nodes.
const IDToNodeMap &getMap() const {
return MyBoundNodes.getMap();
}
private:
friend class internal::BoundNodesTreeBuilder;
/// Create BoundNodes from a pre-filled map of bindings.
BoundNodes(internal::BoundNodesMap &MyBoundNodes)
: MyBoundNodes(MyBoundNodes) {}
internal::BoundNodesMap MyBoundNodes;
};
/// Types of matchers for the top-level classes in the AST class
/// hierarchy.
/// @{
using DeclarationMatcher = internal::Matcher<Decl>;
using StatementMatcher = internal::Matcher<Stmt>;
using TypeMatcher = internal::Matcher<QualType>;
using TypeLocMatcher = internal::Matcher<TypeLoc>;
using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
/// @}
/// Matches any node.
///
/// Useful when another matcher requires a child matcher, but there's no
/// additional constraint. This will often be used with an explicit conversion
/// to an \c internal::Matcher<> type such as \c TypeMatcher.
///
/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
/// \code
/// "int* p" and "void f()" in
/// int* p;
/// void f();
/// \endcode
///
/// Usable as: Any Matcher
inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
/// Matches the top declaration context.
///
/// Given
/// \code
/// int X;
/// namespace NS {
/// int Y;
/// } // namespace NS
/// \endcode
/// decl(hasDeclContext(translationUnitDecl()))
/// matches "int X", but not "int Y".
extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
translationUnitDecl;
/// Matches typedef declarations.
///
/// Given
/// \code
/// typedef int X;
/// using Y = int;
/// \endcode
/// typedefDecl()
/// matches "typedef int X", but not "using Y = int"
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
typedefDecl;
/// Matches typedef name declarations.
///
/// Given
/// \code
/// typedef int X;
/// using Y = int;
/// \endcode
/// typedefNameDecl()
/// matches "typedef int X" and "using Y = int"
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
typedefNameDecl;
/// Matches type alias declarations.
///
/// Given
/// \code
/// typedef int X;
/// using Y = int;
/// \endcode
/// typeAliasDecl()
/// matches "using Y = int", but not "typedef int X"
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
typeAliasDecl;
/// Matches type alias template declarations.
///
/// typeAliasTemplateDecl() matches
/// \code
/// template <typename T>
/// using Y = X<T>;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
typeAliasTemplateDecl;
/// Matches AST nodes that were expanded within the main-file.
///
/// Example matches X but not Y
/// (matcher = cxxRecordDecl(isExpansionInMainFile())
/// \code
/// #include <Y.h>
/// class X {};
/// \endcode
/// Y.h:
/// \code
/// class Y {};
/// \endcode
///
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
auto &SourceManager = Finder->getASTContext().getSourceManager();
return SourceManager.isInMainFile(
SourceManager.getExpansionLoc(Node.getBeginLoc()));
}
/// Matches AST nodes that were expanded within system-header-files.
///
/// Example matches Y but not X
/// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
/// \code
/// #include <SystemHeader.h>
/// class X {};
/// \endcode
/// SystemHeader.h:
/// \code
/// class Y {};
/// \endcode
///
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
auto &SourceManager = Finder->getASTContext().getSourceManager();
auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
if (ExpansionLoc.isInvalid()) {
return false;
}
return SourceManager.isInSystemHeader(ExpansionLoc);
}
/// Matches AST nodes that were expanded within files whose name is
/// partially matching a given regex.
///
/// Example matches Y but not X
/// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
/// \code
/// #include "ASTMatcher.h"
/// class X {};
/// \endcode
/// ASTMatcher.h:
/// \code
/// class Y {};
/// \endcode
///
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt,
TypeLoc),
RegExp) {
auto &SourceManager = Finder->getASTContext().getSourceManager();
auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
if (ExpansionLoc.isInvalid()) {
return false;
}
auto FileEntry =
SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
if (!FileEntry) {
return false;
}
auto Filename = FileEntry->getName();
return RegExp->match(Filename);
}
/// Matches statements that are (transitively) expanded from the named macro.
/// Does not match if only part of the statement is expanded from that macro or
/// if different parts of the the statement are expanded from different
/// appearances of the macro.
AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
std::string, MacroName) {
// Verifies that the statement' beginning and ending are both expanded from
// the same instance of the given macro.
auto& Context = Finder->getASTContext();
llvm::Optional<SourceLocation> B =
internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
if (!B) return false;
llvm::Optional<SourceLocation> E =
internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
if (!E) return false;
return *B == *E;
}
/// Matches declarations.
///
/// Examples matches \c X, \c C, and the friend declaration inside \c C;
/// \code
/// void X();
/// class C {
/// friend X;
/// };
/// \endcode
extern const internal::VariadicAllOfMatcher<Decl> decl;
/// Matches decomposition-declarations.
///
/// Examples matches the declaration node with \c foo and \c bar, but not
/// \c number.
/// (matcher = declStmt(has(decompositionDecl())))
///
/// \code
/// int number = 42;
/// auto [foo, bar] = std::make_pair{42, 42};
/// \endcode
extern const internal::VariadicAllOfMatcher<DecompositionDecl>
decompositionDecl;
/// Matches a declaration of a linkage specification.
///
/// Given
/// \code
/// extern "C" {}
/// \endcode
/// linkageSpecDecl()
/// matches "extern "C" {}"
extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
linkageSpecDecl;
/// Matches a declaration of anything that could have a name.
///
/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
/// \code
/// typedef int X;
/// struct S {
/// union {
/// int i;
/// } U;
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
/// Matches a declaration of label.
///
/// Given
/// \code
/// goto FOO;
/// FOO: bar();
/// \endcode
/// labelDecl()
/// matches 'FOO:'
extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
/// Matches a declaration of a namespace.
///
/// Given
/// \code
/// namespace {}
/// namespace test {}
/// \endcode
/// namespaceDecl()
/// matches "namespace {}" and "namespace test {}"
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
namespaceDecl;
/// Matches a declaration of a namespace alias.
///
/// Given
/// \code
/// namespace test {}
/// namespace alias = ::test;
/// \endcode
/// namespaceAliasDecl()
/// matches "namespace alias" but not "namespace test"
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
namespaceAliasDecl;
/// Matches class, struct, and union declarations.
///
/// Example matches \c X, \c Z, \c U, and \c S
/// \code
/// class X;
/// template<class T> class Z {};
/// struct S {};
/// union U {};
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
/// Matches C++ class declarations.
///
/// Example matches \c X, \c Z
/// \code
/// class X;
/// template<class T> class Z {};
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
cxxRecordDecl;
/// Matches C++ class template declarations.
///
/// Example matches \c Z
/// \code
/// template<class T> class Z {};
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
classTemplateDecl;
/// Matches C++ class template specializations.
///
/// Given
/// \code
/// template<typename T> class A {};
/// template<> class A<double> {};
/// A<int> a;
/// \endcode
/// classTemplateSpecializationDecl()
/// matches the specializations \c A<int> and \c A<double>
extern const internal::VariadicDynCastAllOfMatcher<
Decl, ClassTemplateSpecializationDecl>
classTemplateSpecializationDecl;
/// Matches C++ class template partial specializations.
///
/// Given
/// \code
/// template<class T1, class T2, int I>
/// class A {};
///
/// template<class T, int I>
/// class A<T, T*, I> {};
///
/// template<>
/// class A<int, int, 1> {};
/// \endcode
/// classTemplatePartialSpecializationDecl()
/// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
extern const internal::VariadicDynCastAllOfMatcher<
Decl, ClassTemplatePartialSpecializationDecl>
classTemplatePartialSpecializationDecl;
/// Matches declarator declarations (field, variable, function
/// and non-type template parameter declarations).
///
/// Given
/// \code
/// class X { int y; };
/// \endcode
/// declaratorDecl()
/// matches \c int y.
extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
declaratorDecl;
/// Matches parameter variable declarations.
///
/// Given
/// \code
/// void f(int x);
/// \endcode
/// parmVarDecl()
/// matches \c int x.
extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
parmVarDecl;
/// Matches C++ access specifier declarations.
///
/// Given
/// \code
/// class C {
/// public:
/// int a;
/// };
/// \endcode
/// accessSpecDecl()
/// matches 'public:'
extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
accessSpecDecl;
/// Matches constructor initializers.
///
/// Examples matches \c i(42).
/// \code
/// class C {
/// C() : i(42) {}
/// int i;
/// };
/// \endcode
extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
cxxCtorInitializer;
/// Matches template arguments.
///
/// Given
/// \code
/// template <typename T> struct C {};
/// C<int> c;
/// \endcode
/// templateArgument()
/// matches 'int' in C<int>.
extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
/// Matches template arguments (with location info).
///
/// Given
/// \code
/// template <typename T> struct C {};
/// C<int> c;
/// \endcode
/// templateArgumentLoc()
/// matches 'int' in C<int>.
extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
templateArgumentLoc;
/// Matches template name.
///
/// Given
/// \code
/// template <typename T> class X { };
/// X<int> xi;
/// \endcode
/// templateName()
/// matches 'X' in X<int>.
extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
/// Matches non-type template parameter declarations.
///
/// Given
/// \code
/// template <typename T, int N> struct C {};
/// \endcode
/// nonTypeTemplateParmDecl()
/// matches 'N', but not 'T'.
extern const internal::VariadicDynCastAllOfMatcher<Decl,
NonTypeTemplateParmDecl>
nonTypeTemplateParmDecl;
/// Matches template type parameter declarations.
///
/// Given
/// \code
/// template <typename T, int N> struct C {};
/// \endcode
/// templateTypeParmDecl()
/// matches 'T', but not 'N'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
templateTypeParmDecl;
/// Matches template template parameter declarations.
///
/// Given
/// \code
/// template <template <typename> class Z, int N> struct C {};
/// \endcode
/// templateTypeParmDecl()
/// matches 'Z', but not 'N'.
extern const internal::VariadicDynCastAllOfMatcher<Decl,
TemplateTemplateParmDecl>
templateTemplateParmDecl;
/// Matches public C++ declarations and C++ base specifers that specify public
/// inheritance.
///
/// Examples:
/// \code
/// class C {
/// public: int a; // fieldDecl(isPublic()) matches 'a'
/// protected: int b;
/// private: int c;
/// };
/// \endcode
///
/// \code
/// class Base {};
/// class Derived1 : public Base {}; // matches 'Base'
/// struct Derived2 : Base {}; // matches 'Base'
/// \endcode
AST_POLYMORPHIC_MATCHER(isPublic,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
CXXBaseSpecifier)) {
return getAccessSpecifier(Node) == AS_public;
}
/// Matches protected C++ declarations and C++ base specifers that specify
/// protected inheritance.
///
/// Examples:
/// \code
/// class C {
/// public: int a;
/// protected: int b; // fieldDecl(isProtected()) matches 'b'
/// private: int c;
/// };
/// \endcode
///
/// \code
/// class Base {};
/// class Derived : protected Base {}; // matches 'Base'
/// \endcode
AST_POLYMORPHIC_MATCHER(isProtected,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
CXXBaseSpecifier)) {
return getAccessSpecifier(Node) == AS_protected;
}
/// Matches private C++ declarations and C++ base specifers that specify private
/// inheritance.
///
/// Examples:
/// \code
/// class C {
/// public: int a;
/// protected: int b;
/// private: int c; // fieldDecl(isPrivate()) matches 'c'
/// };
/// \endcode
///
/// \code
/// struct Base {};
/// struct Derived1 : private Base {}; // matches 'Base'
/// class Derived2 : Base {}; // matches 'Base'
/// \endcode
AST_POLYMORPHIC_MATCHER(isPrivate,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
CXXBaseSpecifier)) {
return getAccessSpecifier(Node) == AS_private;
}
/// Matches non-static data members that are bit-fields.
///
/// Given
/// \code
/// class C {
/// int a : 2;
/// int b;
/// };
/// \endcode
/// fieldDecl(isBitField())
/// matches 'int a;' but not 'int b;'.
AST_MATCHER(FieldDecl, isBitField) {
return Node.isBitField();
}
/// Matches non-static data members that are bit-fields of the specified
/// bit width.
///
/// Given
/// \code
/// class C {
/// int a : 2;
/// int b : 4;
/// int c : 2;
/// };
/// \endcode
/// fieldDecl(hasBitWidth(2))
/// matches 'int a;' and 'int c;' but not 'int b;'.
AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
return Node.isBitField() &&
Node.getBitWidthValue(Finder->getASTContext()) == Width;
}
/// Matches non-static data members that have an in-class initializer.
///
/// Given
/// \code
/// class C {
/// int a = 2;
/// int b = 3;
/// int c;
/// };
/// \endcode
/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
/// matches 'int a;' but not 'int b;'.
/// fieldDecl(hasInClassInitializer(anything()))
/// matches 'int a;' and 'int b;' but not 'int c;'.
AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *Initializer = Node.getInClassInitializer();
return (Initializer != nullptr &&
InnerMatcher.matches(*Initializer, Finder, Builder));
}
/// Determines whether the function is "main", which is the entry point
/// into an executable program.
AST_MATCHER(FunctionDecl, isMain) {
return Node.isMain();
}
/// Matches the specialized template of a specialization declaration.
///
/// Given
/// \code
/// template<typename T> class A {}; #1
/// template<> class A<int> {}; #2
/// \endcode
/// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
/// matches '#2' with classTemplateDecl() matching the class template
/// declaration of 'A' at #1.
AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
return (Decl != nullptr &&
InnerMatcher.matches(*Decl, Finder, Builder));
}
/// Matches a declaration that has been implicitly added
/// by the compiler (eg. implicit default/copy constructors).
AST_MATCHER(Decl, isImplicit) {
return Node.isImplicit();
}
/// Matches classTemplateSpecializations, templateSpecializationType and
/// functionDecl that have at least one TemplateArgument matching the given
/// InnerMatcher.
///
/// Given
/// \code
/// template<typename T> class A {};
/// template<> class A<double> {};
/// A<int> a;
///
/// template<typename T> f() {};
/// void func() { f<int>(); };
/// \endcode
///
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToType(asString("int"))))
/// matches the specialization \c A<int>
///
/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
/// matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P(
hasAnyTemplateArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
TemplateSpecializationType,
FunctionDecl),
internal::Matcher<TemplateArgument>, InnerMatcher) {
ArrayRef<TemplateArgument> List =
internal::getTemplateSpecializationArgs(Node);
return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
Builder) != List.end();
}
/// Causes all nested matchers to be matched with the specified traversal kind.
///
/// Given
/// \code
/// void foo()
/// {
/// int i = 3.0;
/// }
/// \endcode
/// The matcher
/// \code
/// traverse(TK_IgnoreUnlessSpelledInSource,
/// varDecl(hasInitializer(floatLiteral().bind("init")))
/// )
/// \endcode
/// matches the variable declaration with "init" bound to the "3.0".
template <typename T>
internal::Matcher<T> traverse(TraversalKind TK,
const internal::Matcher<T> &InnerMatcher) {
return internal::DynTypedMatcher::constructRestrictedWrapper(
new internal::TraversalMatcher<T>(TK, InnerMatcher),
InnerMatcher.getID().first)
.template unconditionalConvertTo<T>();
}
template <typename T>
internal::BindableMatcher<T>
traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
return internal::BindableMatcher<T>(
internal::DynTypedMatcher::constructRestrictedWrapper(
new internal::TraversalMatcher<T>(TK, InnerMatcher),
InnerMatcher.getID().first)
.template unconditionalConvertTo<T>());
}
template <typename... T>
internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
traverse(TraversalKind TK,
const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
TK, InnerMatcher);
}
template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
typename T, typename ToTypes>
internal::TraversalWrapper<
internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
return internal::TraversalWrapper<
internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
ToTypes>>(TK, InnerMatcher);
}
template <template <typename T, typename P1> class MatcherT, typename P1,
typename ReturnTypesF>
internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam1<
MatcherT, P1, ReturnTypesF> &InnerMatcher) {
return internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>(
TK, InnerMatcher);
}
template <template <typename T, typename P1, typename P2> class MatcherT,
typename P1, typename P2, typename ReturnTypesF>
internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam2<
MatcherT, P1, P2, ReturnTypesF> &InnerMatcher) {
return internal::TraversalWrapper<
internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>(
TK, InnerMatcher);
}
template <typename... T>
internal::Matcher<typename internal::GetClade<T...>::Type>
traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
return traverse(TK, InnerMatcher.with());
}
/// Matches expressions that match InnerMatcher after any implicit AST
/// nodes are stripped off.
///
/// Parentheses and explicit casts are not discarded.
/// Given
/// \code
/// class C {};
/// C a = C();
/// C b;
/// C c = b;
/// \endcode
/// The matchers
/// \code
/// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
/// \endcode
/// would match the declarations for a, b, and c.
/// While
/// \code
/// varDecl(hasInitializer(cxxConstructExpr()))
/// \endcode
/// only match the declarations for b and c.
AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
}
/// Matches expressions that match InnerMatcher after any implicit casts
/// are stripped off.
///
/// Parentheses and explicit casts are not discarded.
/// Given
/// \code
/// int arr[5];
/// int a = 0;
/// char b = 0;
/// const int c = a;
/// int *d = arr;
/// long e = (long) 0l;
/// \endcode
/// The matchers
/// \code
/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
/// \endcode
/// would match the declarations for a, b, c, and d, but not e.
/// While
/// \code
/// varDecl(hasInitializer(integerLiteral()))
/// varDecl(hasInitializer(declRefExpr()))
/// \endcode
/// only match the declarations for b, c, and d.
AST_MATCHER_P(Expr, ignoringImpCasts,
internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
}
/// Matches expressions that match InnerMatcher after parentheses and
/// casts are stripped off.
///
/// Implicit and non-C Style casts are also discarded.
/// Given
/// \code
/// int a = 0;
/// char b = (0);
/// void* c = reinterpret_cast<char*>(0);
/// char d = char(0);
/// \endcode
/// The matcher
/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
/// would match the declarations for a, b, c, and d.
/// while
/// varDecl(hasInitializer(integerLiteral()))
/// only match the declaration for a.
AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
}
/// Matches expressions that match InnerMatcher after parentheses and
/// Checked C temporary binding expressions are stripped off.
///
/// Given
/// \code
/// char *a = "";
/// \endcode
/// The matcher
/// varDecl(hasInitializer(ignoringParenTmp(stringLiteral())))
/// would match the declaration for a.
/// while
/// varDecl(hasInitializer(stringLiteral()))
/// would match the declaration for a only if the Checked C extension
/// is disabled.
AST_MATCHER_P(Expr, ignoringParenTmp, internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreParenTmp(), Finder, Builder);
}
/// Matches expressions that match InnerMatcher after implicit casts and
/// parentheses are stripped off.
///
/// Explicit casts are not discarded.
/// Given
/// \code
/// int arr[5];
/// int a = 0;
/// char b = (0);
/// const int c = a;
/// int *d = (arr);
/// long e = ((long) 0l);
/// \endcode
/// The matchers
/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
/// would match the declarations for a, b, c, and d, but not e.
/// while
/// varDecl(hasInitializer(integerLiteral()))
/// varDecl(hasInitializer(declRefExpr()))
/// would only match the declaration for a.
AST_MATCHER_P(Expr, ignoringParenImpCasts,
internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
}
/// Matches types that match InnerMatcher after any parens are stripped.
///
/// Given
/// \code
/// void (*fp)(void);
/// \endcode
/// The matcher
/// \code
/// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
/// \endcode
/// would match the declaration for fp.
AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
InnerMatcher, 0) {
return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
}
/// Overload \c ignoringParens for \c Expr.
///
/// Given
/// \code
/// const char* str = ("my-string");
/// \endcode
/// The matcher
/// \code
/// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
/// \endcode
/// would match the implicit cast resulting from the assignment.
AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
InnerMatcher, 1) {
const Expr *E = Node.IgnoreParens();
return InnerMatcher.matches(*E, Finder, Builder);
}
/// Matches expressions that are instantiation-dependent even if it is
/// neither type- nor value-dependent.
///
/// In the following example, the expression sizeof(sizeof(T() + T()))
/// is instantiation-dependent (since it involves a template parameter T),
/// but is neither type- nor value-dependent, since the type of the inner
/// sizeof is known (std::size_t) and therefore the size of the outer
/// sizeof is known.
/// \code
/// template<typename T>
/// void f(T x, T y) { sizeof(sizeof(T() + T()); }
/// \endcode
/// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
AST_MATCHER(Expr, isInstantiationDependent) {
return Node.isInstantiationDependent();
}
/// Matches expressions that are type-dependent because the template type
/// is not yet instantiated.
///
/// For example, the expressions "x" and "x + y" are type-dependent in
/// the following code, but "y" is not type-dependent:
/// \code
/// template<typename T>
/// void add(T x, int y) {
/// x + y;
/// }
/// \endcode
/// expr(isTypeDependent()) matches x + y
AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
/// Matches expression that are value-dependent because they contain a
/// non-type template parameter.
///
/// For example, the array bound of "Chars" in the following example is
/// value-dependent.
/// \code
/// template<int Size> int f() { return Size; }
/// \endcode
/// expr(isValueDependent()) matches return Size
AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
/// Matches classTemplateSpecializations, templateSpecializationType and
/// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
///
/// Given
/// \code
/// template<typename T, typename U> class A {};
/// A<bool, int> b;
/// A<int, bool> c;
///
/// template<typename T> void f() {}
/// void func() { f<int>(); };
/// \endcode
/// classTemplateSpecializationDecl(hasTemplateArgument(
/// 1, refersToType(asString("int"))))
/// matches the specialization \c A<bool, int>
///
/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
/// matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P2(
hasTemplateArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
TemplateSpecializationType,
FunctionDecl),
unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
ArrayRef<TemplateArgument> List =
internal::getTemplateSpecializationArgs(Node);
if (List.size() <= N)
return false;
return InnerMatcher.matches(List[N], Finder, Builder);
}
/// Matches if the number of template arguments equals \p N.
///
/// Given
/// \code
/// template<typename T> struct C {};
/// C<int> c;
/// \endcode
/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
/// matches C<int>.
AST_POLYMORPHIC_MATCHER_P(
templateArgumentCountIs,
AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
TemplateSpecializationType),
unsigned, N) {
return internal::getTemplateSpecializationArgs(Node).size() == N;
}
/// Matches a TemplateArgument that refers to a certain type.
///
/// Given
/// \code
/// struct X {};
/// template<typename T> struct A {};
/// A<X> a;
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToType(class(hasName("X")))))
/// matches the specialization \c A<X>
AST_MATCHER_P(TemplateArgument, refersToType,
internal::Matcher<QualType>, InnerMatcher) {
if (Node.getKind() != TemplateArgument::Type)
return false;
return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
}
/// Matches a TemplateArgument that refers to a certain template.
///
/// Given
/// \code
/// template<template <typename> class S> class X {};
/// template<typename T> class Y {};
/// X<Y> xi;
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToTemplate(templateName())))
/// matches the specialization \c X<Y>
AST_MATCHER_P(TemplateArgument, refersToTemplate,
internal::Matcher<TemplateName>, InnerMatcher) {
if (Node.getKind() != TemplateArgument::Template)
return false;
return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
}
/// Matches a canonical TemplateArgument that refers to a certain
/// declaration.
///
/// Given
/// \code
/// struct B { int next; };
/// template<int(B::*next_ptr)> struct A {};
/// A<&B::next> a;
/// \endcode
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToDeclaration(fieldDecl(hasName("next")))))
/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
/// \c B::next
AST_MATCHER_P(TemplateArgument, refersToDeclaration,
internal::Matcher<Decl>, InnerMatcher) {
if (Node.getKind() == TemplateArgument::Declaration)
return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
return false;
}
/// Matches a sugar TemplateArgument that refers to a certain expression.
///
/// Given
/// \code
/// struct B { int next; };
/// template<int(B::*next_ptr)> struct A {};
/// A<&B::next> a;
/// \endcode
/// templateSpecializationType(hasAnyTemplateArgument(
/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
/// \c B::next
AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
if (Node.getKind() == TemplateArgument::Expression)
return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
return false;
}
/// Matches a TemplateArgument that is an integral value.
///
/// Given
/// \code
/// template<int T> struct C {};
/// C<42> c;
/// \endcode
/// classTemplateSpecializationDecl(
/// hasAnyTemplateArgument(isIntegral()))
/// matches the implicit instantiation of C in C<42>
/// with isIntegral() matching 42.
AST_MATCHER(TemplateArgument, isIntegral) {
return Node.getKind() == TemplateArgument::Integral;
}
/// Matches a TemplateArgument that refers to an integral type.
///
/// Given
/// \code
/// template<int T> struct C {};
/// C<42> c;
/// \endcode
/// classTemplateSpecializationDecl(
/// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
/// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument, refersToIntegralType,
internal::Matcher<QualType>, InnerMatcher) {
if (Node.getKind() != TemplateArgument::Integral)
return false;
return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
}
/// Matches a TemplateArgument of integral type with a given value.
///
/// Note that 'Value' is a string as the template argument's value is
/// an arbitrary precision integer. 'Value' must be euqal to the canonical
/// representation of that integral value in base 10.
///
/// Given
/// \code
/// template<int T> struct C {};
/// C<42> c;
/// \endcode
/// classTemplateSpecializationDecl(
/// hasAnyTemplateArgument(equalsIntegralValue("42")))
/// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
std::string, Value) {
if (Node.getKind() != TemplateArgument::Integral)
return false;
return Node.getAsIntegral().toString(10) == Value;
}
/// Matches an Objective-C autorelease pool statement.
///
/// Given
/// \code
/// @autoreleasepool {
/// int x = 0;
/// }
/// \endcode
/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
/// inside the autorelease pool.
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
/// Matches any value declaration.
///
/// Example matches A, B, C and F
/// \code
/// enum X { A, B, C };
/// void F();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
/// Matches C++ constructor declarations.
///
/// Example matches Foo::Foo() and Foo::Foo(int)
/// \code
/// class Foo {
/// public:
/// Foo();
/// Foo(int);
/// int DoSomething();
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
cxxConstructorDecl;
/// Matches explicit C++ destructor declarations.
///
/// Example matches Foo::~Foo()
/// \code
/// class Foo {
/// public:
/// virtual ~Foo();
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
cxxDestructorDecl;
/// Matches enum declarations.
///
/// Example matches X
/// \code
/// enum X {
/// A, B, C
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
/// Matches enum constants.
///
/// Example matches A, B, C
/// \code
/// enum X {
/// A, B, C
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
enumConstantDecl;
/// Matches tag declarations.
///
/// Example matches X, Z, U, S, E
/// \code
/// class X;
/// template<class T> class Z {};
/// struct S {};
/// union U {};
/// enum E {
/// A, B, C
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
/// Matches method declarations.
///
/// Example matches y
/// \code
/// class X { void y(); };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
cxxMethodDecl;
/// Matches conversion operator declarations.
///
/// Example matches the operator.
/// \code
/// class X { operator int() const; };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
cxxConversionDecl;
/// Matches user-defined and implicitly generated deduction guide.
///
/// Example matches the deduction guide.
/// \code
/// template<typename T>
/// class X { X(int) };
/// X(int) -> X<int>;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
cxxDeductionGuideDecl;
/// Matches variable declarations.
///
/// Note: this does not match declarations of member variables, which are
/// "field" declarations in Clang parlance.
///
/// Example matches a
/// \code
/// int a;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
/// Matches field declarations.
///
/// Given
/// \code
/// class X { int m; };
/// \endcode
/// fieldDecl()
/// matches 'm'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
/// Matches indirect field declarations.
///
/// Given
/// \code
/// struct X { struct { int a; }; };
/// \endcode
/// indirectFieldDecl()
/// matches 'a'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
indirectFieldDecl;
/// Matches function declarations.
///
/// Example matches f
/// \code
/// void f();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
functionDecl;
/// Matches C++ function template declarations.
///
/// Example matches f
/// \code
/// template<class T> void f(T t) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
functionTemplateDecl;
/// Matches friend declarations.
///
/// Given
/// \code
/// class X { friend void foo(); };
/// \endcode
/// friendDecl()
/// matches 'friend void foo()'.
extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
/// Matches statements.
///
/// Given
/// \code
/// { ++a; }
/// \endcode
/// stmt()
/// matches both the compound statement '{ ++a; }' and '++a'.
extern const internal::VariadicAllOfMatcher<Stmt> stmt;
/// Matches declaration statements.
///
/// Given
/// \code
/// int a;
/// \endcode
/// declStmt()
/// matches 'int a'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
/// Matches member expressions.
///
/// Given
/// \code
/// class Y {
/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
/// int a; static int b;
/// };
/// \endcode
/// memberExpr()
/// matches this->x, x, y.x, a, this->b
extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
/// Matches unresolved member expressions.
///
/// Given
/// \code
/// struct X {
/// template <class T> void f();
/// void g();
/// };
/// template <class T> void h() { X x; x.f<T>(); x.g(); }
/// \endcode
/// unresolvedMemberExpr()
/// matches x.f<T>
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
unresolvedMemberExpr;
/// Matches member expressions where the actual member referenced could not be
/// resolved because the base expression or the member name was dependent.
///
/// Given
/// \code
/// template <class T> void f() { T t; t.g(); }
/// \endcode
/// cxxDependentScopeMemberExpr()
/// matches t.g
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
CXXDependentScopeMemberExpr>
cxxDependentScopeMemberExpr;
/// Matches call expressions.
///
/// Example matches x.y() and y()
/// \code
/// X x;
/// x.y();
/// y();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
/// Matches call expressions which were resolved using ADL.
///
/// Example matches y(x) but not y(42) or NS::y(x).
/// \code
/// namespace NS {
/// struct X {};
/// void y(X);
/// }
///
/// void y(...);
///
/// void test() {
/// NS::X x;
/// y(x); // Matches
/// NS::y(x); // Doesn't match
/// y(42); // Doesn't match
/// using NS::y;
/// y(x); // Found by both unqualified lookup and ADL, doesn't match
// }
/// \endcode
AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
/// Matches lambda expressions.
///
/// Example matches [&](){return 5;}
/// \code
/// [&](){return 5;}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
/// Matches member call expressions.
///
/// Example matches x.y()
/// \code
/// X x;
/// x.y();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
cxxMemberCallExpr;
/// Matches ObjectiveC Message invocation expressions.
///
/// The innermost message send invokes the "alloc" class method on the
/// NSString class, while the outermost message send invokes the
/// "initWithString" instance method on the object returned from
/// NSString's "alloc". This matcher should match both message sends.
/// \code
/// [[NSString alloc] initWithString:@"Hello"]
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
objcMessageExpr;
/// Matches Objective-C interface declarations.
///
/// Example matches Foo
/// \code
/// @interface Foo
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
objcInterfaceDecl;
/// Matches Objective-C implementation declarations.
///
/// Example matches Foo
/// \code
/// @implementation Foo
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
objcImplementationDecl;
/// Matches Objective-C protocol declarations.
///
/// Example matches FooDelegate
/// \code
/// @protocol FooDelegate
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
objcProtocolDecl;
/// Matches Objective-C category declarations.
///
/// Example matches Foo (Additions)
/// \code
/// @interface Foo (Additions)
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
objcCategoryDecl;
/// Matches Objective-C category definitions.
///
/// Example matches Foo (Additions)
/// \code
/// @implementation Foo (Additions)
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
objcCategoryImplDecl;
/// Matches Objective-C method declarations.
///
/// Example matches both declaration and definition of -[Foo method]
/// \code
/// @interface Foo
/// - (void)method;
/// @end
///
/// @implementation Foo
/// - (void)method {}
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
objcMethodDecl;
/// Matches block declarations.
///
/// Example matches the declaration of the nameless block printing an input
/// integer.
///
/// \code
/// myFunc(^(int p) {
/// printf("%d", p);
/// })
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
blockDecl;
/// Matches Objective-C instance variable declarations.
///
/// Example matches _enabled
/// \code
/// @implementation Foo {
/// BOOL _enabled;
/// }
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
objcIvarDecl;
/// Matches Objective-C property declarations.
///
/// Example matches enabled
/// \code
/// @interface Foo
/// @property BOOL enabled;
/// @end
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
objcPropertyDecl;
/// Matches Objective-C \@throw statements.
///
/// Example matches \@throw
/// \code
/// @throw obj;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
objcThrowStmt;
/// Matches Objective-C @try statements.
///
/// Example matches @try
/// \code
/// @try {}
/// @catch (...) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
objcTryStmt;
/// Matches Objective-C @catch statements.
///
/// Example matches @catch
/// \code
/// @try {}
/// @catch (...) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
objcCatchStmt;
/// Matches Objective-C @finally statements.
///
/// Example matches @finally
/// \code
/// @try {}
/// @finally {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
objcFinallyStmt;
/// Matches expressions that introduce cleanups to be run at the end
/// of the sub-expression's evaluation.
///
/// Example matches std::string()
/// \code
/// const std::string str = std::string();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
exprWithCleanups;
/// Matches init list expressions.
///
/// Given
/// \code
/// int a[] = { 1, 2 };
/// struct B { int x, y; };
/// B b = { 5, 6 };
/// \endcode
/// initListExpr()
/// matches "{ 1, 2 }" and "{ 5, 6 }"
extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
initListExpr;
/// Matches the syntactic form of init list expressions
/// (if expression have it).
AST_MATCHER_P(InitListExpr, hasSyntacticForm,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *SyntForm = Node.getSyntacticForm();
return (SyntForm != nullptr &&
InnerMatcher.matches(*SyntForm, Finder, Builder));
}
/// Matches C++ initializer list expressions.
///
/// Given
/// \code
/// std::vector<int> a({ 1, 2, 3 });
/// std::vector<int> b = { 4, 5 };
/// int c[] = { 6, 7 };
/// std::pair<int, int> d = { 8, 9 };
/// \endcode
/// cxxStdInitializerListExpr()
/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
CXXStdInitializerListExpr>
cxxStdInitializerListExpr;
/// Matches implicit initializers of init list expressions.
///
/// Given
/// \code
/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
/// \endcode
/// implicitValueInitExpr()
/// matches "[0].y" (implicitly)
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
implicitValueInitExpr;
/// Matches paren list expressions.
/// ParenListExprs don't have a predefined type and are used for late parsing.
/// In the final AST, they can be met in template declarations.
///
/// Given
/// \code
/// template<typename T> class X {
/// void f() {
/// X x(*this);
/// int a = 0, b = 1; int i = (a, b);
/// }
/// };
/// \endcode
/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
/// has a predefined type and is a ParenExpr, not a ParenListExpr.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
parenListExpr;
/// Matches substitutions of non-type template parameters.
///
/// Given
/// \code
/// template <int N>
/// struct A { static const int n = N; };
/// struct B : public A<42> {};
/// \endcode
/// substNonTypeTemplateParmExpr()
/// matches "N" in the right-hand side of "static const int n = N;"
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
SubstNonTypeTemplateParmExpr>
substNonTypeTemplateParmExpr;
/// Matches using declarations.
///
/// Given
/// \code
/// namespace X { int x; }
/// using X::x;
/// \endcode
/// usingDecl()
/// matches \code using X::x \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
/// Matches using namespace declarations.
///
/// Given
/// \code
/// namespace X { int x; }
/// using namespace X;
/// \endcode
/// usingDirectiveDecl()
/// matches \code using namespace X \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
usingDirectiveDecl;
/// Matches reference to a name that can be looked up during parsing
/// but could not be resolved to a specific declaration.
///
/// Given
/// \code
/// template<typename T>
/// T foo() { T a; return a; }
/// template<typename T>
/// void bar() {
/// foo<T>();
/// }
/// \endcode
/// unresolvedLookupExpr()
/// matches \code foo<T>() \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
unresolvedLookupExpr;
/// Matches unresolved using value declarations.
///
/// Given
/// \code
/// template<typename X>
/// class C : private X {
/// using X::x;
/// };
/// \endcode
/// unresolvedUsingValueDecl()
/// matches \code using X::x \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl,
UnresolvedUsingValueDecl>
unresolvedUsingValueDecl;
/// Matches unresolved using value declarations that involve the
/// typename.
///
/// Given
/// \code
/// template <typename T>
/// struct Base { typedef T Foo; };
///
/// template<typename T>
/// struct S : private Base<T> {
/// using typename Base<T>::Foo;
/// };
/// \endcode
/// unresolvedUsingTypenameDecl()
/// matches \code using Base<T>::Foo \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl,
UnresolvedUsingTypenameDecl>
unresolvedUsingTypenameDecl;
/// Matches a constant expression wrapper.
///
/// Example matches the constant in the case statement:
/// (matcher = constantExpr())
/// \code
/// switch (a) {
/// case 37: break;
/// }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
constantExpr;
/// Matches parentheses used in expressions.
///
/// Example matches (foo() + 1)
/// \code
/// int foo() { return 1; }
/// int a = (foo() + 1);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
/// Matches constructor call expressions (including implicit ones).
///
/// Example matches string(ptr, n) and ptr within arguments of f
/// (matcher = cxxConstructExpr())
/// \code
/// void f(const string &a, const string &b);
/// char *ptr;
/// int n;
/// f(string(ptr, n), ptr);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
cxxConstructExpr;
/// Matches unresolved constructor call expressions.
///
/// Example matches T(t) in return statement of f
/// (matcher = cxxUnresolvedConstructExpr())
/// \code
/// template <typename T>
/// void f(const T& t) { return T(t); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
CXXUnresolvedConstructExpr>
cxxUnresolvedConstructExpr;
/// Matches implicit and explicit this expressions.
///
/// Example matches the implicit this expression in "return i".
/// (matcher = cxxThisExpr())
/// \code
/// struct foo {
/// int i;
/// int f() { return i; }
/// };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
cxxThisExpr;
/// Matches nodes where temporaries are created.
///
/// Example matches FunctionTakesString(GetStringByValue())
/// (matcher = cxxBindTemporaryExpr())
/// \code
/// FunctionTakesString(GetStringByValue());
/// FunctionTakesStringByPointer(GetStringPointer());
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
cxxBindTemporaryExpr;
/// Matches nodes where temporaries are materialized.
///
/// Example: Given
/// \code
/// struct T {void func();};
/// T f();
/// void g(T);
/// \endcode
/// materializeTemporaryExpr() matches 'f()' in these statements
/// \code
/// T u(f());
/// g(f());
/// f().func();
/// \endcode
/// but does not match
/// \code
/// f();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
MaterializeTemporaryExpr>
materializeTemporaryExpr;
/// Matches new expressions.
///
/// Given
/// \code
/// new X;
/// \endcode
/// cxxNewExpr()
/// matches 'new X'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
/// Matches delete expressions.
///
/// Given
/// \code
/// delete X;
/// \endcode
/// cxxDeleteExpr()
/// matches 'delete X'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
cxxDeleteExpr;
/// Matches noexcept expressions.
///
/// Given
/// \code
/// bool a() noexcept;
/// bool b() noexcept(true);
/// bool c() noexcept(false);
/// bool d() noexcept(noexcept(a()));
/// bool e = noexcept(b()) || noexcept(c());
/// \endcode
/// cxxNoexceptExpr()
/// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
/// doesn't match the noexcept specifier in the declarations a, b, c or d.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
cxxNoexceptExpr;
/// Matches array subscript expressions.
///
/// Given
/// \code
/// int i = a[1];
/// \endcode
/// arraySubscriptExpr()
/// matches "a[1]"
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
arraySubscriptExpr;
/// Matches the value of a default argument at the call site.
///
/// Example matches the CXXDefaultArgExpr placeholder inserted for the
/// default value of the second parameter in the call expression f(42)
/// (matcher = cxxDefaultArgExpr())
/// \code
/// void f(int x, int y = 0);
/// f(42);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
cxxDefaultArgExpr;
/// Matches overloaded operator calls.
///
/// Note that if an operator isn't overloaded, it won't match. Instead, use
/// binaryOperator matcher.
/// Currently it does not match operators such as new delete.
/// FIXME: figure out why these do not match?
///
/// Example matches both operator<<((o << b), c) and operator<<(o, b)
/// (matcher = cxxOperatorCallExpr())
/// \code
/// ostream &operator<< (ostream &out, int i) { };
/// ostream &o; int b = 1, c = 1;
/// o << b << c;
/// \endcode
/// See also the binaryOperation() matcher for more-general matching of binary
/// uses of this AST node.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
cxxOperatorCallExpr;
/// Matches rewritten binary operators
///
/// Example matches use of "<":
/// \code
/// #include <compare>
/// struct HasSpaceshipMem {
/// int a;
/// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
/// };
/// void compare() {
/// HasSpaceshipMem hs1, hs2;
/// if (hs1 < hs2)
/// return;
/// }
/// \endcode
/// See also the binaryOperation() matcher for more-general matching
/// of this AST node.
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
CXXRewrittenBinaryOperator>
cxxRewrittenBinaryOperator;
/// Matches expressions.
///
/// Example matches x()
/// \code
/// void f() { x(); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
/// Matches expressions that refer to declarations.
///
/// Example matches x in if (x)
/// \code
/// bool x;
/// if (x) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
declRefExpr;
/// Matches a reference to an ObjCIvar.
///
/// Example: matches "a" in "init" method:
/// \code
/// @implementation A {
/// NSString *a;
/// }
/// - (void) init {
/// a = @"hello";
/// }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
objcIvarRefExpr;
/// Matches a reference to a block.
///
/// Example: matches "^{}":
/// \code
/// void f() { ^{}(); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
/// Matches if statements.
///
/// Example matches 'if (x) {}'
/// \code
/// if (x) {}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
/// Matches for statements.
///
/// Example matches 'for (;;) {}'
/// \code
/// for (;;) {}
/// int i[] = {1, 2, 3}; for (auto a : i);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
/// Matches the increment statement of a for loop.
///
/// Example:
/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
/// matches '++x' in
/// \code
/// for (x; x < N; ++x) { }
/// \endcode
AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
InnerMatcher) {
const Stmt *const Increment = Node.getInc();
return (Increment != nullptr &&
InnerMatcher.matches(*Increment, Finder, Builder));
}
/// Matches the initialization statement of a for loop.
///
/// Example:
/// forStmt(hasLoopInit(declStmt()))
/// matches 'int x = 0' in
/// \code
/// for (int x = 0; x < N; ++x) { }
/// \endcode
AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
InnerMatcher) {
const Stmt *const Init = Node.getInit();
return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
}
/// Matches range-based for statements.
///
/// cxxForRangeStmt() matches 'for (auto a : i)'
/// \code
/// int i[] = {1, 2, 3}; for (auto a : i);
/// for(int j = 0; j < 5; ++j);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
cxxForRangeStmt;
/// Matches the initialization statement of a for loop.
///
/// Example:
/// forStmt(hasLoopVariable(anything()))
/// matches 'int x' in
/// \code
/// for (int x : a) { }
/// \endcode
AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
InnerMatcher) {
const VarDecl *const Var = Node.getLoopVariable();
return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
}
/// Matches the range initialization statement of a for loop.
///
/// Example:
/// forStmt(hasRangeInit(anything()))
/// matches 'a' in
/// \code
/// for (int x : a) { }
/// \endcode
AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *const Init = Node.getRangeInit();
return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
}
/// Matches while statements.
///
/// Given
/// \code
/// while (true) {}
/// \endcode
/// whileStmt()
/// matches 'while (true) {}'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
/// Matches do statements.
///
/// Given
/// \code
/// do {} while (true);
/// \endcode
/// doStmt()
/// matches 'do {} while(true)'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
/// Matches break statements.
///
/// Given
/// \code
/// while (true) { break; }
/// \endcode
/// breakStmt()
/// matches 'break'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
/// Matches continue statements.
///
/// Given
/// \code
/// while (true) { continue; }
/// \endcode
/// continueStmt()
/// matches 'continue'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
continueStmt;
/// Matches return statements.
///
/// Given
/// \code
/// return 1;
/// \endcode
/// returnStmt()
/// matches 'return 1'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
/// Matches goto statements.
///
/// Given
/// \code
/// goto FOO;
/// FOO: bar();
/// \endcode
/// gotoStmt()
/// matches 'goto FOO'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
/// Matches label statements.
///
/// Given
/// \code
/// goto FOO;
/// FOO: bar();
/// \endcode
/// labelStmt()
/// matches 'FOO:'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
/// Matches address of label statements (GNU extension).
///
/// Given
/// \code
/// FOO: bar();
/// void *ptr = &&FOO;
/// goto *bar;
/// \endcode
/// addrLabelExpr()
/// matches '&&FOO'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
addrLabelExpr;
/// Matches switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// switchStmt()
/// matches 'switch(a)'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
/// Matches case and default statements inside switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// switchCase()
/// matches 'case 42:' and 'default:'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
/// Matches case statements inside switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// caseStmt()
/// matches 'case 42:'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
/// Matches default statements inside switch statements.
///
/// Given
/// \code
/// switch(a) { case 42: break; default: break; }
/// \endcode
/// defaultStmt()
/// matches 'default:'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
defaultStmt;
/// Matches compound statements.
///
/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
/// \code
/// for (;;) {{}}
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
compoundStmt;
/// Matches catch statements.
///
/// \code
/// try {} catch(int i) {}
/// \endcode
/// cxxCatchStmt()
/// matches 'catch(int i)'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
cxxCatchStmt;
/// Matches try statements.
///
/// \code
/// try {} catch(int i) {}
/// \endcode
/// cxxTryStmt()
/// matches 'try {}'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
/// Matches throw expressions.
///
/// \code
/// try { throw 5; } catch(int i) {}
/// \endcode
/// cxxThrowExpr()
/// matches 'throw 5'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
cxxThrowExpr;
/// Matches null statements.
///
/// \code
/// foo();;
/// \endcode
/// nullStmt()
/// matches the second ';'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
/// Matches asm statements.
///
/// \code
/// int i = 100;
/// __asm("mov al, 2");
/// \endcode
/// asmStmt()
/// matches '__asm("mov al, 2")'
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
/// Matches bool literals.
///
/// Example matches true
/// \code
/// true
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
cxxBoolLiteral;
/// Matches string literals (also matches wide string literals).
///
/// Example matches "abcd", L"abcd"
/// \code
/// char *s = "abcd";
/// wchar_t *ws = L"abcd";
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
stringLiteral;
/// Matches character literals (also matches wchar_t).
///
/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
/// though.
///
/// Example matches 'a', L'a'
/// \code
/// char ch = 'a';
/// wchar_t chw = L'a';
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
characterLiteral;
/// Matches integer literals of all sizes / encodings, e.g.
/// 1, 1L, 0x1 and 1U.
///
/// Does not match character-encoded integers such as L'a'.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
integerLiteral;
/// Matches float literals of all sizes / encodings, e.g.
/// 1.0, 1.0f, 1.0L and 1e10.
///
/// Does not match implicit conversions such as
/// \code
/// float a = 10;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
floatLiteral;
/// Matches imaginary literals, which are based on integer and floating
/// point literals e.g.: 1i, 1.0i
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
imaginaryLiteral;
/// Matches fixed point literals
extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
fixedPointLiteral;
/// Matches user defined literal operator call.
///
/// Example match: "foo"_suffix
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
userDefinedLiteral;
/// Matches compound (i.e. non-scalar) literals
///
/// Example match: {1}, (1, 2)
/// \code
/// int array[4] = {1};
/// vector int myvec = (vector int)(1, 2);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
compoundLiteralExpr;
/// Matches nullptr literal.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
cxxNullPtrLiteralExpr;
/// Matches GNU __builtin_choose_expr.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
chooseExpr;
/// Matches GNU __null expression.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
gnuNullExpr;
/// Matches C11 _Generic expression.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
genericSelectionExpr;
/// Matches atomic builtins.
/// Example matches __atomic_load_n(ptr, 1)
/// \code
/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
/// Matches statement expression (GNU extension).
///
/// Example match: ({ int X = 4; X; })
/// \code
/// int C = ({ int X = 4; X; });
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
/// Matches binary operator expressions.
///
/// Example matches a || b
/// \code
/// !(a || b)
/// \endcode
/// See also the binaryOperation() matcher for more-general matching.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
binaryOperator;
/// Matches unary operator expressions.
///
/// Example matches !a
/// \code
/// !a || b
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
unaryOperator;
/// Matches conditional operator expressions.
///
/// Example matches a ? b : c
/// \code
/// (a ? b : c) + 42
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
conditionalOperator;
/// Matches binary conditional operator expressions (GNU extension).
///
/// Example matches a ?: b
/// \code
/// (a ?: b) + 42;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
BinaryConditionalOperator>
binaryConditionalOperator;
/// Matches opaque value expressions. They are used as helpers
/// to reference another expressions and can be met
/// in BinaryConditionalOperators, for example.
///
/// Example matches 'a'
/// \code
/// (a ?: c) + 42;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
opaqueValueExpr;
/// Matches a C++ static_assert declaration.
///
/// Example:
/// staticAssertExpr()
/// matches
/// static_assert(sizeof(S) == sizeof(int))
/// in
/// \code
/// struct S {
/// int x;
/// };
/// static_assert(sizeof(S) == sizeof(int));
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
staticAssertDecl;
/// Matches a reinterpret_cast expression.
///
/// Either the source expression or the destination type can be matched
/// using has(), but hasDestinationType() is more specific and can be
/// more readable.
///
/// Example matches reinterpret_cast<char*>(&p) in
/// \code
/// void* p = reinterpret_cast<char*>(&p);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
cxxReinterpretCastExpr;
/// Matches a C++ static_cast expression.
///
/// \see hasDestinationType
/// \see reinterpretCast
///
/// Example:
/// cxxStaticCastExpr()
/// matches
/// static_cast<long>(8)
/// in
/// \code
/// long eight(static_cast<long>(8));
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
cxxStaticCastExpr;
/// Matches a dynamic_cast expression.
///
/// Example:
/// cxxDynamicCastExpr()
/// matches
/// dynamic_cast<D*>(&b);
/// in
/// \code
/// struct B { virtual ~B() {} }; struct D : B {};
/// B b;
/// D* p = dynamic_cast<D*>(&b);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
cxxDynamicCastExpr;
/// Matches a const_cast expression.
///
/// Example: Matches const_cast<int*>(&r) in
/// \code
/// int n = 42;
/// const int &r(n);
/// int* p = const_cast<int*>(&r);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
cxxConstCastExpr;
/// Matches a C-style cast expression.
///
/// Example: Matches (int) 2.2f in
/// \code
/// int i = (int) 2.2f;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
cStyleCastExpr;
/// Matches explicit cast expressions.
///
/// Matches any cast expression written in user code, whether it be a
/// C-style cast, a functional-style cast, or a keyword cast.
///
/// Does not match implicit conversions.
///
/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
/// Clang uses the term "cast" to apply to implicit conversions as well as to
/// actual cast expressions.
///
/// \see hasDestinationType.
///
/// Example: matches all five of the casts in
/// \code
/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
/// \endcode
/// but does not match the implicit conversion in
/// \code
/// long ell = 42;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
explicitCastExpr;
/// Matches the implicit cast nodes of Clang's AST.
///
/// This matches many different places, including function call return value
/// eliding, as well as any type conversions.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
implicitCastExpr;
/// Matches any cast nodes of Clang's AST.
///
/// Example: castExpr() matches each of the following:
/// \code
/// (int) 3;
/// const_cast<Expr *>(SubExpr);
/// char c = 0;
/// \endcode
/// but does not match
/// \code
/// int i = (0);
/// int k = 0;
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
/// Matches functional cast expressions
///
/// Example: Matches Foo(bar);
/// \code
/// Foo f = bar;
/// Foo g = (Foo) bar;
/// Foo h = Foo(bar);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
cxxFunctionalCastExpr;
/// Matches functional cast expressions having N != 1 arguments
///
/// Example: Matches Foo(bar, bar)
/// \code
/// Foo h = Foo(bar, bar);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
cxxTemporaryObjectExpr;
/// Matches predefined identifier expressions [C99 6.4.2.2].
///
/// Example: Matches __func__
/// \code
/// printf("%s", __func__);
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
predefinedExpr;
/// Matches C99 designated initializer expressions [C99 6.7.8].
///
/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
/// \code
/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
designatedInitExpr;
/// Matches designated initializer expressions that contain
/// a specific number of designators.
///
/// Example: Given
/// \code
/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
/// \endcode
/// designatorCountIs(2)
/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
return Node.size() == N;
}
/// Matches \c QualTypes in the clang AST.
extern const internal::VariadicAllOfMatcher<QualType> qualType;
/// Matches \c Types in the clang AST.
extern const internal::VariadicAllOfMatcher<Type> type;
/// Matches \c TypeLocs in the clang AST.
extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
/// Matches if any of the given matchers matches.
///
/// Unlike \c anyOf, \c eachOf will generate a match result for each
/// matching submatcher.
///
/// For example, in:
/// \code
/// class A { int a; int b; };
/// \endcode
/// The matcher:
/// \code
/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
/// has(fieldDecl(hasName("b")).bind("v"))))
/// \endcode
/// will generate two results binding "v", the first of which binds
/// the field declaration of \c a, the second the field declaration of
/// \c b.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<
2, std::numeric_limits<unsigned>::max()>
eachOf;
/// Matches if any of the given matchers matches.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<
2, std::numeric_limits<unsigned>::max()>
anyOf;
/// Matches if all given matchers match.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<
2, std::numeric_limits<unsigned>::max()>
allOf;
/// Matches any node regardless of the submatcher.
///
/// However, \c optionally will retain any bindings generated by the submatcher.
/// Useful when additional information which may or may not present about a main
/// matching node is desired.
///
/// For example, in:
/// \code
/// class Foo {
/// int bar;
/// }
/// \endcode
/// The matcher:
/// \code
/// cxxRecordDecl(
/// optionally(has(
/// fieldDecl(hasName("bar")).bind("var")
/// ))).bind("record")
/// \endcode
/// will produce a result binding for both "record" and "var".
/// The matcher will produce a "record" binding for even if there is no data
/// member named "bar" in that class.
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
///
/// Given
/// \code
/// Foo x = bar;
/// int y = sizeof(x) + alignof(x);
/// \endcode
/// unaryExprOrTypeTraitExpr()
/// matches \c sizeof(x) and \c alignof(x)
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
UnaryExprOrTypeTraitExpr>
unaryExprOrTypeTraitExpr;
/// Matches any of the \p NodeMatchers with InnerMatchers nested within
///
/// Given
/// \code
/// if (true);
/// for (; true; );
/// \endcode
/// with the matcher
/// \code
/// mapAnyOf(ifStmt, forStmt).with(
/// hasCondition(cxxBoolLiteralExpr(equals(true)))
/// ).bind("trueCond")
/// \endcode
/// matches the \c if and the \c for. It is equivalent to:
/// \code
/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
/// anyOf(
/// ifStmt(trueCond).bind("trueCond"),
/// forStmt(trueCond).bind("trueCond")
/// );
/// \endcode
///
/// The with() chain-call accepts zero or more matchers which are combined
/// as-if with allOf() in each of the node matchers.
/// Usable as: Any Matcher
template <typename T, typename... U>
auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
return internal::MapAnyOfHelper<U...>();
}
/// Matches nodes which can be used with binary operators.
///
/// The code
/// \code
/// var1 != var2;
/// \endcode
/// might be represented in the clang AST as a binaryOperator, a
/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
///
/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
/// least one is a class type (cxxOperatorCallExpr)
/// * whether the code appears in a template declaration, if at least one of the
/// vars is a dependent-type (binaryOperator)
/// * whether the code relies on a rewritten binary operator, such as a
/// spaceship operator or an inverted equality operator
/// (cxxRewrittenBinaryOperator)
///
/// This matcher elides details in places where the matchers for the nodes are
/// compatible.
///
/// Given
/// \code
/// binaryOperation(
/// hasOperatorName("!="),
/// hasLHS(expr().bind("lhs")),
/// hasRHS(expr().bind("rhs"))
/// )
/// \endcode
/// matches each use of "!=" in:
/// \code
/// struct S{
/// bool operator!=(const S&) const;
/// };
///
/// void foo()
/// {
/// 1 != 2;
/// S() != S();
/// }
///
/// template<typename T>
/// void templ()
/// {
/// 1 != 2;
/// T() != S();
/// }
/// struct HasOpEq
/// {
/// bool operator==(const HasOpEq &) const;
/// };
///
/// void inverse()
/// {
/// HasOpEq s1;
/// HasOpEq s2;
/// if (s1 != s2)
/// return;
/// }
///
/// struct HasSpaceship
/// {
/// bool operator<=>(const HasOpEq &) const;
/// };
///
/// void use_spaceship()
/// {
/// HasSpaceship s1;
/// HasSpaceship s2;
/// if (s1 != s2)
/// return;
/// }
/// \endcode
extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator>
binaryOperation;
/// Matches unary expressions that have a specific type of argument.
///
/// Given
/// \code
/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
/// \endcode
/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
/// matches \c sizeof(a) and \c alignof(c)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
internal::Matcher<QualType>, InnerMatcher) {
const QualType ArgumentType = Node.getTypeOfArgument();
return InnerMatcher.matches(ArgumentType, Finder, Builder);
}
/// Matches unary expressions of a certain kind.
///
/// Given
/// \code
/// int x;
/// int s = sizeof(x) + alignof(x)
/// \endcode
/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
/// matches \c sizeof(x)
///
/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
return Node.getKind() == Kind;
}
/// Same as unaryExprOrTypeTraitExpr, but only matching
/// alignof.
inline internal::BindableMatcher<Stmt> alignOfExpr(
const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
return stmt(unaryExprOrTypeTraitExpr(
allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
InnerMatcher)));
}
/// Same as unaryExprOrTypeTraitExpr, but only matching
/// sizeof.
inline internal::BindableMatcher<Stmt> sizeOfExpr(
const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
return stmt(unaryExprOrTypeTraitExpr(
allOf(ofKind(UETT_SizeOf), InnerMatcher)));
}
/// Matches NamedDecl nodes that have the specified name.
///
/// Supports specifying enclosing namespaces or classes by prefixing the name
/// with '<enclosing>::'.
/// Does not match typedefs of an underlying type with the given name.
///
/// Example matches X (Name == "X")
/// \code
/// class X;
/// \endcode
///
/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
/// \code
/// namespace a { namespace b { class X; } }
/// \endcode
inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
return internal::Matcher<NamedDecl>(
new internal::HasNameMatcher({std::string(Name)}));
}
/// Matches NamedDecl nodes that have any of the specified names.
///
/// This matcher is only provided as a performance optimization of hasName.
/// \code
/// hasAnyName(a, b, c)
/// \endcode
/// is equivalent to, but faster than
/// \code
/// anyOf(hasName(a), hasName(b), hasName(c))
/// \endcode
extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
internal::hasAnyNameFunc>
hasAnyName;
/// Matches NamedDecl nodes whose fully qualified names contain
/// a substring matched by the given RegExp.
///
/// Supports specifying enclosing namespaces or classes by
/// prefixing the name with '<enclosing>::'. Does not match typedefs
/// of an underlying type with the given name.
///
/// Example matches X (regexp == "::X")
/// \code
/// class X;
/// \endcode
///
/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
/// \code
/// namespace foo { namespace bar { class X; } }
/// \endcode
AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
std::string FullNameString = "::" + Node.getQualifiedNameAsString();
return RegExp->match(FullNameString);
}
/// Matches overloaded operator names.
///
/// Matches overloaded operator names specified in strings without the
/// "operator" prefix: e.g. "<<".
///
/// Given:
/// \code
/// class A { int operator*(); };
/// const A &operator<<(const A &a, const A &b);
/// A a;
/// a << a; // <-- This matches
/// \endcode
///
/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
/// specified line and
/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
/// matches the declaration of \c A.
///
/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
inline internal::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
hasOverloadedOperatorName(StringRef Name) {
return internal::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(
{std::string(Name)});
}
/// Matches overloaded operator names.
///
/// Matches overloaded operator names specified in strings without the
/// "operator" prefix: e.g. "<<".
///
/// hasAnyOverloadedOperatorName("+", "-")
/// Is equivalent to
/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
extern const internal::VariadicFunction<
internal::PolymorphicMatcherWithParam1<
internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>,
StringRef, internal::hasAnyOverloadedOperatorNameFunc>
hasAnyOverloadedOperatorName;
/// Matches template-dependent, but known, member names.
///
/// In template declarations, dependent members are not resolved and so can
/// not be matched to particular named declarations.
///
/// This matcher allows to match on the known name of members.
///
/// Given
/// \code
/// template <typename T>
/// struct S {
/// void mem();
/// };
/// template <typename T>
/// void x() {
/// S<T> s;
/// s.mem();
/// }
/// \endcode
/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
return Node.getMember().getAsString() == N;
}
/// Matches template-dependent, but known, member names against an already-bound
/// node
///
/// In template declarations, dependent members are not resolved and so can
/// not be matched to particular named declarations.
///
/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
/// and CXXMethodDecl nodes.
///
/// Given
/// \code
/// template <typename T>
/// struct S {
/// void mem();
/// };
/// template <typename T>
/// void x() {
/// S<T> s;
/// s.mem();
/// }
/// \endcode
/// The matcher
/// @code
/// \c cxxDependentScopeMemberExpr(
/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
/// cxxMethodDecl(hasName("mem")).bind("templMem")
/// )))))
/// )))),
/// memberHasSameNameAsBoundNode("templMem")
/// )
/// @endcode
/// first matches and binds the @c mem member of the @c S template, then
/// compares its name to the usage in @c s.mem() in the @c x function template
AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
std::string, BindingID) {
auto MemberName = Node.getMember().getAsString();
return Builder->removeBindings(
[this, MemberName](const BoundNodesMap &Nodes) {
const auto &BN = Nodes.getNode(this->BindingID);
if (const auto *ND = BN.get<NamedDecl>()) {
if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
return true;
return ND->getName() != MemberName;
}
return true;
});
}
/// Matches C++ classes that are directly or indirectly derived from a class
/// matching \c Base, or Objective-C classes that directly or indirectly
/// subclass a class matching \c Base.
///
/// Note that a class is not considered to be derived from itself.
///
/// Example matches Y, Z, C (Base == hasName("X"))
/// \code
/// class X;
/// class Y : public X {}; // directly derived
/// class Z : public Y {}; // indirectly derived
/// typedef X A;
/// typedef A B;
/// class C : public B {}; // derived from a typedef of X
/// \endcode
///
/// In the following example, Bar matches isDerivedFrom(hasName("X")):
/// \code
/// class Foo;
/// typedef Foo X;
/// class Bar : public Foo {}; // derived from a type that X is a typedef of
/// \endcode
///
/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
/// \code
/// @interface NSObject @end
/// @interface Bar : NSObject @end
/// \endcode
///
/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
AST_POLYMORPHIC_MATCHER_P(
isDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
internal::Matcher<NamedDecl>, Base) {
// Check if the node is a C++ struct/union/class.
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
// The node must be an Objective-C class.
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
/*Directly=*/false);
}
/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
std::string, BaseName, 1) {
if (BaseName.empty())
return false;
const auto M = isDerivedFrom(hasName(BaseName));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Matches C++ classes that have a direct or indirect base matching \p
/// BaseSpecMatcher.
///
/// Example:
/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
/// \code
/// class Foo;
/// class Bar : Foo {};
/// class Baz : Bar {};
/// class SpecialBase;
/// class Proxy : SpecialBase {}; // matches Proxy
/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
/// \endcode
///
// FIXME: Refactor this and isDerivedFrom to reuse implementation.
AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
BaseSpecMatcher) {
return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
}
/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
///
/// Example:
/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
/// \code
/// class Foo;
/// class Bar : Foo {};
/// class Baz : Bar {};
/// class SpecialBase;
/// class Proxy : SpecialBase {}; // matches Proxy
/// class IndirectlyDerived : Proxy {}; // doesn't match
/// \endcode
AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
BaseSpecMatcher) {
return Node.hasDefinition() &&
llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
return BaseSpecMatcher.matches(Base, Finder, Builder);
});
}
/// Similar to \c isDerivedFrom(), but also matches classes that directly
/// match \c Base.
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isSameOrDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
internal::Matcher<NamedDecl>, Base, 0) {
const auto M = anyOf(Base, isDerivedFrom(Base));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Overloaded method as shortcut for
/// \c isSameOrDerivedFrom(hasName(...)).
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isSameOrDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
std::string, BaseName, 1) {
if (BaseName.empty())
return false;
const auto M = isSameOrDerivedFrom(hasName(BaseName));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Matches C++ or Objective-C classes that are directly derived from a class
/// matching \c Base.
///
/// Note that a class is not considered to be derived from itself.
///
/// Example matches Y, C (Base == hasName("X"))
/// \code
/// class X;
/// class Y : public X {}; // directly derived
/// class Z : public Y {}; // indirectly derived
/// typedef X A;
/// typedef A B;
/// class C : public B {}; // derived from a typedef of X
/// \endcode
///
/// In the following example, Bar matches isDerivedFrom(hasName("X")):
/// \code
/// class Foo;
/// typedef Foo X;
/// class Bar : public Foo {}; // derived from a type that X is a typedef of
/// \endcode
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isDirectlyDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
internal::Matcher<NamedDecl>, Base, 0) {
// Check if the node is a C++ struct/union/class.
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
// The node must be an Objective-C class.
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
/*Directly=*/true);
}
/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
isDirectlyDerivedFrom,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
std::string, BaseName, 1) {
if (BaseName.empty())
return false;
const auto M = isDirectlyDerivedFrom(hasName(BaseName));
if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
}
/// Matches the first method of a class or struct that satisfies \c
/// InnerMatcher.
///
/// Given:
/// \code
/// class A { void func(); };
/// class B { void member(); };
/// \endcode
///
/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
/// \c A but not \c B.
AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
InnerMatcher) {
BoundNodesTreeBuilder Result(*Builder);
auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
Node.method_end(), Finder, &Result);
if (MatchIt == Node.method_end())
return false;
if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
return false;
*Builder = std::move(Result);
return true;
}
/// Matches the generated class of lambda expressions.
///
/// Given:
/// \code
/// auto x = []{};
/// \endcode
///
/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
/// \c decltype(x)
AST_MATCHER(CXXRecordDecl, isLambda) {
return Node.isLambda();
}
/// Matches AST nodes that have child AST nodes that match the
/// provided matcher.
///
/// Example matches X, Y
/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
/// \code
/// class X {}; // Matches X, because X::X is a class of name X inside X.
/// class Y { class X {}; };
/// class Z { class Y { class X {}; }; }; // Does not match Z.
/// \endcode
///
/// ChildT must be an AST base type.
///
/// Usable as: Any Matcher
/// Note that has is direct matcher, so it also matches things like implicit
/// casts and paren casts. If you are matching with expr then you should
/// probably consider using ignoringParenImpCasts like:
/// has(ignoringParenImpCasts(expr())).
extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
/// Matches AST nodes that have descendant AST nodes that match the
/// provided matcher.
///
/// Example matches X, Y, Z
/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
/// \code
/// class X {}; // Matches X, because X::X is a class of name X inside X.
/// class Y { class X {}; };
/// class Z { class Y { class X {}; }; };
/// \endcode
///
/// DescendantT must be an AST base type.
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::HasDescendantMatcher>
hasDescendant;
/// Matches AST nodes that have child AST nodes that match the
/// provided matcher.
///
/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
/// \code
/// class X {};
/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
/// // inside Y.
/// class Z { class Y { class X {}; }; }; // Does not match Z.
/// \endcode
///
/// ChildT must be an AST base type.
///
/// As opposed to 'has', 'forEach' will cause a match for each result that
/// matches instead of only on the first one.
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
forEach;
/// Matches AST nodes that have descendant AST nodes that match the
/// provided matcher.
///
/// Example matches X, A, A::X, B, B::C, B::C::X
/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
/// \code
/// class X {};
/// class A { class X {}; }; // Matches A, because A::X is a class of name
/// // X inside A.
/// class B { class C { class X {}; }; };
/// \endcode
///
/// DescendantT must be an AST base type.
///
/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
/// each result that matches instead of only on the first one.
///
/// Note: Recursively combined ForEachDescendant can cause many matches:
/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
/// forEachDescendant(cxxRecordDecl())
/// )))
/// will match 10 times (plus injected class name matches) on:
/// \code
/// class A { class B { class C { class D { class E {}; }; }; }; };
/// \endcode
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::ForEachDescendantMatcher>
forEachDescendant;
/// Matches if the node or any descendant matches.
///
/// Generates results for each match.
///
/// For example, in:
/// \code
/// class A { class B {}; class C {}; };
/// \endcode
/// The matcher:
/// \code
/// cxxRecordDecl(hasName("::A"),
/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
/// \endcode
/// will generate results for \c A, \c B and \c C.
///
/// Usable as: Any Matcher
template <typename T>
internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
return eachOf(Matcher, forEachDescendant(Matcher));
}
/// Matches AST nodes that have a parent that matches the provided
/// matcher.
///
/// Given
/// \code
/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
/// \endcode
/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::HasParentMatcher,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
hasParent;
/// Matches AST nodes that have an ancestor that matches the provided
/// matcher.
///
/// Given
/// \code
/// void f() { if (true) { int x = 42; } }
/// void g() { for (;;) { int x = 43; } }
/// \endcode
/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
///
/// Usable as: Any Matcher
extern const internal::ArgumentAdaptingMatcherFunc<
internal::HasAncestorMatcher,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
hasAncestor;
/// Matches if the provided matcher does not match.
///
/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
/// \code
/// class X {};
/// class Y {};
/// \endcode
///
/// Usable as: Any Matcher
extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
/// Matches a node if the declaration associated with that node
/// matches the given matcher.
///
/// The associated declaration is:
/// - for type nodes, the declaration of the underlying type
/// - for CallExpr, the declaration of the callee
/// - for MemberExpr, the declaration of the referenced member
/// - for CXXConstructExpr, the declaration of the constructor
/// - for CXXNewExpr, the declaration of the operator new
/// - for ObjCIvarExpr, the declaration of the ivar
///
/// For type nodes, hasDeclaration will generally match the declaration of the
/// sugared type. Given
/// \code
/// class X {};
/// typedef X Y;
/// Y y;
/// \endcode
/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
/// typedefDecl. A common use case is to match the underlying, desugared type.
/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
/// \code
/// varDecl(hasType(hasUnqualifiedDesugaredType(
/// recordType(hasDeclaration(decl())))))
/// \endcode
/// In this matcher, the decl will match the CXXRecordDecl of class X.
///
/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
/// Matcher<UnresolvedUsingType>
inline internal::PolymorphicMatcherWithParam1<
internal::HasDeclarationMatcher, internal::Matcher<Decl>,
void(internal::HasDeclarationSupportedTypes)>
hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
return internal::PolymorphicMatcherWithParam1<
internal::HasDeclarationMatcher, internal::Matcher<Decl>,
void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
}
/// Matches a \c NamedDecl whose underlying declaration matches the given
/// matcher.
///
/// Given
/// \code
/// namespace N { template<class T> void f(T t); }
/// template <class T> void g() { using N::f; f(T()); }
/// \endcode
/// \c unresolvedLookupExpr(hasAnyDeclaration(
/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
/// matches the use of \c f in \c g() .
AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
InnerMatcher) {
const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
return UnderlyingDecl != nullptr &&
InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
}
/// Matches on the implicit object argument of a member call expression, after
/// stripping off any parentheses or implicit casts.
///
/// Given
/// \code
/// class Y { public: void m(); };
/// Y g();
/// class X : public Y {};
/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
/// \endcode
/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
/// matches `y.m()` and `(g()).m()`.
/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
/// matches `x.m()`.
/// cxxMemberCallExpr(on(callExpr()))
/// matches `(g()).m()`.
///
/// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *ExprNode = Node.getImplicitObjectArgument()
->IgnoreParenImpCasts();
return (ExprNode != nullptr &&
InnerMatcher.matches(*ExprNode, Finder, Builder));
}
/// Matches on the receiver of an ObjectiveC Message expression.
///
/// Example
/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
/// matches the [webView ...] message invocation.
/// \code
/// NSString *webViewJavaScript = ...
/// UIWebView *webView = ...
/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
/// \endcode
AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
InnerMatcher) {
const QualType TypeDecl = Node.getReceiverType();
return InnerMatcher.matches(TypeDecl, Finder, Builder);
}
/// Returns true when the Objective-C method declaration is a class method.
///
/// Example
/// matcher = objcMethodDecl(isClassMethod())
/// matches
/// \code
/// @interface I + (void)foo; @end
/// \endcode
/// but not
/// \code
/// @interface I - (void)bar; @end
/// \endcode
AST_MATCHER(ObjCMethodDecl, isClassMethod) {
return Node.isClassMethod();
}
/// Returns true when the Objective-C method declaration is an instance method.
///
/// Example
/// matcher = objcMethodDecl(isInstanceMethod())
/// matches
/// \code
/// @interface I - (void)bar; @end
/// \endcode
/// but not
/// \code
/// @interface I + (void)foo; @end
/// \endcode
AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
return Node.isInstanceMethod();
}
/// Returns true when the Objective-C message is sent to a class.
///
/// Example
/// matcher = objcMessageExpr(isClassMessage())
/// matches
/// \code
/// [NSString stringWithFormat:@"format"];
/// \endcode
/// but not
/// \code
/// NSString *x = @"hello";
/// [x containsString:@"h"];
/// \endcode
AST_MATCHER(ObjCMessageExpr, isClassMessage) {
return Node.isClassMessage();
}
/// Returns true when the Objective-C message is sent to an instance.
///
/// Example
/// matcher = objcMessageExpr(isInstanceMessage())
/// matches
/// \code
/// NSString *x = @"hello";
/// [x containsString:@"h"];
/// \endcode
/// but not
/// \code
/// [NSString stringWithFormat:@"format"];
/// \endcode
AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
return Node.isInstanceMessage();
}
/// Matches if the Objective-C message is sent to an instance,
/// and the inner matcher matches on that instance.
///
/// For example the method call in
/// \code
/// NSString *x = @"hello";
/// [x containsString:@"h"];
/// \endcode
/// is matched by
/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *ReceiverNode = Node.getInstanceReceiver();
return (ReceiverNode != nullptr &&
InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
Builder));
}
/// Matches when BaseName == Selector.getAsString()
///
/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
/// matches the outer message expr in the code below, but NOT the message
/// invocation for self.bodyView.
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
Selector Sel = Node.getSelector();
return BaseName.compare(Sel.getAsString()) == 0;
}
/// Matches when at least one of the supplied string equals to the
/// Selector.getAsString()
///
/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
/// matches both of the expressions below:
/// \code
/// [myObj methodA:argA];
/// [myObj methodB:argB];
/// \endcode
extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
StringRef,
internal::hasAnySelectorFunc>
hasAnySelector;
/// Matches ObjC selectors whose name contains
/// a substring matched by the given RegExp.
/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
/// matches the outer message expr in the code below, but NOT the message
/// invocation for self.bodyView.
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
std::string SelectorString = Node.getSelector().getAsString();
return RegExp->match(SelectorString);
}
/// Matches when the selector is the empty selector
///
/// Matches only when the selector of the objCMessageExpr is NULL. This may
/// represent an error condition in the tree!
AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
return Node.getSelector().isNull();
}
/// Matches when the selector is a Unary Selector
///
/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
/// matches self.bodyView in the code below, but NOT the outer message
/// invocation of "loadHTMLString:baseURL:".
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
return Node.getSelector().isUnarySelector();
}
/// Matches when the selector is a keyword selector
///
/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
/// message expression in
///
/// \code
/// UIWebView *webView = ...;
/// CGRect bodyFrame = webView.frame;
/// bodyFrame.size.height = self.bodyContentHeight;
/// webView.frame = bodyFrame;
/// // ^---- matches here
/// \endcode
AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
return Node.getSelector().isKeywordSelector();
}
/// Matches when the selector has the specified number of arguments
///
/// matcher = objCMessageExpr(numSelectorArgs(0));
/// matches self.bodyView in the code below
///
/// matcher = objCMessageExpr(numSelectorArgs(2));
/// matches the invocation of "loadHTMLString:baseURL:" but not that
/// of self.bodyView
/// \code
/// [self.bodyView loadHTMLString:html baseURL:NULL];
/// \endcode
AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
return Node.getSelector().getNumArgs() == N;
}
/// Matches if the call expression's callee expression matches.
///
/// Given
/// \code
/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
/// void f() { f(); }
/// \endcode
/// callExpr(callee(expr()))
/// matches this->x(), x(), y.x(), f()
/// with callee(...)
/// matching this->x, x, y.x, f respectively
///
/// Note: Callee cannot take the more general internal::Matcher<Expr>
/// because this introduces ambiguous overloads with calls to Callee taking a
/// internal::Matcher<Decl>, as the matcher hierarchy is purely
/// implemented in terms of implicit casts.
AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
InnerMatcher) {
const Expr *ExprNode = Node.getCallee();
return (ExprNode != nullptr &&
InnerMatcher.matches(*ExprNode, Finder, Builder));
}
/// Matches if the call expression's callee's declaration matches the
/// given matcher.
///
/// Example matches y.x() (matcher = callExpr(callee(
/// cxxMethodDecl(hasName("x")))))
/// \code
/// class Y { public: void x(); };
/// void z() { Y y; y.x(); }
/// \endcode
AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
1) {
return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
}
/// Matches if the expression's or declaration's type matches a type
/// matcher.
///
/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
/// and U (matcher = typedefDecl(hasType(asString("int")))
/// and friend class X (matcher = friendDecl(hasType("X"))
/// \code
/// class X {};
/// void y(X &x) { x; X z; }
/// typedef int U;
/// class Y { friend class X; };
/// \endcode
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
hasType,
AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
ValueDecl),
internal::Matcher<QualType>, InnerMatcher, 0) {
QualType QT = internal::getUnderlyingType(Node);
if (!QT.isNull())
return InnerMatcher.matches(QT, Finder, Builder);
return false;
}
/// Overloaded to match the declaration of the expression's or value
/// declaration's type.
///
/// In case of a value declaration (for example a variable declaration),
/// this resolves one layer of indirection. For example, in the value
/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
/// declaration of x.
///
/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
/// and friend class X (matcher = friendDecl(hasType("X"))
/// \code
/// class X {};
/// void y(X &x) { x; X z; }
/// class Y { friend class X; };
/// \endcode
///
/// Example matches class Derived
/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
/// \code
/// class Base {};
/// class Derived : Base {};
/// \endcode
///
/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
/// Matcher<CXXBaseSpecifier>
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
hasType,
AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl,
CXXBaseSpecifier),
internal::Matcher<Decl>, InnerMatcher, 1) {
QualType QT = internal::getUnderlyingType(Node);
if (!QT.isNull())
return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
return false;
}
/// Matches if the type location of the declarator decl's type matches
/// the inner matcher.
///
/// Given
/// \code
/// int x;
/// \endcode
/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
/// matches int x
AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
if (!Node.getTypeSourceInfo())
// This happens for example for implicit destructors.
return false;
return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
}
/// Matches if the matched type is represented by the given string.
///
/// Given
/// \code
/// class Y { public: void x(); };
/// void z() { Y* y; y->x(); }
/// \endcode
/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
/// matches y->x()
AST_MATCHER_P(QualType, asString, std::string, Name) {
return Name == Node.getAsString();
}
/// Matches if the matched type is a pointer type and the pointee type
/// matches the specified matcher.
///
/// Example matches y->x()
/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
/// cxxRecordDecl(hasName("Y")))))))
/// \code
/// class Y { public: void x(); };
/// void z() { Y *y; y->x(); }
/// \endcode
AST_MATCHER_P(
QualType, pointsTo, internal::Matcher<QualType>,
InnerMatcher) {
return (!Node.isNull() && Node->isAnyPointerType() &&
InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
}
/// Overloaded to match the pointee type's declaration.
AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
InnerMatcher, 1) {
return pointsTo(qualType(hasDeclaration(InnerMatcher)))
.matches(Node, Finder, Builder);
}
/// Matches if the matched type matches the unqualified desugared
/// type of the matched node.
///
/// For example, in:
/// \code
/// class A {};
/// using B = A;
/// \endcode
/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
/// both B and A.
AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
InnerMatcher) {
return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
Builder);
}
/// Matches if the matched type is a reference type and the referenced
/// type matches the specified matcher.
///
/// Example matches X &x and const X &y
/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
/// \code
/// class X {
/// void a(X b) {
/// X &x = b;
/// const X &y = b;
/// }
/// };
/// \endcode
AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
InnerMatcher) {
return (!Node.isNull() && Node->isReferenceType() &&
InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
}
/// Matches QualTypes whose canonical type matches InnerMatcher.
///
/// Given:
/// \code
/// typedef int &int_ref;
/// int a;
/// int_ref b = a;
/// \endcode
///
/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
/// declaration of b but \c
/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
InnerMatcher) {
if (Node.isNull())
return false;
return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
}
/// Overloaded to match the referenced type's declaration.
AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
InnerMatcher, 1) {
return references(qualType(hasDeclaration(InnerMatcher)))
.matches(Node, Finder, Builder);
}
/// Matches on the implicit object argument of a member call expression. Unlike
/// `on`, matches the argument directly without stripping away anything.
///
/// Given
/// \code
/// class Y { public: void m(); };
/// Y g();
/// class X : public Y { void g(); };
/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
/// \endcode
/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
/// cxxRecordDecl(hasName("Y")))))
/// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
/// cxxMemberCallExpr(on(callExpr()))
/// does not match `(g()).m()`, because the parens are not ignored.
///
/// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *ExprNode = Node.getImplicitObjectArgument();
return (ExprNode != nullptr &&
InnerMatcher.matches(*ExprNode, Finder, Builder));
}
/// Matches if the type of the expression's implicit object argument either
/// matches the InnerMatcher, or is a pointer to a type that matches the
/// InnerMatcher.
///
/// Given
/// \code
/// class Y { public: void m(); };
/// class X : public Y { void g(); };
/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
/// \endcode
/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
/// cxxRecordDecl(hasName("Y")))))
/// matches `y.m()`, `p->m()` and `x.m()`.
/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
/// cxxRecordDecl(hasName("X")))))
/// matches `x.g()`.
AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
internal::Matcher<QualType>, InnerMatcher, 0) {
return onImplicitObjectArgument(
anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
.matches(Node, Finder, Builder);
}
/// Overloaded to match the type's declaration.
AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
internal::Matcher<Decl>, InnerMatcher, 1) {
return onImplicitObjectArgument(
anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
.matches(Node, Finder, Builder);
}
/// Matches a DeclRefExpr that refers to a declaration that matches the
/// specified matcher.
///
/// Example matches x in if(x)
/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
/// \code
/// bool x;
/// if (x) {}
/// \endcode
AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
InnerMatcher) {
const Decl *DeclNode = Node.getDecl();
return (DeclNode != nullptr &&
InnerMatcher.matches(*DeclNode, Finder, Builder));
}
/// Matches a \c DeclRefExpr that refers to a declaration through a
/// specific using shadow declaration.
///
/// Given
/// \code
/// namespace a { void f() {} }
/// using a::f;
/// void g() {
/// f(); // Matches this ..
/// a::f(); // .. but not this.
/// }
/// \endcode
/// declRefExpr(throughUsingDecl(anything()))
/// matches \c f()
AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
internal::Matcher<UsingShadowDecl>, InnerMatcher) {
const NamedDecl *FoundDecl = Node.getFoundDecl();
if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
return InnerMatcher.matches(*UsingDecl, Finder, Builder);
return false;
}
/// Matches an \c OverloadExpr if any of the declarations in the set of
/// overloads matches the given matcher.
///
/// Given
/// \code
/// template <typename T> void foo(T);
/// template <typename T> void bar(T);
/// template <typename T> void baz(T t) {
/// foo(t);
/// bar(t);
/// }
/// \endcode
/// unresolvedLookupExpr(hasAnyDeclaration(
/// functionTemplateDecl(hasName("foo"))))
/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
Node.decls_end(), Finder,
Builder) != Node.decls_end();
}
/// Matches the Decl of a DeclStmt which has a single declaration.
///
/// Given
/// \code
/// int a, b;
/// int c;
/// \endcode
/// declStmt(hasSingleDecl(anything()))
/// matches 'int c;' but not 'int a, b;'.
AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
if (Node.isSingleDecl()) {
const Decl *FoundDecl = Node.getSingleDecl();
return InnerMatcher.matches(*FoundDecl, Finder, Builder);
}
return false;
}
/// Matches a variable declaration that has an initializer expression
/// that matches the given matcher.
///
/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
/// \code
/// bool y() { return true; }
/// bool x = y();
/// \endcode
AST_MATCHER_P(
VarDecl, hasInitializer, internal::Matcher<Expr>,
InnerMatcher) {
const Expr *Initializer = Node.getAnyInitializer();
return (Initializer != nullptr &&
InnerMatcher.matches(*Initializer, Finder, Builder));
}
/// \brief Matches a static variable with local scope.
///
/// Example matches y (matcher = varDecl(isStaticLocal()))
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// static int z;
/// \endcode
AST_MATCHER(VarDecl, isStaticLocal) {
return Node.isStaticLocal();
}
/// Matches a variable declaration that has function scope and is a
/// non-static local variable.
///
/// Example matches x (matcher = varDecl(hasLocalStorage())
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// int z;
/// \endcode
AST_MATCHER(VarDecl, hasLocalStorage) {
return Node.hasLocalStorage();
}
/// Matches a variable declaration that does not have local storage.
///
/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// int z;
/// \endcode
AST_MATCHER(VarDecl, hasGlobalStorage) {
return Node.hasGlobalStorage();
}
/// Matches a variable declaration that has automatic storage duration.
///
/// Example matches x, but not y, z, or a.
/// (matcher = varDecl(hasAutomaticStorageDuration())
/// \code
/// void f() {
/// int x;
/// static int y;
/// thread_local int z;
/// }
/// int a;
/// \endcode
AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
return Node.getStorageDuration() == SD_Automatic;
}
/// Matches a variable declaration that has static storage duration.
/// It includes the variable declared at namespace scope and those declared
/// with "static" and "extern" storage class specifiers.
///
/// \code
/// void f() {
/// int x;
/// static int y;
/// thread_local int z;
/// }
/// int a;
/// static int b;
/// extern int c;
/// varDecl(hasStaticStorageDuration())
/// matches the function declaration y, a, b and c.
/// \endcode
AST_MATCHER(VarDecl, hasStaticStorageDuration) {
return Node.getStorageDuration() == SD_Static;
}
/// Matches a variable declaration that has thread storage duration.
///
/// Example matches z, but not x, z, or a.
/// (matcher = varDecl(hasThreadStorageDuration())
/// \code
/// void f() {
/// int x;
/// static int y;
/// thread_local int z;
/// }
/// int a;
/// \endcode
AST_MATCHER(VarDecl, hasThreadStorageDuration) {
return Node.getStorageDuration() == SD_Thread;
}
/// Matches a variable declaration that is an exception variable from
/// a C++ catch block, or an Objective-C \@catch statement.
///
/// Example matches x (matcher = varDecl(isExceptionVariable())
/// \code
/// void f(int y) {
/// try {
/// } catch (int x) {
/// }
/// }
/// \endcode
AST_MATCHER(VarDecl, isExceptionVariable) {
return Node.isExceptionVariable();
}
/// Checks that a call expression or a constructor call expression has
/// a specific number of arguments (including absent default arguments).
///
/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
/// \code
/// void f(int x, int y);
/// f(0, 0);
/// \endcode
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
AST_POLYMORPHIC_SUPPORTED_TYPES(
CallExpr, CXXConstructExpr,
CXXUnresolvedConstructExpr, ObjCMessageExpr),
unsigned, N) {
unsigned NumArgs = Node.getNumArgs();
if (!Finder->isTraversalIgnoringImplicitNodes())
return NumArgs == N;
while (NumArgs) {
if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
break;
--NumArgs;
}
return NumArgs == N;
}
/// Matches the n'th argument of a call expression or a constructor
/// call expression.
///
/// Example matches y in x(y)
/// (matcher = callExpr(hasArgument(0, declRefExpr())))
/// \code
/// void x(int) { int y; x(y); }
/// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(
CallExpr, CXXConstructExpr,
CXXUnresolvedConstructExpr, ObjCMessageExpr),
unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
if (N >= Node.getNumArgs())
return false;
const Expr *Arg = Node.getArg(N);
if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
return false;
return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
}
/// Matches the n'th item of an initializer list expression.
///
/// Example matches y.
/// (matcher = initListExpr(hasInit(0, expr())))
/// \code
/// int x{y}.
/// \endcode
AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
return N < Node.getNumInits() &&
InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
}
/// Matches declaration statements that contain a specific number of
/// declarations.
///
/// Example: Given
/// \code
/// int a, b;
/// int c;
/// int d = 2, e;
/// \endcode
/// declCountIs(2)
/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
}
/// Matches the n'th declaration of a declaration statement.
///
/// Note that this does not work for global declarations because the AST
/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
/// DeclStmt's.
/// Example: Given non-global declarations
/// \code
/// int a, b = 0;
/// int c;
/// int d = 2, e;
/// \endcode
/// declStmt(containsDeclaration(
/// 0, varDecl(hasInitializer(anything()))))
/// matches only 'int d = 2, e;', and
/// declStmt(containsDeclaration(1, varDecl()))
/// \code
/// matches 'int a, b = 0' as well as 'int d = 2, e;'
/// but 'int c;' is not matched.
/// \endcode
AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
internal::Matcher<Decl>, InnerMatcher) {
const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
if (N >= NumDecls)
return false;
DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
std::advance(Iterator, N);
return InnerMatcher.matches(**Iterator, Finder, Builder);
}
/// Matches a C++ catch statement that has a catch-all handler.
///
/// Given
/// \code
/// try {
/// // ...
/// } catch (int) {
/// // ...
/// } catch (...) {
/// // ...
/// }
/// \endcode
/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
AST_MATCHER(CXXCatchStmt, isCatchAll) {
return Node.getExceptionDecl() == nullptr;
}
/// Matches a constructor initializer.
///
/// Given
/// \code
/// struct Foo {
/// Foo() : foo_(1) { }
/// int foo_;
/// };
/// \endcode
/// cxxRecordDecl(has(cxxConstructorDecl(
/// hasAnyConstructorInitializer(anything())
/// )))
/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
Node.init_end(), Finder, Builder);
if (MatchIt == Node.init_end())
return false;
return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
}
/// Matches the field declaration of a constructor initializer.
///
/// Given
/// \code
/// struct Foo {
/// Foo() : foo_(1) { }
/// int foo_;
/// };
/// \endcode
/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
/// forField(hasName("foo_"))))))
/// matches Foo
/// with forField matching foo_
AST_MATCHER_P(CXXCtorInitializer, forField,
internal::Matcher<FieldDecl>, InnerMatcher) {
const FieldDecl *NodeAsDecl = Node.getAnyMember();
return (NodeAsDecl != nullptr &&
InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
}
/// Matches the initializer expression of a constructor initializer.
///
/// Given
/// \code
/// struct Foo {
/// Foo() : foo_(1) { }
/// int foo_;
/// };
/// \endcode
/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
/// withInitializer(integerLiteral(equals(1)))))))
/// matches Foo
/// with withInitializer matching (1)
AST_MATCHER_P(CXXCtorInitializer, withInitializer,
internal::Matcher<Expr>, InnerMatcher) {
const Expr* NodeAsExpr = Node.getInit();
return (NodeAsExpr != nullptr &&
InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
}
/// Matches a constructor initializer if it is explicitly written in
/// code (as opposed to implicitly added by the compiler).
///
/// Given
/// \code
/// struct Foo {
/// Foo() { }
/// Foo(int) : foo_("A") { }
/// string foo_;
/// };
/// \endcode
/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
/// will match Foo(int), but not Foo()
AST_MATCHER(CXXCtorInitializer, isWritten) {
return Node.isWritten();
}
/// Matches a constructor initializer if it is initializing a base, as
/// opposed to a member.
///
/// Given
/// \code
/// struct B {};
/// struct D : B {
/// int I;
/// D(int i) : I(i) {}
/// };
/// struct E : B {
/// E() : B() {}
/// };
/// \endcode
/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
/// will match E(), but not match D(int).
AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
return Node.isBaseInitializer();
}
/// Matches a constructor initializer if it is initializing a member, as
/// opposed to a base.
///
/// Given
/// \code
/// struct B {};
/// struct D : B {
/// int I;
/// D(int i) : I(i) {}
/// };
/// struct E : B {
/// E() : B() {}
/// };
/// \endcode
/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
/// will match D(int), but not match E().
AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
return Node.isMemberInitializer();
}
/// Matches any argument of a call expression or a constructor call
/// expression, or an ObjC-message-send expression.
///
/// Given
/// \code
/// void x(int, int, int) { int y; x(1, y, 42); }
/// \endcode
/// callExpr(hasAnyArgument(declRefExpr()))
/// matches x(1, y, 42)
/// with hasAnyArgument(...)
/// matching y
///
/// For ObjectiveC, given
/// \code
/// @interface I - (void) f:(int) y; @end
/// void foo(I *i) { [i f:12]; }
/// \endcode
/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
/// matches [i f:12]
AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES(
CallExpr, CXXConstructExpr,
CXXUnresolvedConstructExpr, ObjCMessageExpr),
internal::Matcher<Expr>, InnerMatcher) {
for (const Expr *Arg : Node.arguments()) {
if (Finder->isTraversalIgnoringImplicitNodes() &&
isa<CXXDefaultArgExpr>(Arg))
break;
BoundNodesTreeBuilder Result(*Builder);
if (InnerMatcher.matches(*Arg, Finder, &Result)) {
*Builder = std::move(Result);
return true;
}
}
return false;
}
/// Matches any capture of a lambda expression.
///
/// Given
/// \code
/// void foo() {
/// int x;
/// auto f = [x](){};
/// }
/// \endcode
/// lambdaExpr(hasAnyCapture(anything()))
/// matches [x](){};
AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<VarDecl>,
InnerMatcher, 0) {
for (const LambdaCapture &Capture : Node.captures()) {
if (Capture.capturesVariable()) {
BoundNodesTreeBuilder Result(*Builder);
if (InnerMatcher.matches(*Capture.getCapturedVar(), Finder, &Result)) {
*Builder = std::move(Result);
return true;
}
}
}
return false;
}
/// Matches any capture of 'this' in a lambda expression.
///
/// Given
/// \code
/// struct foo {
/// void bar() {
/// auto f = [this](){};
/// }
/// }
/// \endcode
/// lambdaExpr(hasAnyCapture(cxxThisExpr()))
/// matches [this](){};
AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture,
internal::Matcher<CXXThisExpr>, InnerMatcher, 1) {
return llvm::any_of(Node.captures(), [](const LambdaCapture &LC) {
return LC.capturesThis();
});
}
/// Matches a constructor call expression which uses list initialization.
AST_MATCHER(CXXConstructExpr, isListInitialization) {
return Node.isListInitialization();
}
/// Matches a constructor call expression which requires
/// zero initialization.
///
/// Given
/// \code
/// void foo() {
/// struct point { double x; double y; };
/// point pt[2] = { { 1.0, 2.0 } };
/// }
/// \endcode
/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
/// will match the implicit array filler for pt[1].
AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
return Node.requiresZeroInitialization();
}
/// Matches the n'th parameter of a function or an ObjC method
/// declaration or a block.
///
/// Given
/// \code
/// class X { void f(int x) {} };
/// \endcode
/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
/// matches f(int x) {}
/// with hasParameter(...)
/// matching int x
///
/// For ObjectiveC, given
/// \code
/// @interface I - (void) f:(int) y; @end
/// \endcode
//
/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
/// matches the declaration of method f with hasParameter
/// matching y.
AST_POLYMORPHIC_MATCHER_P2(hasParameter,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
ObjCMethodDecl,
BlockDecl),
unsigned, N, internal::Matcher<ParmVarDecl>,
InnerMatcher) {
return (N < Node.parameters().size()
&& InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
}
/// Matches all arguments and their respective ParmVarDecl.
///
/// Given
/// \code
/// void f(int i);
/// int y;
/// f(y);
/// \endcode
/// callExpr(
/// forEachArgumentWithParam(
/// declRefExpr(to(varDecl(hasName("y")))),
/// parmVarDecl(hasType(isInteger()))
/// ))
/// matches f(y);
/// with declRefExpr(...)
/// matching int y
/// and parmVarDecl(...)
/// matching int i
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
CXXConstructExpr),
internal::Matcher<Expr>, ArgMatcher,
internal::Matcher<ParmVarDecl>, ParamMatcher) {
BoundNodesTreeBuilder Result;
// The first argument of an overloaded member operator is the implicit object
// argument of the method which should not be matched against a parameter, so
// we skip over it here.
BoundNodesTreeBuilder Matches;
unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
.matches(Node, Finder, &Matches)
? 1
: 0;
int ParamIndex = 0;
bool Matched = false;
for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
BoundNodesTreeBuilder ArgMatches(*Builder);
if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
Finder, &ArgMatches)) {
BoundNodesTreeBuilder ParamMatches(ArgMatches);
if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
hasParameter(ParamIndex, ParamMatcher)))),
callExpr(callee(functionDecl(
hasParameter(ParamIndex, ParamMatcher))))))
.matches(Node, Finder, &ParamMatches)) {
Result.addMatch(ParamMatches);
Matched = true;
}
}
++ParamIndex;
}
*Builder = std::move(Result);
return Matched;
}
/// Matches all arguments and their respective types for a \c CallExpr or
/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
/// it works on calls through function pointers as well.
///
/// The difference is, that function pointers do not provide access to a
/// \c ParmVarDecl, but only the \c QualType for each argument.
///
/// Given
/// \code
/// void f(int i);
/// int y;
/// f(y);
/// void (*f_ptr)(int) = f;
/// f_ptr(y);
/// \endcode
/// callExpr(
/// forEachArgumentWithParamType(
/// declRefExpr(to(varDecl(hasName("y")))),
/// qualType(isInteger()).bind("type)
/// ))
/// matches f(y) and f_ptr(y)
/// with declRefExpr(...)
/// matching int y
/// and qualType(...)
/// matching int
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
CXXConstructExpr),
internal::Matcher<Expr>, ArgMatcher,
internal::Matcher<QualType>, ParamMatcher) {
BoundNodesTreeBuilder Result;
// The first argument of an overloaded member operator is the implicit object
// argument of the method which should not be matched against a parameter, so
// we skip over it here.
BoundNodesTreeBuilder Matches;
unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
.matches(Node, Finder, &Matches)
? 1
: 0;
const FunctionProtoType *FProto = nullptr;
if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
if (const auto *Value =
dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
QualType QT = Value->getType().getCanonicalType();
// This does not necessarily lead to a `FunctionProtoType`,
// e.g. K&R functions do not have a function prototype.
if (QT->isFunctionPointerType())
FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
if (QT->isMemberFunctionPointerType()) {
const auto *MP = QT->getAs<MemberPointerType>();
assert(MP && "Must be member-pointer if its a memberfunctionpointer");
FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
assert(FProto &&
"The call must have happened through a member function "
"pointer");
}
}
}
int ParamIndex = 0;
bool Matched = false;
for (; ArgIndex < Node.getNumArgs(); ++ArgIndex, ++ParamIndex) {
BoundNodesTreeBuilder ArgMatches(*Builder);
if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
&ArgMatches)) {
BoundNodesTreeBuilder ParamMatches(ArgMatches);
// This test is cheaper compared to the big matcher in the next if.
// Therefore, please keep this order.
if (FProto) {
QualType ParamType = FProto->getParamType(ParamIndex);
if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
Result.addMatch(ParamMatches);
Matched = true;
continue;
}
}
if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
hasParameter(ParamIndex, hasType(ParamMatcher))))),
callExpr(callee(functionDecl(
hasParameter(ParamIndex, hasType(ParamMatcher)))))))
.matches(Node, Finder, &ParamMatches)) {
Result.addMatch(ParamMatches);
Matched = true;
continue;
}
}
}
*Builder = std::move(Result);
return Matched;
}
/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
/// list. The parameter list could be that of either a block, function, or
/// objc-method.
///
///
/// Given
///
/// \code
/// void f(int a, int b, int c) {
/// }
/// \endcode
///
/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
///
/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
return false;
}
/// Matches any parameter of a function or an ObjC method declaration or a
/// block.
///
/// Does not match the 'this' parameter of a method.
///
/// Given
/// \code
/// class X { void f(int x, int y, int z) {} };
/// \endcode
/// cxxMethodDecl(hasAnyParameter(hasName("y")))
/// matches f(int x, int y, int z) {}
/// with hasAnyParameter(...)
/// matching int y
///
/// For ObjectiveC, given
/// \code
/// @interface I - (void) f:(int) y; @end
/// \endcode
//
/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
/// matches the declaration of method f with hasParameter
/// matching y.
///
/// For blocks, given
/// \code
/// b = ^(int y) { printf("%d", y) };
/// \endcode
///
/// the matcher blockDecl(hasAnyParameter(hasName("y")))
/// matches the declaration of the block b with hasParameter
/// matching y.
AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
ObjCMethodDecl,
BlockDecl),
internal::Matcher<ParmVarDecl>,
InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
Node.param_end(), Finder,
Builder) != Node.param_end();
}
/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
/// specific parameter count.
///
/// Given
/// \code
/// void f(int i) {}
/// void g(int i, int j) {}
/// void h(int i, int j);
/// void j(int i);
/// void k(int x, int y, int z, ...);
/// \endcode
/// functionDecl(parameterCountIs(2))
/// matches \c g and \c h
/// functionProtoType(parameterCountIs(2))
/// matches \c g and \c h
/// functionProtoType(parameterCountIs(3))
/// matches \c k
AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
FunctionProtoType),
unsigned, N) {
return Node.getNumParams() == N;
}
/// Matches \c FunctionDecls that have a noreturn attribute.
///
/// Given
/// \code
/// void nope();
/// [[noreturn]] void a();
/// __attribute__((noreturn)) void b();
/// struct c { [[noreturn]] c(); };
/// \endcode
/// functionDecl(isNoReturn())
/// matches all of those except
/// \code
/// void nope();
/// \endcode
AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
/// Matches the return type of a function declaration.
///
/// Given:
/// \code
/// class X { int f() { return 1; } };
/// \endcode
/// cxxMethodDecl(returns(asString("int")))
/// matches int f() { return 1; }
AST_MATCHER_P(FunctionDecl, returns,
internal::Matcher<QualType>, InnerMatcher) {
return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
}
/// Matches extern "C" function or variable declarations.
///
/// Given:
/// \code
/// extern "C" void f() {}
/// extern "C" { void g() {} }
/// void h() {}
/// extern "C" int x = 1;
/// extern "C" int y = 2;
/// int z = 3;
/// \endcode
/// functionDecl(isExternC())
/// matches the declaration of f and g, but not the declaration of h.
/// varDecl(isExternC())
/// matches the declaration of x and y, but not the declaration of z.
AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
return Node.isExternC();
}
/// Matches variable/function declarations that have "static" storage
/// class specifier ("static" keyword) written in the source.
///
/// Given:
/// \code
/// static void f() {}
/// static int i = 0;
/// extern int j;
/// int k;
/// \endcode
/// functionDecl(isStaticStorageClass())
/// matches the function declaration f.
/// varDecl(isStaticStorageClass())
/// matches the variable declaration i.
AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
return Node.getStorageClass() == SC_Static;
}
/// Matches deleted function declarations.
///
/// Given:
/// \code
/// void Func();
/// void DeletedFunc() = delete;
/// \endcode
/// functionDecl(isDeleted())
/// matches the declaration of DeletedFunc, but not Func.
AST_MATCHER(FunctionDecl, isDeleted) {
return Node.isDeleted();
}
/// Matches defaulted function declarations.
///
/// Given:
/// \code
/// class A { ~A(); };
/// class B { ~B() = default; };
/// \endcode
/// functionDecl(isDefaulted())
/// matches the declaration of ~B, but not ~A.
AST_MATCHER(FunctionDecl, isDefaulted) {
return Node.isDefaulted();
}
/// Matches weak function declarations.
///
/// Given:
/// \code
/// void foo() __attribute__((__weakref__("__foo")));
/// void bar();
/// \endcode
/// functionDecl(isWeak())
/// matches the weak declaration "foo", but not "bar".
AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
/// Matches functions that have a dynamic exception specification.
///
/// Given:
/// \code
/// void f();
/// void g() noexcept;
/// void h() noexcept(true);
/// void i() noexcept(false);
/// void j() throw();
/// void k() throw(int);
/// void l() throw(...);
/// \endcode
/// functionDecl(hasDynamicExceptionSpec()) and
/// functionProtoType(hasDynamicExceptionSpec())
/// match the declarations of j, k, and l, but not f, g, h, or i.
AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
FunctionProtoType)) {
if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
return FnTy->hasDynamicExceptionSpec();
return false;
}
/// Matches functions that have a non-throwing exception specification.
///
/// Given:
/// \code
/// void f();
/// void g() noexcept;
/// void h() throw();
/// void i() throw(int);
/// void j() noexcept(false);
/// \endcode
/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
/// match the declarations of g, and h, but not f, i or j.
AST_POLYMORPHIC_MATCHER(isNoThrow,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
FunctionProtoType)) {
const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
// If the function does not have a prototype, then it is assumed to be a
// throwing function (as it would if the function did not have any exception
// specification).
if (!FnTy)
return false;
// Assume the best for any unresolved exception specification.
if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
return true;
return FnTy->isNothrow();
}
/// Matches constexpr variable and function declarations,
/// and if constexpr.
///
/// Given:
/// \code
/// constexpr int foo = 42;
/// constexpr int bar();
/// void baz() { if constexpr(1 > 0) {} }
/// \endcode
/// varDecl(isConstexpr())
/// matches the declaration of foo.
/// functionDecl(isConstexpr())
/// matches the declaration of bar.
/// ifStmt(isConstexpr())
/// matches the if statement in baz.
AST_POLYMORPHIC_MATCHER(isConstexpr,
AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
FunctionDecl,
IfStmt)) {
return Node.isConstexpr();
}
/// Matches selection statements with initializer.
///
/// Given:
/// \code
/// void foo() {
/// if (int i = foobar(); i > 0) {}
/// switch (int i = foobar(); i) {}
/// for (auto& a = get_range(); auto& x : a) {}
/// }
/// void bar() {
/// if (foobar() > 0) {}
/// switch (foobar()) {}
/// for (auto& x : get_range()) {}
/// }
/// \endcode
/// ifStmt(hasInitStatement(anything()))
/// matches the if statement in foo but not in bar.
/// switchStmt(hasInitStatement(anything()))
/// matches the switch statement in foo but not in bar.
/// cxxForRangeStmt(hasInitStatement(anything()))
/// matches the range for statement in foo but not in bar.
AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt,
CXXForRangeStmt),
internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *Init = Node.getInit();
return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
}
/// Matches the condition expression of an if statement, for loop,
/// switch statement or conditional operator.
///
/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
/// \code
/// if (true) {}
/// \endcode
AST_POLYMORPHIC_MATCHER_P(
hasCondition,
AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
SwitchStmt, AbstractConditionalOperator),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *const Condition = Node.getCond();
return (Condition != nullptr &&
InnerMatcher.matches(*Condition, Finder, Builder));
}
/// Matches the then-statement of an if statement.
///
/// Examples matches the if statement
/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
/// \code
/// if (false) true; else false;
/// \endcode
AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *const Then = Node.getThen();
return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
}
/// Matches the else-statement of an if statement.
///
/// Examples matches the if statement
/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
/// \code
/// if (false) false; else true;
/// \endcode
AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *const Else = Node.getElse();
return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
}
/// Matches if a node equals a previously bound node.
///
/// Matches a node if it equals the node previously bound to \p ID.
///
/// Given
/// \code
/// class X { int a; int b; };
/// \endcode
/// cxxRecordDecl(
/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
/// matches the class \c X, as \c a and \c b have the same type.
///
/// Note that when multiple matches are involved via \c forEach* matchers,
/// \c equalsBoundNodes acts as a filter.
/// For example:
/// compoundStmt(
/// forEachDescendant(varDecl().bind("d")),
/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
/// will trigger a match for each combination of variable declaration
/// and reference to that variable declaration within a compound statement.
AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
QualType),
std::string, ID) {
// FIXME: Figure out whether it makes sense to allow this
// on any other node types.
// For *Loc it probably does not make sense, as those seem
// unique. For NestedNameSepcifier it might make sense, as
// those also have pointer identity, but I'm not sure whether
// they're ever reused.
internal::NotEqualsBoundNodePredicate Predicate;
Predicate.ID = ID;
Predicate.Node = DynTypedNode::create(Node);
return Builder->removeBindings(Predicate);
}
/// Matches the condition variable statement in an if statement.
///
/// Given
/// \code
/// if (A* a = GetAPointer()) {}
/// \endcode
/// hasConditionVariableStatement(...)
/// matches 'A* a = GetAPointer()'.
AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
internal::Matcher<DeclStmt>, InnerMatcher) {
const DeclStmt* const DeclarationStatement =
Node.getConditionVariableDeclStmt();
return DeclarationStatement != nullptr &&
InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
}
/// Matches the index expression of an array subscript expression.
///
/// Given
/// \code
/// int i[5];
/// void f() { i[1] = 42; }
/// \endcode
/// arraySubscriptExpression(hasIndex(integerLiteral()))
/// matches \c i[1] with the \c integerLiteral() matching \c 1
AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
internal::Matcher<Expr>, InnerMatcher) {
if (const Expr* Expression = Node.getIdx())
return InnerMatcher.matches(*Expression, Finder, Builder);
return false;
}
/// Matches the base expression of an array subscript expression.
///
/// Given
/// \code
/// int i[5];
/// void f() { i[1] = 42; }
/// \endcode
/// arraySubscriptExpression(hasBase(implicitCastExpr(
/// hasSourceExpression(declRefExpr()))))
/// matches \c i[1] with the \c declRefExpr() matching \c i
AST_MATCHER_P(ArraySubscriptExpr, hasBase,
internal::Matcher<Expr>, InnerMatcher) {
if (const Expr* Expression = Node.getBase())
return InnerMatcher.matches(*Expression, Finder, Builder);
return false;
}
/// Matches a 'for', 'while', 'do while' statement or a function
/// definition that has a given body. Note that in case of functions
/// this matcher only matches the definition itself and not the other
/// declarations of the same function.
///
/// Given
/// \code
/// for (;;) {}
/// \endcode
/// hasBody(compoundStmt())
/// matches 'for (;;) {}'
/// with compoundStmt()
/// matching '{}'
///
/// Given
/// \code
/// void f();
/// void f() {}
/// \endcode
/// hasBody(functionDecl())
/// matches 'void f() {}'
/// with compoundStmt()
/// matching '{}'
/// but does not match 'void f();'
AST_POLYMORPHIC_MATCHER_P(hasBody,
AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
WhileStmt,
CXXForRangeStmt,
FunctionDecl),
internal::Matcher<Stmt>, InnerMatcher) {
if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
return false;
const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
return (Statement != nullptr &&
InnerMatcher.matches(*Statement, Finder, Builder));
}
/// Matches a function declaration that has a given body present in the AST.
/// Note that this matcher matches all the declarations of a function whose
/// body is present in the AST.
///
/// Given
/// \code
/// void f();
/// void f() {}
/// void g();
/// \endcode
/// hasAnyBody(functionDecl())
/// matches both 'void f();'
/// and 'void f() {}'
/// with compoundStmt()
/// matching '{}'
/// but does not match 'void g();'
AST_MATCHER_P(FunctionDecl, hasAnyBody,
internal::Matcher<Stmt>, InnerMatcher) {
const Stmt *const Statement = Node.getBody();
return (Statement != nullptr &&
InnerMatcher.matches(*Statement, Finder, Builder));
}
/// Matches compound statements where at least one substatement matches
/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
///
/// Given
/// \code
/// { {}; 1+2; }
/// \endcode
/// hasAnySubstatement(compoundStmt())
/// matches '{ {}; 1+2; }'
/// with compoundStmt()
/// matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
StmtExpr),
internal::Matcher<Stmt>, InnerMatcher) {
const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
CS->body_end(), Finder,
Builder) != CS->body_end();
}
/// Checks that a compound statement contains a specific number of
/// child statements.
///
/// Example: Given
/// \code
/// { for (;;) {} }
/// \endcode
/// compoundStmt(statementCountIs(0)))
/// matches '{}'
/// but does not match the outer compound statement.
AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
return Node.size() == N;
}
/// Matches literals that are equal to the given value of type ValueT.
///
/// Given
/// \code
/// f('\0', false, 3.14, 42);
/// \endcode
/// characterLiteral(equals(0))
/// matches '\0'
/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
/// match false
/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
/// match 3.14
/// integerLiteral(equals(42))
/// matches 42
///
/// Note that you cannot directly match a negative numeric literal because the
/// minus sign is not part of the literal: It is a unary operator whose operand
/// is the positive numeric literal. Instead, you must use a unaryOperator()
/// matcher to match the minus sign:
///
/// unaryOperator(hasOperatorName("-"),
/// hasUnaryOperand(integerLiteral(equals(13))))
///
/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
template <typename ValueT>
internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
equals(const ValueT &Value) {
return internal::PolymorphicMatcherWithParam1<
internal::ValueEqualsMatcher,
ValueT>(Value);
}
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
CXXBoolLiteralExpr,
IntegerLiteral),
bool, Value, 0) {
return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
.matchesNode(Node);
}
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
CXXBoolLiteralExpr,
IntegerLiteral),
unsigned, Value, 1) {
return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
.matchesNode(Node);
}
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
CXXBoolLiteralExpr,
FloatingLiteral,
IntegerLiteral),
double, Value, 2) {
return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
.matchesNode(Node);
}
/// Matches the operator Name of operator expressions (binary or
/// unary).
///
/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
/// \code
/// !(a || b)
/// \endcode
AST_POLYMORPHIC_MATCHER_P(
hasOperatorName,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator, UnaryOperator),
std::string, Name) {
if (Optional<StringRef> OpName = internal::getOpName(Node))
return *OpName == Name;
return false;
}
/// Matches operator expressions (binary or unary) that have any of the
/// specified names.
///
/// hasAnyOperatorName("+", "-")
/// Is equivalent to
/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
extern const internal::VariadicFunction<
internal::PolymorphicMatcherWithParam1<
internal::HasAnyOperatorNameMatcher, std::vector<std::string>,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator,
UnaryOperator)>,
StringRef, internal::hasAnyOperatorNameFunc>
hasAnyOperatorName;
/// Matches all kinds of assignment operators.
///
/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
/// \code
/// if (a == b)
/// a += b;
/// \endcode
///
/// Example 2: matches s1 = s2
/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
/// \code
/// struct S { S& operator=(const S&); };
/// void x() { S s1, s2; s1 = s2; }
/// \endcode
AST_POLYMORPHIC_MATCHER(
isAssignmentOperator,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator)) {
return Node.isAssignmentOp();
}
/// Matches comparison operators.
///
/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
/// \code
/// if (a == b)
/// a += b;
/// \endcode
///
/// Example 2: matches s1 < s2
/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
/// \code
/// struct S { bool operator<(const S& other); };
/// void x(S s1, S s2) { bool b1 = s1 < s2; }
/// \endcode
AST_POLYMORPHIC_MATCHER(
isComparisonOperator,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator)) {
return Node.isComparisonOp();
}
/// Matches the left hand side of binary operator expressions.
///
/// Example matches a (matcher = binaryOperator(hasLHS()))
/// \code
/// a || b
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasLHS,
AST_POLYMORPHIC_SUPPORTED_TYPES(
BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator, ArraySubscriptExpr),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *LeftHandSide = internal::getLHS(Node);
return (LeftHandSide != nullptr &&
InnerMatcher.matches(*LeftHandSide, Finder, Builder));
}
/// Matches the right hand side of binary operator expressions.
///
/// Example matches b (matcher = binaryOperator(hasRHS()))
/// \code
/// a || b
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasRHS,
AST_POLYMORPHIC_SUPPORTED_TYPES(
BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator, ArraySubscriptExpr),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *RightHandSide = internal::getRHS(Node);
return (RightHandSide != nullptr &&
InnerMatcher.matches(*RightHandSide, Finder, Builder));
}
/// Matches if either the left hand side or the right hand side of a
/// binary operator matches.
AST_POLYMORPHIC_MATCHER_P(
hasEitherOperand,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator),
internal::Matcher<Expr>, InnerMatcher) {
return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
.matches(Node, Finder, Builder);
}
/// Matches if both matchers match with opposite sides of the binary operator.
///
/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
/// integerLiteral(equals(2)))
/// \code
/// 1 + 2 // Match
/// 2 + 1 // Match
/// 1 + 1 // No match
/// 2 + 2 // No match
/// \endcode
AST_POLYMORPHIC_MATCHER_P2(
hasOperands,
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator),
internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
.matches(Node, Finder, Builder);
}
/// Matches if the operand of a unary operator matches.
///
/// Example matches true (matcher = hasUnaryOperand(
/// cxxBoolLiteral(equals(true))))
/// \code
/// !true
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand,
AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator,
CXXOperatorCallExpr),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *const Operand = internal::getSubExpr(Node);
return (Operand != nullptr &&
InnerMatcher.matches(*Operand, Finder, Builder));
}
/// Matches if the cast's source expression
/// or opaque value's source expression matches the given matcher.
///
/// Example 1: matches "a string"
/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
/// \code
/// class URL { URL(string); };
/// URL url = "a string";
/// \endcode
///
/// Example 2: matches 'b' (matcher =
/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
/// \code
/// int a = b ?: 1;
/// \endcode
AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
OpaqueValueExpr),
internal::Matcher<Expr>, InnerMatcher) {
const Expr *const SubExpression =
internal::GetSourceExpressionMatcher<NodeType>::get(Node);
return (SubExpression != nullptr &&
InnerMatcher.matches(*SubExpression, Finder, Builder));
}
/// Matches casts that has a given cast kind.
///
/// Example: matches the implicit cast around \c 0
/// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
/// \code
/// int *p = 0;
/// \endcode
///
/// If the matcher is use from clang-query, CastKind parameter
/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
return Node.getCastKind() == Kind;
}
/// Matches casts whose destination type matches a given matcher.
///
/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
/// actual casts "explicit" casts.)
AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
internal::Matcher<QualType>, InnerMatcher) {
const QualType NodeType = Node.getTypeAsWritten();
return InnerMatcher.matches(NodeType, Finder, Builder);
}
/// Matches implicit casts whose destination type matches a given
/// matcher.
///
/// FIXME: Unit test this matcher
AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
internal::Matcher<QualType>, InnerMatcher) {
return InnerMatcher.matches(Node.getType(), Finder, Builder);
}
/// Matches TagDecl object that are spelled with "struct."
///
/// Example matches S, but not C, U or E.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isStruct) {
return Node.isStruct();
}
/// Matches TagDecl object that are spelled with "union."
///
/// Example matches U, but not C, S or E.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isUnion) {
return Node.isUnion();
}
/// Matches TagDecl object that are spelled with "class."
///
/// Example matches C, but not S, U or E.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isClass) {
return Node.isClass();
}
/// Matches TagDecl object that are spelled with "enum."
///
/// Example matches E, but not C, S or U.
/// \code
/// struct S {};
/// class C {};
/// union U {};
/// enum E {};
/// \endcode
AST_MATCHER(TagDecl, isEnum) {
return Node.isEnum();
}
/// Matches the true branch expression of a conditional operator.
///
/// Example 1 (conditional ternary operator): matches a
/// \code
/// condition ? a : b
/// \endcode
///
/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
/// \code
/// condition ?: b
/// \endcode
AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *Expression = Node.getTrueExpr();
return (Expression != nullptr &&
InnerMatcher.matches(*Expression, Finder, Builder));
}
/// Matches the false branch expression of a conditional operator
/// (binary or ternary).
///
/// Example matches b
/// \code
/// condition ? a : b
/// condition ?: b
/// \endcode
AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
internal::Matcher<Expr>, InnerMatcher) {
const Expr *Expression = Node.getFalseExpr();
return (Expression != nullptr &&
InnerMatcher.matches(*Expression, Finder, Builder));
}
/// Matches if a declaration has a body attached.
///
/// Example matches A, va, fa
/// \code
/// class A {};
/// class B; // Doesn't match, as it has no body.
/// int va;
/// extern int vb; // Doesn't match, as it doesn't define the variable.
/// void fa() {}
/// void fb(); // Doesn't match, as it has no body.
/// @interface X
/// - (void)ma; // Doesn't match, interface is declaration.
/// @end
/// @implementation X
/// - (void)ma {}
/// @end
/// \endcode
///
/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
/// Matcher<ObjCMethodDecl>
AST_POLYMORPHIC_MATCHER(isDefinition,
AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
ObjCMethodDecl,
FunctionDecl)) {
return Node.isThisDeclarationADefinition();
}
/// Matches if a function declaration is variadic.
///
/// Example matches f, but not g or h. The function i will not match, even when
/// compiled in C mode.
/// \code
/// void f(...);
/// void g(int);
/// template <typename... Ts> void h(Ts...);
/// void i();
/// \endcode
AST_MATCHER(FunctionDecl, isVariadic) {
return Node.isVariadic();
}
/// Matches the class declaration that the given method declaration
/// belongs to.
///
/// FIXME: Generalize this for other kinds of declarations.
/// FIXME: What other kind of declarations would we need to generalize
/// this to?
///
/// Example matches A() in the last line
/// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
/// ofClass(hasName("A"))))))
/// \code
/// class A {
/// public:
/// A();
/// };
/// A a = A();
/// \endcode
AST_MATCHER_P(CXXMethodDecl, ofClass,
internal::Matcher<CXXRecordDecl>, InnerMatcher) {
ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
const CXXRecordDecl *Parent = Node.getParent();
return (Parent != nullptr &&
InnerMatcher.matches(*Parent, Finder, Builder));
}
/// Matches each method overridden by the given method. This matcher may
/// produce multiple matches.
///
/// Given
/// \code
/// class A { virtual void f(); };
/// class B : public A { void f(); };
/// class C : public B { void f(); };
/// \endcode
/// cxxMethodDecl(ofClass(hasName("C")),
/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
/// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
/// that B::f is not overridden by C::f).
///
/// The check can produce multiple matches in case of multiple inheritance, e.g.
/// \code
/// class A1 { virtual void f(); };
/// class A2 { virtual void f(); };
/// class C : public A1, public A2 { void f(); };
/// \endcode
/// cxxMethodDecl(ofClass(hasName("C")),
/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
/// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
/// once with "b" binding "A2::f" and "d" binding "C::f".
AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
internal::Matcher<CXXMethodDecl>, InnerMatcher) {
BoundNodesTreeBuilder Result;
bool Matched = false;
for (const auto *Overridden : Node.overridden_methods()) {
BoundNodesTreeBuilder OverriddenBuilder(*Builder);
const bool OverriddenMatched =
InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
if (OverriddenMatched) {
Matched = true;
Result.addMatch(OverriddenBuilder);
}
}
*Builder = std::move(Result);
return Matched;
}
/// Matches declarations of virtual methods and C++ base specifers that specify
/// virtual inheritance.
///
/// Example:
/// \code
/// class A {
/// public:
/// virtual void x(); // matches x
/// };
/// \endcode
///
/// Example:
/// \code
/// class Base {};
/// class DirectlyDerived : virtual Base {}; // matches Base
/// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
/// \endcode
///
/// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
AST_POLYMORPHIC_MATCHER(isVirtual,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl,
CXXBaseSpecifier)) {
return Node.isVirtual();
}
/// Matches if the given method declaration has an explicit "virtual".
///
/// Given
/// \code
/// class A {
/// public:
/// virtual void x();
/// };
/// class B : public A {
/// public:
/// void x();
/// };
/// \endcode
/// matches A::x but not B::x
AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
return Node.isVirtualAsWritten();
}
/// Matches if the given method or class declaration is final.
///
/// Given:
/// \code
/// class A final {};
///
/// struct B {
/// virtual void f();
/// };
///
/// struct C : B {
/// void f() final;
/// };
/// \endcode
/// matches A and C::f, but not B, C, or B::f
AST_POLYMORPHIC_MATCHER(isFinal,
AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
CXXMethodDecl)) {
return Node.template hasAttr<FinalAttr>();
}
/// Matches if the given method declaration is pure.
///
/// Given
/// \code
/// class A {
/// public:
/// virtual void x() = 0;
/// };
/// \endcode
/// matches A::x
AST_MATCHER(CXXMethodDecl, isPure) {
return Node.isPure();
}
/// Matches if the given method declaration is const.
///
/// Given
/// \code
/// struct A {
/// void foo() const;
/// void bar();
/// };
/// \endcode
///
/// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
AST_MATCHER(CXXMethodDecl, isConst) {
return Node.isConst();
}
/// Matches if the given method declaration declares a copy assignment
/// operator.
///
/// Given
/// \code
/// struct A {
/// A &operator=(const A &);
/// A &operator=(A &&);
/// };
/// \endcode
///
/// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
/// the second one.
AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
return Node.isCopyAssignmentOperator();
}
/// Matches if the given method declaration declares a move assignment
/// operator.
///
/// Given
/// \code
/// struct A {
/// A &operator=(const A &);
/// A &operator=(A &&);
/// };
/// \endcode
///
/// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
/// the first one.
AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
return Node.isMoveAssignmentOperator();
}
/// Matches if the given method declaration overrides another method.
///
/// Given
/// \code
/// class A {
/// public:
/// virtual void x();
/// };
/// class B : public A {
/// public:
/// virtual void x();
/// };
/// \endcode
/// matches B::x
AST_MATCHER(CXXMethodDecl, isOverride) {
return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
}
/// Matches method declarations that are user-provided.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &) = default; // #2
/// S(S &&) = delete; // #3
/// };
/// \endcode
/// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
AST_MATCHER(CXXMethodDecl, isUserProvided) {
return Node.isUserProvided();
}
/// Matches member expressions that are called with '->' as opposed
/// to '.'.
///
/// Member calls on the implicit this pointer match as called with '->'.
///
/// Given
/// \code
/// class Y {
/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
/// template <class T> void f() { this->f<T>(); f<T>(); }
/// int a;
/// static int b;
/// };
/// template <class T>
/// class Z {
/// void x() { this->m; }
/// };
/// \endcode
/// memberExpr(isArrow())
/// matches this->x, x, y.x, a, this->b
/// cxxDependentScopeMemberExpr(isArrow())
/// matches this->m
/// unresolvedMemberExpr(isArrow())
/// matches this->f<T>, f<T>
AST_POLYMORPHIC_MATCHER(
isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
CXXDependentScopeMemberExpr)) {
return Node.isArrow();
}
/// Matches QualType nodes that are of integer type.
///
/// Given
/// \code
/// void a(int);
/// void b(long);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isInteger())))
/// matches "a(int)", "b(long)", but not "c(double)".
AST_MATCHER(QualType, isInteger) {
return Node->isIntegerType();
}
/// Matches QualType nodes that are of unsigned integer type.
///
/// Given
/// \code
/// void a(int);
/// void b(unsigned long);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
/// matches "b(unsigned long)", but not "a(int)" and "c(double)".
AST_MATCHER(QualType, isUnsignedInteger) {
return Node->isUnsignedIntegerType();
}
/// Matches QualType nodes that are of signed integer type.
///
/// Given
/// \code
/// void a(int);
/// void b(unsigned long);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
/// matches "a(int)", but not "b(unsigned long)" and "c(double)".
AST_MATCHER(QualType, isSignedInteger) {
return Node->isSignedIntegerType();
}
/// Matches QualType nodes that are of character type.
///
/// Given
/// \code
/// void a(char);
/// void b(wchar_t);
/// void c(double);
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
/// matches "a(char)", "b(wchar_t)", but not "c(double)".
AST_MATCHER(QualType, isAnyCharacter) {
return Node->isAnyCharacterType();
}
/// Matches QualType nodes that are of any pointer type; this includes
/// the Objective-C object pointer type, which is different despite being
/// syntactically similar.
///
/// Given
/// \code
/// int *i = nullptr;
///
/// @interface Foo
/// @end
/// Foo *f;
///
/// int j;
/// \endcode
/// varDecl(hasType(isAnyPointer()))
/// matches "int *i" and "Foo *f", but not "int j".
AST_MATCHER(QualType, isAnyPointer) {
return Node->isAnyPointerType();
}
/// Matches QualType nodes that are const-qualified, i.e., that
/// include "top-level" const.
///
/// Given
/// \code
/// void a(int);
/// void b(int const);
/// void c(const int);
/// void d(const int*);
/// void e(int const) {};
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
/// matches "void b(int const)", "void c(const int)" and
/// "void e(int const) {}". It does not match d as there
/// is no top-level const on the parameter type "const int *".
AST_MATCHER(QualType, isConstQualified) {
return Node.isConstQualified();
}
/// Matches QualType nodes that are volatile-qualified, i.e., that
/// include "top-level" volatile.
///
/// Given
/// \code
/// void a(int);
/// void b(int volatile);
/// void c(volatile int);
/// void d(volatile int*);
/// void e(int volatile) {};
/// \endcode
/// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
/// matches "void b(int volatile)", "void c(volatile int)" and
/// "void e(int volatile) {}". It does not match d as there
/// is no top-level volatile on the parameter type "volatile int *".
AST_MATCHER(QualType, isVolatileQualified) {
return Node.isVolatileQualified();
}
/// Matches QualType nodes that have local CV-qualifiers attached to
/// the node, not hidden within a typedef.
///
/// Given
/// \code
/// typedef const int const_int;
/// const_int i;
/// int *const j;
/// int *volatile k;
/// int m;
/// \endcode
/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
/// \c i is const-qualified but the qualifier is not local.
AST_MATCHER(QualType, hasLocalQualifiers) {
return Node.hasLocalQualifiers();
}
/// Matches a member expression where the member is matched by a
/// given matcher.
///
/// Given
/// \code
/// struct { int first, second; } first, second;
/// int i(second.first);
/// int j(first.second);
/// \endcode
/// memberExpr(member(hasName("first")))
/// matches second.first
/// but not first.second (because the member name there is "second").
AST_MATCHER_P(MemberExpr, member,
internal::Matcher<ValueDecl>, InnerMatcher) {
return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
}
/// Matches a member expression where the object expression is matched by a
/// given matcher. Implicit object expressions are included; that is, it matches
/// use of implicit `this`.
///
/// Given
/// \code
/// struct X {
/// int m;
/// int f(X x) { x.m; return m; }
/// };
/// \endcode
/// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
/// matches `x.m`, but not `m`; however,
/// memberExpr(hasObjectExpression(hasType(pointsTo(
// cxxRecordDecl(hasName("X"))))))
/// matches `m` (aka. `this->m`), but not `x.m`.
AST_POLYMORPHIC_MATCHER_P(
hasObjectExpression,
AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
CXXDependentScopeMemberExpr),
internal::Matcher<Expr>, InnerMatcher) {
if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
if (E->isImplicitAccess())
return false;
if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
if (E->isImplicitAccess())
return false;
return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
}
/// Matches any using shadow declaration.
///
/// Given
/// \code
/// namespace X { void b(); }
/// using X::b;
/// \endcode
/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
/// matches \code using X::b \endcode
AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
internal::Matcher<UsingShadowDecl>, InnerMatcher) {
return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
Node.shadow_end(), Finder,
Builder) != Node.shadow_end();
}
/// Matches a using shadow declaration where the target declaration is
/// matched by the given matcher.
///
/// Given
/// \code
/// namespace X { int a; void b(); }
/// using X::a;
/// using X::b;
/// \endcode
/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
/// matches \code using X::b \endcode
/// but not \code using X::a \endcode
AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
internal::Matcher<NamedDecl>, InnerMatcher) {
return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
}
/// Matches template instantiations of function, class, or static
/// member variable template instantiations.
///
/// Given
/// \code
/// template <typename T> class X {}; class A {}; X<A> x;
/// \endcode
/// or
/// \code
/// template <typename T> class X {}; class A {}; template class X<A>;
/// \endcode
/// or
/// \code
/// template <typename T> class X {}; class A {}; extern template class X<A>;
/// \endcode
/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
/// matches the template instantiation of X<A>.
///
/// But given
/// \code
/// template <typename T> class X {}; class A {};
/// template <> class X<A> {}; X<A> x;
/// \endcode
/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
/// does not match, as X<A> is an explicit template specialization.
///
/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
CXXRecordDecl)) {
return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
Node.getTemplateSpecializationKind() ==
TSK_ExplicitInstantiationDefinition ||
Node.getTemplateSpecializationKind() ==
TSK_ExplicitInstantiationDeclaration);
}
/// Matches declarations that are template instantiations or are inside
/// template instantiations.
///
/// Given
/// \code
/// template<typename T> void A(T t) { T i; }
/// A(0);
/// A(0U);
/// \endcode
/// functionDecl(isInstantiated())
/// matches 'A(int) {...};' and 'A(unsigned) {...}'.
AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
functionDecl(isTemplateInstantiation())));
return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
}
/// Matches statements inside of a template instantiation.
///
/// Given
/// \code
/// int j;
/// template<typename T> void A(T t) { T i; j += 42;}
/// A(0);
/// A(0U);
/// \endcode
/// declStmt(isInTemplateInstantiation())
/// matches 'int i;' and 'unsigned i'.
/// unless(stmt(isInTemplateInstantiation()))
/// will NOT match j += 42; as it's shared between the template definition and
/// instantiation.
AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
return stmt(
hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
functionDecl(isTemplateInstantiation())))));
}
/// Matches explicit template specializations of function, class, or
/// static member variable template instantiations.
///
/// Given
/// \code
/// template<typename T> void A(T t) { }
/// template<> void A(int N) { }
/// \endcode
/// functionDecl(isExplicitTemplateSpecialization())
/// matches the specialization A<int>().
///
/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
CXXRecordDecl)) {
return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
}
/// Matches \c TypeLocs for which the given inner
/// QualType-matcher matches.
AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
internal::Matcher<QualType>, InnerMatcher, 0) {
return internal::BindableMatcher<TypeLoc>(
new internal::TypeLocTypeMatcher(InnerMatcher));
}
/// Matches type \c bool.
///
/// Given
/// \code
/// struct S { bool func(); };
/// \endcode
/// functionDecl(returns(booleanType()))
/// matches "bool func();"
AST_MATCHER(Type, booleanType) {
return Node.isBooleanType();
}
/// Matches type \c void.
///
/// Given
/// \code
/// struct S { void func(); };
/// \endcode
/// functionDecl(returns(voidType()))
/// matches "void func();"
AST_MATCHER(Type, voidType) {
return Node.isVoidType();
}
template <typename NodeType>
using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
/// Matches builtin Types.
///
/// Given
/// \code
/// struct A {};
/// A a;
/// int b;
/// float c;
/// bool d;
/// \endcode
/// builtinType()
/// matches "int b", "float c" and "bool d"
extern const AstTypeMatcher<BuiltinType> builtinType;
/// Matches all kinds of arrays.
///
/// Given
/// \code
/// int a[] = { 2, 3 };
/// int b[4];
/// void f() { int c[a[0]]; }
/// \endcode
/// arrayType()
/// matches "int a[]", "int b[4]" and "int c[a[0]]";
extern const AstTypeMatcher<ArrayType> arrayType;
/// Matches C99 complex types.
///
/// Given
/// \code
/// _Complex float f;
/// \endcode
/// complexType()
/// matches "_Complex float f"
extern const AstTypeMatcher<ComplexType> complexType;
/// Matches any real floating-point type (float, double, long double).
///
/// Given
/// \code
/// int i;
/// float f;
/// \endcode
/// realFloatingPointType()
/// matches "float f" but not "int i"
AST_MATCHER(Type, realFloatingPointType) {
return Node.isRealFloatingType();
}
/// Matches arrays and C99 complex types that have a specific element
/// type.
///
/// Given
/// \code
/// struct A {};
/// A a[7];
/// int b[7];
/// \endcode
/// arrayType(hasElementType(builtinType()))
/// matches "int b[7]"
///
/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
ComplexType));
/// Matches C arrays with a specified constant size.
///
/// Given
/// \code
/// void() {
/// int a[2];
/// int b[] = { 2, 3 };
/// int c[b[0]];
/// }
/// \endcode
/// constantArrayType()
/// matches "int a[2]"
extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
/// Matches nodes that have the specified size.
///
/// Given
/// \code
/// int a[42];
/// int b[2 * 21];
/// int c[41], d[43];
/// char *s = "abcd";
/// wchar_t *ws = L"abcd";
/// char *w = "a";
/// \endcode
/// constantArrayType(hasSize(42))
/// matches "int a[42]" and "int b[2 * 21]"
/// stringLiteral(hasSize(4))
/// matches "abcd", L"abcd"
AST_POLYMORPHIC_MATCHER_P(hasSize,
AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
StringLiteral),
unsigned, N) {
return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
}
/// Matches C++ arrays whose size is a value-dependent expression.
///
/// Given
/// \code
/// template<typename T, int Size>
/// class array {
/// T data[Size];
/// };
/// \endcode
/// dependentSizedArrayType
/// matches "T data[Size]"
extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
/// Matches C arrays with unspecified size.
///
/// Given
/// \code
/// int a[] = { 2, 3 };
/// int b[42];
/// void f(int c[]) { int d[a[0]]; };
/// \endcode
/// incompleteArrayType()
/// matches "int a[]" and "int c[]"
extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
/// Matches C arrays with a specified size that is not an
/// integer-constant-expression.
///
/// Given
/// \code
/// void f() {
/// int a[] = { 2, 3 }
/// int b[42];
/// int c[a[0]];
/// }
/// \endcode
/// variableArrayType()
/// matches "int c[a[0]]"
extern const AstTypeMatcher<VariableArrayType> variableArrayType;
/// Matches \c VariableArrayType nodes that have a specific size
/// expression.
///
/// Given
/// \code
/// void f(int b) {
/// int a[b];
/// }
/// \endcode
/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
/// varDecl(hasName("b")))))))
/// matches "int a[b]"
AST_MATCHER_P(VariableArrayType, hasSizeExpr,
internal::Matcher<Expr>, InnerMatcher) {
return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
}
/// Matches atomic types.
///
/// Given
/// \code
/// _Atomic(int) i;
/// \endcode
/// atomicType()
/// matches "_Atomic(int) i"
extern const AstTypeMatcher<AtomicType> atomicType;
/// Matches atomic types with a specific value type.
///
/// Given
/// \code
/// _Atomic(int) i;
/// _Atomic(float) f;
/// \endcode
/// atomicType(hasValueType(isInteger()))
/// matches "_Atomic(int) i"
///
/// Usable as: Matcher<AtomicType>
AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
/// Matches types nodes representing C++11 auto types.
///
/// Given:
/// \code
/// auto n = 4;
/// int v[] = { 2, 3 }
/// for (auto i : v) { }
/// \endcode
/// autoType()
/// matches "auto n" and "auto i"
extern const AstTypeMatcher<AutoType> autoType;
/// Matches types nodes representing C++11 decltype(<expr>) types.
///
/// Given:
/// \code
/// short i = 1;
/// int j = 42;
/// decltype(i + j) result = i + j;
/// \endcode
/// decltypeType()
/// matches "decltype(i + j)"
extern const AstTypeMatcher<DecltypeType> decltypeType;
/// Matches \c AutoType nodes where the deduced type is a specific type.
///
/// Note: There is no \c TypeLoc for the deduced type and thus no
/// \c getDeducedLoc() matcher.
///
/// Given
/// \code
/// auto a = 1;
/// auto b = 2.0;
/// \endcode
/// autoType(hasDeducedType(isInteger()))
/// matches "auto a"
///
/// Usable as: Matcher<AutoType>
AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
/// Matches \c DecltypeType nodes to find out the underlying type.
///
/// Given
/// \code
/// decltype(1) a = 1;
/// decltype(2.0) b = 2.0;
/// \endcode
/// decltypeType(hasUnderlyingType(isInteger()))
/// matches the type of "a"
///
/// Usable as: Matcher<DecltypeType>
AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
/// Matches \c FunctionType nodes.
///
/// Given
/// \code
/// int (*f)(int);
/// void g();
/// \endcode
/// functionType()
/// matches "int (*f)(int)" and the type of "g".
extern const AstTypeMatcher<FunctionType> functionType;
/// Matches \c FunctionProtoType nodes.
///
/// Given
/// \code
/// int (*f)(int);
/// void g();
/// \endcode
/// functionProtoType()
/// matches "int (*f)(int)" and the type of "g" in C++ mode.
/// In C mode, "g" is not matched because it does not contain a prototype.
extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
/// Matches \c ParenType nodes.
///
/// Given
/// \code
/// int (*ptr_to_array)[4];
/// int *array_of_ptrs[4];
/// \endcode
///
/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
/// \c array_of_ptrs.
extern const AstTypeMatcher<ParenType> parenType;
/// Matches \c ParenType nodes where the inner type is a specific type.
///
/// Given
/// \code
/// int (*ptr_to_array)[4];
/// int (*ptr_to_func)(int);
/// \endcode
///
/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
/// \c ptr_to_func but not \c ptr_to_array.
///
/// Usable as: Matcher<ParenType>
AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
/// Matches block pointer types, i.e. types syntactically represented as
/// "void (^)(int)".
///
/// The \c pointee is always required to be a \c FunctionType.
extern const AstTypeMatcher<BlockPointerType> blockPointerType;
/// Matches member pointer types.
/// Given
/// \code
/// struct A { int i; }
/// A::* ptr = A::i;
/// \endcode
/// memberPointerType()
/// matches "A::* ptr"
extern const AstTypeMatcher<MemberPointerType> memberPointerType;
/// Matches pointer types, but does not match Objective-C object pointer
/// types.
///
/// Given
/// \code
/// int *a;
/// int &b = *a;
/// int c = 5;
///
/// @interface Foo
/// @end
/// Foo *f;
/// \endcode
/// pointerType()
/// matches "int *a", but does not match "Foo *f".
extern const AstTypeMatcher<PointerType> pointerType;
/// Matches an Objective-C object pointer type, which is different from
/// a pointer type, despite being syntactically similar.
///
/// Given
/// \code
/// int *a;
///
/// @interface Foo
/// @end
/// Foo *f;
/// \endcode
/// pointerType()
/// matches "Foo *f", but does not match "int *a".
extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
/// Matches both lvalue and rvalue reference types.
///
/// Given
/// \code
/// int *a;
/// int &b = *a;
/// int &&c = 1;
/// auto &d = b;
/// auto &&e = c;
/// auto &&f = 2;
/// int g = 5;
/// \endcode
///
/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
extern const AstTypeMatcher<ReferenceType> referenceType;
/// Matches lvalue reference types.
///
/// Given:
/// \code
/// int *a;
/// int &b = *a;
/// int &&c = 1;
/// auto &d = b;
/// auto &&e = c;
/// auto &&f = 2;
/// int g = 5;
/// \endcode
///
/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
/// matched since the type is deduced as int& by reference collapsing rules.
extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
/// Matches rvalue reference types.
///
/// Given:
/// \code
/// int *a;
/// int &b = *a;
/// int &&c = 1;
/// auto &d = b;
/// auto &&e = c;
/// auto &&f = 2;
/// int g = 5;
/// \endcode
///
/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
/// matched as it is deduced to int& by reference collapsing rules.
extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
/// Narrows PointerType (and similar) matchers to those where the
/// \c pointee matches a given matcher.
///
/// Given
/// \code
/// int *a;
/// int const *b;
/// float const *f;
/// \endcode
/// pointerType(pointee(isConstQualified(), isInteger()))
/// matches "int const *b"
///
/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
/// Matcher<PointerType>, Matcher<ReferenceType>
AST_TYPELOC_TRAVERSE_MATCHER_DECL(
pointee, getPointee,
AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
PointerType, ReferenceType));
/// Matches typedef types.
///
/// Given
/// \code
/// typedef int X;
/// \endcode
/// typedefType()
/// matches "typedef int X"
extern const AstTypeMatcher<TypedefType> typedefType;
/// Matches enum types.
///
/// Given
/// \code
/// enum C { Green };
/// enum class S { Red };
///
/// C c;
/// S s;
/// \endcode
//
/// \c enumType() matches the type of the variable declarations of both \c c and
/// \c s.
extern const AstTypeMatcher<EnumType> enumType;
/// Matches template specialization types.
///
/// Given
/// \code
/// template <typename T>
/// class C { };
///
/// template class C<int>; // A
/// C<char> var; // B
/// \endcode
///
/// \c templateSpecializationType() matches the type of the explicit
/// instantiation in \c A and the type of the variable declaration in \c B.
extern const AstTypeMatcher<TemplateSpecializationType>
templateSpecializationType;
/// Matches C++17 deduced template specialization types, e.g. deduced class
/// template types.
///
/// Given
/// \code
/// template <typename T>
/// class C { public: C(T); };
///
/// C c(123);
/// \endcode
/// \c deducedTemplateSpecializationType() matches the type in the declaration
/// of the variable \c c.
extern const AstTypeMatcher<DeducedTemplateSpecializationType>
deducedTemplateSpecializationType;
/// Matches types nodes representing unary type transformations.
///
/// Given:
/// \code
/// typedef __underlying_type(T) type;
/// \endcode
/// unaryTransformType()
/// matches "__underlying_type(T)"
extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
/// Matches record types (e.g. structs, classes).
///
/// Given
/// \code
/// class C {};
/// struct S {};
///
/// C c;
/// S s;
/// \endcode
///
/// \c recordType() matches the type of the variable declarations of both \c c
/// and \c s.
extern const AstTypeMatcher<RecordType> recordType;
/// Matches tag types (record and enum types).
///
/// Given
/// \code
/// enum E {};
/// class C {};
///
/// E e;
/// C c;
/// \endcode
///
/// \c tagType() matches the type of the variable declarations of both \c e
/// and \c c.
extern const AstTypeMatcher<TagType> tagType;
/// Matches types specified with an elaborated type keyword or with a
/// qualified name.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// class C {};
///
/// class C c;
/// N::M::D d;
/// \endcode
///
/// \c elaboratedType() matches the type of the variable declarations of both
/// \c c and \c d.
extern const AstTypeMatcher<ElaboratedType> elaboratedType;
/// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
/// matches \c InnerMatcher if the qualifier exists.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// N::M::D d;
/// \endcode
///
/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
/// matches the type of the variable declaration of \c d.
AST_MATCHER_P(ElaboratedType, hasQualifier,
internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
return InnerMatcher.matches(*Qualifier, Finder, Builder);
return false;
}
/// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// N::M::D d;
/// \endcode
///
/// \c elaboratedType(namesType(recordType(
/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
/// declaration of \c d.
AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
InnerMatcher) {
return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
}
/// Matches types that represent the result of substituting a type for a
/// template type parameter.
///
/// Given
/// \code
/// template <typename T>
/// void F(T t) {
/// int i = 1 + t;
/// }
/// \endcode
///
/// \c substTemplateTypeParmType() matches the type of 't' but not '1'
extern const AstTypeMatcher<SubstTemplateTypeParmType>
substTemplateTypeParmType;
/// Matches template type parameter substitutions that have a replacement
/// type that matches the provided matcher.
///
/// Given
/// \code
/// template <typename T>
/// double F(T t);
/// int i;
/// double j = F(i);
/// \endcode
///
/// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
AST_TYPE_TRAVERSE_MATCHER(
hasReplacementType, getReplacementType,
AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
/// Matches template type parameter types.
///
/// Example matches T, but not int.
/// (matcher = templateTypeParmType())
/// \code
/// template <typename T> void f(int i);
/// \endcode
extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
/// Matches injected class name types.
///
/// Example matches S s, but not S<T> s.
/// (matcher = parmVarDecl(hasType(injectedClassNameType())))
/// \code
/// template <typename T> struct S {
/// void f(S s);
/// void g(S<T> s);
/// };
/// \endcode
extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
/// Matches decayed type
/// Example matches i[] in declaration of f.
/// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
/// Example matches i[1].
/// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
/// \code
/// void f(int i[]) {
/// i[1] = 0;
/// }
/// \endcode
extern const AstTypeMatcher<DecayedType> decayedType;
/// Matches the decayed type, whoes decayed type matches \c InnerMatcher
AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
InnerType) {
return InnerType.matches(Node.getDecayedType(), Finder, Builder);
}
/// Matches declarations whose declaration context, interpreted as a
/// Decl, matches \c InnerMatcher.
///
/// Given
/// \code
/// namespace N {
/// namespace M {
/// class D {};
/// }
/// }
/// \endcode
///
/// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
/// declaration of \c class \c D.
AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
const DeclContext *DC = Node.getDeclContext();
if (!DC) return false;
return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
}
/// Matches nested name specifiers.
///
/// Given
/// \code
/// namespace ns {
/// struct A { static void f(); };
/// void A::f() {}
/// void g() { A::f(); }
/// }
/// ns::A a;
/// \endcode
/// nestedNameSpecifier()
/// matches "ns::" and both "A::"
extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
nestedNameSpecifier;
/// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
nestedNameSpecifierLoc;
/// Matches \c NestedNameSpecifierLocs for which the given inner
/// NestedNameSpecifier-matcher matches.
AST_MATCHER_FUNCTION_P_OVERLOAD(
internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
return internal::BindableMatcher<NestedNameSpecifierLoc>(
new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
InnerMatcher));
}
/// Matches nested name specifiers that specify a type matching the
/// given \c QualType matcher without qualifiers.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifier(specifiesType(
/// hasDeclaration(cxxRecordDecl(hasName("A")))
/// ))
/// matches "A::"
AST_MATCHER_P(NestedNameSpecifier, specifiesType,
internal::Matcher<QualType>, InnerMatcher) {
if (!Node.getAsType())
return false;
return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
}
/// Matches nested name specifier locs that specify a type matching the
/// given \c TypeLoc.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
/// hasDeclaration(cxxRecordDecl(hasName("A")))))))
/// matches "A::"
AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
internal::Matcher<TypeLoc>, InnerMatcher) {
return Node && Node.getNestedNameSpecifier()->getAsType() &&
InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
}
/// Matches on the prefix of a \c NestedNameSpecifier.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
/// matches "A::"
AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
internal::Matcher<NestedNameSpecifier>, InnerMatcher,
0) {
const NestedNameSpecifier *NextNode = Node.getPrefix();
if (!NextNode)
return false;
return InnerMatcher.matches(*NextNode, Finder, Builder);
}
/// Matches on the prefix of a \c NestedNameSpecifierLoc.
///
/// Given
/// \code
/// struct A { struct B { struct C {}; }; };
/// A::B::C c;
/// \endcode
/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
/// matches "A::"
AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
1) {
NestedNameSpecifierLoc NextNode = Node.getPrefix();
if (!NextNode)
return false;
return InnerMatcher.matches(NextNode, Finder, Builder);
}
/// Matches nested name specifiers that specify a namespace matching the
/// given namespace matcher.
///
/// Given
/// \code
/// namespace ns { struct A {}; }
/// ns::A a;
/// \endcode
/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
/// matches "ns::"
AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
internal::Matcher<NamespaceDecl>, InnerMatcher) {
if (!Node.getAsNamespace())
return false;
return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
}
/// Overloads for the \c equalsNode matcher.
/// FIXME: Implement for other node types.
/// @{
/// Matches if a node equals another node.
///
/// \c Decl has pointer identity in the AST.
AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
return &Node == Other;
}
/// Matches if a node equals another node.
///
/// \c Stmt has pointer identity in the AST.
AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
return &Node == Other;
}
/// Matches if a node equals another node.
///
/// \c Type has pointer identity in the AST.
AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
return &Node == Other;
}
/// @}
/// Matches each case or default statement belonging to the given switch
/// statement. This matcher may produce multiple matches.
///
/// Given
/// \code
/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
/// \endcode
/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
/// matches four times, with "c" binding each of "case 1:", "case 2:",
/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
/// "switch (1)", "switch (2)" and "switch (2)".
AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
InnerMatcher) {
BoundNodesTreeBuilder Result;
// FIXME: getSwitchCaseList() does not necessarily guarantee a stable
// iteration order. We should use the more general iterating matchers once
// they are capable of expressing this matcher (for example, it should ignore
// case statements belonging to nested switch statements).
bool Matched = false;
for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
SC = SC->getNextSwitchCase()) {
BoundNodesTreeBuilder CaseBuilder(*Builder);
bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
if (CaseMatched) {
Matched = true;
Result.addMatch(CaseBuilder);
}
}
*Builder = std::move(Result);
return Matched;
}
/// Matches each constructor initializer in a constructor definition.
///
/// Given
/// \code
/// class A { A() : i(42), j(42) {} int i; int j; };
/// \endcode
/// cxxConstructorDecl(forEachConstructorInitializer(
/// forField(decl().bind("x"))
/// ))
/// will trigger two matches, binding for 'i' and 'j' respectively.
AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
BoundNodesTreeBuilder Result;
bool Matched = false;
for (const auto *I : Node.inits()) {
if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
continue;
BoundNodesTreeBuilder InitBuilder(*Builder);
if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
Matched = true;
Result.addMatch(InitBuilder);
}
}
*Builder = std::move(Result);
return Matched;
}
/// Matches constructor declarations that are copy constructors.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &); // #2
/// S(S &&); // #3
/// };
/// \endcode
/// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
return Node.isCopyConstructor();
}
/// Matches constructor declarations that are move constructors.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &); // #2
/// S(S &&); // #3
/// };
/// \endcode
/// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
return Node.isMoveConstructor();
}
/// Matches constructor declarations that are default constructors.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(const S &); // #2
/// S(S &&); // #3
/// };
/// \endcode
/// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
return Node.isDefaultConstructor();
}
/// Matches constructors that delegate to another constructor.
///
/// Given
/// \code
/// struct S {
/// S(); // #1
/// S(int) {} // #2
/// S(S &&) : S() {} // #3
/// };
/// S::S() : S(0) {} // #4
/// \endcode
/// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
/// #1 or #2.
AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
return Node.isDelegatingConstructor();
}
/// Matches constructor, conversion function, and deduction guide declarations
/// that have an explicit specifier if this explicit specifier is resolved to
/// true.
///
/// Given
/// \code
/// template<bool b>
/// struct S {
/// S(int); // #1
/// explicit S(double); // #2
/// operator int(); // #3
/// explicit operator bool(); // #4
/// explicit(false) S(bool) // # 7
/// explicit(true) S(char) // # 8
/// explicit(b) S(S) // # 9
/// };
/// S(int) -> S<true> // #5
/// explicit S(double) -> S<false> // #6
/// \endcode
/// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
/// cxxConversionDecl(isExplicit()) will match #4, but not #3.
/// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
CXXConstructorDecl, CXXConversionDecl,
CXXDeductionGuideDecl)) {
return Node.isExplicit();
}
/// Matches the expression in an explicit specifier if present in the given
/// declaration.
///
/// Given
/// \code
/// template<bool b>
/// struct S {
/// S(int); // #1
/// explicit S(double); // #2
/// operator int(); // #3
/// explicit operator bool(); // #4
/// explicit(false) S(bool) // # 7
/// explicit(true) S(char) // # 8
/// explicit(b) S(S) // # 9
/// };
/// S(int) -> S<true> // #5
/// explicit S(double) -> S<false> // #6
/// \endcode
/// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
/// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
/// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
InnerMatcher) {
ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
if (!ES.getExpr())
return false;
ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
}
/// Matches function and namespace declarations that are marked with
/// the inline keyword.
///
/// Given
/// \code
/// inline void f();
/// void g();
/// namespace n {
/// inline namespace m {}
/// }
/// \endcode
/// functionDecl(isInline()) will match ::f().
/// namespaceDecl(isInline()) will match n::m.
AST_POLYMORPHIC_MATCHER(isInline,
AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
FunctionDecl)) {
// This is required because the spelling of the function used to determine
// whether inline is specified or not differs between the polymorphic types.
if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
return FD->isInlineSpecified();
else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
return NSD->isInline();
llvm_unreachable("Not a valid polymorphic type");
}
/// Matches anonymous namespace declarations.
///
/// Given
/// \code
/// namespace n {
/// namespace {} // #1
/// }
/// \endcode
/// namespaceDecl(isAnonymous()) will match #1 but not ::n.
AST_MATCHER(NamespaceDecl, isAnonymous) {
return Node.isAnonymousNamespace();
}
/// Matches declarations in the namespace `std`, but not in nested namespaces.
///
/// Given
/// \code
/// class vector {};
/// namespace foo {
/// class vector {};
/// namespace std {
/// class vector {};
/// }
/// }
/// namespace std {
/// inline namespace __1 {
/// class vector {}; // #1
/// namespace experimental {
/// class vector {};
/// }
/// }
/// }
/// \endcode
/// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
/// If the given case statement does not use the GNU case range
/// extension, matches the constant given in the statement.
///
/// Given
/// \code
/// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
/// \endcode
/// caseStmt(hasCaseConstant(integerLiteral()))
/// matches "case 1:"
AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
InnerMatcher) {
if (Node.getRHS())
return false;
return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
}
/// Matches declaration that has a given attribute.
///
/// Given
/// \code
/// __attribute__((device)) void f() { ... }
/// \endcode
/// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
/// f. If the matcher is used from clang-query, attr::Kind parameter should be
/// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
for (const auto *Attr : Node.attrs()) {
if (Attr->getKind() == AttrKind)
return true;
}
return false;
}
/// Matches the return value expression of a return statement
///
/// Given
/// \code
/// return a + b;
/// \endcode
/// hasReturnValue(binaryOperator())
/// matches 'return a + b'
/// with binaryOperator()
/// matching 'a + b'
AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
InnerMatcher) {
if (const auto *RetValue = Node.getRetValue())
return InnerMatcher.matches(*RetValue, Finder, Builder);
return false;
}
/// Matches CUDA kernel call expression.
///
/// Example matches,
/// \code
/// kernel<<<i,j>>>();
/// \endcode
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
cudaKernelCallExpr;
/// Matches expressions that resolve to a null pointer constant, such as
/// GNU's __null, C++11's nullptr, or C's NULL macro.
///
/// Given:
/// \code
/// void *v1 = NULL;
/// void *v2 = nullptr;
/// void *v3 = __null; // GNU extension
/// char *cp = (char *)0;
/// int *ip = 0;
/// int i = 0;
/// \endcode
/// expr(nullPointerConstant())
/// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
/// initializer for i.
AST_MATCHER(Expr, nullPointerConstant) {
return Node.isNullPointerConstant(Finder->getASTContext(),
Expr::NPC_ValueDependentIsNull);
}
/// Matches declaration of the function the statement belongs to
///
/// Given:
/// \code
/// F& operator=(const F& o) {
/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
/// return *this;
/// }
/// \endcode
/// returnStmt(forFunction(hasName("operator=")))
/// matches 'return *this'
/// but does not match 'return v > 0'
AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
InnerMatcher) {
const auto &Parents = Finder->getASTContext().getParents(Node);
llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
while(!Stack.empty()) {
const auto &CurNode = Stack.back();
Stack.pop_back();
if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
return true;
}
} else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
Finder, Builder)) {
return true;
}
} else {
for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
Stack.push_back(Parent);
}
}
return false;
}
/// Matches a declaration that has external formal linkage.
///
/// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
/// \code
/// void f() {
/// int x;
/// static int y;
/// }
/// int z;
/// \endcode
///
/// Example matches f() because it has external formal linkage despite being
/// unique to the translation unit as though it has internal likage
/// (matcher = functionDecl(hasExternalFormalLinkage()))
///
/// \code
/// namespace {
/// void f() {}
/// }
/// \endcode
AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
return Node.hasExternalFormalLinkage();
}
/// Matches a declaration that has default arguments.
///
/// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
/// \code
/// void x(int val) {}
/// void y(int val = 0) {}
/// \endcode
///
/// Deprecated. Use hasInitializer() instead to be able to
/// match on the contents of the default argument. For example:
///
/// \code
/// void x(int val = 7) {}
/// void y(int val = 42) {}
/// \endcode
/// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
/// matches the parameter of y
///
/// A matcher such as
/// parmVarDecl(hasInitializer(anything()))
/// is equivalent to parmVarDecl(hasDefaultArgument()).
AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
return Node.hasDefaultArg();
}
/// Matches array new expressions.
///
/// Given:
/// \code
/// MyClass *p1 = new MyClass[10];
/// \endcode
/// cxxNewExpr(isArray())
/// matches the expression 'new MyClass[10]'.
AST_MATCHER(CXXNewExpr, isArray) {
return Node.isArray();
}
/// Matches placement new expression arguments.
///
/// Given:
/// \code
/// MyClass *p1 = new (Storage, 16) MyClass();
/// \endcode
/// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
/// matches the expression 'new (Storage, 16) MyClass()'.
AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
internal::Matcher<Expr>, InnerMatcher) {
return Node.getNumPlacementArgs() > Index &&
InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder);
}
/// Matches any placement new expression arguments.
///
/// Given:
/// \code
/// MyClass *p1 = new (Storage) MyClass();
/// \endcode
/// cxxNewExpr(hasAnyPlacementArg(anything()))
/// matches the expression 'new (Storage, 16) MyClass()'.
AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
InnerMatcher) {
return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
return InnerMatcher.matches(*Arg, Finder, Builder);
});
}
/// Matches array new expressions with a given array size.
///
/// Given:
/// \code
/// MyClass *p1 = new MyClass[10];
/// \endcode
/// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
/// matches the expression 'new MyClass[10]'.
AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
return Node.isArray() && *Node.getArraySize() &&
InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
}
/// Matches a class declaration that is defined.
///
/// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
/// \code
/// class x {};
/// class y;
/// \endcode
AST_MATCHER(CXXRecordDecl, hasDefinition) {
return Node.hasDefinition();
}
/// Matches C++11 scoped enum declaration.
///
/// Example matches Y (matcher = enumDecl(isScoped()))
/// \code
/// enum X {};
/// enum class Y {};
/// \endcode
AST_MATCHER(EnumDecl, isScoped) {
return Node.isScoped();
}
/// Matches a function declared with a trailing return type.
///
/// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
/// \code
/// int X() {}
/// auto Y() -> int {}
/// \endcode
AST_MATCHER(FunctionDecl, hasTrailingReturn) {
if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
return F->hasTrailingReturn();
return false;
}
/// Matches expressions that match InnerMatcher that are possibly wrapped in an
/// elidable constructor and other corresponding bookkeeping nodes.
///
/// In C++17, elidable copy constructors are no longer being generated in the
/// AST as it is not permitted by the standard. They are, however, part of the
/// AST in C++14 and earlier. So, a matcher must abstract over these differences
/// to work in all language modes. This matcher skips elidable constructor-call
/// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
/// various implicit nodes inside the constructor calls, all of which will not
/// appear in the C++17 AST.
///
/// Given
///
/// \code
/// struct H {};
/// H G();
/// void f() {
/// H D = G();
/// }
/// \endcode
///
/// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
/// matches ``H D = G()`` in C++11 through C++17 (and beyond).
AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
// E tracks the node that we are examining.
const Expr *E = &Node;
// If present, remove an outer `ExprWithCleanups` corresponding to the
// underlying `CXXConstructExpr`. This check won't cover all cases of added
// `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
// EWC is placed on the outermost node of the expression, which this may not
// be), but, it still improves the coverage of this matcher.
if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
E = CleanupsExpr->getSubExpr();
if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
if (CtorExpr->isElidable()) {
if (const auto *MaterializeTemp =
dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder,
Builder);
}
}
}
return InnerMatcher.matches(Node, Finder, Builder);
}
//----------------------------------------------------------------------------//
// OpenMP handling.
//----------------------------------------------------------------------------//
/// Matches any ``#pragma omp`` executable directive.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// #pragma omp taskyield
/// \endcode
///
/// ``ompExecutableDirective()`` matches ``omp parallel``,
/// ``omp parallel default(none)`` and ``omp taskyield``.
extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
ompExecutableDirective;
/// Matches standalone OpenMP directives,
/// i.e., directives that can't have a structured block.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// {}
/// #pragma omp taskyield
/// \endcode
///
/// ``ompExecutableDirective(isStandaloneDirective()))`` matches
/// ``omp taskyield``.
AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
return Node.isStandaloneDirective();
}
/// Matches the structured-block of the OpenMP executable directive
///
/// Prerequisite: the executable directive must not be standalone directive.
/// If it is, it will never match.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// ;
/// #pragma omp parallel
/// {}
/// \endcode
///
/// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
internal::Matcher<Stmt>, InnerMatcher) {
if (Node.isStandaloneDirective())
return false; // Standalone directives have no structured blocks.
return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
}
/// Matches any clause in an OpenMP directive.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// \endcode
///
/// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
/// ``omp parallel default(none)``.
AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
internal::Matcher<OMPClause>, InnerMatcher) {
ArrayRef<OMPClause *> Clauses = Node.clauses();
return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
Clauses.end(), Finder,
Builder) != Clauses.end();
}
/// Matches OpenMP ``default`` clause.
///
/// Given
///
/// \code
/// #pragma omp parallel default(none)
/// #pragma omp parallel default(shared)
/// #pragma omp parallel default(firstprivate)
/// #pragma omp parallel
/// \endcode
///
/// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``, and
/// ``default(firstprivate)``
extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
ompDefaultClause;
/// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// #pragma omp parallel default(shared)
/// #pragma omp parallel default(firstprivate)
/// \endcode
///
/// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
AST_MATCHER(OMPDefaultClause, isNoneKind) {
return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
}
/// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// #pragma omp parallel default(shared)
/// #pragma omp parallel default(firstprivate)
/// \endcode
///
/// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
AST_MATCHER(OMPDefaultClause, isSharedKind) {
return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
}
/// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind
/// specified.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel default(none)
/// #pragma omp parallel default(shared)
/// #pragma omp parallel default(firstprivate)
/// \endcode
///
/// ``ompDefaultClause(isFirstPrivateKind())`` matches only
/// ``default(firstprivate)``.
AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) {
return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate;
}
/// Matches if the OpenMP directive is allowed to contain the specified OpenMP
/// clause kind.
///
/// Given
///
/// \code
/// #pragma omp parallel
/// #pragma omp parallel for
/// #pragma omp for
/// \endcode
///
/// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
/// ``omp parallel`` and ``omp parallel for``.
///
/// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
/// should be passed as a quoted string. e.g.,
/// ``isAllowedToContainClauseKind("OMPC_default").``
AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
OpenMPClauseKind, CKind) {
return llvm::omp::isAllowedClauseForDirective(
Node.getDirectiveKind(), CKind,
Finder->getASTContext().getLangOpts().OpenMP);
}
//----------------------------------------------------------------------------//
// End OpenMP handling.
//----------------------------------------------------------------------------//
} // namespace ast_matchers
} // namespace clang
#endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
|
GB_bitmap_emult_template.c | //------------------------------------------------------------------------------
// GB_bitmap_emult_template: C = A.*B, C<M>=A.*B, and C<!M>=A.*B, C bitmap
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// C is bitmap. A and B are bitmap or full. M depends on the method
{
//--------------------------------------------------------------------------
// get C, A, and B
//--------------------------------------------------------------------------
const int8_t *restrict Ab = A->b ;
const int8_t *restrict Bb = B->b ;
const int64_t vlen = A->vlen ;
ASSERT (GB_IS_BITMAP (A) || GB_IS_FULL (A) || GB_as_if_full (A)) ;
ASSERT (GB_IS_BITMAP (B) || GB_IS_FULL (A) || GB_as_if_full (B)) ;
const bool A_iso = A->iso ;
const bool B_iso = B->iso ;
int8_t *restrict Cb = C->b ;
const int64_t cnz = GB_nnz_held (C) ;
#ifdef GB_ISO_EMULT
ASSERT (C->iso) ;
#else
ASSERT (!C->iso) ;
ASSERT (!(A_iso && B_iso)) ; // one of A or B can be iso, but not both
const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ;
const GB_BTYPE *restrict Bx = (GB_BTYPE *) B->x ;
GB_CTYPE *restrict Cx = (GB_CTYPE *) C->x ;
#endif
//--------------------------------------------------------------------------
// C=A.*B, C<M>=A.*B, or C<!M>=A.*B: C is bitmap
//--------------------------------------------------------------------------
// TODO modify this method so it can modify C in-place, and also use the
// accum operator.
int64_t cnvals = 0 ;
if (ewise_method == GB_EMULT_METHOD5)
{
//----------------------------------------------------------------------
// Method5: C is bitmap, M is not present
//----------------------------------------------------------------------
// ------------------------------------------
// C = A .* B
// ------------------------------------------
// bitmap . bitmap bitmap (method: 5)
// bitmap . bitmap full (method: 5)
// bitmap . full bitmap (method: 5)
int tid ;
#pragma omp parallel for num_threads(C_nthreads) schedule(static) \
reduction(+:cnvals)
for (tid = 0 ; tid < C_nthreads ; tid++)
{
int64_t pstart, pend, task_cnvals = 0 ;
GB_PARTITION (pstart, pend, cnz, tid, C_nthreads) ;
for (int64_t p = pstart ; p < pend ; p++)
{
if (GBB (Ab, p) && GBB (Bb,p))
{
// C (i,j) = A (i,j) + B (i,j)
#ifndef GB_ISO_EMULT
GB_GETA (aij, Ax, p, A_iso) ;
GB_GETB (bij, Bx, p, B_iso) ;
GB_BINOP (GB_CX (p), aij, bij, p % vlen, p / vlen) ;
#endif
Cb [p] = 1 ;
task_cnvals++ ;
}
}
cnvals += task_cnvals ;
}
}
else if (ewise_method == GB_EMULT_METHOD6)
{
//----------------------------------------------------------------------
// Method6: C is bitmap, !M is sparse or hyper
//----------------------------------------------------------------------
// ------------------------------------------
// C <!M>= A .* B
// ------------------------------------------
// bitmap sparse bitmap bitmap (method: 6)
// bitmap sparse bitmap full (method: 6)
// bitmap sparse full bitmap (method: 6)
// M is sparse and complemented. If M is sparse and not
// complemented, then C is constructed as sparse, not bitmap.
ASSERT (M != NULL) ;
ASSERT (Mask_comp) ;
ASSERT (GB_IS_SPARSE (M) || GB_IS_HYPERSPARSE (M)) ;
// C(i,j) = A(i,j) .* B(i,j) can only be computed where M(i,j) is
// not present in the sparse pattern of M, and where it is present
// but equal to zero.
//----------------------------------------------------------------------
// scatter M into the C bitmap
//----------------------------------------------------------------------
GB_bitmap_M_scatter_whole (C, M, Mask_struct, GB_BITMAP_M_SCATTER_SET_2,
M_ek_slicing, M_ntasks, M_nthreads, Context) ;
// C(i,j) has been marked, in Cb, with the value 2 where M(i,j)=1.
// These positions will not be computed in C(i,j). C(i,j) can only
// be modified where Cb [p] is zero.
int tid ;
#pragma omp parallel for num_threads(C_nthreads) schedule(static) \
reduction(+:cnvals)
for (tid = 0 ; tid < C_nthreads ; tid++)
{
int64_t pstart, pend, task_cnvals = 0 ;
GB_PARTITION (pstart, pend, cnz, tid, C_nthreads) ;
for (int64_t p = pstart ; p < pend ; p++)
{
if (Cb [p] == 0)
{
// M(i,j) is zero, so C(i,j) can be computed
if (GBB (Ab, p) && GBB (Bb, p))
{
// C (i,j) = A (i,j) + B (i,j)
#ifndef GB_ISO_EMULT
GB_GETA (aij, Ax, p, A_iso) ;
GB_GETB (bij, Bx, p, B_iso) ;
GB_BINOP (GB_CX (p), aij, bij, p % vlen, p / vlen) ;
#endif
Cb [p] = 1 ;
task_cnvals++ ;
}
}
else
{
// M(i,j) == 1, so C(i,j) is not computed
Cb [p] = 0 ;
}
}
cnvals += task_cnvals ;
}
}
else // if (ewise_method == GB_EMULT_METHOD7)
{
//----------------------------------------------------------------------
// Method7: C is bitmap; M is bitmap or full
//----------------------------------------------------------------------
// ------------------------------------------
// C <M> = A .* B
// ------------------------------------------
// bitmap bitmap bitmap bitmap (method: 7)
// bitmap bitmap bitmap full (method: 7)
// bitmap bitmap full bitmap (method: 7)
// ------------------------------------------
// C <M> = A .* B
// ------------------------------------------
// bitmap full bitmap bitmap (method: 7)
// bitmap full bitmap full (method: 7)
// bitmap full full bitmap (method: 7)
// ------------------------------------------
// C <!M> = A .* B
// ------------------------------------------
// bitmap bitmap bitmap bitmap (method: 7)
// bitmap bitmap bitmap full (method: 7)
// bitmap bitmap full bitmap (method: 7)
// ------------------------------------------
// C <!M> = A .* B
// ------------------------------------------
// bitmap full bitmap bitmap (method: 7)
// bitmap full bitmap full (method: 7)
// bitmap full full bitmap (method: 7)
ASSERT (GB_IS_BITMAP (M) || GB_IS_FULL (M)) ;
const int8_t *restrict Mb = M->b ;
const GB_void *restrict Mx = (GB_void *) (Mask_struct ? NULL : (M->x)) ;
size_t msize = M->type->size ;
#undef GB_GET_MIJ
#define GB_GET_MIJ(p) \
bool mij = GBB (Mb, p) && GB_mcast (Mx, p, msize) ; \
if (Mask_comp) mij = !mij ; /* TODO: use ^ */
int tid ;
#pragma omp parallel for num_threads(C_nthreads) schedule(static) \
reduction(+:cnvals)
for (tid = 0 ; tid < C_nthreads ; tid++)
{
int64_t pstart, pend, task_cnvals = 0 ;
GB_PARTITION (pstart, pend, cnz, tid, C_nthreads) ;
for (int64_t p = pstart ; p < pend ; p++)
{
GB_GET_MIJ (p) ;
if (mij)
{
// M(i,j) is true, so C(i,j) can be computed
if (GBB (Ab, p) && GBB (Bb, p))
{
// C (i,j) = A (i,j) + B (i,j)
#ifndef GB_ISO_EMULT
GB_GETA (aij, Ax, p, A_iso) ;
GB_GETB (bij, Bx, p, B_iso) ;
GB_BINOP (GB_CX (p), aij, bij, p % vlen, p / vlen) ;
#endif
Cb [p] = 1 ;
task_cnvals++ ;
}
}
else
{
// M(i,j) == 1, so C(i,j) is not computed
Cb [p] = 0 ;
}
}
cnvals += task_cnvals ;
}
}
C->nvals = cnvals ;
}
|
transform.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT RRRR AAA N N SSSSS FFFFF OOO RRRR M M %
% T R R A A NN N SS F O O R R MM MM %
% T RRRR AAAAA N N N SSS FFF O O RRRR M M M %
% T R R A A N NN SS F O O R R M M %
% T R R A A N N SSSSS F OOO R R M M %
% %
% %
% MagickCore Image Transform Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/effect.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/memory_.h"
#include "magick/layer.h"
#include "magick/list.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-private.h"
#include "magick/resource_.h"
#include "magick/resize.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/transform.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o O r i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoOrientImage() adjusts an image so that its orientation is suitable for
% viewing (i.e. top-left orientation).
%
% The format of the AutoOrientImage method is:
%
% Image *AutoOrientImage(const Image *image,
% const OrientationType orientation,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o orientation: Current image orientation.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *AutoOrientImage(const Image *image,
const OrientationType orientation,ExceptionInfo *exception)
{
Image
*orient_image;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
orient_image=(Image *) NULL;
switch(orientation)
{
case UndefinedOrientation:
case TopLeftOrientation:
default:
{
orient_image=CloneImage(image,0,0,MagickTrue,exception);
break;
}
case TopRightOrientation:
{
orient_image=FlopImage(image,exception);
break;
}
case BottomRightOrientation:
{
orient_image=RotateImage(image,180.0,exception);
break;
}
case BottomLeftOrientation:
{
orient_image=FlipImage(image,exception);
break;
}
case LeftTopOrientation:
{
orient_image=TransposeImage(image,exception);
break;
}
case RightTopOrientation:
{
orient_image=RotateImage(image,90.0,exception);
break;
}
case RightBottomOrientation:
{
orient_image=TransverseImage(image,exception);
break;
}
case LeftBottomOrientation:
{
orient_image=RotateImage(image,270.0,exception);
break;
}
}
if (orient_image != (Image *) NULL)
orient_image->orientation=TopLeftOrientation;
return(orient_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ChopImage() removes a region of an image and collapses the image to occupy
% the removed portion.
%
% The format of the ChopImage method is:
%
% Image *ChopImage(const Image *image,const RectangleInfo *chop_info)
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o chop_info: Define the region of the image to chop.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info,
ExceptionInfo *exception)
{
#define ChopImageTag "Chop/Image"
CacheView
*chop_view,
*image_view;
Image
*chop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
extent;
ssize_t
y;
/*
Check chop geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
assert(chop_info != (RectangleInfo *) NULL);
if (((chop_info->x+(ssize_t) chop_info->width) < 0) ||
((chop_info->y+(ssize_t) chop_info->height) < 0) ||
(chop_info->x > (ssize_t) image->columns) ||
(chop_info->y > (ssize_t) image->rows))
ThrowImageException(OptionWarning,"GeometryDoesNotContainImage");
extent=(*chop_info);
if ((extent.x+(ssize_t) extent.width) > (ssize_t) image->columns)
extent.width=(size_t) ((ssize_t) image->columns-extent.x);
if ((extent.y+(ssize_t) extent.height) > (ssize_t) image->rows)
extent.height=(size_t) ((ssize_t) image->rows-extent.y);
if (extent.x < 0)
{
extent.width-=(size_t) (-extent.x);
extent.x=0;
}
if (extent.y < 0)
{
extent.height-=(size_t) (-extent.y);
extent.y=0;
}
chop_image=CloneImage(image,image->columns-extent.width,image->rows-
extent.height,MagickTrue,exception);
if (chop_image == (Image *) NULL)
return((Image *) NULL);
/*
Extract chop image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
chop_view=AcquireAuthenticCacheView(chop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,chop_image,extent.y,1)
#endif
for (y=0; y < (ssize_t) extent.y; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict chop_indexes,
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,y,chop_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
chop_indexes=GetCacheViewAuthenticIndexQueue(chop_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
*q=(*p);
if (indexes != (IndexPacket *) NULL)
{
if (chop_indexes != (IndexPacket *) NULL)
*chop_indexes++=GetPixelIndex(indexes+x);
}
q++;
}
p++;
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ChopImage)
#endif
proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
/*
Extract chop image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) (image->rows-(extent.y+extent.height)); y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict chop_indexes,
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,extent.y+extent.height+y,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,extent.y+y,chop_image->columns,
1,exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
chop_indexes=GetCacheViewAuthenticIndexQueue(chop_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
*q=(*p);
if (indexes != (IndexPacket *) NULL)
{
if (chop_indexes != (IndexPacket *) NULL)
*chop_indexes++=GetPixelIndex(indexes+x);
}
q++;
}
p++;
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ChopImage)
#endif
proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
chop_view=DestroyCacheView(chop_view);
image_view=DestroyCacheView(image_view);
chop_image->type=image->type;
if (status == MagickFalse)
chop_image=DestroyImage(chop_image);
return(chop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n s o l i d a t e C M Y K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConsolidateCMYKImage() consolidates separate C, M, Y, and K planes into a
% single image.
%
% The format of the ConsolidateCMYKImage method is:
%
% Image *ConsolidateCMYKImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image sequence.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ConsolidateCMYKImages(const Image *images,
ExceptionInfo *exception)
{
CacheView
*cmyk_view,
*image_view;
Image
*cmyk_image,
*cmyk_images;
register ssize_t
i;
ssize_t
y;
/*
Consolidate separate C, M, Y, and K planes into a single image.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
cmyk_images=NewImageList();
for (i=0; i < (ssize_t) GetImageListLength(images); i+=4)
{
cmyk_image=CloneImage(images,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 critical (MagickCore_CropImage)
#endif
proceed=SetImageProgress(image,CropImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
crop_view=DestroyCacheView(crop_view);
image_view=DestroyCacheView(image_view);
crop_image->type=image->type;
if (status == MagickFalse)
crop_image=DestroyImage(crop_image);
return(crop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C r o p I m a g e T o T i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropImageToTiles() crops a single image, into a possible list of tiles.
% This may include a single sub-region of the image. This basically applies
% all the normal geometry flags for Crop.
%
% Image *CropImageToTiles(const Image *image,
% const RectangleInfo *crop_geometry, ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
MagickExport Image *CropImageToTiles(const Image *image,
const char *crop_geometry,ExceptionInfo *exception)
{
Image
*next,
*crop_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
crop_image=NewImageList();
next=NewImageList();
flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception);
if ((flags & AreaValue) != 0)
{
PointInfo
delta,
offset;
RectangleInfo
crop;
size_t
height,
width;
/*
Crop into NxM tiles (@ flag).
*/
width=image->columns;
height=image->rows;
if (geometry.width == 0)
geometry.width=1;
if (geometry.height == 0)
geometry.height=1;
if ((flags & AspectValue) == 0)
{
width-=(geometry.x < 0 ? -1 : 1)*geometry.x;
height-=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
else
{
width+=(geometry.x < 0 ? -1 : 1)*geometry.x;
height+=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
delta.x=(double) width/geometry.width;
delta.y=(double) height/geometry.height;
if (delta.x < 1.0)
delta.x=1.0;
if (delta.y < 1.0)
delta.y=1.0;
for (offset.y=0; offset.y < (double) height; )
{
if ((flags & AspectValue) == 0)
{
crop.y=(ssize_t) MagickRound((MagickRealType) (offset.y-
(geometry.y > 0 ? 0 : geometry.y)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) MagickRound((MagickRealType) (offset.y+
(geometry.y < 0 ? 0 : geometry.y)));
}
else
{
crop.y=(ssize_t) MagickRound((MagickRealType) (offset.y-
(geometry.y > 0 ? geometry.y : 0)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) MagickRound((MagickRealType) (offset.y+
(geometry.y < 0 ? geometry.y : 0)));
}
crop.height-=crop.y;
crop.y+=image->page.y;
for (offset.x=0; offset.x < (double) width; )
{
if ((flags & AspectValue) == 0)
{
crop.x=(ssize_t) MagickRound((MagickRealType) (offset.x-
(geometry.x > 0 ? 0 : geometry.x)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) MagickRound((MagickRealType) (offset.x+
(geometry.x < 0 ? 0 : geometry.x)));
}
else
{
crop.x=(ssize_t) MagickRound((MagickRealType) (offset.x-
(geometry.x > 0 ? geometry.x : 0)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) MagickRound((MagickRealType) (offset.x+
(geometry.x < 0 ? geometry.x : 0)));
}
crop.width-=crop.x;
crop.x+=image->page.x;
next=CropImage(image,&crop,exception);
if (next != (Image *) NULL)
AppendImageToList(&crop_image,next);
}
}
ClearMagickException(exception);
return(crop_image);
}
if (((geometry.width == 0) && (geometry.height == 0)) ||
((flags & XValue) != 0) || ((flags & YValue) != 0))
{
/*
Crop a single region at +X+Y.
*/
crop_image=CropImage(image,&geometry,exception);
if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0))
{
crop_image->page.width=geometry.width;
crop_image->page.height=geometry.height;
crop_image->page.x-=geometry.x;
crop_image->page.y-=geometry.y;
}
return(crop_image);
}
if ((image->columns > geometry.width) || (image->rows > geometry.height))
{
RectangleInfo
page;
size_t
height,
width;
ssize_t
x,
y;
/*
Crop into tiles of fixed size WxH.
*/
page=image->page;
if (page.width == 0)
page.width=image->columns;
if (page.height == 0)
page.height=image->rows;
width=geometry.width;
if (width == 0)
width=page.width;
height=geometry.height;
if (height == 0)
height=page.height;
next=NewImageList();
for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height)
{
for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width)
{
geometry.width=width;
geometry.height=height;
geometry.x=x;
geometry.y=y;
next=CropImage(image,&geometry,exception);
if (next == (Image *) NULL)
break;
AppendImageToList(&crop_image,next);
}
if (next == (Image *) NULL)
break;
}
return(crop_image);
}
return(CloneImage(image,0,0,MagickTrue,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x c e r p t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExcerptImage() returns a excerpt of the image as defined by the geometry.
%
% The format of the ExcerptImage method is:
%
% Image *ExcerptImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExcerptImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define ExcerptImageTag "Excerpt/Image"
CacheView
*excerpt_view,
*image_view;
Image
*excerpt_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate excerpt image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
excerpt_image=CloneImage(image,geometry->width,geometry->height,MagickTrue,
exception);
if (excerpt_image == (Image *) NULL)
return((Image *) NULL);
/*
Excerpt each row.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
excerpt_view=AcquireAuthenticCacheView(excerpt_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,excerpt_image,excerpt_image->rows,1)
#endif
for (y=0; y < (ssize_t) excerpt_image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict excerpt_indexes,
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,geometry->x,geometry->y+y,
geometry->width,1,exception);
q=GetCacheViewAuthenticPixels(excerpt_view,0,y,excerpt_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
(void) memcpy(q,p,(size_t) excerpt_image->columns*sizeof(*q));
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if (indexes != (IndexPacket *) NULL)
{
excerpt_indexes=GetCacheViewAuthenticIndexQueue(excerpt_view);
if (excerpt_indexes != (IndexPacket *) NULL)
(void) memcpy(excerpt_indexes,indexes,(size_t)
excerpt_image->columns*sizeof(*excerpt_indexes));
}
if (SyncCacheViewAuthenticPixels(excerpt_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ExcerptImage)
#endif
proceed=SetImageProgress(image,ExcerptImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
excerpt_view=DestroyCacheView(excerpt_view);
image_view=DestroyCacheView(image_view);
excerpt_image->type=image->type;
if (status == MagickFalse)
excerpt_image=DestroyImage(excerpt_image);
return(excerpt_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x t e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExtentImage() extends the image as defined by the geometry, gravity, and
% image background color. Set the (x,y) offset of the geometry to move the
% original image relative to the extended image.
%
% The format of the ExtentImage method is:
%
% Image *ExtentImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExtentImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
Image
*extent_image;
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 critical (MagickCore_FlipImage)
#endif
proceed=SetImageProgress(image,FlipImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flip_view=DestroyCacheView(flip_view);
image_view=DestroyCacheView(image_view);
flip_image->type=image->type;
if (page.height != 0)
page.y=(ssize_t) (page.height-flip_image->rows-page.y);
flip_image->page=page;
if (status == MagickFalse)
flip_image=DestroyImage(flip_image);
return(flip_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FlopImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis.
%
% The format of the FlopImage method is:
%
% Image *FlopImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FlopImage(const Image *image,ExceptionInfo *exception)
{
#define FlopImageTag "Flop/Image"
CacheView
*flop_view,
*image_view;
Image
*flop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
flop_image=CloneImage(image,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 critical (MagickCore_FlopImage)
#endif
proceed=SetImageProgress(image,FlopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flop_view=DestroyCacheView(flop_view);
image_view=DestroyCacheView(image_view);
flop_image->type=image->type;
if (page.width != 0)
page.x=(ssize_t) (page.width-flop_image->columns-page.x);
flop_image->page=page;
if (status == MagickFalse)
flop_image=DestroyImage(flop_image);
return(flop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R o l l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RollImage() offsets an image as defined by x_offset and y_offset.
%
% The format of the RollImage method is:
%
% Image *RollImage(const Image *image,const ssize_t x_offset,
% const ssize_t y_offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x_offset: the number of columns to roll in the horizontal direction.
%
% o y_offset: the number of rows to roll in the vertical direction.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType CopyImageRegion(Image *destination,const Image *source, const size_t columns,const size_t rows,const ssize_t sx,const ssize_t sy,
const ssize_t dx,const ssize_t dy,ExceptionInfo *exception)
{
CacheView
*source_view,
*destination_view;
MagickBooleanType
status;
ssize_t
y;
if (columns == 0)
return(MagickTrue);
status=MagickTrue;
source_view=AcquireVirtualCacheView(source,exception);
destination_view=AcquireAuthenticCacheView(destination,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(source,destination,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict destination_indexes;
register PixelPacket
*magick_restrict q;
/*
Transfer scanline.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,sx,sy+y,columns,1,exception);
q=GetCacheViewAuthenticPixels(destination_view,dx,dy+y,columns,1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(source_view);
(void) memcpy(q,p,(size_t) columns*sizeof(*p));
if (indexes != (IndexPacket *) NULL)
{
destination_indexes=GetCacheViewAuthenticIndexQueue(destination_view);
if (destination_indexes != (IndexPacket *) NULL)
(void) memcpy(destination_indexes,indexes,(size_t)
columns*sizeof(*indexes));
}
sync=SyncCacheViewAuthenticPixels(destination_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
destination_view=DestroyCacheView(destination_view);
source_view=DestroyCacheView(source_view);
return(status);
}
MagickExport Image *RollImage(const Image *image,const ssize_t x_offset,
const ssize_t y_offset,ExceptionInfo *exception)
{
#define RollImageTag "Roll/Image"
Image
*roll_image;
MagickStatusType
status;
RectangleInfo
offset;
/*
Initialize roll image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
roll_image=CloneImage(image,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 critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,splice_image,splice_image->rows,1)
#endif
for (y=(ssize_t) (splice_geometry.y+splice_geometry.height);
y < (ssize_t) splice_image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict indexes,
*magick_restrict splice_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
if ((y < 0) || (y >= (ssize_t)splice_image->rows))
continue;
p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,
splice_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
splice_indexes=GetCacheViewAuthenticIndexQueue(splice_view);
for (x=0; x < columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes));
indexes++;
p++;
q++;
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q++;
for ( ; x < (ssize_t) splice_image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes));
indexes++;
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
splice_view=DestroyCacheView(splice_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
splice_image=DestroyImage(splice_image);
return(splice_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImage() is a convenience method that behaves like ResizeImage() or
% CropImage() but accepts scaling and/or cropping information as a region
% geometry specification. If the operation fails, the original image handle
% is left as is.
%
% This should only be used for single images.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImage(Image **image,const char *crop_geometry,
% const char *image_geometry)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
*/
/*
DANGER: This function destroys what it assumes to be a single image list.
If the input image is part of a larger list, all other images in that list
will be simply 'lost', not destroyed.
Also if the crop generates a list of images only the first image is resized.
And finally if the crop succeeds and the resize failed, you will get a
cropped image, as well as a 'false' or 'failed' report.
This function and should probably be deprecated in favor of direct calls
to CropImageToTiles() or ResizeImage(), as appropriate.
*/
MagickExport MagickBooleanType TransformImage(Image **image,
const char *crop_geometry,const char *image_geometry)
{
Image
*resize_image,
*transform_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image **) NULL);
assert((*image)->signature == MagickCoreSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
transform_image=(*image);
if (crop_geometry != (const char *) NULL)
{
Image
*crop_image;
/*
Crop image to a user specified size.
*/
crop_image=CropImageToTiles(*image,crop_geometry,&(*image)->exception);
if (crop_image == (Image *) NULL)
transform_image=CloneImage(*image,0,0,MagickTrue,&(*image)->exception);
else
{
transform_image=DestroyImage(transform_image);
transform_image=GetFirstImageInList(crop_image);
}
*image=transform_image;
}
if (image_geometry == (const char *) NULL)
return(MagickTrue);
/*
Scale image to a user specified size.
*/
flags=ParseRegionGeometry(transform_image,image_geometry,&geometry,
&(*image)->exception);
(void) flags;
if ((transform_image->columns == geometry.width) &&
(transform_image->rows == geometry.height))
return(MagickTrue);
resize_image=ResizeImage(transform_image,geometry.width,geometry.height,
transform_image->filter,transform_image->blur,&(*image)->exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
transform_image=DestroyImage(transform_image);
transform_image=resize_image;
*image=transform_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImages() calls TransformImage() on each image of a sequence.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImages(Image **image,
% const char *crop_geometry,const char *image_geometry)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
*/
MagickExport MagickBooleanType TransformImages(Image **images,
const char *crop_geometry,const char *image_geometry)
{
Image
*image,
**image_list,
*transform_images;
MagickStatusType
status;
register ssize_t
i;
assert(images != (Image **) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
image_list=ImageListToArray(*images,&(*images)->exception);
if (image_list == (Image **) NULL)
return(MagickFalse);
status=MagickTrue;
transform_images=NewImageList();
for (i=0; image_list[i] != (Image *) NULL; i++)
{
image=image_list[i];
status&=TransformImage(&image,crop_geometry,image_geometry);
AppendImageToList(&transform_images,image);
}
*images=transform_images;
image_list=(Image **) RelinquishMagickMemory(image_list);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p o s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransposeImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis while rotating them by 90 degrees.
%
% The format of the TransposeImage method is:
%
% Image *TransposeImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TransposeImage(const Image *image,ExceptionInfo *exception)
{
#define TransposeImageTag "Transpose/Image"
CacheView
*image_view,
*transpose_view;
Image
*transpose_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
transpose_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transpose_image == (Image *) NULL)
return((Image *) NULL);
/*
Transpose image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transpose_view=AcquireAuthenticCacheView(transpose_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,transpose_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict transpose_indexes,
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-y-1,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transpose_view,(ssize_t) (image->rows-y-1),
0,1,transpose_image->rows,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
(void) memcpy(q,p,(size_t) image->columns*sizeof(*q));
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if (indexes != (IndexPacket *) NULL)
{
transpose_indexes=GetCacheViewAuthenticIndexQueue(transpose_view);
if (transpose_indexes != (IndexPacket *) NULL)
(void) memcpy(transpose_indexes,indexes,(size_t)
image->columns*sizeof(*transpose_indexes));
}
if (SyncCacheViewAuthenticPixels(transpose_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,TransposeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transpose_view=DestroyCacheView(transpose_view);
image_view=DestroyCacheView(image_view);
transpose_image->type=image->type;
page=transpose_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
transpose_image->page=page;
if (status == MagickFalse)
transpose_image=DestroyImage(transpose_image);
return(transpose_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s v e r s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransverseImage() creates a vertical mirror image by reflecting the pixels
% around the central x-axis while rotating them by 270 degrees.
%
% The format of the TransverseImage method is:
%
% Image *TransverseImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TransverseImage(const Image *image,ExceptionInfo *exception)
{
#define TransverseImageTag "Transverse/Image"
CacheView
*image_view,
*transverse_view;
Image
*transverse_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
transverse_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transverse_image == (Image *) NULL)
return((Image *) NULL);
/*
Transverse image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transverse_view=AcquireAuthenticCacheView(transverse_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,transverse_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict transverse_indexes,
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transverse_view,(ssize_t) (image->rows-y-
1),0,1,transverse_image->rows,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
q+=image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
*--q=(*p++);
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if (indexes != (IndexPacket *) NULL)
{
transverse_indexes=GetCacheViewAuthenticIndexQueue(transverse_view);
if (transverse_indexes != (IndexPacket *) NULL)
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(transverse_indexes+image->columns-x-1,
GetPixelIndex(indexes+x));
}
sync=SyncCacheViewAuthenticPixels(transverse_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransverseImage)
#endif
proceed=SetImageProgress(image,TransverseImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transverse_view=DestroyCacheView(transverse_view);
image_view=DestroyCacheView(image_view);
transverse_image->type=image->type;
page=transverse_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
if (page.width != 0)
page.x=(ssize_t) (page.width-transverse_image->columns-page.x);
if (page.height != 0)
page.y=(ssize_t) (page.height-transverse_image->rows-page.y);
transverse_image->page=page;
if (status == MagickFalse)
transverse_image=DestroyImage(transverse_image);
return(transverse_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r i m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TrimImage() trims pixels from the image edges. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the TrimImage method is:
%
% Image *TrimImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TrimImage(const Image *image,ExceptionInfo *exception)
{
RectangleInfo
geometry;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
geometry=GetImageBoundingBox(image,exception);
if ((geometry.width == 0) || (geometry.height == 0))
{
Image
*crop_image;
crop_image=CloneImage(image,1,1,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->background_color.opacity=(Quantum) TransparentOpacity;
(void) SetImageBackgroundColor(crop_image);
crop_image->page=image->page;
crop_image->page.x=(-1);
crop_image->page.y=(-1);
return(crop_image);
}
geometry.x+=image->page.x;
geometry.y+=image->page.y;
return(CropImage(image,&geometry,exception));
}
|
core_dsygst.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zhegst.c, normal z -> d, Fri Sep 28 17:38:23 2018
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "core_lapack.h"
/***************************************************************************//**
*
* @ingroup core_hegst
*
* Reduces a complex symmetric-definite generalized eigenproblem to standard
* form.
*
* If ITYPE = 1, the problem is A*x = lambda*B*x,
* and A is overwritten by inv(U^T)*A*inv(U) or inv(L)*A*inv(L^T)
*
* If ITYPE = 2 or 3, the problem is A*B*x = lambda*x or
* B*A*x = lambda*x, and A is overwritten by U*A*U^T or L^T*A*L.
*
*******************************************************************************
*
* @param[in] itype
* = 1: compute inv(U^T)*A*inv(U) or inv(L)*A*inv(L^T);
* = 2 or 3: compute U*A*U^T or L^T*A*L.
*
* @param[in] uplo
* If PlasmaUpper, upper triangle of A is stored and B is factored as
* U^T*U;
* If PlasmaLower, lower triangle of A is stored and B is factored as
* L*L^T.
*
* @param[in] n
* The order of the matrices A and B. N >= 0.
*
* @param[in,out] A
* On entry, the symmetric matrix A. If UPLO = 'U', the leading
* N-by-N upper triangular part of A contains the upper
* triangular part of the matrix A, and the strictly lower
* triangular part of A is not referenced. If UPLO = 'L', the
* leading N-by-N lower triangular part of A contains the lower
* triangular part of the matrix A, and the strictly upper
* triangular part of A is not referenced.
*
* On exit, if INFO = 0, the transformed matrix, stored in the
* same format as A.
*
* @param[in] lda
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[in,out] B
* The triangular factor from the Cholesky factorization of B,
* as returned by DPOTRF.
*
* @param[in] ldb
* The leading dimension of the array B. LDB >= max(1,N).
*
******************************************************************************/
__attribute__((weak))
int plasma_core_dsygst(int itype, plasma_enum_t uplo,
int n,
double *A, int lda,
double *B, int ldb)
{
int info = LAPACKE_dsygst_work(
LAPACK_COL_MAJOR,
itype,
lapack_const(uplo),
n, A, lda, B, ldb );
return info;
}
/******************************************************************************/
void plasma_core_omp_dsygst(int itype, plasma_enum_t uplo,
int n,
double *A, int lda,
double *B, int ldb,
plasma_sequence_t *sequence,
plasma_request_t *request)
{
#pragma omp task depend(inout:A[0:lda*n]) \
depend(in:B[0:ldb*n])
{
if (sequence->status == PlasmaSuccess)
plasma_core_dsygst(itype, uplo,
n,
A, lda,
B, ldb);
}
}
|
GB_unop__identity_int32_int16.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_int32_int16)
// op(A') function: GB (_unop_tran__identity_int32_int16)
// C type: int32_t
// A type: int16_t
// cast: int32_t cij = (int32_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
int32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int32_t z = (int32_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int32_t z = (int32_t) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int32_int16)
(
int32_t *Cx, // Cx and Ax may be aliased
const int16_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int16_t aij = Ax [p] ;
int32_t z = (int32_t) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int16_t aij = Ax [p] ;
int32_t z = (int32_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_int32_int16)
(
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
|
channel.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC H H AAA N N N N EEEEE L %
% C H H A A NN N NN N E L %
% C HHHHH AAAAA N N N N N N EEE L %
% C H H A A N NN N NN E L %
% CCCC H H A A N N N N EEEEE LLLLL %
% %
% %
% MagickCore Image Channel Methods %
% %
% Software Design %
% Cristy %
% December 2003 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/channel.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/image.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h a n n e l F x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ChannelFxImage() applies a channel expression to the specified image. The
% expression consists of one or more channels, either mnemonic or numeric (e.g.
% red, 1), separated by actions as follows:
%
% <=> exchange two channels (e.g. red<=>blue)
% => copy one channel to another channel (e.g. red=>green)
% = assign a constant value to a channel (e.g. red=50%)
% , write new image channels in the specified order (e.g. red, green)
% | add a new output image for the next set of channel operations
% ; move to the next input image for the source of channel data
%
% For example, to create 3 grayscale images from the red, green, and blue
% channels of an image, use:
%
% -channel-fx "red; green; blue"
%
% A channel without an operation symbol implies separate (i.e, semicolon).
%
% The format of the ChannelFxImage method is:
%
% Image *ChannelFxImage(const Image *image,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: A channel expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef enum
{
ExtractChannelOp,
AssignChannelOp,
ExchangeChannelOp,
TransferChannelOp
} ChannelFx;
static MagickBooleanType ChannelImage(Image *destination_image,
const PixelChannel destination_channel,const ChannelFx channel_op,
const Image *source_image,const PixelChannel source_channel,
const Quantum pixel,ExceptionInfo *exception)
{
CacheView
*source_view,
*destination_view;
MagickBooleanType
status;
size_t
height,
width;
ssize_t
y;
status=MagickTrue;
source_view=AcquireVirtualCacheView(source_image,exception);
destination_view=AcquireAuthenticCacheView(destination_image,exception);
height=MagickMin(source_image->rows,destination_image->rows);
width=MagickMin(source_image->columns,destination_image->columns);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(source_image,source_image,height,1)
#endif
for (y=0; y < (ssize_t) height; y++)
{
PixelTrait
destination_traits,
source_traits;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(destination_view,0,y,
destination_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
destination_traits=GetPixelChannelTraits(destination_image,
destination_channel);
source_traits=GetPixelChannelTraits(source_image,source_channel);
if ((destination_traits == UndefinedPixelTrait) ||
(source_traits == UndefinedPixelTrait))
continue;
for (x=0; x < (ssize_t) width; x++)
{
if (channel_op == AssignChannelOp)
SetPixelChannel(destination_image,destination_channel,pixel,q);
else
SetPixelChannel(destination_image,destination_channel,
GetPixelChannel(source_image,source_channel,p),q);
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(destination_image);
}
if (SyncCacheViewAuthenticPixels(destination_view,exception) == MagickFalse)
status=MagickFalse;
}
destination_view=DestroyCacheView(destination_view);
source_view=DestroyCacheView(source_view);
return(status);
}
MagickExport Image *ChannelFxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
#define ChannelFxImageTag "ChannelFx/Image"
ChannelFx
channel_op;
ChannelType
channel_mask;
char
token[MagickPathExtent];
const char
*p;
const Image
*source_image;
double
pixel;
Image
*destination_image;
MagickBooleanType
status;
PixelChannel
source_channel,
destination_channel;
ssize_t
channels;
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);
source_image=image;
destination_image=CloneImage(source_image,0,0,MagickTrue,exception);
if (destination_image == (Image *) NULL)
return((Image *) NULL);
if (expression == (const char *) NULL)
return(destination_image);
status=SetImageStorageClass(destination_image,DirectClass,exception);
if (status == MagickFalse)
{
destination_image=GetLastImageInList(destination_image);
return((Image *) NULL);
}
destination_channel=RedPixelChannel;
channel_mask=UndefinedChannel;
pixel=0.0;
p=(char *) expression;
GetNextToken(p,&p,MagickPathExtent,token);
channel_op=ExtractChannelOp;
for (channels=0; *token != '\0'; )
{
ssize_t
i;
/*
Interpret channel expression.
*/
switch (*token)
{
case ',':
{
GetNextToken(p,&p,MagickPathExtent,token);
break;
}
case '|':
{
if (GetNextImageInList(source_image) != (Image *) NULL)
source_image=GetNextImageInList(source_image);
else
source_image=GetFirstImageInList(source_image);
GetNextToken(p,&p,MagickPathExtent,token);
break;
}
case ';':
{
Image
*canvas;
(void) SetPixelChannelMask(destination_image,channel_mask);
if ((channel_op == ExtractChannelOp) && (channels == 1))
{
(void) SetPixelMetaChannels(destination_image,0,exception);
(void) SetImageColorspace(destination_image,GRAYColorspace,
exception);
}
canvas=CloneImage(source_image,0,0,MagickTrue,exception);
if (canvas == (Image *) NULL)
{
destination_image=DestroyImageList(destination_image);
return(destination_image);
}
AppendImageToList(&destination_image,canvas);
destination_image=GetLastImageInList(destination_image);
status=SetImageStorageClass(destination_image,DirectClass,exception);
if (status == MagickFalse)
{
destination_image=GetLastImageInList(destination_image);
return((Image *) NULL);
}
GetNextToken(p,&p,MagickPathExtent,token);
channels=0;
destination_channel=RedPixelChannel;
channel_mask=UndefinedChannel;
break;
}
default:
break;
}
i=ParsePixelChannelOption(token);
if (i < 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnrecognizedChannelType","`%s'",token);
destination_image=DestroyImageList(destination_image);
return(destination_image);
}
source_channel=(PixelChannel) i;
channel_op=ExtractChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == '<')
{
channel_op=ExchangeChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
}
if (*token == '=')
{
if (channel_op != ExchangeChannelOp)
channel_op=AssignChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
}
if (*token == '>')
{
if (channel_op != ExchangeChannelOp)
channel_op=TransferChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
}
switch (channel_op)
{
case AssignChannelOp:
case ExchangeChannelOp:
case TransferChannelOp:
{
if (channel_op == AssignChannelOp)
pixel=StringToDoubleInterval(token,(double) QuantumRange+1.0);
else
{
i=ParsePixelChannelOption(token);
if (i < 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnrecognizedChannelType","`%s'",token);
destination_image=DestroyImageList(destination_image);
return(destination_image);
}
}
destination_channel=(PixelChannel) i;
if (i >= (ssize_t) GetPixelChannels(destination_image))
(void) SetPixelMetaChannels(destination_image,(size_t) (
destination_channel-GetPixelChannels(destination_image)+1),
exception);
if (image->colorspace != UndefinedColorspace)
switch (destination_channel)
{
case RedPixelChannel:
case GreenPixelChannel:
case BluePixelChannel:
case BlackPixelChannel:
case IndexPixelChannel:
break;
case AlphaPixelChannel:
{
destination_image->alpha_trait=BlendPixelTrait;
break;
}
case ReadMaskPixelChannel:
{
destination_image->read_mask=MagickTrue;
break;
}
case WriteMaskPixelChannel:
{
destination_image->write_mask=MagickTrue;
break;
}
case MetaPixelChannel:
default:
{
(void) SetPixelMetaChannels(destination_image,(size_t) (
destination_channel-GetPixelChannels(destination_image)+1),
exception);
break;
}
}
channel_mask=(ChannelType) (channel_mask | ParseChannelOption(token));
if (((channels >= 1) || (destination_channel >= 1)) &&
(IsGrayColorspace(destination_image->colorspace) != MagickFalse))
(void) SetImageColorspace(destination_image,sRGBColorspace,exception);
GetNextToken(p,&p,MagickPathExtent,token);
break;
}
default:
break;
}
status=ChannelImage(destination_image,destination_channel,channel_op,
source_image,source_channel,ClampToQuantum(pixel),exception);
if (status == MagickFalse)
{
destination_image=DestroyImageList(destination_image);
break;
}
channels++;
if (channel_op == ExchangeChannelOp)
{
status=ChannelImage(destination_image,source_channel,channel_op,
source_image,destination_channel,ClampToQuantum(pixel),exception);
if (status == MagickFalse)
{
destination_image=DestroyImageList(destination_image);
break;
}
channels++;
}
switch (channel_op)
{
case ExtractChannelOp:
{
channel_mask=(ChannelType) (channel_mask | (1 << destination_channel));
destination_channel=(PixelChannel) (destination_channel+1);
break;
}
default:
break;
}
status=SetImageProgress(source_image,ChannelFxImageTag,p-expression,
strlen(expression));
if (status == MagickFalse)
break;
}
(void) SetPixelChannelMask(destination_image,channel_mask);
if ((channel_op == ExtractChannelOp) && (channels == 1))
{
(void) SetPixelMetaChannels(destination_image,0,exception);
(void) SetImageColorspace(destination_image,GRAYColorspace,exception);
}
return(GetFirstImageInList(destination_image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m b i n e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CombineImages() combines one or more images into a single image. The
% grayscale value of the pixels of each image in the sequence is assigned in
% order to the specified channels of the combined image. The typical
% ordering would be image 1 => Red, 2 => Green, 3 => Blue, etc.
%
% The format of the CombineImages method is:
%
% Image *CombineImages(const Image *images,const ColorspaceType colorspace,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o colorspace: the image colorspace.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CombineImages(const Image *image,
const ColorspaceType colorspace,ExceptionInfo *exception)
{
#define CombineImageTag "Combine/Image"
CacheView
*combine_view;
Image
*combine_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Ensure the image are the same size.
*/
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);
combine_image=CloneImage(image,0,0,MagickTrue,exception);
if (combine_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(combine_image,DirectClass,exception) == MagickFalse)
{
combine_image=DestroyImage(combine_image);
return((Image *) NULL);
}
if (colorspace != UndefinedColorspace)
(void) SetImageColorspace(combine_image,colorspace,exception);
else
if (fabs(image->gamma-1.0) <= MagickEpsilon)
(void) SetImageColorspace(combine_image,RGBColorspace,exception);
else
(void) SetImageColorspace(combine_image,sRGBColorspace,exception);
switch (combine_image->colorspace)
{
case UndefinedColorspace:
case sRGBColorspace:
{
if (GetImageListLength(image) > 3)
combine_image->alpha_trait=BlendPixelTrait;
break;
}
case GRAYColorspace:
{
if (GetImageListLength(image) > 1)
combine_image->alpha_trait=BlendPixelTrait;
break;
}
case CMYKColorspace:
{
if (GetImageListLength(image) > 4)
combine_image->alpha_trait=BlendPixelTrait;
break;
}
default:
break;
}
/*
Combine images.
*/
status=MagickTrue;
progress=0;
combine_view=AcquireAuthenticCacheView(combine_image,exception);
for (y=0; y < (ssize_t) combine_image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
Quantum
*pixels;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
i;
if (status == MagickFalse)
continue;
pixels=GetCacheViewAuthenticPixels(combine_view,0,y,combine_image->columns,
1,exception);
if (pixels == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
next=image;
for (i=0; i < (ssize_t) GetPixelChannels(combine_image); i++)
{
register ssize_t
x;
PixelChannel channel = GetPixelChannelChannel(combine_image,i);
PixelTrait traits = GetPixelChannelTraits(combine_image,channel);
if (traits == UndefinedPixelTrait)
continue;
if (next == (Image *) NULL)
continue;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception);
if (p == (const Quantum *) NULL)
continue;
q=pixels;
for (x=0; x < (ssize_t) combine_image->columns; x++)
{
if (x < (ssize_t) next->columns)
{
q[i]=GetPixelGray(next,p);
p+=GetPixelChannels(next);
}
q+=GetPixelChannels(combine_image);
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
if (SyncCacheViewAuthenticPixels(combine_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,CombineImageTag,progress++,
combine_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
combine_view=DestroyCacheView(combine_view);
if (status == MagickFalse)
combine_image=DestroyImage(combine_image);
return(combine_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e A l p h a C h a n n e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageAlphaChannel() returns MagickFalse if the image alpha channel is
% not activated. That is, the image is RGB rather than RGBA or CMYK rather
% than CMYKA.
%
% The format of the GetImageAlphaChannel method is:
%
% MagickBooleanType GetImageAlphaChannel(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType GetImageAlphaChannel(const Image *image)
{
assert(image != (const Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
return(image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p a r a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SeparateImage() separates a channel from the image and returns it as a
% grayscale image.
%
% The format of the SeparateImage method is:
%
% Image *SeparateImage(const Image *image,const ChannelType channel,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the image channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SeparateImage(const Image *image,
const ChannelType channel_type,ExceptionInfo *exception)
{
#define GetChannelBit(mask,bit) (((size_t) (mask) >> (size_t) (bit)) & 0x01)
#define SeparateImageTag "Separate/Image"
CacheView
*image_view,
*separate_view;
Image
*separate_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize separate 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);
separate_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (separate_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(separate_image,DirectClass,exception) == MagickFalse)
{
separate_image=DestroyImage(separate_image);
return((Image *) NULL);
}
separate_image->intensity=Rec709LuminancePixelIntensityMethod;
separate_image->alpha_trait=UndefinedPixelTrait;
(void) SetImageColorspace(separate_image,GRAYColorspace,exception);
/*
Separate image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
separate_view=AcquireAuthenticCacheView(separate_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register 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(separate_view,0,y,separate_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;
if (GetPixelWriteMask(image,p) <= (QuantumRange/2))
{
SetPixelBackgoundColor(separate_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(separate_image);
continue;
}
SetPixelChannel(separate_image,GrayPixelChannel,0,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
(GetChannelBit(channel_type,channel) == 0))
continue;
SetPixelChannel(separate_image,GrayPixelChannel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(separate_image);
}
if (SyncCacheViewAuthenticPixels(separate_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SeparateImage)
#endif
proceed=SetImageProgress(image,SeparateImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
separate_view=DestroyCacheView(separate_view);
image_view=DestroyCacheView(image_view);
(void) SetImageChannelMask(separate_image,DefaultChannels);
if (status == MagickFalse)
separate_image=DestroyImage(separate_image);
return(separate_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p a r a t e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SeparateImages() returns a separate grayscale image for each channel
% specified.
%
% The format of the SeparateImages method is:
%
% Image *SeparateImages(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 *SeparateImages(const Image *image,ExceptionInfo *exception)
{
Image
*images,
*separate_image;
register ssize_t
i;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
images=NewImageList();
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0))
continue;
separate_image=SeparateImage(image,(ChannelType) (1 << channel),exception);
if (separate_image != (Image *) NULL)
AppendImageToList(&images,separate_image);
}
if (images == (Image *) NULL)
images=SeparateImage(image,UndefinedChannel,exception);
return(images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e A l p h a C h a n n e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageAlphaChannel() activates, deactivates, resets, or sets the alpha
% channel.
%
% The format of the SetImageAlphaChannel method is:
%
% MagickBooleanType SetImageAlphaChannel(Image *image,
% const AlphaChannelOption alpha_type,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o alpha_type: The alpha channel type: ActivateAlphaChannel,
% AssociateAlphaChannel, CopyAlphaChannel, DeactivateAlphaChannel,
% DisassociateAlphaChannel, ExtractAlphaChannel, OffAlphaChannel,
% OnAlphaChannel, OpaqueAlphaChannel, SetAlphaChannel, ShapeAlphaChannel,
% and TransparentAlphaChannel.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void FlattenPixelInfo(const Image *image,const PixelInfo *p,
const double alpha,const Quantum *q,const double beta,
Quantum *composite)
{
double
Da,
gamma,
Sa;
register ssize_t
i;
/*
Compose pixel p over pixel q with the given alpha.
*/
Sa=QuantumScale*alpha;
Da=QuantumScale*beta,
gamma=Sa*(-Da)+Sa+Da;
gamma=PerceptibleReciprocal(gamma);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
switch (channel)
{
case RedPixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->red,alpha));
break;
}
case GreenPixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->green,alpha));
break;
}
case BluePixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->blue,alpha));
break;
}
case BlackPixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->black,alpha));
break;
}
case AlphaPixelChannel:
{
composite[i]=ClampToQuantum(QuantumRange*(Sa*(-Da)+Sa+Da));
break;
}
default:
break;
}
}
}
MagickExport MagickBooleanType SetImageAlphaChannel(Image *image,
const AlphaChannelOption alpha_type,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
status=MagickTrue;
switch (alpha_type)
{
case ActivateAlphaChannel:
{
image->alpha_trait=BlendPixelTrait;
break;
}
case AssociateAlphaChannel:
{
/*
Associate alpha.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
if (GetPixelWriteMask(image,q) <= (QuantumRange/2))
{
q+=GetPixelChannels(image);
continue;
}
gamma=QuantumScale*GetPixelAlpha(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (channel == AlphaPixelChannel)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(gamma*q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=CopyPixelTrait;
return(status);
}
case BackgroundAlphaChannel:
{
/*
Set transparent pixels to background color.
*/
if (image->alpha_trait == UndefinedPixelTrait)
break;
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) == TransparentAlpha)
{
SetPixelViaPixelInfo(image,&image->background_color,q);
SetPixelChannel(image,AlphaPixelChannel,TransparentAlpha,q);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
case CopyAlphaChannel:
{
image->alpha_trait=UpdatePixelTrait;
status=CompositeImage(image,image,IntensityCompositeOp,MagickTrue,0,0,
exception);
break;
}
case DeactivateAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=CopyPixelTrait;
break;
}
case DisassociateAlphaChannel:
{
/*
Disassociate alpha.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image->alpha_trait=BlendPixelTrait;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma,
Sa;
register ssize_t
i;
if (GetPixelWriteMask(image,q) <= (QuantumRange/2))
{
q+=GetPixelChannels(image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,q);
gamma=PerceptibleReciprocal(Sa);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (channel == AlphaPixelChannel)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(gamma*q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=UndefinedPixelTrait;
return(status);
}
case DiscreteAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=UpdatePixelTrait;
break;
}
case ExtractAlphaChannel:
{
status=CompositeImage(image,image,AlphaCompositeOp,MagickTrue,0,0,
exception);
image->alpha_trait=UndefinedPixelTrait;
break;
}
case OffAlphaChannel:
{
image->alpha_trait=UndefinedPixelTrait;
break;
}
case OnAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=BlendPixelTrait;
break;
}
case OpaqueAlphaChannel:
{
status=SetImageAlpha(image,OpaqueAlpha,exception);
break;
}
case RemoveAlphaChannel:
{
/*
Remove transparency.
*/
if (image->alpha_trait == UndefinedPixelTrait)
break;
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
FlattenPixelInfo(image,&image->background_color,
image->background_color.alpha,q,(double)
GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=image->background_color.alpha_trait;
break;
}
case SetAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
break;
}
case ShapeAlphaChannel:
{
/*
Set alpha channel by shape.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image->alpha_trait=UpdatePixelTrait;
(void) SetImageMask(image,WritePixelMask,image,exception);
(void) LevelImageColors(image,&image->background_color,
&image->background_color,MagickTrue,exception);
(void) SetImageMask(image,WritePixelMask,(Image *) NULL,exception);
break;
}
case TransparentAlphaChannel:
{
status=SetImageAlpha(image,TransparentAlpha,exception);
break;
}
case UndefinedAlphaChannel:
break;
}
if (status == MagickFalse)
return(status);
(void) SetPixelChannelMask(image,image->channel_mask);
return(SyncImagePixelCache(image,exception));
}
|
GB_binop__islt_int32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__islt_int32)
// A.*B function (eWiseMult): GB (_AemultB_08__islt_int32)
// A.*B function (eWiseMult): GB (_AemultB_02__islt_int32)
// A.*B function (eWiseMult): GB (_AemultB_04__islt_int32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_int32)
// A*D function (colscale): GB (_AxD__islt_int32)
// D*A function (rowscale): GB (_DxB__islt_int32)
// C+=B function (dense accum): GB (_Cdense_accumB__islt_int32)
// C+=b function (dense accum): GB (_Cdense_accumb__islt_int32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_int32)
// C=scalar+B GB (_bind1st__islt_int32)
// C=scalar+B' GB (_bind1st_tran__islt_int32)
// C=A+scalar GB (_bind2nd__islt_int32)
// C=A'+scalar GB (_bind2nd_tran__islt_int32)
// C type: int32_t
// A type: int32_t
// B,b type: int32_t
// BinaryOp: cij = (aij < bij)
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int32_t
#define GB_CTYPE \
int32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int32_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int32_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x < y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISLT || GxB_NO_INT32 || GxB_NO_ISLT_INT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__islt_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__islt_int32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__islt_int32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int32_t
int32_t bwork = (*((int32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__islt_int32)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__islt_int32)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__islt_int32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__islt_int32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__islt_int32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__islt_int32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__islt_int32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__islt_int32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *Cx = (int32_t *) Cx_output ;
int32_t x = (*((int32_t *) x_input)) ;
int32_t *Bx = (int32_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 ;
int32_t bij = GBX (Bx, p, false) ;
Cx [p] = (x < bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__islt_int32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int32_t *Cx = (int32_t *) Cx_output ;
int32_t *Ax = (int32_t *) Ax_input ;
int32_t y = (*((int32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int32_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij < y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB (_bind1st_tran__islt_int32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB (_bind2nd_tran__islt_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t y = (*((const int32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
Pstd.h | #pragma once
#include "Constants.h"
#include "FieldSolver.h"
#include "Grid.h"
#include "Vectors.h"
#include "PmlPstd.h"
namespace pfc {
class PSTD : public SpectralFieldSolver<PSTDGridType>
{
public:
PSTD(PSTDGrid * grid);
void updateFields();
void updateHalfB();
void updateE();
void setPML(int sizePMLx, int sizePMLy, int sizePMLz);
private:
PmlSpectral<GridTypes::PSTDGridType>* getPml() {
return (PmlSpectral<GridTypes::PSTDGridType>*)pml.get();
}
};
inline PSTD::PSTD(PSTDGrid* grid) :
SpectralFieldSolver<GridTypes::PSTDGridType>(grid)
{
updateDims();
updateInternalDims();
}
inline void PSTD::setPML(int sizePMLx, int sizePMLy, int sizePMLz)
{
pml.reset(new PmlPstd(this, Int3(sizePMLx, sizePMLy, sizePMLz)));
updateInternalDims();
}
inline void PSTD::updateFields()
{
doFourierTransform(RtoC);
if (pml.get()) getPml()->updateBSplit();
updateHalfB();
if (pml.get()) getPml()->updateESplit();
updateE();
if (pml.get()) getPml()->updateBSplit();
updateHalfB();
doFourierTransform(CtoR);
if (pml.get()) getPml()->doSecondStep();
}
inline void PSTD::updateHalfB()
{
const Int3 begin = updateComplexBAreaBegin;
const Int3 end = updateComplexBAreaEnd;
double dt = grid->dt / 2;
#pragma omp parallel for
for (int i = begin.x; i < end.x; i++)
for (int j = begin.y; j < end.y; j++)
{
//#pragma omp simd
for (int k = begin.z; k < end.z; k++)
{
ComplexFP3 E(complexGrid->Ex(i, j, k), complexGrid->Ey(i, j, k), complexGrid->Ez(i, j, k));
ComplexFP3 crossKE = cross((ComplexFP3)getWaveVector(Int3(i, j, k)), E);
complexFP coeff = -complexFP::i() * constants::c * dt;
complexGrid->Bx(i, j, k) += coeff * crossKE.x;
complexGrid->By(i, j, k) += coeff * crossKE.y;
complexGrid->Bz(i, j, k) += coeff * crossKE.z;
}
}
}
inline void PSTD::updateE()
{
const Int3 begin = updateComplexEAreaBegin;
const Int3 end = updateComplexEAreaEnd;
double dt = grid->dt;
#pragma omp parallel for
for (int i = begin.x; i < end.x; i++)
for (int j = begin.y; j < end.y; j++)
{
//#pragma omp simd
for (int k = begin.z; k < end.z; k++)
{
ComplexFP3 B(complexGrid->Bx(i, j, k), complexGrid->By(i, j, k), complexGrid->Bz(i, j, k));
ComplexFP3 J(complexGrid->Jx(i, j, k), complexGrid->Jy(i, j, k), complexGrid->Jz(i, j, k));
ComplexFP3 crossKB = cross((ComplexFP3)getWaveVector(Int3(i, j, k)), B);
complexFP coeff = complexFP::i() * constants::c * dt;
complexGrid->Ex(i, j, k) += coeff * crossKB.x - 4 * constants::pi * dt * J.x;
complexGrid->Ey(i, j, k) += coeff * crossKB.y - 4 * constants::pi * dt * J.y;
complexGrid->Ez(i, j, k) += coeff * crossKB.z - 4 * constants::pi * dt * J.z;
}
}
}
}
|
convolution_sgemm.h | // BUG1989 is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2019 BUG1989. 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 conv_im2col_sgemm_transform_kernel_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size)
{
const float* kernel = _kernel;
#if __ARM_NEON && __aarch64__
// kernel memory packed 8 x 8
kernel_tm.create(8 * kernel_size, inch, outch / 8 + (outch % 8) / 4 + outch % 4);
#else
// kernel memory packed 4 x 8
kernel_tm.create(4 * kernel_size, inch, outch / 4 + outch % 4);
#endif
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 8;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
const float* k4 = kernel + (p + 4) * inch * kernel_size;
const float* k5 = kernel + (p + 5) * inch * kernel_size;
const float* k6 = kernel + (p + 6) * inch * kernel_size;
const float* k7 = kernel + (p + 7) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 8);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp[4] = k4[0];
ktmp[5] = k5[0];
ktmp[6] = k6[0];
ktmp[7] = k7[0];
ktmp += 8;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
k4 += 1;
k5 += 1;
k6 += 1;
k7 += 1;
}
}
#endif
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
#if __ARM_NEON && __aarch64__
float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4);
#else
float* ktmp = kernel_tm.channel(p / 4);
#endif // __ARM_NEON && __aarch64__
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp += 4;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
}
}
remain_outch_start += nn_outch << 2;
for (int p = remain_outch_start; p < outch; p++)
{
const float* k0 = kernel + (p + 0) * inch * kernel_size;
#if __ARM_NEON && __aarch64__
float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
float* ktmp = kernel_tm.channel(p / 4 + p % 4);
#endif // __ARM_NEON && __aarch64__
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp++;
k0++;
}
}
}
static void conv_im2col_sgemm_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias,
const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// im2col
Mat bottom_im2col(outw * outh, kernel_h * kernel_w * inch, elemsize, opt.workspace_allocator);
{
const int stride = kernel_h * kernel_w * outw * outh;
float* ret = (float*)bottom_im2col;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const float* input = bottom_blob.channel(p);
int retID = stride * p;
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
int row = u + i * stride_h;
int col = v + j * stride_w;
int index = row * w + col;
ret[retID] = input[index];
retID++;
}
}
}
}
}
}
int kernel_size = kernel_w * kernel_h;
int out_size = outw * outh;
// bottom_im2col memory packed 8 x 8
Mat bottom_tm(8 * kernel_size, inch, out_size / 8 + out_size % 8, elemsize, opt.workspace_allocator);
{
int nn_size = out_size >> 3;
int remain_size_start = nn_size << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = ii * 8;
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 8);
for (int q = 0; q < inch * kernel_size; q++)
{
#if __ARM_NEON
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.4s, v1.4s}, [%0] \n"
"st1 {v0.4s, v1.4s}, [%1] \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "cc", "memory", "v0", "v1");
#else
asm volatile(
"pld [%0, #256] \n"
"vld1.f32 {d0-d3}, [%0] \n"
"vst1.f32 {d0-d3}, [%1] \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1");
#endif // __aarch64__
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
tmpptr[4] = img0[4];
tmpptr[5] = img0[5];
tmpptr[6] = img0[6];
tmpptr[7] = img0[7];
#endif // __ARM_NEON
tmpptr += 8;
img0 += out_size;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < out_size; i++)
{
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 8 + i % 8);
for (int q = 0; q < inch * kernel_size; q++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += out_size;
}
}
}
// sgemm(int M, int N, int L, float* A, float* B, float* C)
{
//int M = outch; // outch
int N = outw * outh; // outsize or out stride
int L = kernel_w * kernel_h * inch; // ksize * inch
int nn_outch = 0;
int remain_outch_start = 0;
#if __aarch64__
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int i = pp * 8;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
float* output4 = top_blob.channel(i + 4);
float* output5 = top_blob.channel(i + 5);
float* output6 = top_blob.channel(i + 6);
float* output7 = top_blob.channel(i + 7);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
const float* va = kernel_tm.channel(i / 8);
#if __ARM_NEON
asm volatile(
"ld1 {v0.4s, v1.4s}, [%21] \n"
"dup v16.4s, v0.s[0] \n" // sum0
"dup v17.4s, v0.s[0] \n"
"dup v18.4s, v0.s[1] \n" // sum1
"dup v19.4s, v0.s[1] \n"
"dup v20.4s, v0.s[2] \n" // sum2
"dup v21.4s, v0.s[2] \n"
"dup v22.4s, v0.s[3] \n" // sum3
"dup v23.4s, v0.s[3] \n"
"dup v24.4s, v1.s[0] \n" // sum4
"dup v25.4s, v1.s[0] \n"
"dup v26.4s, v1.s[1] \n" // sum5
"dup v27.4s, v1.s[1] \n"
"dup v28.4s, v1.s[2] \n" // sum6
"dup v29.4s, v1.s[2] \n"
"dup v30.4s, v1.s[3] \n" // sum7
"dup v31.4s, v1.s[3] \n"
"lsr w4, %w20, #2 \n" // r4 = nn = L >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n" // for (; k+3<L; k=k+4)
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" // kernel
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n"
"prfm pldl1keep, [%8, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n" // data
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%8], #64 \n"
// k0
"fmla v16.4s, v8.4s, v0.s[0] \n" // sum0 += (a00-a70) * k00
"fmla v17.4s, v9.4s, v0.s[0] \n" //
"fmla v18.4s, v8.4s, v0.s[1] \n" // sum1 += (a00-a70) * k10
"fmla v19.4s, v9.4s, v0.s[1] \n" //
"fmla v20.4s, v8.4s, v0.s[2] \n" // sum2 += (a00-a70) * k20
"fmla v21.4s, v9.4s, v0.s[2] \n" //
"fmla v22.4s, v8.4s, v0.s[3] \n" // sum3 += (a00-a70) * k30
"fmla v23.4s, v9.4s, v0.s[3] \n" //
"fmla v24.4s, v8.4s, v1.s[0] \n" // sum4 += (a00-a70) * k40
"fmla v25.4s, v9.4s, v1.s[0] \n" //
"fmla v26.4s, v8.4s, v1.s[1] \n" // sum5 += (a00-a70) * k50
"fmla v27.4s, v9.4s, v1.s[1] \n" //
"fmla v28.4s, v8.4s, v1.s[2] \n" // sum6 += (a00-a70) * k60
"fmla v29.4s, v9.4s, v1.s[2] \n" //
"fmla v30.4s, v8.4s, v1.s[3] \n" // sum7 += (a00-a70) * k70
"fmla v31.4s, v9.4s, v1.s[3] \n" //
// k1
"fmla v16.4s, v10.4s, v2.s[0] \n" // sum0 += (a01-a71) * k01
"fmla v17.4s, v11.4s, v2.s[0] \n" //
"fmla v18.4s, v10.4s, v2.s[1] \n" // sum1 += (a01-a71) * k11
"fmla v19.4s, v11.4s, v2.s[1] \n" //
"fmla v20.4s, v10.4s, v2.s[2] \n" // sum2 += (a01-a71) * k21
"fmla v21.4s, v11.4s, v2.s[2] \n" //
"fmla v22.4s, v10.4s, v2.s[3] \n" // sum3 += (a01-a71) * k31
"fmla v23.4s, v11.4s, v2.s[3] \n" //
"fmla v24.4s, v10.4s, v3.s[0] \n" // sum4 += (a01-a71) * k41
"fmla v25.4s, v11.4s, v3.s[0] \n" //
"fmla v26.4s, v10.4s, v3.s[1] \n" // sum5 += (a01-a71) * k51
"fmla v27.4s, v11.4s, v3.s[1] \n" //
"fmla v28.4s, v10.4s, v3.s[2] \n" // sum6 += (a01-a71) * k61
"fmla v29.4s, v11.4s, v3.s[2] \n" //
"fmla v30.4s, v10.4s, v3.s[3] \n" // sum7 += (a01-a71) * k71
"fmla v31.4s, v11.4s, v3.s[3] \n" //
// k2
"fmla v16.4s, v12.4s, v4.s[0] \n" // sum0 += (a02-a72) * k02
"fmla v17.4s, v13.4s, v4.s[0] \n" //
"fmla v18.4s, v12.4s, v4.s[1] \n" // sum1 += (a02-a72) * k12
"fmla v19.4s, v13.4s, v4.s[1] \n" //
"fmla v20.4s, v12.4s, v4.s[2] \n" // sum2 += (a02-a72) * k22
"fmla v21.4s, v13.4s, v4.s[2] \n" //
"fmla v22.4s, v12.4s, v4.s[3] \n" // sum3 += (a02-a72) * k32
"fmla v23.4s, v13.4s, v4.s[3] \n" //
"fmla v24.4s, v12.4s, v5.s[0] \n" // sum4 += (a02-a72) * k42
"fmla v25.4s, v13.4s, v5.s[0] \n" //
"fmla v26.4s, v12.4s, v5.s[1] \n" // sum5 += (a02-a72) * k52
"fmla v27.4s, v13.4s, v5.s[1] \n" //
"fmla v28.4s, v12.4s, v5.s[2] \n" // sum6 += (a02-a72) * k62
"fmla v29.4s, v13.4s, v5.s[2] \n" //
"fmla v30.4s, v12.4s, v5.s[3] \n" // sum7 += (a02-a72) * k72
"fmla v31.4s, v13.4s, v5.s[3] \n" //
// k3
"fmla v16.4s, v14.4s, v6.s[0] \n" // sum0 += (a03-a73) * k03
"fmla v17.4s, v15.4s, v6.s[0] \n" //
"fmla v18.4s, v14.4s, v6.s[1] \n" // sum1 += (a03-a73) * k13
"fmla v19.4s, v15.4s, v6.s[1] \n" //
"fmla v20.4s, v14.4s, v6.s[2] \n" // sum2 += (a03-a73) * k23
"fmla v21.4s, v15.4s, v6.s[2] \n" //
"fmla v22.4s, v14.4s, v6.s[3] \n" // sum3 += (a03-a73) * k33
"fmla v23.4s, v15.4s, v6.s[3] \n" //
"fmla v24.4s, v14.4s, v7.s[0] \n" // sum4 += (a03-a73) * k43
"fmla v25.4s, v15.4s, v7.s[0] \n" //
"fmla v26.4s, v14.4s, v7.s[1] \n" // sum5 += (a03-a73) * k53
"fmla v27.4s, v15.4s, v7.s[1] \n" //
"fmla v28.4s, v14.4s, v7.s[2] \n" // sum6 += (a03-a73) * k63
"fmla v29.4s, v15.4s, v7.s[2] \n" //
"fmla v30.4s, v14.4s, v7.s[3] \n" // sum7 += (a03-a73) * k73
"fmla v31.4s, v15.4s, v7.s[3] \n" //
"subs w4, w4, #1 \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w20, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s}, [%9], #32 \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v8.4s, v9.4s}, [%8], #32 \n"
// k0
"fmla v16.4s, v8.4s, v0.s[0] \n" // sum0 += (a00-a70) * k00
"fmla v17.4s, v9.4s, v0.s[0] \n" //
"fmla v18.4s, v8.4s, v0.s[1] \n" // sum1 += (a00-a70) * k10
"fmla v19.4s, v9.4s, v0.s[1] \n" //
"fmla v20.4s, v8.4s, v0.s[2] \n" // sum2 += (a00-a70) * k20
"fmla v21.4s, v9.4s, v0.s[2] \n" //
"fmla v22.4s, v8.4s, v0.s[3] \n" // sum3 += (a00-a70) * k30
"fmla v23.4s, v9.4s, v0.s[3] \n" //
"fmla v24.4s, v8.4s, v1.s[0] \n" // sum4 += (a00-a70) * k40
"fmla v25.4s, v9.4s, v1.s[0] \n" //
"fmla v26.4s, v8.4s, v1.s[1] \n" // sum5 += (a00-a70) * k50
"fmla v27.4s, v9.4s, v1.s[1] \n" //
"fmla v28.4s, v8.4s, v1.s[2] \n" // sum6 += (a00-a70) * k60
"fmla v29.4s, v9.4s, v1.s[2] \n" //
"fmla v30.4s, v8.4s, v1.s[3] \n" // sum7 += (a00-a70) * k70
"fmla v31.4s, v9.4s, v1.s[3] \n" //
"subs w4, w4, #1 \n"
"bne 2b \n"
"3: \n"
"st1 {v16.4s, v17.4s}, [%0] \n"
"st1 {v18.4s, v19.4s}, [%1] \n"
"st1 {v20.4s, v21.4s}, [%2] \n"
"st1 {v22.4s, v23.4s}, [%3] \n"
"st1 {v24.4s, v25.4s}, [%4] \n"
"st1 {v26.4s, v27.4s}, [%5] \n"
"st1 {v28.4s, v29.4s}, [%6] \n"
"st1 {v30.4s, v31.4s}, [%7] \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(output2), // %2
"=r"(output3), // %3
"=r"(output4), // %4
"=r"(output5), // %5
"=r"(output6), // %6
"=r"(output7), // %7
"=r"(vb), // %8
"=r"(va) // %9
: "0"(output0),
"1"(output1),
"2"(output2),
"3"(output3),
"4"(output4),
"5"(output5),
"6"(output6),
"7"(output7),
"8"(vb),
"9"(va),
"r"(L), // %20
"r"(biasptr) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
float sum4[8] = {0};
float sum5[8] = {0};
float sum6[8] = {0};
float sum7[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
va += 8;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
sum4[n] += va[4] * vb[n + 8];
sum5[n] += va[5] * vb[n + 8];
sum6[n] += va[6] * vb[n + 8];
sum7[n] += va[7] * vb[n + 8];
va += 8;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
sum4[n] += va[4] * vb[n + 16];
sum5[n] += va[5] * vb[n + 16];
sum6[n] += va[6] * vb[n + 16];
sum7[n] += va[7] * vb[n + 16];
va += 8;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
sum4[n] += va[4] * vb[n + 24];
sum5[n] += va[5] * vb[n + 24];
sum6[n] += va[6] * vb[n + 24];
sum7[n] += va[7] * vb[n + 24];
va += 8;
sum0[n] += va[0] * vb[n + 32];
sum1[n] += va[1] * vb[n + 32];
sum2[n] += va[2] * vb[n + 32];
sum3[n] += va[3] * vb[n + 32];
sum4[n] += va[4] * vb[n + 32];
sum5[n] += va[5] * vb[n + 32];
sum6[n] += va[6] * vb[n + 32];
sum7[n] += va[7] * vb[n + 32];
va += 8;
sum0[n] += va[0] * vb[n + 40];
sum1[n] += va[1] * vb[n + 40];
sum2[n] += va[2] * vb[n + 40];
sum3[n] += va[3] * vb[n + 40];
sum4[n] += va[4] * vb[n + 40];
sum5[n] += va[5] * vb[n + 40];
sum6[n] += va[6] * vb[n + 40];
sum7[n] += va[7] * vb[n + 40];
va += 8;
sum0[n] += va[0] * vb[n + 48];
sum1[n] += va[1] * vb[n + 48];
sum2[n] += va[2] * vb[n + 48];
sum3[n] += va[3] * vb[n + 48];
sum4[n] += va[4] * vb[n + 48];
sum5[n] += va[5] * vb[n + 48];
sum6[n] += va[6] * vb[n + 48];
sum7[n] += va[7] * vb[n + 48];
va += 8;
sum0[n] += va[0] * vb[n + 56];
sum1[n] += va[1] * vb[n + 56];
sum2[n] += va[2] * vb[n + 56];
sum3[n] += va[3] * vb[n + 56];
sum4[n] += va[4] * vb[n + 56];
sum5[n] += va[5] * vb[n + 56];
sum6[n] += va[6] * vb[n + 56];
sum7[n] += va[7] * vb[n + 56];
va -= 56;
}
va += 64;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
}
va += 8;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
output4[n] = sum4[n] + biasptr[4];
output5[n] = sum5[n] + biasptr[5];
output6[n] = sum6[n] + biasptr[6];
output7[n] = sum7[n] + biasptr[7];
}
#endif // __ARM_NEON
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
output4 += 8;
output5 += 8;
output6 += 8;
output7 += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
const float* va = kernel_tm.channel(i / 8);
#if __ARM_NEON
asm volatile(
"ld1 {v14.4s, v15.4s}, [%21] \n" // sum0_7 inital with bias
"eor v16.16b, v16.16b, v16.16b \n" // sum0
"eor v17.16b, v17.16b, v17.16b \n" // sum1
"eor v18.16b, v18.16b, v18.16b \n" // sum2
"eor v19.16b, v19.16b, v19.16b \n" // sum3
"eor v20.16b, v20.16b, v20.16b \n" // sum4
"eor v21.16b, v21.16b, v21.16b \n" // sum5
"eor v22.16b, v22.16b, v22.16b \n" // sum6
"eor v23.16b, v23.16b, v23.16b \n" // sum7
"lsr w4, %w20, #2 \n" // r4 = nn = L >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n" // for (; k+3<L; k=k+4)
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" // k
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n"
"prfm pldl1keep, [%8, #128] \n"
"ld1 {v8.4s}, [%8], #16 \n" // d
// k0
"fmla v16.4s, v0.4s, v8.s[0] \n" // sum0 += (k00-k70) * a00
"fmla v17.4s, v1.4s, v8.s[0] \n" //
"fmla v18.4s, v2.4s, v8.s[1] \n" // sum1 += (k01-k71) * a10
"fmla v19.4s, v3.4s, v8.s[1] \n" //
"fmla v20.4s, v4.4s, v8.s[2] \n" // sum2 += (k02-k72) * a20
"fmla v21.4s, v5.4s, v8.s[2] \n" //
"fmla v22.4s, v6.4s, v8.s[3] \n" // sum3 += (k03-k73) * a30
"fmla v23.4s, v7.4s, v8.s[3] \n" //
"subs w4, w4, #1 \n"
"bne 0b \n"
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"fadd v20.4s, v20.4s, v22.4s \n"
"fadd v21.4s, v21.4s, v23.4s \n"
"fadd v16.4s, v16.4s, v20.4s \n"
"fadd v17.4s, v17.4s, v21.4s \n"
"fadd v14.4s, v14.4s, v16.4s \n"
"fadd v15.4s, v15.4s, v17.4s \n"
"1: \n"
// remain loop
"and w4, %w20, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4s, v1.4s}, [%9], #32 \n"
"prfm pldl1keep, [%8, #32] \n"
"ld1r {v8.4s}, [%8], #4 \n"
// k0
"fmla v14.4s, v8.4s, v0.4s \n" // sum0 += (k00-k70) * a00
"fmla v15.4s, v8.4s, v1.4s \n" //
"subs w4, w4, #1 \n"
"bne 2b \n"
"3: \n"
"st1 {v14.s}[0], [%0] \n"
"st1 {v14.s}[1], [%1] \n"
"st1 {v14.s}[2], [%2] \n"
"st1 {v14.s}[3], [%3] \n"
"st1 {v15.s}[0], [%4] \n"
"st1 {v15.s}[1], [%5] \n"
"st1 {v15.s}[2], [%6] \n"
"st1 {v15.s}[3], [%7] \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(output2), // %2
"=r"(output3), // %3
"=r"(output4), // %4
"=r"(output5), // %5
"=r"(output6), // %6
"=r"(output7), // %7
"=r"(vb), // %8
"=r"(va) // %9
: "0"(output0),
"1"(output1),
"2"(output2),
"3"(output3),
"4"(output4),
"5"(output5),
"6"(output6),
"7"(output7),
"8"(vb),
"9"(va),
"r"(L), // %20
"r"(biasptr) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
float sum4 = biasptr[4];
float sum5 = biasptr[5];
float sum6 = biasptr[6];
float sum7 = biasptr[7];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
sum4 += va[4] * vb[0];
sum5 += va[5] * vb[0];
sum6 += va[6] * vb[0];
sum7 += va[7] * vb[0];
va += 8;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
output4[0] = sum4;
output5[0] = sum5;
output6[0] = sum6;
output7[0] = sum7;
#endif // __ARM_NEON
output0++;
output1++;
output2++;
output3++;
output4++;
output5++;
output6++;
output7++;
}
}
#endif // __aarch64__
nn_outch = (outch - remain_outch_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int i = remain_outch_start + pp * 4;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
#if __ARM_NEON && __aarch64__
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4);
#else
const float* va = kernel_tm.channel(i / 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%13] \n"
"dup v16.4s, v0.s[0] \n" // sum0
"dup v17.4s, v0.s[0] \n"
"dup v18.4s, v0.s[1] \n" // sum1
"dup v19.4s, v0.s[1] \n"
"dup v20.4s, v0.s[2] \n" // sum2
"dup v21.4s, v0.s[2] \n"
"dup v22.4s, v0.s[3] \n" // sum3
"dup v23.4s, v0.s[3] \n"
"lsr w4, %w12, #2 \n" // r4 = nn = L >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n" // for (; k+3<L; k=k+4)
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" // kernel
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // data
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n"
"subs w4, w4, #1 \n"
// k0
"fmla v16.4s, v8.4s, v0.s[0] \n" // sum0 += (a00-a70) * k00
"fmla v17.4s, v9.4s, v0.s[0] \n" //
"fmla v18.4s, v8.4s, v0.s[1] \n" // sum1 += (a00-a70) * k10
"fmla v19.4s, v9.4s, v0.s[1] \n" //
"fmla v20.4s, v8.4s, v0.s[2] \n" // sum2 += (a00-a70) * k20
"fmla v21.4s, v9.4s, v0.s[2] \n" //
"fmla v22.4s, v8.4s, v0.s[3] \n" // sum3 += (a00-a70) * k30
"fmla v23.4s, v9.4s, v0.s[3] \n" //
// k1
"fmla v16.4s, v10.4s, v1.s[0] \n" // sum0 += (a01-a71) * k01
"fmla v17.4s, v11.4s, v1.s[0] \n" //
"fmla v18.4s, v10.4s, v1.s[1] \n" // sum1 += (a01-a71) * k11
"fmla v19.4s, v11.4s, v1.s[1] \n" //
"fmla v20.4s, v10.4s, v1.s[2] \n" // sum2 += (a01-a71) * k21
"fmla v21.4s, v11.4s, v1.s[2] \n" //
"fmla v22.4s, v10.4s, v1.s[3] \n" // sum3 += (a01-a71) * k31
"fmla v23.4s, v11.4s, v1.s[3] \n" //
// k2
"fmla v16.4s, v12.4s, v2.s[0] \n" // sum0 += (a02-a72) * k02
"fmla v17.4s, v13.4s, v2.s[0] \n" //
"fmla v18.4s, v12.4s, v2.s[1] \n" // sum1 += (a02-a72) * k12
"fmla v19.4s, v13.4s, v2.s[1] \n" //
"fmla v20.4s, v12.4s, v2.s[2] \n" // sum2 += (a02-a72) * k22
"fmla v21.4s, v13.4s, v2.s[2] \n" //
"fmla v22.4s, v12.4s, v2.s[3] \n" // sum3 += (a02-a72) * k32
"fmla v23.4s, v13.4s, v2.s[3] \n" //
// k3
"fmla v16.4s, v14.4s, v3.s[0] \n" // sum0 += (a03-a73) * k03
"fmla v17.4s, v15.4s, v3.s[0] \n" //
"fmla v18.4s, v14.4s, v3.s[1] \n" // sum1 += (a03-a73) * k13
"fmla v19.4s, v15.4s, v3.s[1] \n" //
"fmla v20.4s, v14.4s, v3.s[2] \n" // sum2 += (a03-a73) * k23
"fmla v21.4s, v15.4s, v3.s[2] \n" //
"fmla v22.4s, v14.4s, v3.s[3] \n" // sum3 += (a03-a73) * k33
"fmla v23.4s, v15.4s, v3.s[3] \n" //
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w12, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v8.4s, v9.4s}, [%4], #32 \n"
// k0
"fmla v16.4s, v8.4s, v0.s[0] \n" // sum0 += (a00-a70) * k00
"fmla v17.4s, v9.4s, v0.s[0] \n" //
"fmla v18.4s, v8.4s, v0.s[1] \n" // sum1 += (a00-a70) * k10
"fmla v19.4s, v9.4s, v0.s[1] \n" //
"fmla v20.4s, v8.4s, v0.s[2] \n" // sum2 += (a00-a70) * k20
"fmla v21.4s, v9.4s, v0.s[2] \n" //
"fmla v22.4s, v8.4s, v0.s[3] \n" // sum3 += (a00-a70) * k30
"fmla v23.4s, v9.4s, v0.s[3] \n" //
"subs w4, w4, #1 \n"
"bne 2b \n"
"3: \n"
"st1 {v16.4s, v17.4s}, [%0] \n"
"st1 {v18.4s, v19.4s}, [%1] \n"
"st1 {v20.4s, v21.4s}, [%2] \n"
"st1 {v22.4s, v23.4s}, [%3] \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(output2), // %2
"=r"(output3), // %3
"=r"(vb), // %4
"=r"(va) // %5
: "0"(output0),
"1"(output1),
"2"(output2),
"3"(output3),
"4"(vb),
"5"(va),
"r"(L), // %12
"r"(biasptr) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
#else
asm volatile(
"vld1.f32 {d0-d1}, [%13] \n"
"vdup.f32 q8, d0[0] \n"
"vdup.f32 q9, d0[0] \n"
"vdup.f32 q10, d0[1] \n"
"vdup.f32 q11, d0[1] \n"
"vdup.f32 q12, d1[0] \n"
"vdup.f32 q13, d1[0] \n"
"vdup.f32 q14, d1[1] \n"
"vdup.f32 q15, d1[1] \n"
"lsr r4, %12, #2 \n" // r4 = nn = L >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n" // for(; nn != 0; nn--)
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n" // kernel
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n" // data
"vmla.f32 q8, q4, d0[0] \n" // sum0 = (a00-a07) * k00
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n" // sum1 = (a00-a07) * k10
"vmla.f32 q11, q5, d0[1] \n"
"vmla.f32 q12, q4, d1[0] \n" // sum2 = (a00-a07) * k20
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n" // sum3 = (a00-a07) * k30
"vmla.f32 q15, q5, d1[1] \n"
"vmla.f32 q8, q6, d2[0] \n" // sum0 += (a10-a17) * k01
"vmla.f32 q9, q7, d2[0] \n"
"vmla.f32 q10, q6, d2[1] \n" // sum1 += (a10-a17) * k11
"vmla.f32 q11, q7, d2[1] \n"
"vmla.f32 q12, q6, d3[0] \n" // sum2 += (a10-a17) * k21
"vmla.f32 q13, q7, d3[0] \n"
"vmla.f32 q14, q6, d3[1] \n" // sum3 += (a10-a17) * k31
"vmla.f32 q15, q7, d3[1] \n"
"pld [%4, #512] \n"
"vldm %4!, {d8-d15} \n" // data
"vmla.f32 q8, q4, d4[0] \n" // sum0 += (a20-a27) * k02
"vmla.f32 q9, q5, d4[0] \n"
"vmla.f32 q10, q4, d4[1] \n" // sum1 += (a20-a27) * k12
"vmla.f32 q11, q5, d4[1] \n"
"vmla.f32 q12, q4, d5[0] \n" // sum2 += (a20-a27) * k22
"vmla.f32 q13, q5, d5[0] \n"
"vmla.f32 q14, q4, d5[1] \n" // sum3 += (a20-a27) * k32
"vmla.f32 q15, q5, d5[1] \n"
"vmla.f32 q8, q6, d6[0] \n" // sum0 += (a30-a37) * k03
"vmla.f32 q9, q7, d6[0] \n"
"vmla.f32 q10, q6, d6[1] \n" // sum1 += (a30-a37) * k13
"vmla.f32 q11, q7, d6[1] \n"
"vmla.f32 q12, q6, d7[0] \n" // sum2 += (a30-a37) * k23
"vmla.f32 q13, q7, d7[0] \n"
"vmla.f32 q14, q6, d7[1] \n" // sum3 += (a30-a37) * k33
"vmla.f32 q15, q7, d7[1] \n"
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"1: \n"
// remain loop
"and r4, %12, #3 \n" // r4 = remain = inch & 3
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n" // for(; remain != 0; remain--)
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5]! \n"
"pld [%4, #256] \n"
"vld1.f32 {d8-d11}, [%4]! \n"
"vmla.f32 q8, q4, d0[0] \n" // sum0 += (a00-a70) * k00
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n" // sum1 += (a00-a70) * k10
"vmla.f32 q11, q5, d0[1] \n"
"vmla.f32 q12, q4, d1[0] \n" // sum2 += (a00-a70) * k20
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n" // sum3 += (a00-a70) * k30
"vmla.f32 q15, q5, d1[1] \n"
"subs r4, r4, #1 \n"
"bne 2b \n"
"3: \n" // store the result to memory
"vst1.f32 {d16-d19}, [%0] \n"
"vst1.f32 {d20-d23}, [%1] \n"
"vst1.f32 {d24-d27}, [%2] \n"
"vst1.f32 {d28-d31}, [%3] \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(output2), // %2
"=r"(output3), // %3
"=r"(vb), // %4
"=r"(va) // %5
: "0"(output0),
"1"(output1),
"2"(output2),
"3"(output3),
"4"(vb),
"5"(va),
"r"(L), // %12
"r"(biasptr) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
va += 4;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
va += 4;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
va += 4;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
va += 4;
sum0[n] += va[0] * vb[n + 32];
sum1[n] += va[1] * vb[n + 32];
sum2[n] += va[2] * vb[n + 32];
sum3[n] += va[3] * vb[n + 32];
va += 4;
sum0[n] += va[0] * vb[n + 40];
sum1[n] += va[1] * vb[n + 40];
sum2[n] += va[2] * vb[n + 40];
sum3[n] += va[3] * vb[n + 40];
va += 4;
sum0[n] += va[0] * vb[n + 48];
sum1[n] += va[1] * vb[n + 48];
sum2[n] += va[2] * vb[n + 48];
sum3[n] += va[3] * vb[n + 48];
va += 4;
sum0[n] += va[0] * vb[n + 56];
sum1[n] += va[1] * vb[n + 56];
sum2[n] += va[2] * vb[n + 56];
sum3[n] += va[3] * vb[n + 56];
va -= 28;
}
va += 32;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
}
va += 4;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
}
#endif // __ARM_NEON
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
}
for (; j < N; j++)
{
float* vb = bottom_tm.channel(j / 8 + j % 8);
#if __ARM_NEON && __aarch64__
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4);
#else
const float* va = kernel_tm.channel(i / 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v14.4s}, [%13] \n" // sum0_3 inital with bias
"lsr w4, %w12, #2 \n" // r4 = nn = L >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"eor v16.16b, v16.16b, v16.16b \n" // sum0
"eor v17.16b, v17.16b, v17.16b \n" // sum1
"eor v18.16b, v18.16b, v18.16b \n" // sum2
"eor v19.16b, v19.16b, v19.16b \n" // sum3
"0: \n" // for (; k+3<L; k=k+4)
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" // k
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v8.4s}, [%4], #16 \n" // d
"subs w4, w4, #1 \n"
"fmla v16.4s, v0.4s, v8.s[0] \n" // sum0 += (k00-k30) * a00
"fmla v17.4s, v1.4s, v8.s[1] \n" // sum1 += (k01-k31) * a10
"fmla v18.4s, v2.4s, v8.s[2] \n" // sum2 += (k02-k32) * a20
"fmla v19.4s, v3.4s, v8.s[3] \n" // sum3 += (k03-k33) * a30
"bne 0b \n"
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"fadd v14.4s, v14.4s, v16.4s \n"
"fadd v14.4s, v14.4s, v17.4s \n"
"1: \n"
// remain loop
"and w4, %w12, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"prfm pldl1keep, [%4, #32] \n"
"ld1r {v8.4s}, [%4], #4 \n"
"subs w4, w4, #1 \n"
// k0
"fmla v14.4s, v8.4s, v0.4s \n" // sum0 += (k00-k30) * a00
"bne 2b \n"
"3: \n"
"st1 {v14.s}[0], [%0] \n"
"st1 {v14.s}[1], [%1] \n"
"st1 {v14.s}[2], [%2] \n"
"st1 {v14.s}[3], [%3] \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(output2), // %2
"=r"(output3), // %3
"=r"(vb), // %4
"=r"(va) // %5
: "0"(output0),
"1"(output1),
"2"(output2),
"3"(output3),
"4"(vb),
"5"(va),
"r"(L), // %12
"r"(biasptr) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
#else
asm volatile(
// inch loop
"vld1.f32 {d24-d25}, [%13] \n"
"lsr r4, %12, #2 \n" // r4 = nn = L >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"veor q8, q8, q8 \n"
"veor q9, q9, q9 \n"
"veor q10, q10, q10 \n"
"veor q11, q11, q11 \n"
"0: \n" // for(; nn != 0; nn--)
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n" // kernel
"pld [%4, #128] \n"
"vld1.f32 {d8-d9}, [%4]! \n" // data
"vmla.f32 q8, q0, d8[0] \n" // (k00-k30) * a00
"vmla.f32 q9, q1, d8[1] \n" // (k01-k31) * a01
"vmla.f32 q10, q2, d9[0] \n" // (k02-k32) * a02
"vmla.f32 q11, q3, d9[1] \n" // (k03-k33) * a03
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vadd.f32 q8, q8, q9 \n"
"vadd.f32 q10, q10, q11 \n"
"vadd.f32 q8, q8, q10 \n"
"vadd.f32 q12, q12, q8 \n"
"1: \n"
// remain loop
"and r4, %12, #3 \n" // r4 = remain = inch & 3
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n" // for(; remain != 0; remain--)
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5]! \n"
"pld [%4, #32] \n"
"vld1.f32 {d8[],d9[]}, [%4]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q12, q0, q4 \n"
"bne 2b \n"
"3: \n" // store the result to memory
"vst1.f32 {d24[0]}, [%0] \n"
"vst1.f32 {d24[1]}, [%1] \n"
"vst1.f32 {d25[0]}, [%2] \n"
"vst1.f32 {d25[1]}, [%3] \n"
: "=r"(output0), // %0
"=r"(output1), // %1
"=r"(output2), // %2
"=r"(output3), // %3
"=r"(vb), // %4
"=r"(va) // %5
: "0"(output0),
"1"(output1),
"2"(output2),
"3"(output3),
"4"(vb),
"5"(va),
"r"(L), // %12
"r"(biasptr) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12");
#endif // __aarch64__
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
va += 4;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
#endif // __ARM_NEON
output0++;
output1++;
output2++;
output3++;
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_outch_start; i < outch; i++)
{
float* output = top_blob.channel(i);
const float bias0 = bias ? bias[i] : 0.f;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
#if __ARM_NEON && __aarch64__
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4 + i % 4);
#else
const float* va = kernel_tm.channel(i / 4 + i % 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"dup v16.4s, %w7 \n" // sum0
"dup v17.4s, %w7 \n" // sum0n
"lsr w4, %w6, #2 \n" // r4 = nn = L >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n" // for (; k+3<L; k=k+4)
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4s}, [%2], #16 \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n" // data
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
// k0
"fmla v16.4s, v8.4s, v0.s[0] \n" // sum0 += (a00-a70) * k00
"fmla v17.4s, v9.4s, v0.s[0] \n" //
// k1
"fmla v16.4s, v10.4s, v0.s[1] \n" // sum0 += (a01-a71) * k01
"fmla v17.4s, v11.4s, v0.s[1] \n" //
// k2
"fmla v16.4s, v12.4s, v0.s[2] \n" // sum0 += (a02-a72) * k02
"fmla v17.4s, v13.4s, v0.s[2] \n" //
// k3
"fmla v16.4s, v14.4s, v0.s[3] \n" // sum0 += (a03-a73) * k03
"fmla v17.4s, v15.4s, v0.s[3] \n" //
"subs w4, w4, #1 \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w6, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%2, #32] \n"
"ld1r {v0.4s}, [%2], #4 \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v8.4s, v9.4s}, [%1], #32 \n"
"subs w4, w4, #1 \n"
// k0
"fmla v16.4s, v0.4s, v8.4s \n" // sum0 += (a00-a70) * k00
"fmla v17.4s, v0.4s, v9.4s \n" //
"bne 2b \n"
"3: \n"
"st1 {v16.4s, v17.4s}, [%0] \n"
: "=r"(output), // %0
"=r"(vb), // %1
"=r"(va) // %2
: "0"(output),
"1"(vb),
"2"(va),
"r"(L), // %6
"r"(bias0) // %7
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17");
#else
asm volatile(
"vdup.f32 q8, %7 \n"
"vdup.f32 q9, %7 \n"
// inch loop
"lsr r4, %6, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%1, #512] \n"
"vldm %1!, {d8-d15} \n"
"pld [%2, #128] \n"
"vld1.f32 {d0-d1}, [%2]! \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[0] \n"
"pld [%1, #512] \n"
"vldm %1!, {d24-d31} \n"
"vmla.f32 q8, q6, d0[1] \n"
"vmla.f32 q9, q7, d0[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q12, d1[0] \n"
"vmla.f32 q9, q13, d1[0] \n"
"vmla.f32 q8, q14, d1[1] \n"
"vmla.f32 q9, q15, d1[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %6, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%1, #256] \n"
"vld1.f32 {d8-d11}, [%1]! \n"
"pld [%2, #32] \n"
"vld1.f32 {d0[],d1[]}, [%2]! \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, q0 \n"
"vmla.f32 q9, q5, q0 \n"
"bne 2b \n"
"3: \n"
"vst1.f32 {d16-d19}, [%0] \n"
: "=r"(output), // %0
"=r"(vb), // %1
"=r"(va) // %2
: "0"(output),
"1"(vb),
"2"(va),
"r"(L), // %6
"r"(bias0) // %7
: "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
float sum[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum[n] += va[0] * vb[n];
sum[n] += va[1] * vb[n + 8];
sum[n] += va[2] * vb[n + 16];
sum[n] += va[3] * vb[n + 24];
sum[n] += va[4] * vb[n + 32];
sum[n] += va[5] * vb[n + 40];
sum[n] += va[6] * vb[n + 48];
sum[n] += va[7] * vb[n + 56];
}
va += 8;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum[n] += va[0] * vb[n];
}
va += 1;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output[n] = sum[n] + bias0;
}
#endif // __ARM_NEON
output += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
#if __ARM_NEON && __aarch64__
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4 + i % 4);
#else
const float* va = kernel_tm.channel(i / 4 + i % 4);
#endif // __ARM_NEON && __aarch64__
int k = 0;
#if __ARM_NEON
float32x4_t _sum0 = vdupq_n_f32(0.f);
for (; k + 3 < L; k += 4)
{
float32x4_t _p0 = vld1q_f32(vb);
vb += 4;
float32x4_t _k0 = vld1q_f32(va);
va += 4;
#if __aarch64__
_sum0 = vfmaq_f32(_sum0, _p0, _k0);
#else
_sum0 = vmlaq_f32(_sum0, _p0, _k0);
#endif
}
#if __aarch64__
float sum0 = bias0 + vaddvq_f32(_sum0);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float sum0 = bias0 + vget_lane_f32(vpadd_f32(_ss, _ss), 0);
#endif
#else
float sum0 = bias0;
#endif // __ARM_NEON
for (; k < L; k++)
{
sum0 += va[0] * vb[0];
va += 1;
vb += 1;
}
output[0] = sum0;
output++;
}
}
}
}
|
DRACC_OMP_027_MxV_Partially_Missing_Exit_Data_yes.c | /*
Matrix Vector multiplication without complitly copying back the result c, while utilising the enter data construct.
*/
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define C 512
int *a;
int *b;
int *c;
int init(){
for(int i=0; i<C; i++){
for(int j=0; j<C; j++){
b[j+i*C]=1;
}
a[i]=1;
c[i]=0;
}
return 0;
}
int Mult(){
#pragma omp target enter data map(to:a[0:C],b[0:C*C],c[0:C]) device(0)
#pragma omp target device(0)
{
#pragma omp teams distribute parallel for
for(int i=0; i<C; i++){
for(int j=0; j<C; j++){
c[i]+=b[j+i*C]*a[j];
}
}
}
#pragma omp target exit data map(from:c[0:C/2]) map(release:a[0:C],b[0:C*C]) device(0)
return 0;
}
int check(){
bool test = false;
for(int i=0; i<C; i++){
if(c[i]!=C){
test = true;
}
}
printf("Memory Access Issue visible: %s\n",test ? "true" : "false");
return 0;
}
int main(){
a = malloc(C*sizeof(int));
b = malloc(C*C*sizeof(int));
c = malloc(C*sizeof(int));
init();
Mult();
check();
free(a);
free(b);
free(c);
return 0;
} |
yescrypt-opt_c.h | /*-
* Copyright 2009 Colin Percival
* Copyright 2013,2014 Alexander Peslyak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
#ifdef __i386__
#warning "This implementation does not use SIMD, and thus it runs a lot slower than the SIMD-enabled implementation. Enable at least SSE2 in the C compiler and use yescrypt-best.c instead unless you're building this SIMD-less implementation on purpose (portability to older CPUs or testing)."
#elif defined(__x86_64__)
#warning "This implementation does not use SIMD, and thus it runs a lot slower than the SIMD-enabled implementation. Use yescrypt-best.c instead unless you're building this SIMD-less implementation on purpose (for testing only)."
#endif
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include "sha256.h"
#include "sysendian.h"
#include "yescrypt.h"
#include "yescrypt-platform_c.h"
static inline void
blkcpy(uint64_t * dest, const uint64_t * src, size_t count)
{
do {
*dest++ = *src++; *dest++ = *src++;
*dest++ = *src++; *dest++ = *src++;
} while (count -= 4);
}
static inline void
blkxor(uint64_t * dest, const uint64_t * src, size_t count)
{
do {
*dest++ ^= *src++; *dest++ ^= *src++;
*dest++ ^= *src++; *dest++ ^= *src++;
} while (count -= 4);
}
typedef union {
uint32_t w[16];
uint64_t d[8];
} salsa20_blk_t;
static inline void
salsa20_simd_shuffle(const salsa20_blk_t * Bin, salsa20_blk_t * Bout)
{
#define COMBINE(out, in1, in2) \
Bout->d[out] = Bin->w[in1 * 2] | ((uint64_t)Bin->w[in2 * 2 + 1] << 32);
COMBINE(0, 0, 2)
COMBINE(1, 5, 7)
COMBINE(2, 2, 4)
COMBINE(3, 7, 1)
COMBINE(4, 4, 6)
COMBINE(5, 1, 3)
COMBINE(6, 6, 0)
COMBINE(7, 3, 5)
#undef COMBINE
}
static inline void
salsa20_simd_unshuffle(const salsa20_blk_t * Bin, salsa20_blk_t * Bout)
{
#define COMBINE(out, in1, in2) \
Bout->w[out * 2] = Bin->d[in1]; \
Bout->w[out * 2 + 1] = Bin->d[in2] >> 32;
COMBINE(0, 0, 6)
COMBINE(1, 5, 3)
COMBINE(2, 2, 0)
COMBINE(3, 7, 5)
COMBINE(4, 4, 2)
COMBINE(5, 1, 7)
COMBINE(6, 6, 4)
COMBINE(7, 3, 1)
#undef COMBINE
}
/**
* salsa20_8(B):
* Apply the salsa20/8 core to the provided block.
*/
static void
salsa20_8(uint64_t B[8])
{
size_t i;
salsa20_blk_t X;
#define x X.w
salsa20_simd_unshuffle((const salsa20_blk_t *)B, &X);
for (i = 0; i < 8; i += 2) {
#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
/* Operate on columns */
x[ 4] ^= R(x[ 0]+x[12], 7); x[ 8] ^= R(x[ 4]+x[ 0], 9);
x[12] ^= R(x[ 8]+x[ 4],13); x[ 0] ^= R(x[12]+x[ 8],18);
x[ 9] ^= R(x[ 5]+x[ 1], 7); x[13] ^= R(x[ 9]+x[ 5], 9);
x[ 1] ^= R(x[13]+x[ 9],13); x[ 5] ^= R(x[ 1]+x[13],18);
x[14] ^= R(x[10]+x[ 6], 7); x[ 2] ^= R(x[14]+x[10], 9);
x[ 6] ^= R(x[ 2]+x[14],13); x[10] ^= R(x[ 6]+x[ 2],18);
x[ 3] ^= R(x[15]+x[11], 7); x[ 7] ^= R(x[ 3]+x[15], 9);
x[11] ^= R(x[ 7]+x[ 3],13); x[15] ^= R(x[11]+x[ 7],18);
/* Operate on rows */
x[ 1] ^= R(x[ 0]+x[ 3], 7); x[ 2] ^= R(x[ 1]+x[ 0], 9);
x[ 3] ^= R(x[ 2]+x[ 1],13); x[ 0] ^= R(x[ 3]+x[ 2],18);
x[ 6] ^= R(x[ 5]+x[ 4], 7); x[ 7] ^= R(x[ 6]+x[ 5], 9);
x[ 4] ^= R(x[ 7]+x[ 6],13); x[ 5] ^= R(x[ 4]+x[ 7],18);
x[11] ^= R(x[10]+x[ 9], 7); x[ 8] ^= R(x[11]+x[10], 9);
x[ 9] ^= R(x[ 8]+x[11],13); x[10] ^= R(x[ 9]+x[ 8],18);
x[12] ^= R(x[15]+x[14], 7); x[13] ^= R(x[12]+x[15], 9);
x[14] ^= R(x[13]+x[12],13); x[15] ^= R(x[14]+x[13],18);
#undef R
}
#undef x
{
salsa20_blk_t Y;
salsa20_simd_shuffle(&X, &Y);
for (i = 0; i < 16; i += 4) {
((salsa20_blk_t *)B)->w[i] += Y.w[i];
((salsa20_blk_t *)B)->w[i + 1] += Y.w[i + 1];
((salsa20_blk_t *)B)->w[i + 2] += Y.w[i + 2];
((salsa20_blk_t *)B)->w[i + 3] += Y.w[i + 3];
}
}
}
/**
* blockmix_salsa8(Bin, Bout, X, r):
* Compute Bout = BlockMix_{salsa20/8, r}(Bin). The input Bin must be 128r
* bytes in length; the output Bout must also be the same size. The
* temporary space X must be 64 bytes.
*/
static void
blockmix_salsa8(const uint64_t * Bin, uint64_t * Bout, uint64_t * X, size_t r)
{
size_t i;
/* 1: X <-- B_{2r - 1} */
blkcpy(X, &Bin[(2 * r - 1) * 8], 8);
/* 2: for i = 0 to 2r - 1 do */
for (i = 0; i < 2 * r; i += 2) {
/* 3: X <-- H(X \xor B_i) */
blkxor(X, &Bin[i * 8], 8);
salsa20_8(X);
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
blkcpy(&Bout[i * 4], X, 8);
/* 3: X <-- H(X \xor B_i) */
blkxor(X, &Bin[i * 8 + 8], 8);
salsa20_8(X);
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
blkcpy(&Bout[i * 4 + r * 8], X, 8);
}
}
/* These are tunable */
#define S_BITS 8
#define S_SIMD 2
#define S_P 4
#define S_ROUNDS 6
/* Number of S-boxes. Not tunable, hard-coded in a few places. */
#define S_N 2
/* Derived values. Not tunable on their own. */
#define S_SIZE1 (1 << S_BITS)
#define S_MASK ((S_SIZE1 - 1) * S_SIMD * 8)
#define S_MASK2 (((uint64_t)S_MASK << 32) | S_MASK)
#define S_SIZE_ALL (S_N * S_SIZE1 * S_SIMD)
#define S_P_SIZE (S_P * S_SIMD)
#define S_MIN_R ((S_P * S_SIMD + 15) / 16)
/**
* pwxform(B):
* Transform the provided block using the provided S-boxes.
*/
static void
block_pwxform(uint64_t * B, const uint64_t * S)
{
uint64_t (*X)[S_SIMD] = (uint64_t (*)[S_SIMD])B;
const uint8_t *S0 = (const uint8_t *)S;
const uint8_t *S1 = (const uint8_t *)(S + S_SIZE1 * S_SIMD);
size_t i, j;
#if S_SIMD > 2
size_t k;
#endif
for (j = 0; j < S_P; j++) {
uint64_t *Xj = X[j];
uint64_t x0 = Xj[0];
#if S_SIMD > 1
uint64_t x1 = Xj[1];
#endif
for (i = 0; i < S_ROUNDS; i++) {
uint64_t x = x0 & S_MASK2;
const uint64_t *p0, *p1;
p0 = (const uint64_t *)(S0 + (uint32_t)x);
p1 = (const uint64_t *)(S1 + (x >> 32));
x0 = (uint64_t)(x0 >> 32) * (uint32_t)x0;
x0 += p0[0];
x0 ^= p1[0];
#if S_SIMD > 1
x1 = (uint64_t)(x1 >> 32) * (uint32_t)x1;
x1 += p0[1];
x1 ^= p1[1];
#endif
#if S_SIMD > 2
for (k = 2; k < S_SIMD; k++) {
x = Xj[k];
x = (uint64_t)(x >> 32) * (uint32_t)x;
x += p0[k];
x ^= p1[k];
Xj[k] = x;
}
#endif
}
Xj[0] = x0;
#if S_SIMD > 1
Xj[1] = x1;
#endif
}
}
/**
* blockmix_pwxform(Bin, Bout, S, r):
* Compute Bout = BlockMix_pwxform{salsa20/8, S, r}(Bin). The input Bin must
* be 128r bytes in length; the output Bout must also be the same size.
*
* S lacks const qualifier to match blockmix_salsa8()'s prototype, which we
* need to refer to both functions via the same function pointers.
*/
static void
blockmix_pwxform(const uint64_t * Bin, uint64_t * Bout, uint64_t * S, size_t r)
{
size_t r1, r2, i;
/* Convert 128-byte blocks to (S_P_SIZE * 64-bit) blocks */
r1 = r * 128 / (S_P_SIZE * 8);
/* X <-- B_{r1 - 1} */
blkcpy(Bout, &Bin[(r1 - 1) * S_P_SIZE], S_P_SIZE);
/* X <-- X \xor B_i */
blkxor(Bout, Bin, S_P_SIZE);
/* X <-- H'(X) */
/* B'_i <-- X */
block_pwxform(Bout, S);
/* for i = 0 to r1 - 1 do */
for (i = 1; i < r1; i++) {
/* X <-- X \xor B_i */
blkcpy(&Bout[i * S_P_SIZE], &Bout[(i - 1) * S_P_SIZE],
S_P_SIZE);
blkxor(&Bout[i * S_P_SIZE], &Bin[i * S_P_SIZE], S_P_SIZE);
/* X <-- H'(X) */
/* B'_i <-- X */
block_pwxform(&Bout[i * S_P_SIZE], S);
}
/* Handle partial blocks */
if (i * S_P_SIZE < r * 16)
blkcpy(&Bout[i * S_P_SIZE], &Bin[i * S_P_SIZE],
r * 16 - i * S_P_SIZE);
i = (r1 - 1) * S_P_SIZE / 8;
/* Convert 128-byte blocks to 64-byte blocks */
r2 = r * 2;
/* B'_i <-- H(B'_i) */
salsa20_8(&Bout[i * 8]);
i++;
for (; i < r2; i++) {
/* B'_i <-- H(B'_i \xor B'_{i-1}) */
blkxor(&Bout[i * 8], &Bout[(i - 1) * 8], 8);
salsa20_8(&Bout[i * 8]);
}
}
/**
* integerify(B, r):
* Return the result of parsing B_{2r-1} as a little-endian integer.
*/
static inline uint64_t
integerify(const uint64_t * B, size_t r)
{
/*
* Our 64-bit words are in host byte order, and word 6 holds the second 32-bit
* word of B_{2r-1} due to SIMD shuffling. The 64-bit value we return is also
* in host byte order, as it should be.
*/
const uint64_t * X = &B[(2 * r - 1) * 8];
uint32_t lo = X[0];
uint32_t hi = X[6] >> 32;
return ((uint64_t)hi << 32) + lo;
}
/**
* smix1(B, r, N, flags, V, NROM, shared, XY, S):
* Compute first loop of B = SMix_r(B, N). The input B must be 128r bytes in
* length; the temporary storage V must be 128rN bytes in length; the temporary
* storage XY must be 256r + 64 bytes in length. The value N must be even and
* no smaller than 2.
*/
static void
smix1(uint64_t * B, size_t r, uint64_t N, yescrypt_flags_t flags,
uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared,
uint64_t * XY, uint64_t * S)
{
void (*blockmix)(const uint64_t *, uint64_t *, uint64_t *, size_t) =
(S ? blockmix_pwxform : blockmix_salsa8);
const uint64_t * VROM = shared->shared1.aligned;
uint32_t VROM_mask = shared->mask1;
size_t s = 16 * r;
uint64_t * X = V;
uint64_t * Y = &XY[s];
uint64_t * Z = S ? S : &XY[2 * s];
uint64_t n, i, j;
size_t k;
/* 1: X <-- B */
/* 3: V_i <-- X */
for (i = 0; i < 2 * r; i++) {
const salsa20_blk_t *src = (const salsa20_blk_t *)&B[i * 8];
salsa20_blk_t *tmp = (salsa20_blk_t *)Y;
salsa20_blk_t *dst = (salsa20_blk_t *)&X[i * 8];
for (k = 0; k < 16; k++)
tmp->w[k] = le32dec(&src->w[k]);
salsa20_simd_shuffle(tmp, dst);
}
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
blockmix(X, Y, Z, r);
blkcpy(&V[s], Y, s);
X = XY;
if (NROM && (VROM_mask & 1)) {
if ((1 & VROM_mask) == 1) {
/* j <-- Integerify(X) mod NROM */
j = integerify(Y, r) & (NROM - 1);
/* X <-- H(X \xor VROM_j) */
blkxor(Y, &VROM[j * s], s);
}
blockmix(Y, X, Z, r);
/* 2: for i = 0 to N - 1 do */
for (n = 1, i = 2; i < N; i += 2) {
/* 3: V_i <-- X */
blkcpy(&V[i * s], X, s);
if ((i & (i - 1)) == 0)
n <<= 1;
/* j <-- Wrap(Integerify(X), i) */
j = integerify(X, r) & (n - 1);
j += i - n;
/* X <-- X \xor V_j */
blkxor(X, &V[j * s], s);
/* 4: X <-- H(X) */
blockmix(X, Y, Z, r);
/* 3: V_i <-- X */
blkcpy(&V[(i + 1) * s], Y, s);
j = integerify(Y, r);
if (((i + 1) & VROM_mask) == 1) {
/* j <-- Integerify(X) mod NROM */
j &= NROM - 1;
/* X <-- H(X \xor VROM_j) */
blkxor(Y, &VROM[j * s], s);
} else {
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += i + 1 - n;
/* X <-- H(X \xor V_j) */
blkxor(Y, &V[j * s], s);
}
blockmix(Y, X, Z, r);
}
} else {
yescrypt_flags_t rw = flags & YESCRYPT_RW;
/* 4: X <-- H(X) */
blockmix(Y, X, Z, r);
/* 2: for i = 0 to N - 1 do */
for (n = 1, i = 2; i < N; i += 2) {
/* 3: V_i <-- X */
blkcpy(&V[i * s], X, s);
if (rw) {
if ((i & (i - 1)) == 0)
n <<= 1;
/* j <-- Wrap(Integerify(X), i) */
j = integerify(X, r) & (n - 1);
j += i - n;
/* X <-- X \xor V_j */
blkxor(X, &V[j * s], s);
}
/* 4: X <-- H(X) */
blockmix(X, Y, Z, r);
/* 3: V_i <-- X */
blkcpy(&V[(i + 1) * s], Y, s);
if (rw) {
/* j <-- Wrap(Integerify(X), i) */
j = integerify(Y, r) & (n - 1);
j += (i + 1) - n;
/* X <-- X \xor V_j */
blkxor(Y, &V[j * s], s);
}
/* 4: X <-- H(X) */
blockmix(Y, X, Z, r);
}
}
/* B' <-- X */
for (i = 0; i < 2 * r; i++) {
const salsa20_blk_t *src = (const salsa20_blk_t *)&X[i * 8];
salsa20_blk_t *tmp = (salsa20_blk_t *)Y;
salsa20_blk_t *dst = (salsa20_blk_t *)&B[i * 8];
for (k = 0; k < 16; k++)
le32enc(&tmp->w[k], src->w[k]);
salsa20_simd_unshuffle(tmp, dst);
}
}
/**
* smix2(B, r, N, Nloop, flags, V, NROM, shared, XY, S):
* Compute second loop of B = SMix_r(B, N). The input B must be 128r bytes in
* length; the temporary storage V must be 128rN bytes in length; the temporary
* storage XY must be 256r + 64 bytes in length. The value N must be a
* power of 2 greater than 1. The value Nloop must be even.
*/
static void
smix2(uint64_t * B, size_t r, uint64_t N, uint64_t Nloop,
yescrypt_flags_t flags,
uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared,
uint64_t * XY, uint64_t * S)
{
void (*blockmix)(const uint64_t *, uint64_t *, uint64_t *, size_t) =
(S ? blockmix_pwxform : blockmix_salsa8);
const uint64_t * VROM = shared->shared1.aligned;
uint32_t VROM_mask = shared->mask1 | 1;
size_t s = 16 * r;
yescrypt_flags_t rw = flags & YESCRYPT_RW;
uint64_t * X = XY;
uint64_t * Y = &XY[s];
uint64_t * Z = S ? S : &XY[2 * s];
uint64_t i, j;
size_t k;
if (Nloop == 0)
return;
/* X <-- B' */
for (i = 0; i < 2 * r; i++) {
const salsa20_blk_t *src = (const salsa20_blk_t *)&B[i * 8];
salsa20_blk_t *tmp = (salsa20_blk_t *)Y;
salsa20_blk_t *dst = (salsa20_blk_t *)&X[i * 8];
for (k = 0; k < 16; k++)
tmp->w[k] = le32dec(&src->w[k]);
salsa20_simd_shuffle(tmp, dst);
}
if (NROM) {
/* 6: for i = 0 to N - 1 do */
for (i = 0; i < Nloop; i += 2) {
/* 7: j <-- Integerify(X) mod N */
j = integerify(X, r) & (N - 1);
/* 8: X <-- H(X \xor V_j) */
blkxor(X, &V[j * s], s);
/* V_j <-- Xprev \xor V_j */
if (rw)
blkcpy(&V[j * s], X, s);
blockmix(X, Y, Z, r);
j = integerify(Y, r);
if (((i + 1) & VROM_mask) == 1) {
/* j <-- Integerify(X) mod NROM */
j &= NROM - 1;
/* X <-- H(X \xor VROM_j) */
blkxor(Y, &VROM[j * s], s);
} else {
/* 7: j <-- Integerify(X) mod N */
j &= N - 1;
/* 8: X <-- H(X \xor V_j) */
blkxor(Y, &V[j * s], s);
/* V_j <-- Xprev \xor V_j */
if (rw)
blkcpy(&V[j * s], Y, s);
}
blockmix(Y, X, Z, r);
}
} else {
/* 6: for i = 0 to N - 1 do */
i = Nloop / 2;
do {
/* 7: j <-- Integerify(X) mod N */
j = integerify(X, r) & (N - 1);
/* 8: X <-- H(X \xor V_j) */
blkxor(X, &V[j * s], s);
/* V_j <-- Xprev \xor V_j */
if (rw)
blkcpy(&V[j * s], X, s);
blockmix(X, Y, Z, r);
/* 7: j <-- Integerify(X) mod N */
j = integerify(Y, r) & (N - 1);
/* 8: X <-- H(X \xor V_j) */
blkxor(Y, &V[j * s], s);
/* V_j <-- Xprev \xor V_j */
if (rw)
blkcpy(&V[j * s], Y, s);
blockmix(Y, X, Z, r);
} while (--i);
}
/* 10: B' <-- X */
for (i = 0; i < 2 * r; i++) {
const salsa20_blk_t *src = (const salsa20_blk_t *)&X[i * 8];
salsa20_blk_t *tmp = (salsa20_blk_t *)Y;
salsa20_blk_t *dst = (salsa20_blk_t *)&B[i * 8];
for (k = 0; k < 16; k++)
le32enc(&tmp->w[k], src->w[k]);
salsa20_simd_unshuffle(tmp, dst);
}
}
/**
* p2floor(x):
* Largest power of 2 not greater than argument.
*/
static uint64_t
p2floor(uint64_t x)
{
uint64_t y;
while ((y = x & (x - 1)))
x = y;
return x;
}
/**
* smix(B, r, N, p, t, flags, V, NROM, shared, XY, S):
* Compute B = SMix_r(B, N). The input B must be 128rp bytes in length; the
* temporary storage V must be 128rN bytes in length; the temporary storage
* XY must be 256r+64 or (256r+64)*p bytes in length (the larger size is
* required with OpenMP-enabled builds). The value N must be a power of 2
* greater than 1.
*/
static void
smix(uint64_t * B, size_t r, uint64_t N, uint32_t p, uint32_t t,
yescrypt_flags_t flags,
uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared,
uint64_t * XY, uint64_t * S)
{
size_t s = 16 * r;
uint64_t Nchunk = N / p, Nloop_all, Nloop_rw;
uint32_t i;
Nloop_all = Nchunk;
if (flags & YESCRYPT_RW) {
if (t <= 1) {
if (t)
Nloop_all *= 2; /* 2/3 */
Nloop_all = (Nloop_all + 2) / 3; /* 1/3, round up */
} else {
Nloop_all *= t - 1;
}
} else if (t) {
if (t == 1)
Nloop_all += (Nloop_all + 1) / 2; /* 1.5, round up */
Nloop_all *= t;
}
Nloop_rw = 0;
if (flags & __YESCRYPT_INIT_SHARED)
Nloop_rw = Nloop_all;
else if (flags & YESCRYPT_RW)
Nloop_rw = Nloop_all / p;
Nchunk &= ~(uint64_t)1; /* round down to even */
Nloop_all++; Nloop_all &= ~(uint64_t)1; /* round up to even */
Nloop_rw &= ~(uint64_t)1; /* round down to even */
#ifdef _OPENMP
#pragma omp parallel if (p > 1) default(none) private(i) shared(B, r, N, p, flags, V, NROM, shared, XY, S, s, Nchunk, Nloop_all, Nloop_rw)
{
#pragma omp for
#endif
for (i = 0; i < p; i++) {
uint64_t Vchunk = i * Nchunk;
uint64_t * Bp = &B[i * s];
uint64_t * Vp = &V[Vchunk * s];
#ifdef _OPENMP
uint64_t * XYp = &XY[i * (2 * s + 8)];
#else
uint64_t * XYp = XY;
#endif
uint64_t Np = (i < p - 1) ? Nchunk : (N - Vchunk);
uint64_t * Sp = S ? &S[i * S_SIZE_ALL] : S;
if (Sp)
smix1(Bp, 1, S_SIZE_ALL / 16,
flags & ~YESCRYPT_PWXFORM,
Sp, NROM, shared, XYp, NULL);
if (!(flags & __YESCRYPT_INIT_SHARED_2))
smix1(Bp, r, Np, flags, Vp, NROM, shared, XYp, Sp);
smix2(Bp, r, p2floor(Np), Nloop_rw, flags, Vp,
NROM, shared, XYp, Sp);
}
if (Nloop_all > Nloop_rw) {
#ifdef _OPENMP
#pragma omp for
#endif
for (i = 0; i < p; i++) {
uint64_t * Bp = &B[i * s];
#ifdef _OPENMP
uint64_t * XYp = &XY[i * (2 * s + 8)];
#else
uint64_t * XYp = XY;
#endif
uint64_t * Sp = S ? &S[i * S_SIZE_ALL] : S;
smix2(Bp, r, N, Nloop_all - Nloop_rw,
flags & ~YESCRYPT_RW, V, NROM, shared, XYp, Sp);
}
}
#ifdef _OPENMP
}
#endif
}
/**
* yescrypt_kdf(shared, local, passwd, passwdlen, salt, saltlen,
* N, r, p, t, flags, buf, buflen):
* Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,
* p, buflen), or a revision of scrypt as requested by flags and shared, and
* write the result into buf. The parameters r, p, and buflen must satisfy
* r * p < 2^30 and buflen <= (2^32 - 1) * 32. The parameter N must be a power
* of 2 greater than 1.
*
* t controls computation time while not affecting peak memory usage. shared
* and flags may request special modes as described in yescrypt.h. local is
* the thread-local data structure, allowing to preserve and reuse a memory
* allocation across calls, thereby reducing its overhead.
*
* Return 0 on success; or -1 on error.
*/
static int
yescrypt_kdf(const yescrypt_shared_t * shared, yescrypt_local_t * local,
const uint8_t * passwd, size_t passwdlen,
const uint8_t * salt, size_t saltlen,
uint64_t N, uint32_t r, uint32_t p, uint32_t t, yescrypt_flags_t flags,
uint8_t * buf, size_t buflen)
{
yescrypt_region_t tmp;
uint64_t NROM;
size_t B_size, V_size, XY_size, need;
uint64_t * B, * V, * XY, * S;
uint64_t sha256[4];
/*
* YESCRYPT_PARALLEL_SMIX is a no-op at p = 1 for its intended purpose,
* so don't let it have side-effects. Without this adjustment, it'd
* enable the SHA-256 password pre-hashing and output post-hashing,
* because any deviation from classic scrypt implies those.
*/
if (p == 1)
flags &= ~YESCRYPT_PARALLEL_SMIX;
/* Sanity-check parameters */
if (flags & ~YESCRYPT_KNOWN_FLAGS) {
errno = EINVAL;
return -1;
}
#if SIZE_MAX > UINT32_MAX
if (buflen > (((uint64_t)(1) << 32) - 1) * 32) {
errno = EFBIG;
return -1;
}
#endif
if ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) {
errno = EFBIG;
return -1;
}
if (((N & (N - 1)) != 0) || (N <= 1) || (r < 1) || (p < 1)) {
errno = EINVAL;
return -1;
}
if ((flags & YESCRYPT_PARALLEL_SMIX) && (N / p <= 1)) {
errno = EINVAL;
return -1;
}
#if S_MIN_R > 1
if ((flags & YESCRYPT_PWXFORM) && (r < S_MIN_R)) {
errno = EINVAL;
return -1;
}
#endif
if ((p > SIZE_MAX / ((size_t)256 * r + 64)) ||
#if SIZE_MAX / 256 <= UINT32_MAX
(r > SIZE_MAX / 256) ||
#endif
(N > SIZE_MAX / 128 / r)) {
errno = ENOMEM;
return -1;
}
if (N > UINT64_MAX / ((uint64_t)t + 1)) {
errno = EFBIG;
return -1;
}
#ifdef _OPENMP
if (!(flags & YESCRYPT_PARALLEL_SMIX) &&
(N > SIZE_MAX / 128 / (r * p))) {
errno = ENOMEM;
return -1;
}
#endif
if ((flags & YESCRYPT_PWXFORM) &&
#ifndef _OPENMP
(flags & YESCRYPT_PARALLEL_SMIX) &&
#endif
p > SIZE_MAX / (S_SIZE_ALL * sizeof(*S))) {
errno = ENOMEM;
return -1;
}
NROM = 0;
if (shared->shared1.aligned) {
NROM = shared->shared1.aligned_size / ((size_t)128 * r);
if (((NROM & (NROM - 1)) != 0) || (NROM <= 1) ||
!(flags & YESCRYPT_RW)) {
errno = EINVAL;
return -1;
}
}
/* Allocate memory */
V = NULL;
V_size = (size_t)128 * r * N;
#ifdef _OPENMP
if (!(flags & YESCRYPT_PARALLEL_SMIX))
V_size *= p;
#endif
need = V_size;
if (flags & __YESCRYPT_INIT_SHARED) {
if (local->aligned_size < need) {
if (local->base || local->aligned ||
local->base_size || local->aligned_size) {
errno = EINVAL;
return -1;
}
if (!alloc_region(local, need))
return -1;
}
V = (uint64_t *)local->aligned;
need = 0;
}
B_size = (size_t)128 * r * p;
need += B_size;
if (need < B_size) {
errno = ENOMEM;
return -1;
}
XY_size = (size_t)256 * r + 64;
#ifdef _OPENMP
XY_size *= p;
#endif
need += XY_size;
if (need < XY_size) {
errno = ENOMEM;
return -1;
}
if (flags & YESCRYPT_PWXFORM) {
size_t S_size = S_SIZE_ALL * sizeof(*S);
#ifdef _OPENMP
S_size *= p;
#else
if (flags & YESCRYPT_PARALLEL_SMIX)
S_size *= p;
#endif
need += S_size;
if (need < S_size) {
errno = ENOMEM;
return -1;
}
}
if (flags & __YESCRYPT_INIT_SHARED) {
if (!alloc_region(&tmp, need))
return -1;
B = (uint64_t *)tmp.aligned;
XY = (uint64_t *)((uint8_t *)B + B_size);
} else {
init_region(&tmp);
if (local->aligned_size < need) {
if (free_region(local))
return -1;
if (!alloc_region(local, need))
return -1;
}
B = (uint64_t *)local->aligned;
V = (uint64_t *)((uint8_t *)B + B_size);
XY = (uint64_t *)((uint8_t *)V + V_size);
}
S = NULL;
if (flags & YESCRYPT_PWXFORM)
S = (uint64_t *)((uint8_t *)XY + XY_size);
if (t || flags) {
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, passwd, passwdlen);
SHA256_Final((uint8_t *)sha256, &ctx);
passwd = (uint8_t *)sha256;
passwdlen = sizeof(sha256);
}
/* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */
PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1,
(uint8_t *)B, B_size);
if (t || flags)
blkcpy(sha256, B, sizeof(sha256) / sizeof(sha256[0]));
if (p == 1 || (flags & YESCRYPT_PARALLEL_SMIX)) {
smix(B, r, N, p, t, flags, V, NROM, shared, XY, S);
} else {
uint32_t i;
/* 2: for i = 0 to p - 1 do */
#ifdef _OPENMP
#pragma omp parallel for default(none) private(i) shared(B, r, N, p, t, flags, V, NROM, shared, XY, S)
#endif
for (i = 0; i < p; i++) {
/* 3: B_i <-- MF(B_i, N) */
#ifdef _OPENMP
smix(&B[(size_t)16 * r * i], r, N, 1, t, flags,
&V[(size_t)16 * r * i * N],
NROM, shared,
&XY[((size_t)32 * r + 8) * i],
S ? &S[S_SIZE_ALL * i] : S);
#else
smix(&B[(size_t)16 * r * i], r, N, 1, t, flags, V,
NROM, shared, XY, S);
#endif
}
}
/* 5: DK <-- PBKDF2(P, B, 1, dkLen) */
PBKDF2_SHA256(passwd, passwdlen, (uint8_t *)B, B_size, 1, buf, buflen);
/*
* Except when computing classic scrypt, allow all computation so far
* to be performed on the client. The final steps below match those of
* SCRAM (RFC 5802), so that an extension of SCRAM (with the steps so
* far in place of SCRAM's use of PBKDF2 and with SHA-256 in place of
* SCRAM's use of SHA-1) would be usable with yescrypt hashes.
*/
if ((t || flags) && buflen == sizeof(sha256)) {
/* Compute ClientKey */
{
HMAC_SHA256_CTX ctx;
HMAC_SHA256_Init(&ctx, buf, buflen);
HMAC_SHA256_Update(&ctx, salt, saltlen);
HMAC_SHA256_Final((uint8_t *)sha256, &ctx);
}
/* Compute StoredKey */
{
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, (uint8_t *)sha256, sizeof(sha256));
SHA256_Final(buf, &ctx);
}
}
if (free_region(&tmp))
return -1;
/* Success! */
return 0;
}
|
agmgLevel.c | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus, Rajesh Gandham
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.
*/
#include "agmg.h"
// parAlmond's function call-backs
void agmgAx(void **args, dfloat *x, dfloat *Ax){
parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
axpy(level->A, 1.0, x, 0.0, Ax,parAlmond->nullSpace,parAlmond->nullSpacePenalty);
}
void agmgCoarsen(void **args, dfloat *r, dfloat *Rr){
// parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
axpy(level->R, 1.0, r, 0.0, Rr,false,0.);
}
void agmgProlongate(void **args, dfloat *x, dfloat *Px){
// parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
axpy(level->P, 1.0, x, 1.0, Px,false,0.);
}
void agmgSmooth(void **args, dfloat *rhs, dfloat *x, bool x_is_zero){
parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
if(level->stype == JACOBI){
smoothJacobi(parAlmond, level, level->A, rhs, x, x_is_zero);
} else if(level->stype == DAMPED_JACOBI){
smoothDampedJacobi(parAlmond, level, level->A, rhs, x, x_is_zero);
} else if(level->stype == CHEBYSHEV){
smoothChebyshev(parAlmond, level, level->A, rhs, x, x_is_zero);
}
}
void device_agmgAx(void **args, occa::memory &o_x, occa::memory &o_Ax){
parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
axpy(parAlmond,level->deviceA, 1.0, o_x, 0.0, o_Ax,parAlmond->nullSpace,parAlmond->nullSpacePenalty);
}
void device_agmgCoarsen(void **args, occa::memory &o_r, occa::memory &o_Rr){
parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
axpy(parAlmond, level->deviceR, 1.0, o_r, 0.0, o_Rr,false,0.);
}
void device_agmgProlongate(void **args, occa::memory &o_x, occa::memory &o_Px){
parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
axpy(parAlmond, level->dcsrP, 1.0, o_x, 1.0, o_Px);
}
void device_agmgSmooth(void **args, occa::memory &o_rhs, occa::memory &o_x, bool x_is_zero){
parAlmond_t *parAlmond = (parAlmond_t *) args[0];
agmgLevel *level = (agmgLevel *) args[1];
if(level->stype == JACOBI){
smoothJacobi(parAlmond, level, level->deviceA, o_rhs, o_x, x_is_zero);
} else if(level->stype == DAMPED_JACOBI){
smoothDampedJacobi(parAlmond, level, level->deviceA, o_rhs, o_x, x_is_zero);
} else if(level->stype == CHEBYSHEV){
smoothChebyshev(parAlmond, level, level->deviceA, o_rhs, o_x, x_is_zero);
}
}
dfloat rhoDinvA(parAlmond_t *parAlmond, csr *A, dfloat *invD);
void setupSmoother(parAlmond_t *parAlmond, agmgLevel *level, SmoothType s){
level->stype = s;
if((s == DAMPED_JACOBI)||(s == CHEBYSHEV)){
// estimate rho(invD * A)
dfloat rho=0;
if(level->A->Nrows)
level->A->diagInv = (dfloat *) calloc(level->A->Nrows, sizeof(dfloat));
for (dlong i=0;i<level->A->Nrows;i++) {
dfloat diag = level->A->diagCoefs[level->A->diagRowStarts[i]];
if (parAlmond->nullSpace) {
diag += parAlmond->nullSpacePenalty*level->A->null[i]*level->A->null[i];
}
level->A->diagInv[i] = 1.0/diag;
}
rho = rhoDinvA(parAlmond, level->A, level->A->diagInv);
if (s == DAMPED_JACOBI) {
level->smoother_params = (dfloat *) calloc(1,sizeof(dfloat));
level->smoother_params[0] = (4./3.)/rho;
//temp storage for smoothing
if (level->Ncols) level->smootherResidual = (dfloat *) calloc(level->Ncols,sizeof(dfloat));
if (level->Ncols) level->o_smootherResidual = parAlmond->device.malloc(level->Ncols*sizeof(dfloat),level->smootherResidual);
} else if (s == CHEBYSHEV) {
level->smoother_params = (dfloat *) calloc(2,sizeof(dfloat));
level->smoother_params[0] = rho;
level->smoother_params[1] = rho/10.;
//temp storage for smoothing
if (level->Ncols) level->smootherResidual = (dfloat *) calloc(level->Ncols,sizeof(dfloat));
if (level->Ncols) level->smootherResidual2 = (dfloat *) calloc(level->Ncols,sizeof(dfloat));
if (level->Ncols) level->smootherUpdate = (dfloat *) calloc(level->Ncols,sizeof(dfloat));
if (level->Ncols) level->o_smootherResidual = parAlmond->device.malloc(level->Ncols*sizeof(dfloat),level->smootherResidual);
if (level->Ncols) level->o_smootherResidual2 = parAlmond->device.malloc(level->Ncols*sizeof(dfloat),level->smootherResidual);
if (level->Ncols) level->o_smootherUpdate = parAlmond->device.malloc(level->Ncols*sizeof(dfloat),level->smootherUpdate);
}
}
}
extern "C"{
void dgeev_(char *JOBVL, char *JOBVR, int *N, double *A, int *LDA, double *WR, double *WI,
double *VL, int *LDVL, double *VR, int *LDVR, double *WORK, int *LWORK, int *INFO );
}
static void eig(const int Nrows, double *A, double *WR,
double *WI){
if(Nrows){
int NB = 256;
char JOBVL = 'V';
char JOBVR = 'V';
int N = Nrows;
int LDA = Nrows;
int LWORK = (NB+2)*N;
double *WORK = new double[LWORK];
double *VL = new double[Nrows*Nrows];
double *VR = new double[Nrows*Nrows];
int INFO = -999;
dgeev_ (&JOBVL, &JOBVR, &N, A, &LDA, WR, WI,
VL, &LDA, VR, &LDA, WORK, &LWORK, &INFO);
assert(INFO == 0);
delete [] VL;
delete [] VR;
delete [] WORK;
}
}
dfloat rhoDinvA(parAlmond_t* parAlmond,csr *A, dfloat *invD){
const dlong N = A->Nrows;
const dlong M = A->Ncols;
int k = 10;
int rank, size;
rank = agmg::rank;
size = agmg::size;
hlong Nlocal = (hlong) N;
hlong Ntotal = 0;
MPI_Allreduce(&Nlocal, &Ntotal, 1, MPI_HLONG, MPI_SUM, agmg::comm);
if(k > Ntotal)
k = (int) Ntotal;
// do an arnoldi
// allocate memory for Hessenberg matrix
double *H = (double *) calloc(k*k,sizeof(double));
// allocate memory for basis
dfloat **V = (dfloat **) calloc(k+1, sizeof(dfloat *));
dfloat *Vx = (dfloat *) calloc(M, sizeof(dfloat));
for(int i=0; i<=k; i++)
V[i] = (dfloat *) calloc(N, sizeof(dfloat));
// generate a random vector for initial basis vector
for (dlong i=0;i<N;i++)
Vx[i] = (dfloat) drand48();
dfloat norm_vo = 0.;
for (dlong i=0;i<N;i++)
norm_vo += Vx[i]*Vx[i];
dfloat gNorm_vo = 0;
MPI_Allreduce(&norm_vo, &gNorm_vo, 1, MPI_DFLOAT, MPI_SUM, agmg::comm);
gNorm_vo = sqrt(gNorm_vo);
for (dlong i=0;i<N;i++)
Vx[i] /= gNorm_vo;
for (dlong i=0;i<N;i++)
V[0][i] = Vx[i];
for(int j=0; j<k; j++){
for (dlong i=0;i<N;i++)
Vx[i] = V[j][i];
// v[j+1] = invD*(A*v[j])
axpy(A, 1.0, Vx, 0., V[j+1],parAlmond->nullSpace,parAlmond->nullSpacePenalty);
dotStar(N, invD, V[j+1]);
// modified Gram-Schmidth
for(int i=0; i<=j; i++){
// H(i,j) = v[i]'*A*v[j]
dfloat hij = innerProd(N, V[i], V[j+1]);
dfloat ghij = 0;
MPI_Allreduce(&hij, &ghij, 1, MPI_DFLOAT, MPI_SUM, agmg::comm);
// v[j+1] = v[j+1] - hij*v[i]
vectorAdd(N,-ghij, V[i], 1.0, V[j+1]);
H[i + j*k] = (double) ghij;
}
if(j+1 < k){
dfloat norm_vj = 0.;
for (dlong i=0;i<N;i++)
norm_vj += V[j+1][i]*V[j+1][i];
dfloat gNorm_vj;
MPI_Allreduce(&norm_vj, &gNorm_vj, 1, MPI_DFLOAT, MPI_SUM, agmg::comm);
gNorm_vj = sqrt(gNorm_vj);
H[j+1+ j*k] = (double) gNorm_vj;
scaleVector(N,V[j+1], 1./H[j+1 + j*k]);
}
}
double *WR = (double *) calloc(k,sizeof(double));
double *WI = (double *) calloc(k,sizeof(double));
eig(k, H, WR, WI);
double rho = 0.;
for(int i=0; i<k; i++){
double rho_i = sqrt(WR[i]*WR[i] + WI[i]*WI[i]);
if(rho < rho_i) {
rho = rho_i;
}
}
free(H);
free(WR);
free(WI);
// free memory
for(int i=0; i<=k; i++){
free(V[i]);
}
if ((rank==0)&& (parAlmond->options.compareArgs("VERBOSE","TRUE"))) printf("weight = %g \n", rho);
return rho;
}
void matrixInverse(int N, dfloat *A);
//set up exact solver using xxt
void setupExactSolve(parAlmond_t *parAlmond, agmgLevel *level, bool nullSpace, dfloat nullSpacePenalty) {
int rank, size;
rank = agmg::rank;
size = agmg::size;
//copy the global coarse partition as ints
int *coarseOffsets = (int* ) calloc(size+1,sizeof(int));
for (int r=0;r<size+1;r++) coarseOffsets[r] = (int) level->globalRowStarts[r];
int coarseTotal = coarseOffsets[size];
int coarseOffset = coarseOffsets[rank];
csr *A = level->A;
int N = (int) level->Nrows;
int localNNZ;
int *rows;
int *cols;
dfloat *vals;
if((rank==0)&&(parAlmond->options.compareArgs("VERBOSE","TRUE"))) printf("Setting up coarse solver...");fflush(stdout);
if(!nullSpace) {
//if no nullspace, use sparse A
localNNZ = (int) (A->diagNNZ+A->offdNNZ);
if (localNNZ) {
rows = (int *) calloc(localNNZ,sizeof(int));
cols = (int *) calloc(localNNZ,sizeof(int));
vals = (dfloat *) calloc(localNNZ,sizeof(dfloat));
}
//populate matrix
int cnt = 0;
for (int n=0;n<N;n++) {
int start = (int) A->diagRowStarts[n];
int end = (int) A->diagRowStarts[n+1];
for (int m=start;m<end;m++) {
rows[cnt] = n + coarseOffset;
cols[cnt] = (int) (A->diagCols[m] + coarseOffset);
vals[cnt] = A->diagCoefs[m];
cnt++;
}
start = (int) A->offdRowStarts[n];
end = (int) A->offdRowStarts[n+1];
for (dlong m=A->offdRowStarts[n];m<A->offdRowStarts[n+1];m++) {
rows[cnt] = n + coarseOffset;
cols[cnt] = (int) A->colMap[A->offdCols[m]];
vals[cnt] = A->offdCoefs[m];
cnt++;
}
}
} else {
localNNZ = (int) (A->Nrows*coarseTotal); //A is dense due to nullspace augmentation
if (localNNZ) {
rows = (int *) calloc(localNNZ,sizeof(int));
cols = (int *) calloc(localNNZ,sizeof(int));
vals = (dfloat *) calloc(localNNZ,sizeof(dfloat));
}
//gather null vector
dfloat *nullTotal = (dfloat*) calloc(coarseTotal,sizeof(dfloat));
int *nullCounts = (int*) calloc(size,sizeof(int));
for (int r=0;r<size;r++)
nullCounts[r] = coarseOffsets[r+1]-coarseOffsets[r];
MPI_Allgatherv(A->null, N, MPI_DFLOAT, nullTotal, nullCounts, coarseOffsets, MPI_DFLOAT, agmg::comm);
//populate matrix
for (int n=0;n<N;n++) {
for (int m=0;m<coarseTotal;m++) {
rows[n*coarseTotal+m] = n + coarseOffset;
cols[n*coarseTotal+m] = m;
vals[n*coarseTotal+m] = nullSpacePenalty*nullTotal[n+coarseOffset]*nullTotal[m];
}
}
for (int n=0;n<N;n++) {
int start = (int) A->diagRowStarts[n];
int end = (int) A->diagRowStarts[n+1];
for (int m=start;m<end;m++) {
int col = (int) (A->diagCols[m] + coarseOffset);
vals[n*coarseTotal+col] += A->diagCoefs[m];
}
start = (int) A->offdRowStarts[n];
end = (int) A->offdRowStarts[n+1];
for (int m=start;m<end;m++) {
int col = (int) A->colMap[A->offdCols[m]];
vals[n*coarseTotal+col] += A->offdCoefs[m];
}
}
}
//ge the nonzero counts from all ranks
int *NNZ = (int*) calloc(size,sizeof(int));
int *NNZoffsets = (int*) calloc(size+1,sizeof(int));
MPI_Allgather(&localNNZ, 1, MPI_INT, NNZ, 1, MPI_INT, agmg::comm);
int totalNNZ = 0;
for (int r=0;r<size;r++) {
totalNNZ += NNZ[r];
NNZoffsets[r+1] = NNZoffsets[r] + NNZ[r];
}
int *Arows = (int *) calloc(totalNNZ,sizeof(int));
int *Acols = (int *) calloc(totalNNZ,sizeof(int));
dfloat *Avals = (dfloat *) calloc(totalNNZ,sizeof(dfloat));
MPI_Allgatherv(rows, localNNZ, MPI_INT, Arows, NNZ, NNZoffsets, MPI_INT, agmg::comm);
MPI_Allgatherv(cols, localNNZ, MPI_INT, Acols, NNZ, NNZoffsets, MPI_INT, agmg::comm);
MPI_Allgatherv(vals, localNNZ, MPI_DFLOAT, Avals, NNZ, NNZoffsets, MPI_DFLOAT, agmg::comm);
//assemble the full matrix
dfloat *coarseA = (dfloat *) calloc(coarseTotal*coarseTotal,sizeof(dfloat));
for (int i=0;i<totalNNZ;i++) {
int n = Arows[i];
int m = Acols[i];
coarseA[n*coarseTotal+m] = Avals[i];
}
matrixInverse(coarseTotal, coarseA);
//store only the local rows of the full inverse
parAlmond->invCoarseA = (dfloat *) calloc(A->Nrows*coarseTotal,sizeof(dfloat));
for (int n=0;n<N;n++) {
for (int m=0;m<coarseTotal;m++) {
parAlmond->invCoarseA[n*coarseTotal+m] = coarseA[(n+coarseOffset)*coarseTotal+m];
}
}
parAlmond->coarseTotal = coarseTotal;
parAlmond->coarseOffset = coarseOffset;
parAlmond->coarseOffsets = coarseOffsets;
parAlmond->coarseCounts = (int*) calloc(size,sizeof(int));
for (int r=0;r<size;r++)
parAlmond->coarseCounts[r] = coarseOffsets[r+1]-coarseOffsets[r];
parAlmond->xCoarse = (dfloat*) calloc(coarseTotal,sizeof(dfloat));
parAlmond->rhsCoarse = (dfloat*) calloc(coarseTotal,sizeof(dfloat));
if (localNNZ) {
free(rows);
free(cols);
free(vals);
}
if (totalNNZ) {
free(Arows);
free(Acols);
free(Avals);
}
if(coarseTotal) {
free(coarseA);
}
if((rank==0)&&(parAlmond->options.compareArgs("VERBOSE","TRUE"))) printf("done.\n");
}
void exactCoarseSolve(parAlmond_t *parAlmond, int N, dfloat *rhs, dfloat *x) {
//gather the full vector
MPI_Allgatherv(rhs, N, MPI_DFLOAT, parAlmond->rhsCoarse, parAlmond->coarseCounts, parAlmond->coarseOffsets, MPI_DFLOAT, agmg::comm);
//multiply by local part of the exact matrix inverse
#pragma omp parallel for
for (int n=0;n<N;n++) {
x[n] = 0.;
for (int m=0;m<parAlmond->coarseTotal;m++) {
x[n] += parAlmond->invCoarseA[n*parAlmond->coarseTotal+m]*parAlmond->rhsCoarse[m];
}
}
}
void device_exactCoarseSolve(parAlmond_t *parAlmond, int N, occa::memory o_rhs, occa::memory o_x) {
dfloat *rhs = parAlmond->levels[parAlmond->numLevels-1]->rhs;
dfloat *x = parAlmond->levels[parAlmond->numLevels-1]->x;
//use coarse solver
o_rhs.copyTo(rhs);
//gather the full vector
MPI_Allgatherv(rhs, N, MPI_DFLOAT, parAlmond->rhsCoarse, parAlmond->coarseCounts, parAlmond->coarseOffsets, MPI_DFLOAT, agmg::comm);
//multiply by local part of the exact matrix inverse
#pragma omp parallel for
for (int n=0;n<N;n++) {
x[n] = 0.;
for (int m=0;m<parAlmond->coarseTotal;m++) {
x[n] += parAlmond->invCoarseA[n*parAlmond->coarseTotal+m]*parAlmond->rhsCoarse[m];
}
}
o_x.copyFrom(x);
}
#if 0
//set up exact solver using xxt
void setupExactSolve(parAlmond_t *parAlmond, agmgLevel *level, bool nullSpace, dfloat nullSpacePenalty) {
int rank, size;
rank = agmg::rank;
size = agmg::size;
int* coarseOffsets = level->globalRowStarts;
int coarseTotal = coarseOffsets[size];
int coarseOffset = coarseOffsets[rank];
int *globalNumbering = (int *) calloc(coarseTotal,sizeof(int));
for (int n=0;n<coarseTotal;n++)
globalNumbering[n] = n;
csr *A = level->A;
int N = level->Nrows;
int totalNNZ;
int *rows;
int *cols;
dfloat *vals;
if(!nullSpace) {
//if no nullspace, use sparse A
totalNNZ = A->diagNNZ+A->offdNNZ;
if (totalNNZ) {
rows = (int *) calloc(totalNNZ,sizeof(int));
cols = (int *) calloc(totalNNZ,sizeof(int));
vals = (dfloat *) calloc(totalNNZ,sizeof(dfloat));
}
//populate matrix
int cnt = 0;
for (int n=0;n<N;n++) {
for (int m=A->diagRowStarts[n];m<A->diagRowStarts[n+1];m++) {
rows[cnt] = n + coarseOffset;
cols[cnt] = A->diagCols[m] + coarseOffset;
vals[cnt] = A->diagCoefs[m];
cnt++;
}
for (int m=A->offdRowStarts[n];m<A->offdRowStarts[n+1];m++) {
rows[cnt] = n + coarseOffset;
cols[cnt] = A->colMap[A->offdCols[m]];
vals[cnt] = A->offdCoefs[m];
cnt++;
}
}
} else {
totalNNZ = A->Nrows*coarseTotal; //A is dense due to nullspace augmentation
if (totalNNZ) {
rows = (int *) calloc(totalNNZ,sizeof(int));
cols = (int *) calloc(totalNNZ,sizeof(int));
vals = (dfloat *) calloc(totalNNZ,sizeof(dfloat));
}
//gather null vector
dfloat *nullTotal = (dfloat*) calloc(coarseTotal,sizeof(dfloat));
int *nullCounts = (int*) calloc(size,sizeof(int));
for (int r=0;r<size;r++)
nullCounts[r] = coarseOffsets[r+1]-coarseOffsets[r];
MPI_Allgatherv(A->null, A->Nrows, MPI_DFLOAT, nullTotal, nullCounts, coarseOffsets, MPI_DFLOAT, agmg::comm);
//populate matrix
for (int n=0;n<N;n++) {
for (int m=0;m<coarseTotal;m++) {
rows[n*coarseTotal+m] = n + coarseOffset;
cols[n*coarseTotal+m] = m;
vals[n*coarseTotal+m] = nullSpacePenalty*nullTotal[n+coarseOffset]*nullTotal[m];
}
}
for (int n=0;n<N;n++) {
for (int m=A->diagRowStarts[n];m<A->diagRowStarts[n+1];m++) {
int col = A->diagCols[m] + coarseOffset;
vals[n*coarseTotal+col] += A->diagCoefs[m];
}
for (int m=A->offdRowStarts[n];m<A->offdRowStarts[n+1];m++) {
int col = A->colMap[A->offdCols[m]];
vals[n*coarseTotal+col] += A->offdCoefs[m];
}
}
}
parAlmond->ExactSolve = xxtSetup(A->Nrows,
globalNumbering,
totalNNZ,
rows,
cols,
vals,
0,
"int",
dfloatString);
parAlmond->coarseTotal = coarseTotal;
parAlmond->coarseOffset = coarseOffset;
parAlmond->xCoarse = (dfloat*) calloc(coarseTotal,sizeof(dfloat));
parAlmond->rhsCoarse = (dfloat*) calloc(coarseTotal,sizeof(dfloat));
free(globalNumbering);
if (totalNNZ) {
free(rows);
free(cols);
free(vals);
}
printf("Done UberCoarse setup\n");
}
void exactCoarseSolve(parAlmond_t *parAlmond, int N, dfloat *rhs, dfloat *x) {
//use coarse solver
for (int n=0;n<parAlmond->coarseTotal;n++)
parAlmond->rhsCoarse[n] =0.;
for (int n=0;n<N;n++)
parAlmond->rhsCoarse[n+parAlmond->coarseOffset] = rhs[n];
xxtSolve(parAlmond->xCoarse, parAlmond->ExactSolve, parAlmond->rhsCoarse);
for (int n=0;n<N;n++)
x[n] = parAlmond->xCoarse[n+parAlmond->coarseOffset];
}
void device_exactCoarseSolve(parAlmond_t *parAlmond, int N, occa::memory o_rhs, occa::memory o_x) {
//use coarse solver
for (int n=0;n<parAlmond->coarseTotal;n++)
parAlmond->rhsCoarse[n] =0.;
o_rhs.copyTo(parAlmond->rhsCoarse+parAlmond->coarseOffset);
xxtSolve(parAlmond->xCoarse, parAlmond->ExactSolve, parAlmond->rhsCoarse);
o_x.copyFrom(parAlmond->xCoarse+parAlmond->coarseOffset,N*sizeof(dfloat));
}
#endif
|
3d25pt.c | /*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 8;
tile_size[3] = 64;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*(
coef0* A[t%2][i ][j ][k ] +
coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] +
A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] +
A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) +
coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] +
A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] +
A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) +
coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] +
A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] +
A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) +
coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] +
A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] +
A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) );
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = MIN(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
FastTree-2.1.11.c | // Downloaded from <http://www.microbesonline.org/fasttree/FastTree-2.1.11.c>
/*
* FastTree -- inferring approximately-maximum-likelihood trees for large
* multiple sequence alignments.
*
* Morgan N. Price
* http://www.microbesonline.org/fasttree/
*
* Thanks to Jim Hester of the Cleveland Clinic Foundation for
* providing the first parallel (OpenMP) code, Siavash Mirarab of
* UT Austin for implementing the WAG option, Samuel Shepard
* at the CDC for suggesting and helping with the -quote option, and
* Aaron Darling (University of Technology, Sydney) for numerical changes
* for wide alignments of closely-related sequences.
*
* Copyright (C) 2008-2015 The Regents of the University of California
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* or visit http://www.gnu.org/copyleft/gpl.html
*
* Disclaimer
*
* NEITHER THE UNITED STATES NOR THE UNITED STATES DEPARTMENT OF ENERGY,
* NOR ANY OF THEIR EMPLOYEES, MAKES ANY WARRANTY, EXPRESS OR IMPLIED,
* OR ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY,
* COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, APPARATUS, PRODUCT,
* OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE
* PRIVATELY OWNED RIGHTS.
*/
/*
* To compile FastTree, do:
* gcc -Wall -O3 -finline-functions -funroll-loops -o FastTree -lm FastTree.c
* Use -DNO_SSE to turn off use of SSE3 instructions
* (should not be necessary because compiler should not set __SSE__ if
* not available, and modern mallocs should return 16-byte-aligned values)
* Use -DOPENMP -fopenmp to use multiple threads (note, old versions of gcc
* may not support -fopenmp)
* Use -DTRACK_MEMORY if you want detailed reports of memory usage,
* but results are not correct above 4GB because mallinfo stores int values.
* It also makes FastTree run significantly slower.
*
* To get usage guidance, do:
* FastTree -help
*
* FastTree uses profiles instead of a distance matrix, and computes
* support values for each split from the profiles of the 4 nodes
* around the split. It stores a profile for each node and a average
* profile over all active nodes (the "out-profile" for computing the
* total sum of distance to other nodes). The neighbor joining phase
* requires O(N*L*a) space, where N is the number of sequences, L is
* the alignment width, and a is the alphabet size. The top-hits
* heuristic requires an additional O(N sqrt(N)) memory. After
* neighbor-joining, FastTree improves the topology with
* nearest-neighbor interchanges (NNIs) and subtree-prune-regraft
* moves (SPRs), which does not have a significant additional memory
* requirement. (We need only store "up-profiles" on the path from our
* current traversal point to the root.) These take O(NLa) time per
* round, and with default settings, O(N log(N) L a) time total.
* FastTree further improves the topology with maximum-likelihood
* NNIs, using similar data structures and complexity, but with a
* higher constant factor, and now the "profiles" are actually
* posterior distributions for that subtree. Finally, FastTree
* resamples the site likelihoods around each NNI and uses
* the Shimodaira Hasegawa test to estimate the reliability of each split.
*
* Overview of the neighbor-joining phase:
*
* Although FastTree uses a log correction on profile distances to
* account for multiple substitutions when doing NNIs and SPRs, the
* operations on the profiles themselves involve "additive" distances
* -- either %different (for nucleotide) or by using an amino acid
* similarity matrix (for proteins). If we are using %different as
* our distance matrix then
*
* Profile_distance(A,B) = 1 - sum over characters of freq(A)*freq(B)
*
* and we can average this value over positions. Positions with gaps
* are weighted by %ungapped(A) * %ungapped(B).
*
* If we are using an amino acid dissimilarity matrix D(i,j) then at
* each position
*
* Profile_distance(A,B) = sum(i,j) freq(A==i) * freq(B==j) * D(i,j)
* = sum(k) Ak * Bk * Lambda(k)
*
* where k iterates over 20 eigenvectors, Lambda(k) is the eigenvalue,
* and if A==i, then Ak is the kth column of the inverse of the
* eigenvector matrix.
*
* The exhaustive approach (-slow) takes O(N**3*L*a) time, but
* this can be reduced to as little as O(N**(3/2)*log(N)*L*a) time
* by using heuristics.
*
* It uses a combination of three heuristics: a visible set similar to
* that of FastTree (Elias & Lagergren 2005), a local hill-climbing
* search for a better join (as in relaxed neighbor-joining, Evans et
* al. 2006), and a top-hit list to reduce the search space (see
* below).
*
* The "visible" set stores, for each node, the best join for that
* node, as identified at some point in the past
*
* If top-hits are not being used, then the neighbor-joining phase can
* be summarized as:
*
* Compute the out-profile by averaging the leaves
* Compute the out-distance of each leaf quickly, using the out-profile
* Compute the visible set (or approximate it using top-hits, see below)
* Until we're down to 3 active nodes:
* Find the best join in the visible set
* (This involves recomputing the neighbor-joining criterion,
* as out-distances and #active nodes may have changed)
* Follow a chain of best hits (again recomputing the criterion)
* until we find a locally best join, as in relaxed neighbor joining
* Create a profile of the parent node, either using simple averages (default)
* or using weighted joining as in BIONJ (if -bionj was specified)
* Update the out-profile and the out-distances
* Update the visible set:
* find the best join for the new joined node
* replace hits to the joined children with hits to the parent
* if we stumble across a join for the new node that is better
* than the corresponding entry in the visible set, "reset"
* that entry.
*
* For each iteration, this method does
* O(N) work to find the best hit in the visible set
* O(L*N*a*log(N)) work to do the local search, where log(N)
* is a pessimistic estimate of the number of iterations. In
* practice, we average <1 iteration for 2,000 sequences.
* With -fastest, this step is omitted.
* O(N*a) work to compute the joined profile and update the out-profile
* O(L*N*a) work to update the out-distances
* O(L*N*a) work to compare the joined profile to the other nodes
* (to find the new entry in the visible set)
*
* and there are N-3 iterations, so it takes O(N**2 * L * log(N) * a) time.
*
* The profile distances give exactly the same result as matrix
* distances in neighbor-joining or BIONJ would if there are no gaps
* in the alignment. If there are gaps, then it is an
* approximation. To get the same result we also store a "diameter"
* for each node (diameter is 0 for leaves).
*
* In the simpler case (NJ rather than BIONJ), when we join A and B to
* give a new node AB,
*
* Profile(AB) = (A+B)/2
* Profile_distance(AB,C) = (Profile_distance(A,C)+Profile_distance(B,C))/2
* because the formulas above are linear
*
* And according to the neighor-joining rule,
* d(AB,C) = (d(A,C)+d(B,C)-d(A,B))/2
*
* and we can achieve the same value by writing
* diameter(AB) = pd(A,B)/2
* diameter(leaf) = 0
* d(A,B) = pd(A,B) - diameter(A) - diameter(B)
*
* because
* d(AB,C) = (d(A,C)+d(B,C)-d(A,B))/2
* = (pd(A,C)-diam(A)-diam(C)+pd(B,C)-diam(B)-diam(C)-d(A,B)+diam(A)+diam(B))/2
* = (pd(A,C)+pd(B,C))/2 - diam(C) - pd(A,B)
* = pd(AB,C) - diam(AB) - diam(C)
*
* If we are using BIONJ, with weight lambda for the join:
* Profile(AB) = lambda*A + (1-lambda)*B
* then a similar argument gives
* diam(AB) = lambda*diam(A) + (1-lambda)*diam(B) + lambda*d(A,AB) + (1-lambda)*d(B,AB),
*
* where, as in neighbor joining,
* d(A,AB) = d(A,B) + (total out_distance(A) - total out_distance(B))/(n-2)
*
* A similar recursion formula works for the "variance" matrix of BIONJ,
* var(AB,C) = lambda*var(A,C) + (1-lambda)*var(B,C) - lambda*(1-lambda)*var(A,B)
* is equivalent to
* var(A,B) = pv(A,B) - vd(A) - vd(B), where
* pv(A,B) = pd(A,B)
* vd(A) = 0 for leaves
* vd(AB) = lambda*vd(A) + (1-lambda)*vd(B) + lambda*(1-lambda)*var(A,B)
*
* The top-hist heuristic to reduce the work below O(N**2*L) stores a top-hit
* list of size m=sqrt(N) for each active node.
*
* The list can be initialized for all the leaves in sub (N**2 * L) time as follows:
* Pick a "seed" sequence and compare it to all others
* Store the top m hits of the seed as its top-hit list
* Take "close" hits of the seed(within the top m, and see the "close" parameter),
* and assume that their top m hits lie within the top 2*m hits of the seed.
* So, compare them to the seed's neighors (if they do not already
* have a top hit list) and set their top hits.
*
* This method does O(N*L) work for each seed, or O(N**(3/2)*L) work total.
*
* To avoid doing O(N*L) work at each iteration, we need to avoid
* updating the visible set and the out-distances. So, we use "stale"
* out-distances, and when searching the visible set for the best hit,
* we only inspect the top m=sqrt(N) entries. We then update those
* out-distances (up to 2*m*L*a work) and then find the best hit.
*
* To avoid searching the entire visible set, FastTree keeps
* and updates a list of the top sqrt(N) entries in the visible set.
* This costs O(sqrt(N)) time per join to find the best entry and to
* update, or (N sqrt(N)) time overall.
*
* Similarly, when doing the local hill-climbing, we avoid O(N*L) work
* by only considering the top-hits for the current node. So this adds
* O(m*a*log(N)) work per iteration.
*
* When we join two nodes, we compute profiles and update the
* out-profile as before. We need to compute the best hits of the node
* -- we merge the lists for the children and select the best up-to-m
* hits. If the top hit list contains a stale node we replace it with
* its parent. If we still have <m/2 entries, we do a "refresh".
*
* In a "refresh", similar to the fast top-hit computation above, we
* compare the "seed", in this case the new joined node, to all other
* nodes. We compare its close neighbors (the top m hits) to all
* neighbors (the top 2*m hits) and update the top-hit lists of all
* neighbors (by merging to give a list of 3*m entries and then
* selecting the best m entries).
*
* Finally, during these processes we update the visible sets for
* other nodes with better hits if we find them, and we set the
* visible entry for the new joined node to the best entry in its
* top-hit list. (And whenever we update a visible entry, we
* do O(sqrt(N)) work to update the top-visible list.)
* These udpates are not common so they do not alter the
* O(N sqrt(N) log(N) L a) total running time for the joining phase.
*
* Second-level top hits
*
* With -fastest or with -2nd, FastTree uses an additional "2nd-level" top hits
* heuristic to reduce the running time for the top-hits phase to
* O(N**1.25 L) and for the neighbor-joining phase to O(N**1.25 L a).
* This also reduces the memory usage for the top-hits lists to
* O(N**1.25), which is important for alignments with a million
* sequences. The key idea is to store just q = sqrt(m) top hits for
* most sequences.
*
* Given the neighbors of A -- either for a seed or for a neighbor
* from the top-hits heuristic, if B is within the top q hits of A, we
* set top-hits(B) from the top 3*q top-hits of A. And, we record that
* A is the "source" of the hits for B, so if we run low on hits for
* B, instead of doing a full refresh, we can do top-hits(B) :=
* top-hits(B) union top-hits(active_ancestor(A)).
* During a refresh, these "2nd-level" top hits are updated just as
* normal, but the source is maintained and only q entries are stored,
* until we near the end of the neighbor joining phase (until the
* root as 2*m children or less).
*
* Parallel execution with OpenMP
*
* If you compile FastTree with OpenMP support, it will take
* advantage of multiple CPUs on one machine. It will parallelize:
*
* The top hits phase
* Comparing one node to many others during the NJ phase (the simplest kind of join)
* The refresh phase
* Optimizing likelihoods for 3 alternate topologies during ML NNIs and ML supports
* (only 3 threads can be used)
*
* This accounts for most of the O(N L a) or slower steps except for
* minimum-evolution NNIs (which are fast anyway), minimum-evolution SPRs,
* selecting per-site rates, and optimizing branch lengths outside of ML NNIs.
*
* Parallelizing the top hits phase may lead to a slight change in the tree,
* as some top hits are computed from different (and potentially less optimal source).
* This means that results on repeated runs may not be 100% identical.
* However, this should not have any significant effect on tree quality
* after the NNIs and SPRs.
*
* The OpenMP code also turns off the star-topology test during ML
* NNIs, which may lead to slight improvements in likelihood.
*/
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <sys/time.h>
#include <ctype.h>
#include <unistd.h>
#ifdef TRACK_MEMORY
/* malloc.h apparently doesn't exist on MacOS */
#include <malloc.h>
#endif
/* Compile with -DOPENMP to turn on multithreading */
#ifdef OPENMP
#include <omp.h>
#endif
/* By default, tries to compile with SSE instructions for greater speed.
But if compiled with -DUSE_DOUBLE, uses double precision instead of single-precision
floating point (2x memory required), does not use SSE, and allows much shorter
branch lengths.
*/
#ifdef __SSE__
#if !defined(NO_SSE) && !defined(USE_DOUBLE)
#define USE_SSE3
#endif
#endif
#ifdef USE_DOUBLE
#define SSE_STRING "Double precision (No SSE3)"
typedef double numeric_t;
#define ScanNumericSpec "%lf"
#else
typedef float numeric_t;
#define ScanNumericSpec "%f"
#endif
#ifdef USE_SSE3
#define SSE_STRING "SSE3"
#define ALIGNED __attribute__((aligned(16)))
#define IS_ALIGNED(X) ((((unsigned long) new) & 15L) == 0L)
#include <xmmintrin.h>
#else
#define ALIGNED
#define IS_ALIGNED(X) 1
#ifndef USE_DOUBLE
#define SSE_STRING "No SSE3"
#endif
#endif /* USE_SSE3 */
#define FT_VERSION "2.1.11"
char *usage =
" FastTree protein_alignment > tree\n"
" FastTree < protein_alignment > tree\n"
" FastTree -out tree protein_alignment\n"
" FastTree -nt nucleotide_alignment > tree\n"
" FastTree -nt -gtr < nucleotide_alignment > tree\n"
" FastTree < nucleotide_alignment > tree\n"
"FastTree accepts alignments in fasta or phylip interleaved formats\n"
"\n"
"Common options (must be before the alignment file):\n"
" -quiet to suppress reporting information\n"
" -nopr to suppress progress indicator\n"
" -log logfile -- save intermediate trees, settings, and model details\n"
" -fastest -- speed up the neighbor joining phase & reduce memory usage\n"
" (recommended for >50,000 sequences)\n"
" -n <number> to analyze multiple alignments (phylip format only)\n"
" (use for global bootstrap, with seqboot and CompareToBootstrap.pl)\n"
" -nosupport to not compute support values\n"
" -intree newick_file to set the starting tree(s)\n"
" -intree1 newick_file to use this starting tree for all the alignments\n"
" (for faster global bootstrap on huge alignments)\n"
" -pseudo to use pseudocounts (recommended for highly gapped sequences)\n"
" -gtr -- generalized time-reversible model (nucleotide alignments only)\n"
" -lg -- Le-Gascuel 2008 model (amino acid alignments only)\n"
" -wag -- Whelan-And-Goldman 2001 model (amino acid alignments only)\n"
" -quote -- allow spaces and other restricted characters (but not ' ) in\n"
" sequence names and quote names in the output tree (fasta input only;\n"
" FastTree will not be able to read these trees back in)\n"
" -noml to turn off maximum-likelihood\n"
" -nome to turn off minimum-evolution NNIs and SPRs\n"
" (recommended if running additional ML NNIs with -intree)\n"
" -nome -mllen with -intree to optimize branch lengths for a fixed topology\n"
" -cat # to specify the number of rate categories of sites (default 20)\n"
" or -nocat to use constant rates\n"
" -gamma -- after optimizing the tree under the CAT approximation,\n"
" rescale the lengths to optimize the Gamma20 likelihood\n"
" -constraints constraintAlignment to constrain the topology search\n"
" constraintAlignment should have 1s or 0s to indicates splits\n"
" -expert -- see more options\n"
"For more information, see http://www.microbesonline.org/fasttree/\n";
char *expertUsage =
"FastTree [-nt] [-n 100] [-quote] [-pseudo | -pseudo 1.0]\n"
" [-boot 1000 | -nosupport]\n"
" [-intree starting_trees_file | -intree1 starting_tree_file]\n"
" [-quiet | -nopr]\n"
" [-nni 10] [-spr 2] [-noml | -mllen | -mlnni 10]\n"
" [-mlacc 2] [-cat 20 | -nocat] [-gamma]\n"
" [-slow | -fastest] [-2nd | -no2nd] [-slownni] [-seed 1253] \n"
" [-top | -notop] [-topm 1.0 [-close 0.75] [-refresh 0.8]]\n"
" [-gtr] [-gtrrates ac ag at cg ct gt] [-gtrfreq A C G T]\n"
" [ -lg | -wag | -trans transitionmatrixfile ]\n"
" [-matrix Matrix | -nomatrix] [-nj | -bionj]\n"
" [ -constraints constraintAlignment [ -constraintWeight 100.0 ] ]\n"
" [-log logfile]\n"
" [ alignment_file ]\n"
" [ -out output_newick_file | > newick_tree]\n"
"\n"
"or\n"
"\n"
"FastTree [-nt] [-matrix Matrix | -nomatrix] [-rawdist] -makematrix [alignment]\n"
" [-n 100] > phylip_distance_matrix\n"
"\n"
" FastTree supports fasta or phylip interleaved alignments\n"
" By default FastTree expects protein alignments, use -nt for nucleotides\n"
" FastTree reads standard input if no alignment file is given\n"
"\n"
"Input/output options:\n"
" -n -- read in multiple alignments in. This only\n"
" works with phylip interleaved format. For example, you can\n"
" use it with the output from phylip's seqboot. If you use -n, FastTree\n"
" will write 1 tree per line to standard output.\n"
" -intree newickfile -- read the starting tree in from newickfile.\n"
" Any branch lengths in the starting trees are ignored.\n"
" -intree with -n will read a separate starting tree for each alignment.\n"
" -intree1 newickfile -- read the same starting tree for each alignment\n"
" -quiet -- do not write to standard error during normal operation (no progress\n"
" indicator, no options summary, no likelihood values, etc.)\n"
" -nopr -- do not write the progress indicator to stderr\n"
" -log logfile -- save intermediate trees so you can extract\n"
" the trees and restart long-running jobs if they crash\n"
" -log also reports the per-site rates (1 means slowest category)\n"
" -quote -- quote sequence names in the output and allow spaces, commas,\n"
" parentheses, and colons in them but not ' characters (fasta files only)\n"
"\n"
"Distances:\n"
" Default: For protein sequences, log-corrected distances and an\n"
" amino acid dissimilarity matrix derived from BLOSUM45\n"
" or for nucleotide sequences, Jukes-Cantor distances\n"
" To specify a different matrix, use -matrix FilePrefix or -nomatrix\n"
" Use -rawdist to turn the log-correction off\n"
" or to use %different instead of Jukes-Cantor\n"
" (These options affect minimum-evolution computations only;\n"
" use -trans to affect maximum-likelihoood computations)\n"
"\n"
" -pseudo [weight] -- Use pseudocounts to estimate distances between\n"
" sequences with little or no overlap. (Off by default.) Recommended\n"
" if analyzing the alignment has sequences with little or no overlap.\n"
" If the weight is not specified, it is 1.0\n"
"\n"
"Topology refinement:\n"
" By default, FastTree tries to improve the tree with up to 4*log2(N)\n"
" rounds of minimum-evolution nearest-neighbor interchanges (NNI),\n"
" where N is the number of unique sequences, 2 rounds of\n"
" subtree-prune-regraft (SPR) moves (also min. evo.), and\n"
" up to 2*log(N) rounds of maximum-likelihood NNIs.\n"
" Use -nni to set the number of rounds of min. evo. NNIs,\n"
" and -spr to set the rounds of SPRs.\n"
" Use -noml to turn off both min-evo NNIs and SPRs (useful if refining\n"
" an approximately maximum-likelihood tree with further NNIs)\n"
" Use -sprlength set the maximum length of a SPR move (default 10)\n"
" Use -mlnni to set the number of rounds of maximum-likelihood NNIs\n"
" Use -mlacc 2 or -mlacc 3 to always optimize all 5 branches at each NNI,\n"
" and to optimize all 5 branches in 2 or 3 rounds\n"
" Use -mllen to optimize branch lengths without ML NNIs\n"
" Use -mllen -nome with -intree to optimize branch lengths on a fixed topology\n"
" Use -slownni to turn off heuristics to avoid constant subtrees (affects both\n"
" ML and ME NNIs)\n"
"\n"
"Maximum likelihood model options:\n"
" -lg -- Le-Gascuel 2008 model instead of (default) Jones-Taylor-Thorton 1992 model (a.a. only)\n"
" -wag -- Whelan-And-Goldman 2001 model instead of (default) Jones-Taylor-Thorton 1992 model (a.a. only)\n"
" -gtr -- generalized time-reversible instead of (default) Jukes-Cantor (nt only)\n"
" -cat # -- specify the number of rate categories of sites (default 20)\n"
" -nocat -- no CAT model (just 1 category)\n"
" - trans filename -- use the transition matrix from filename\n"
" This is supported for amino acid alignments only\n"
" The file must be tab-delimited with columns in the order ARNDCQEGHILKMFPSTWYV*\n"
" The additional column named * is for the stationary distribution\n"
" Each row must have a row name in the same order ARNDCQEGHILKMFPSTWYV\n"
" -gamma -- after the final round of optimizing branch lengths with the CAT model,\n"
" report the likelihood under the discrete gamma model with the same\n"
" number of categories. FastTree uses the same branch lengths but\n"
" optimizes the gamma shape parameter and the scale of the lengths.\n"
" The final tree will have rescaled lengths. Used with -log, this\n"
" also generates per-site likelihoods for use with CONSEL, see\n"
" GammaLogToPaup.pl and documentation on the FastTree web site.\n"
"\n"
"Support value options:\n"
" By default, FastTree computes local support values by resampling the site\n"
" likelihoods 1,000 times and the Shimodaira Hasegawa test. If you specify -nome,\n"
" it will compute minimum-evolution bootstrap supports instead\n"
" In either case, the support values are proportions ranging from 0 to 1\n"
"\n"
" Use -nosupport to turn off support values or -boot 100 to use just 100 resamples\n"
" Use -seed to initialize the random number generator\n"
"\n"
"Searching for the best join:\n"
" By default, FastTree combines the 'visible set' of fast neighbor-joining with\n"
" local hill-climbing as in relaxed neighbor-joining\n"
" -slow -- exhaustive search (like NJ or BIONJ, but different gap handling)\n"
" -slow takes half an hour instead of 8 seconds for 1,250 proteins\n"
" -fastest -- search the visible set (the top hit for each node) only\n"
" Unlike the original fast neighbor-joining, -fastest updates visible(C)\n"
" after joining A and B if join(AB,C) is better than join(C,visible(C))\n"
" -fastest also updates out-distances in a very lazy way,\n"
" -fastest sets -2nd on as well, use -fastest -no2nd to avoid this\n"
"\n"
"Top-hit heuristics:\n"
" By default, FastTree uses a top-hit list to speed up search\n"
" Use -notop (or -slow) to turn this feature off\n"
" and compare all leaves to each other,\n"
" and all new joined nodes to each other\n"
" -topm 1.0 -- set the top-hit list size to parameter*sqrt(N)\n"
" FastTree estimates the top m hits of a leaf from the\n"
" top 2*m hits of a 'close' neighbor, where close is\n"
" defined as d(seed,close) < 0.75 * d(seed, hit of rank 2*m),\n"
" and updates the top-hits as joins proceed\n"
" -close 0.75 -- modify the close heuristic, lower is more conservative\n"
" -refresh 0.8 -- compare a joined node to all other nodes if its\n"
" top-hit list is less than 80% of the desired length,\n"
" or if the age of the top-hit list is log2(m) or greater\n"
" -2nd or -no2nd to turn 2nd-level top hits heuristic on or off\n"
" This reduces memory usage and running time but may lead to\n"
" marginal reductions in tree quality.\n"
" (By default, -fastest turns on -2nd.)\n"
"\n"
"Join options:\n"
" -nj: regular (unweighted) neighbor-joining (default)\n"
" -bionj: weighted joins as in BIONJ\n"
" FastTree will also weight joins during NNIs\n"
"\n"
"Constrained topology search options:\n"
" -constraints alignmentfile -- an alignment with values of 0, 1, and -\n"
" Not all sequences need be present. A column of 0s and 1s defines a\n"
" constrained split. Some constraints may be violated\n"
" (see 'violating constraints:' in standard error).\n"
" -constraintWeight -- how strongly to weight the constraints. A value of 1\n"
" means a penalty of 1 in tree length for violating a constraint\n"
" Default: 100.0\n"
"\n"
"For more information, see http://www.microbesonline.org/fasttree/\n"
" or the comments in the source code\n";
;
#define MAXCODES 20
#define NOCODE 127
/* Note -- sequence lines longer than BUFFER_SIZE are
allowed, but FASTA header lines must be within this limit */
#define BUFFER_SIZE 5000
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
typedef struct {
int nPos;
int nSeq;
char **names;
char **seqs;
int nSaved; /* actual allocated size of names and seqs */
} alignment_t;
/* For each position in a profile, we have a weight (% non-gapped) and a
frequency vector. (If using a matrix, the frequency vector is in eigenspace).
We also store codes for simple profile positions (all gaps or only 1 value)
If weight[pos] > 0 && codes[pos] == NOCODE then we store the vector
vectors itself is sets of nCodes long, so the vector for the ith nonconstant position
starts at &vectors[nCodes*i]
To speed up comparison of outprofile to a sequence or other simple profile, we also
(for outprofiles) store codeDist[iPos*nCodes+k] = dist(k,profile[iPos])
For constraints, we store a vector of nOn and nOff
If not using constraints, those will be NULL
*/
typedef struct {
/* alignment profile */
numeric_t *weights;
unsigned char *codes;
numeric_t *vectors; /* NULL if no non-constant positions, e.g. for leaves */
int nVectors;
numeric_t *codeDist; /* Optional -- distance to each code at each position */
/* constraint profile */
int *nOn;
int *nOff;
} profile_t;
/* A visible node is a pair of nodes i, j such that j is the best hit of i,
using the neighbor-joining criterion, at the time the comparison was made,
or approximately so since then.
Note that variance = dist because in BIONJ, constant factors of variance do not matter,
and because we weight ungapped sequences higher naturally when averaging profiles,
so we do not take this into account in the computation of "lambda" for BIONJ.
For the top-hit list heuristic, if the top hit list becomes "too short",
we store invalid entries with i=j=-1 and dist/criterion very high.
*/
typedef struct {
int i, j;
numeric_t weight; /* Total product of weights (maximum value is nPos)
This is needed for weighted joins and for pseudocounts,
but not in most other places.
For example, it is not maintained by the top hits code */
numeric_t dist; /* The uncorrected distance (includes diameter correction) */
numeric_t criterion; /* changes when we update the out-profile or change nActive */
} besthit_t;
typedef struct {
int nChild;
int child[3];
} children_t;
typedef struct {
/* Distances between amino acids */
numeric_t distances[MAXCODES][MAXCODES];
/* Inverse of the eigenvalue matrix, for rotating a frequency vector
into eigenspace so that profile similarity computations are
O(alphabet) not O(alphabet*alphabet) time.
*/
numeric_t eigeninv[MAXCODES][MAXCODES];
numeric_t eigenval[MAXCODES]; /* eigenvalues */
/* eigentot=eigeninv times the all-1s frequency vector
useful for normalizing rotated frequency vectors
*/
numeric_t eigentot[MAXCODES];
/* codeFreq is the transpose of the eigeninv matrix is
the rotated frequency vector for each code */
numeric_t codeFreq[MAXCODES][MAXCODES];
numeric_t gapFreq[MAXCODES];
} distance_matrix_t;
/* A transition matrix gives the instantaneous rate of change of frequencies
df/dt = M . f
which is solved by
f(t) = exp(M) . f(0)
and which is not a symmetric matrix because of
non-uniform stationary frequencies stat, so that
M stat = 0
M(i,j) is instantaneous rate of j -> i, not of i -> j
S = diag(sqrt(stat)) is a correction so that
M' = S**-1 M S is symmetric
Let W L W**-1 = M' be an eigendecomposition of M'
Because M' is symmetric, W can be a rotation, and W**-1 = t(W)
Set V = S*W
M = V L V**-1 is an eigendecomposition of M
Note V**-1 = W**-1 S**-1 = t(W) S**-1
Evolution by time t is given by
exp(M*t) = V exp(L*t) V**-1
P(A & B | t) = B . exp(M*t) . (A * stat)
note this is *not* the same as P(A->B | t)
and we can reduce some of the computations from O(a**2) to O(a) time,
where a is the alphabet size, by storing frequency vectors as
t(V) . f = t(W) . t(S) . f
Then
P(f0 & f1 | t) = f1 . exp(M*t) . f0 * (f0 . stat) = sum(r0j * r1j * exp(l_j*t))
where r0 and r1 are the transformed vectors
Posterior distribution of P given children f0 and f1 is given by
P(i | f0, f1, t0, t1) = stat * P(i->f0 | t0) * P(i->f1 | t1)
= P(i & f0 | t0) * P(i & f1 | t1) / stat
~ (V . exp(t0*L) . r0) * (V . exp(t1*L) . r1) / stat
When normalize this posterior distribution (to sum to 1), divide by stat,
and transform by t(V) -- this is the "profile" of internal nodes
To eliminate the O(N**2) step of transforming by t(V), if the posterior
distribution of an amino acid is near 1 then we can approximate it by
P(i) ~= (i==A) * w + nearP(i) * (1-w), where
w is fit so that P(i==A) is correct
nearP = Posterior(i | i, i, 0.1, 0.1) [0.1 is an arbitrary choice]
and we confirm that the approximation works well before we use it.
Given this parameter w we can set
rotated_posterior = rotation(w * (i==A)/stat + (1-w) * nearP/stat)
= codeFreq(A) * w/stat(A) + nearFreq(A) * (1-w)
*/
typedef struct {
numeric_t stat[MAXCODES]; /* The stationary distribution */
numeric_t statinv[MAXCODES]; /* 1/stat */
/* the eigenmatrix, with the eigenvectors as columns and rotations of individual
characters as rows. Also includes a NOCODE entry for gaps */
numeric_t codeFreq[NOCODE+1][MAXCODES];
numeric_t eigeninv[MAXCODES][MAXCODES]; /* Inverse of eigenmatrix */
numeric_t eigeninvT[MAXCODES][MAXCODES]; /* transpose of eigeninv */
numeric_t eigenval[MAXCODES]; /* Eigenvalues */
/* These are for approximate posteriors (off by default) */
numeric_t nearP[MAXCODES][MAXCODES]; /* nearP[i][j] = P(parent=j | both children are i, both lengths are 0.1 */
numeric_t nearFreq[MAXCODES][MAXCODES]; /* rotation of nearP/stat */
} transition_matrix_t;
typedef struct {
int nRateCategories;
numeric_t *rates; /* 1 per rate category */
unsigned int *ratecat; /* 1 category per position */
} rates_t;
typedef struct {
/* The input */
int nSeq;
int nPos;
char **seqs; /* the aligment sequences array (not reallocated) */
distance_matrix_t *distance_matrix; /* a pointer (not reallocated), or NULL if using %identity distance */
transition_matrix_t *transmat; /* a pointer (is allocated), or NULL for Jukes-Cantor */
/* Topological constraints are represented for each sequence as binary characters
with values of '0', '1', or '-' (for missing data)
Sequences that have no constraint may have a NULL string
*/
int nConstraints;
char **constraintSeqs;
/* The profile data structures */
int maxnode; /* The next index to allocate */
int maxnodes; /* Space allocated in data structures below */
profile_t **profiles; /* Profiles of leaves and intermediate nodes */
numeric_t *diameter; /* To correct for distance "up" from children (if any) */
numeric_t *varDiameter; /* To correct variances for distance "up" */
numeric_t *selfdist; /* Saved for use in some formulas */
numeric_t *selfweight; /* Saved for use in some formulas */
/* Average profile of all active nodes, the "outprofile"
* If all inputs are ungapped, this has weight 1 (not nSequences) at each position
* The frequencies all sum to one (or that is implied by the eigen-representation)
*/
profile_t *outprofile;
double totdiam;
/* We sometimes use stale out-distances, so we remember what nActive was */
numeric_t *outDistances; /* Sum of distances to other active (parent==-1) nodes */
int *nOutDistActive; /* What nActive was when this outDistance was computed */
/* the inferred tree */
int root; /* index of the root. Unlike other internal nodes, it has 3 children */
int *parent; /* -1 or index of parent */
children_t *child;
numeric_t *branchlength; /* Distance to parent */
numeric_t *support; /* 1 for high-confidence nodes */
/* auxilliary data for maximum likelihood (defaults to 1 category of rate=1.0) */
rates_t rates;
} NJ_t;
/* Uniquify sequences in an alignment -- map from indices
in the alignment to unique indicies in a NJ_t
*/
typedef struct {
int nSeq;
int nUnique;
int *uniqueFirst; /* iUnique -> iAln */
int *alnNext; /* iAln -> next, or -1 */
int *alnToUniq; /* iAln -> iUnique, or -1 if another was the exemplar */
char **uniqueSeq; /* indexed by iUniq -- points to strings allocated elsewhere */
} uniquify_t;
/* Describes which switch to do */
typedef enum {ABvsCD,ACvsBD,ADvsBC} nni_t;
/* A list of these describes a chain of NNI moves in a rooted tree,
making up, in total, an SPR move
*/
typedef struct {
int nodes[2];
double deltaLength; /* change in tree length for this step (lower is better) */
} spr_step_t;
/* Keep track of hits for the top-hits heuristic without wasting memory
j = -1 means empty
If j is an inactive node, this may be replaced by that node's parent (and dist recomputed)
*/
typedef struct {
int j;
numeric_t dist;
} hit_t;
typedef struct {
int nHits; /* the allocated and desired size; some of them may be empty */
hit_t *hits;
int hitSource; /* where to refresh hits from if a 2nd-level top-hit list, or -1 */
int age; /* number of joins since a refresh */
} top_hits_list_t;
typedef struct {
int m; /* size of a full top hits list, usually sqrt(N) */
int q; /* size of a 2nd-level top hits, usually sqrt(m) */
int maxnodes;
top_hits_list_t *top_hits_lists; /* one per node */
hit_t *visible; /* the "visible" (very best) hit for each node */
/* The top-visible set is a subset, usually of size m, of the visible set --
it is the set of joins to select from
Each entry is either a node whose visible set entry has a good (low) criterion,
or -1 for empty, or is an obsolete node (which is effectively the same).
Whenever we update the visible set, should also call UpdateTopVisible()
which ensures that none of the topvisible set are stale (that is, they
all point to an active node).
*/
int nTopVisible; /* nTopVisible = m * topvisibleMult */
int *topvisible;
int topvisibleAge; /* joins since the top-visible list was recomputed */
#ifdef OPENMP
/* 1 lock to read or write any top hits list, no thread grabs more than one */
omp_lock_t *locks;
#endif
} top_hits_t;
/* Global variables */
/* Options */
int verbose = 1;
int showProgress = 1;
int slow = 0;
int fastest = 0;
bool useTopHits2nd = false; /* use the second-level top hits heuristic? */
int bionj = 0;
double tophitsMult = 1.0; /* 0 means compare nodes to all other nodes */
double tophitsClose = -1.0; /* Parameter for how close is close; also used as a coverage req. */
double topvisibleMult = 1.5; /* nTopVisible = m * topvisibleMult; 1 or 2 did not make much difference
in either running time or accuracy so I chose a compromise. */
double tophitsRefresh = 0.8; /* Refresh if fraction of top-hit-length drops to this */
double tophits2Mult = 1.0; /* Second-level top heuristic -- only with -fastest */
int tophits2Safety = 3; /* Safety factor for second level of top-hits heuristic */
double tophits2Refresh = 0.6; /* Refresh 2nd-level top hits if drops down to this fraction of length */
double staleOutLimit = 0.01; /* nActive changes by at most this amount before we recompute
an out-distance. (Only applies if using the top-hits heuristic) */
double fResetOutProfile = 0.02; /* Recompute out profile from scratch if nActive has changed
by more than this proportion, and */
int nResetOutProfile = 200; /* nActive has also changed more than this amount */
int nCodes=20; /* 20 if protein, 4 if nucleotide */
bool useMatrix=true; /* If false, use %different as the uncorrected distance */
bool logdist = true; /* If true, do a log-correction (scoredist-like or Jukes-Cantor)
but only during NNIs and support values, not during neighbor-joining */
double pseudoWeight = 0.0; /* The weight of pseudocounts to avoid artificial long branches when
nearby sequences in the tree have little or no overlap
(off by default). The prior distance is based on
all overlapping positions among the quartet or triplet under
consideration. The log correction takes place after the
pseudocount is used. */
double constraintWeight = 100.0;/* Cost of violation of a topological constraint in evolutionary distance
or likelihood */
double MEMinDelta = 1.0e-4; /* Changes of less than this in tree-length are discounted for
purposes of identifying fixed subtrees */
bool fastNNI = true;
bool gammaLogLk = false; /* compute gamma likelihood without reoptimizing branch lengths? */
/* Maximum likelihood options and constants */
/* These are used to rescale likelihood values and avoid taking a logarithm at each position */
const double LkUnderflow = 1.0e-4;
const double LkUnderflowInv = 1.0e4;
const double LogLkUnderflow = 9.21034037197618; /* -log(LkUnderflowInv) */
const double Log2 = 0.693147180559945;
/* These are used to limit the optimization of branch lengths.
Also very short branch lengths can create numerical problems.
In version 2.1.7, the minimum branch lengths (MLMinBranchLength and MLMinRelBranchLength)
were increased to prevent numerical problems in rare cases.
In version 2.1.8, to provide useful branch lengths for genome-wide alignments,
the minimum branch lengths were dramatically decreased if USE_DOUBLE is defined.
*/
#ifndef USE_DOUBLE
const double MLMinBranchLengthTolerance = 1.0e-4; /* absolute tolerance for optimizing branch lengths */
const double MLFTolBranchLength = 0.001; /* fractional tolerance for optimizing branch lengths */
const double MLMinBranchLength = 5.0e-4; /* minimum value for branch length */
const double MLMinRelBranchLength = 2.5e-4; /* minimum of rate * length */
const double fPostTotalTolerance = 1.0e-10; /* posterior vector must sum to at least this before rescaling */
#else
const double MLMinBranchLengthTolerance = 1.0e-9;
const double MLFTolBranchLength = 0.001;
const double MLMinBranchLength = 5.0e-9;
const double MLMinRelBranchLength = 2.5e-9;
const double fPostTotalTolerance = 1.0e-20;
#endif
int mlAccuracy = 1; /* Rounds of optimization of branch lengths; 1 means do 2nd round only if close */
double closeLogLkLimit = 5.0; /* If partial optimization of an NNI looks like it would decrease the log likelihood
by this much or more then do not optimize it further */
double treeLogLkDelta = 0.1; /* Give up if tree log-lk changes by less than this; NNIs that change
likelihood by less than this also are considered unimportant
by some heuristics */
bool exactML = true; /* Exact or approximate posterior distributions for a.a.s */
double approxMLminf = 0.95; /* Only try to approximate posterior distributions if max. value is at least this high */
double approxMLminratio = 2/3.0;/* Ratio of approximated/true posterior values must be at least this high */
double approxMLnearT = 0.2; /* 2nd component of near-constant posterior distribution uses this time scale */
const int nDefaultRateCats = 20;
/* Performance and memory usage */
long profileOps = 0; /* Full profile-based distance operations */
long outprofileOps = 0; /* How many of profileOps are comparisons to outprofile */
long seqOps = 0; /* Faster leaf-based distance operations */
long profileAvgOps = 0; /* Number of profile-average steps */
long nHillBetter = 0; /* Number of hill-climbing steps */
long nCloseUsed = 0; /* Number of "close" neighbors we avoid full search for */
long nClose2Used = 0; /* Number of "close" neighbors we use 2nd-level top hits for */
long nRefreshTopHits = 0; /* Number of full-blown searches (interior nodes) */
long nVisibleUpdate = 0; /* Number of updates of the visible set */
long nNNI = 0; /* Number of NNI changes performed */
long nSPR = 0; /* Number of SPR changes performed */
long nML_NNI = 0; /* Number of max-lik. NNI changes performed */
long nSuboptimalSplits = 0; /* # of splits that are rejected given final tree (during bootstrap) */
long nSuboptimalConstrained = 0; /* Bad splits that are due to constraints */
long nConstraintViolations = 0; /* Number of constraint violations */
long nProfileFreqAlloc = 0;
long nProfileFreqAvoid = 0;
long szAllAlloc = 0;
long mymallocUsed = 0; /* useful allocations by mymalloc */
long maxmallocHeap = 0; /* Maximum of mi.arena+mi.hblkhd from mallinfo (actual mem usage) */
long nLkCompute = 0; /* # of likelihood computations for pairs of probability vectors */
long nPosteriorCompute = 0; /* # of computations of posterior probabilities */
long nAAPosteriorExact = 0; /* # of times compute exact AA posterior */
long nAAPosteriorRough = 0; /* # of times use rough approximation */
long nStarTests = 0; /* # of times we use star test to avoid testing an NNI */
/* Protein character set */
unsigned char *codesStringAA = (unsigned char*) "ARNDCQEGHILKMFPSTWYV";
unsigned char *codesStringNT = (unsigned char*) "ACGT";
unsigned char *codesString = NULL;
distance_matrix_t *ReadDistanceMatrix(char *prefix);
void SetupDistanceMatrix(/*IN/OUT*/distance_matrix_t *); /* set eigentot, codeFreq, gapFreq */
void ReadMatrix(char *filename, /*OUT*/numeric_t codes[MAXCODES][MAXCODES], bool check_codes);
void ReadVector(char *filename, /*OUT*/numeric_t codes[MAXCODES]);
alignment_t *ReadAlignment(/*READ*/FILE *fp, bool bQuote); /* Returns a list of strings (exits on failure) */
alignment_t *FreeAlignment(alignment_t *); /* returns NULL */
void FreeAlignmentSeqs(/*IN/OUT*/alignment_t *);
/* Takes as input the transpose of the matrix V, with i -> j
This routine takes care of setting the diagonals
*/
transition_matrix_t *CreateTransitionMatrix(/*IN*/double matrix[MAXCODES][MAXCODES],
/*IN*/double stat[MAXCODES]);
transition_matrix_t *CreateGTR(double *gtrrates/*ac,ag,at,cg,ct,gt*/, double *gtrfreq/*ACGT*/);
transition_matrix_t *ReadAATransitionMatrix(/*IN*/char *filename);
/* For converting profiles from 1 rotation to another, or converts NULL to NULL */
distance_matrix_t *TransMatToDistanceMat(transition_matrix_t *transmat);
/* Allocates memory, initializes leaf profiles */
NJ_t *InitNJ(char **sequences, int nSeqs, int nPos,
/*IN OPTIONAL*/char **constraintSeqs, int nConstraints,
/*IN OPTIONAL*/distance_matrix_t *,
/*IN OPTIONAL*/transition_matrix_t *);
NJ_t *FreeNJ(NJ_t *NJ); /* returns NULL */
void FastNJ(/*IN/OUT*/NJ_t *NJ); /* Does the joins */
void ReliabilityNJ(/*IN/OUT*/NJ_t *NJ, int nBootstrap); /* Estimates the reliability of the joins */
/* nni_stats_t is meaningless for leaves and root, so all of those entries
will just be high (for age) or 0 (for delta)
*/
typedef struct {
int age; /* number of rounds since this node was modified by an NNI */
int subtreeAge; /* number of rounds since self or descendent had a significant improvement */
double delta; /* improvement in score for this node (or 0 if no change) */
double support; /* improvement of score for self over better of alternatives */
} nni_stats_t;
/* One round of nearest-neighbor interchanges according to the
minimum-evolution or approximate maximum-likelihood criterion.
If doing maximum likelihood then this modifies the branch lengths.
age is the # of rounds since a node was NNId
Returns the # of topological changes performed
*/
int NNI(/*IN/OUT*/NJ_t *NJ, int iRound, int nRounds, bool useML,
/*IN/OUT*/nni_stats_t *stats,
/*OUT*/double *maxDeltaCriterion);
nni_stats_t *InitNNIStats(NJ_t *NJ);
nni_stats_t *FreeNNIStats(nni_stats_t *, NJ_t *NJ); /* returns NULL */
/* One round of subtree-prune-regraft moves (minimum evolution) */
void SPR(/*IN/OUT*/NJ_t *NJ, int maxSPRLength, int iRound, int nRounds);
/* Recomputes all branch lengths by minimum evolution criterion*/
void UpdateBranchLengths(/*IN/OUT*/NJ_t *NJ);
/* Recomputes all branch lengths and, optionally, internal profiles */
double TreeLength(/*IN/OUT*/NJ_t *NJ, bool recomputeProfiles);
typedef struct {
int nBadSplits;
int nConstraintViolations;
int nBadBoth;
int nSplits;
/* How much length would be reduce or likelihood would be increased by the
best NNI we find (the worst "miss") */
double dWorstDeltaUnconstrained;
double dWorstDeltaConstrained;
} SplitCount_t;
void TestSplitsMinEvo(NJ_t *NJ, /*OUT*/SplitCount_t *splitcount);
/* Sets SH-like support values if nBootstrap>0 */
void TestSplitsML(/*IN/OUT*/NJ_t *NJ, /*OUT*/SplitCount_t *splitcount, int nBootstrap);
/* Pick columns for resampling, stored as returned_vector[iBoot*nPos + j] */
int *ResampleColumns(int nPos, int nBootstrap);
/* Use out-profile and NJ->totdiam to recompute out-distance for node iNode
Only does this computation if the out-distance is "stale" (nOutDistActive[iNode] != nActive)
Note "IN/UPDATE" for NJ always means that we may update out-distances but otherwise
make no changes.
*/
void SetOutDistance(/*IN/UPDATE*/NJ_t *NJ, int iNode, int nActive);
/* Always sets join->criterion; may update NJ->outDistance and NJ->nOutDistActive,
assumes join's weight and distance are already set,
and that the constraint penalty (if any) is included in the distance
*/
void SetCriterion(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join);
/* Computes weight and distance (which includes the constraint penalty)
and then sets the criterion (maybe update out-distances)
*/
void SetDistCriterion(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join);
/* If join->i or join->j are inactive nodes, replaces them with their active ancestors.
After doing this, if i == j, or either is -1, sets weight to 0 and dist and criterion to 1e20
and returns false (not a valid join)
Otherwise, if i or j changed, recomputes the distance and criterion.
Note that if i and j are unchanged then the criterion could be stale
If bUpdateDist is false, and i or j change, then it just sets dist to a negative number
*/
bool UpdateBestHit(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join,
bool bUpdateDist);
/* This recomputes the criterion, or returns false if the visible node
is no longer active.
*/
bool GetVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits,
int iNode, /*OUT*/besthit_t *visible);
int ActiveAncestor(/*IN*/NJ_t *NJ, int node);
/* Compute the constraint penalty for a join. This is added to the "distance"
by SetCriterion */
int JoinConstraintPenalty(/*IN*/NJ_t *NJ, int node1, int node2);
int JoinConstraintPenaltyPiece(NJ_t *NJ, int node1, int node2, int iConstraint);
/* Helper function for computing the number of constraints violated by
a split, represented as counts of on and off on each side */
int SplitConstraintPenalty(int nOn1, int nOff1, int nOn2, int nOff2);
/* Reports the (min. evo.) support for the (1,2) vs. (3,4) split
col[iBoot*nPos+j] is column j for bootstrap iBoot
*/
double SplitSupport(profile_t *p1, profile_t *p2, profile_t *p3, profile_t *p4,
/*OPTIONAL*/distance_matrix_t *dmat,
int nPos,
int nBootstrap,
int *col);
/* Returns SH-like support given resampling spec. (in col) and site likelihods
for the three quartets
*/
double SHSupport(int nPos, int nBoostrap, int *col, double loglk[3], double *site_likelihoods[3]);
profile_t *SeqToProfile(/*IN/OUT*/NJ_t *NJ,
char *seq, int nPos,
/*OPTIONAL*/char *constraintSeqs, int nConstraints,
int iNode,
unsigned long counts[256]);
/* ProfileDist and SeqDist only set the dist and weight fields
If using an outprofile, use the second argument of ProfileDist
for better performance.
These produce uncorrected distances.
*/
void ProfileDist(profile_t *profile1, profile_t *profile2, int nPos,
/*OPTIONAL*/distance_matrix_t *distance_matrix,
/*OUT*/besthit_t *hit);
void SeqDist(unsigned char *codes1, unsigned char *codes2, int nPos,
/*OPTIONAL*/distance_matrix_t *distance_matrix,
/*OUT*/besthit_t *hit);
/* Computes all pairs of profile distances, applies pseudocounts
if pseudoWeight > 0, and applies log-correction if logdist is true.
The lower index is compared to the higher index, e.g. for profiles
A,B,C,D the comparison will be as in quartet_pair_t
*/
typedef enum {qAB,qAC,qAD,qBC,qBD,qCD} quartet_pair_t;
void CorrectedPairDistances(profile_t **profiles, int nProfiles,
/*OPTIONAL*/distance_matrix_t *distance_matrix,
int nPos,
/*OUT*/double *distances);
/* output is indexed by nni_t
To ensure good behavior while evaluating a subtree-prune-regraft move as a series
of nearest-neighbor interchanges, this uses a distance-ish model of constraints,
as given by PairConstraintDistance(), rather than
counting the number of violated splits (which is what FastTree does
during neighbor-joining).
Thus, penalty values may well be >0 even if no constraints are violated, but the
relative scores for the three NNIs will be correct.
*/
void QuartetConstraintPenalties(profile_t *profiles[4], int nConstraints, /*OUT*/double d[3]);
double PairConstraintDistance(int nOn1, int nOff1, int nOn2, int nOff2);
/* the split is consistent with the constraint if any of the profiles have no data
or if three of the profiles have the same uniform value (all on or all off)
or if AB|CD = 00|11 or 11|00 (all uniform)
*/
bool SplitViolatesConstraint(profile_t *profiles[4], int iConstraint);
/* If false, no values were set because this constraint was not relevant.
output is for the 3 splits
*/
bool QuartetConstraintPenaltiesPiece(profile_t *profiles[4], int iConstraint, /*OUT*/double penalty[3]);
/* Apply Jukes-Cantor or scoredist-like log(1-d) transform
to correct the distance for multiple substitutions.
*/
double LogCorrect(double distance);
/* AverageProfile is used to do a weighted combination of nodes
when doing a join. If weight is negative, then the value is ignored and the profiles
are averaged. The weight is *not* adjusted for the gap content of the nodes.
Also, the weight does not affect the representation of the constraints
*/
profile_t *AverageProfile(profile_t *profile1, profile_t *profile2,
int nPos, int nConstraints,
distance_matrix_t *distance_matrix,
double weight1);
/* PosteriorProfile() is like AverageProfile() but it computes posterior probabilities
rather than an average
*/
profile_t *PosteriorProfile(profile_t *profile1, profile_t *profile2,
double len1, double len2,
/*OPTIONAL*/transition_matrix_t *transmat,
rates_t *rates,
int nPos, int nConstraints);
/* Set a node's profile from its children.
Deletes the previous profile if it exists
Use -1.0 for a balanced join
Fails unless the node has two children (e.g., no leaves or root)
*/
void SetProfile(/*IN/OUT*/NJ_t *NJ, int node, double weight1);
/* OutProfile does an unweighted combination of nodes to create the
out-profile. It always sets code to NOCODE so that UpdateOutProfile
can work.
*/
profile_t *OutProfile(profile_t **profiles, int nProfiles,
int nPos, int nConstraints,
distance_matrix_t *distance_matrix);
void UpdateOutProfile(/*UPDATE*/profile_t *out, profile_t *old1, profile_t *old2,
profile_t *new, int nActiveOld,
int nPos, int nConstraints,
distance_matrix_t *distance_matrix);
profile_t *NewProfile(int nPos, int nConstraints); /* returned has no vectors */
profile_t *FreeProfile(profile_t *profile, int nPos, int nConstraints); /* returns NULL */
void AllocRateCategories(/*IN/OUT*/rates_t *rates, int nRateCategories, int nPos);
/* f1 can be NULL if code1 != NOCODE, and similarly for f2
Or, if (say) weight1 was 0, then can have code1==NOCODE *and* f1==NULL
In that case, returns an arbitrary large number.
*/
double ProfileDistPiece(unsigned int code1, unsigned int code2,
numeric_t *f1, numeric_t *f2,
/*OPTIONAL*/distance_matrix_t *dmat,
/*OPTIONAL*/numeric_t *codeDist2);
/* Adds (or subtracts, if weight is negative) fIn/codeIn from fOut
fOut is assumed to exist (as from an outprofile)
do not call unless weight of input profile > 0
*/
void AddToFreq(/*IN/OUT*/numeric_t *fOut, double weight,
unsigned int codeIn, /*OPTIONAL*/numeric_t *fIn,
/*OPTIONAL*/distance_matrix_t *dmat);
/* Divide the vector (of length nCodes) by a constant
so that the total (unrotated) frequency is 1.0 */
void NormalizeFreq(/*IN/OUT*/numeric_t *freq, distance_matrix_t *distance_matrix);
/* Allocate, if necessary, and recompute the codeDist*/
void SetCodeDist(/*IN/OUT*/profile_t *profile, int nPos, distance_matrix_t *dmat);
/* The allhits list contains the distances of the node to all other active nodes
This is useful for the "reset" improvement to the visible set
Note that the following routines do not handle the tophits heuristic
and assume that out-distances are up to date.
*/
void SetBestHit(int node, NJ_t *NJ, int nActive,
/*OUT*/besthit_t *bestjoin,
/*OUT OPTIONAL*/besthit_t *allhits);
void ExhaustiveNJSearch(NJ_t *NJ, int nActive, /*OUT*/besthit_t *bestjoin);
/* Searches the visible set */
void FastNJSearch(NJ_t *NJ, int nActive, /*UPDATE*/besthit_t *visible, /*OUT*/besthit_t *bestjoin);
/* Subroutines for handling the tophits heuristic */
top_hits_t *InitTopHits(NJ_t *NJ, int m);
top_hits_t *FreeTopHits(top_hits_t *tophits); /* returns NULL */
/* Before we do any joins -- sets tophits and visible
NJ may be modified by setting out-distances
*/
void SetAllLeafTopHits(/*IN/UPDATE*/NJ_t *NJ, /*IN/OUT*/top_hits_t *tophits);
/* Find the best join to do. */
void TopHitNJSearch(/*IN/UPDATE*/NJ_t *NJ,
int nActive,
/*IN/OUT*/top_hits_t *tophits,
/*OUT*/besthit_t *bestjoin);
/* Returns the best hit within top hits
NJ may be modified because it updates out-distances if they are too stale
Does *not* update visible set
*/
void GetBestFromTopHits(int iNode, /*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN*/top_hits_t *tophits,
/*OUT*/besthit_t *bestjoin);
/* visible set is modifiable so that we can reset it more globally when we do
a "refresh", but we also set the visible set for newnode and do any
"reset" updates too. And, we update many outdistances.
*/
void TopHitJoin(int newnode,
/*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN/OUT*/top_hits_t *tophits);
/* Sort the input besthits by criterion
and save the best nOut hits as a new array in top_hits_lists
Does not update criterion or out-distances
Ignores (silently removes) hit to self
Saved list may be shorter than requested if there are insufficient entries
*/
void SortSaveBestHits(int iNode, /*IN/SORT*/besthit_t *besthits,
int nIn, int nOut,
/*IN/OUT*/top_hits_t *tophits);
/* Given candidate hits from one node, "transfer" them to another node:
Stores them in a new place in the same order
searches up to active nodes if hits involve non-active nodes
If update flag is set, it also recomputes distance and criterion
(and ensures that out-distances are updated); otherwise
it sets dist to -1e20 and criterion to 1e20
*/
void TransferBestHits(/*IN/UPDATE*/NJ_t *NJ, int nActive,
int iNode,
/*IN*/besthit_t *oldhits,
int nOldHits,
/*OUT*/besthit_t *newhits,
bool updateDistance);
/* Create best hit objects from 1 or more hits. Do not update out-distances or set criteria */
void HitsToBestHits(/*IN*/hit_t *hits, int nHits, int iNode, /*OUT*/besthit_t *newhits);
besthit_t HitToBestHit(int i, hit_t hit);
/* Given a set of besthit entries,
look for improvements to the visible set of the j entries.
Updates out-distances as it goes.
Also replaces stale nodes with this node, because a join is usually
how this happens (i.e. it does not need to walk up to ancestors).
Note this calls UpdateTopVisible() on any change
*/
void UpdateVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN*/besthit_t *tophitsNode,
int nTopHits,
/*IN/OUT*/top_hits_t *tophits);
/* Update the top-visible list to perhaps include this hit (O(sqrt(N)) time) */
void UpdateTopVisible(/*IN*/NJ_t * NJ, int nActive,
int iNode, /*IN*/hit_t *hit,
/*IN/OUT*/top_hits_t *tophits);
/* Recompute the top-visible subset of the visible set */
void ResetTopVisible(/*IN/UPDATE*/NJ_t *NJ,
int nActive,
/*IN/OUT*/top_hits_t *tophits);
/* Make a shorter list with only unique entries.
Replaces any "dead" hits to nodes that have parents with their active ancestors
and ignores any that become dead.
Updates all criteria.
Combined gets sorted by i & j
The returned list is allocated to nCombined even though only *nUniqueOut entries are filled
*/
besthit_t *UniqueBestHits(/*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN/SORT*/besthit_t *combined, int nCombined,
/*OUT*/int *nUniqueOut);
nni_t ChooseNNI(profile_t *profiles[4],
/*OPTIONAL*/distance_matrix_t *dmat,
int nPos, int nConstraints,
/*OUT*/double criteria[3]); /* The three internal branch lengths or log likelihoods*/
/* length[] is ordered as described by quartet_length_t, but after we do the swap
of B with C (to give AC|BD) or B with D (to get AD|BC), if that is the returned choice
bFast means do not consider NNIs if AB|CD is noticeably better than the star topology
(as implemented by MLQuartetOptimize).
If there are constraints, then the constraint penalty is included in criteria[]
*/
nni_t MLQuartetNNI(profile_t *profiles[4],
/*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
int nPos, int nConstraints,
/*OUT*/double criteria[3], /* The three potential quartet log-likelihoods */
/*IN/OUT*/numeric_t length[5],
bool bFast);
void OptimizeAllBranchLengths(/*IN/OUT*/NJ_t *NJ);
double TreeLogLk(/*IN*/NJ_t *NJ, /*OPTIONAL OUT*/double *site_loglk);
double MLQuartetLogLk(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD,
int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
/*IN*/double branch_lengths[5],
/*OPTIONAL OUT*/double *site_likelihoods);
/* Given a topology and branch lengths, estimate rates & recompute profiles */
void SetMLRates(/*IN/OUT*/NJ_t *NJ, int nRateCategories);
/* Returns a set of nRateCategories potential rates; the caller must free it */
numeric_t *MLSiteRates(int nRateCategories);
/* returns site_loglk so that
site_loglk[nPos*iRate + j] is the log likelihood of site j with rate iRate
The caller must free it.
*/
double *MLSiteLikelihoodsByRate(/*IN*/NJ_t *NJ, /*IN*/numeric_t *rates, int nRateCategories);
typedef struct {
double mult; /* multiplier for the rates / divisor for the tree-length */
double alpha;
int nPos;
int nRateCats;
numeric_t *rates;
double *site_loglk;
} siteratelk_t;
double GammaLogLk(/*IN*/siteratelk_t *s, /*OPTIONAL OUT*/double *gamma_loglk_sites);
/* Input site_loglk must be for each rate. Note that FastTree does not reoptimize
the branch lengths under the Gamma model -- it optimizes the overall scale.
Reports the gamma log likelihhod (and logs site likelihoods if fpLog is set),
and reports the rescaling value.
*/
double RescaleGammaLogLk(int nPos, int nRateCats,
/*IN*/numeric_t *rates, /*IN*/double *site_loglk,
/*OPTIONAL*/FILE *fpLog);
/* P(value<=x) for the gamma distribution with shape parameter alpha and scale 1/alpha */
double PGamma(double x, double alpha);
/* Given a topology and branch lengths, optimize GTR rates and quickly reoptimize branch lengths
If gtrfreq is NULL, then empirical frequencies are used
*/
void SetMLGtr(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL IN*/double *gtrfreq, /*OPTIONAL WRITE*/FILE *fpLog);
/* P(A & B | len) = P(B | A, len) * P(A)
If site_likelihoods is present, multiplies those values by the site likelihood at each point
(Note it does not handle underflow)
*/
double PairLogLk(/*IN*/profile_t *p1, /*IN*/profile_t *p2, double length,
int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
/*OPTIONAL IN/OUT*/double *site_likelihoods);
/* Branch lengths for 4-taxon tree ((A,B),C,D); I means internal */
typedef enum {LEN_A,LEN_B,LEN_C,LEN_D,LEN_I} quartet_length_t;
typedef struct {
int nPos;
transition_matrix_t *transmat;
rates_t *rates;
int nEval; /* number of likelihood evaluations */
/* The pair to optimize */
profile_t *pair1;
profile_t *pair2;
} quartet_opt_t;
double PairNegLogLk(double x, void *data); /* data must be a quartet_opt_t */
typedef struct {
NJ_t *NJ;
double freq[4];
double rates[6];
int iRate; /* which rate to set x from */
FILE *fpLog; /* OPTIONAL WRITE */
} gtr_opt_t;
/* Returns -log_likelihood for the tree with the given rates
data must be a gtr_opt_t and x is used to set rate iRate
Does not recompute profiles -- assumes that the caller will
*/
double GTRNegLogLk(double x, void *data);
/* Returns the resulting log likelihood. Optionally returns whether other
topologies should be abandoned, based on the difference between AB|CD and
the "star topology" (AB|CD with a branch length of MLMinBranchLength) exceeding
closeLogLkLimit.
If bStarTest is passed in, it only optimized the internal branch if
the star test is true. Otherwise, it optimized all 5 branch lengths
in turn.
*/
double MLQuartetOptimize(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD,
int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
/*IN/OUT*/double branch_lengths[5],
/*OPTIONAL OUT*/bool *pStarTest,
/*OPTIONAL OUT*/double *site_likelihoods);
/* Returns the resulting log likelihood */
double MLPairOptimize(profile_t *pA, profile_t *pB,
int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
/*IN/OUT*/double *branch_length);
/* Returns the number of steps considered, with the actual steps in steps[]
Modifies the tree by this chain of NNIs
*/
int FindSPRSteps(/*IN/OUT*/NJ_t *NJ,
int node,
int parent, /* sibling or parent of node to NNI to start the chain */
/*IN/OUT*/profile_t **upProfiles,
/*OUT*/spr_step_t *steps,
int maxSteps,
bool bFirstAC);
/* Undo a single NNI */
void UnwindSPRStep(/*IN/OUT*/NJ_t *NJ,
/*IN*/spr_step_t *step,
/*IN/OUT*/profile_t **upProfiles);
/* Update the profile of node and its ancestor, and delete nearby out-profiles */
void UpdateForNNI(/*IN/OUT*/NJ_t *NJ, int node, /*IN/OUT*/profile_t **upProfiles, bool useML);
/* Sets NJ->parent[newchild] and replaces oldchild with newchild
in the list of children of parent
*/
void ReplaceChild(/*IN/OUT*/NJ_t *NJ, int parent, int oldchild, int newchild);
int CompareHitsByCriterion(const void *c1, const void *c2);
int CompareHitsByIJ(const void *c1, const void *c2);
int NGaps(NJ_t *NJ, int node); /* only handles leaf sequences */
/* node is the parent of AB, sibling of C
node cannot be root or a leaf
If node is the child of root, then D is the other sibling of node,
and the 4th profile is D's profile.
Otherwise, D is the parent of node, and we use its upprofile
Call this with profiles=NULL to get the nodes, without fetching or
computing profiles
*/
void SetupABCD(NJ_t *NJ, int node,
/* the 4 profiles for ABCD; the last one is an upprofile */
/*OPTIONAL OUT*/profile_t *profiles[4],
/*OPTIONAL IN/OUT*/profile_t **upProfiles,
/*OUT*/int nodeABCD[4],
bool useML);
int Sibling(NJ_t *NJ, int node); /* At root, no unique sibling so returns -1 */
void RootSiblings(NJ_t *NJ, int node, /*OUT*/int sibs[2]);
/* JC probability of nucleotide not changing, for each rate category */
double *PSameVector(double length, rates_t *rates);
/* JC probability of nucleotide not changing, for each rate category */
double *PDiffVector(double *pSame, rates_t *rates);
/* expeigen[iRate*nCodes + j] = exp(length * rate iRate * eigenvalue j) */
numeric_t *ExpEigenRates(double length, transition_matrix_t *transmat, rates_t *rates);
/* Print a progress report if more than 0.1 second has gone by since the progress report */
/* Format should include 0-4 %d references and no newlines */
void ProgressReport(char *format, int iArg1, int iArg2, int iArg3, int iArg4);
void LogTree(char *format, int round, /*OPTIONAL WRITE*/FILE *fp, NJ_t *NJ, char **names, uniquify_t *unique, bool bQuote);
void LogMLRates(/*OPTIONAL WRITE*/FILE *fpLog, NJ_t *NJ);
void *mymalloc(size_t sz); /* Prints "Out of memory" and exits on failure */
void *myfree(void *, size_t sz); /* Always returns NULL */
/* One-dimensional minimization using brent's function, with
a fractional and an absolute tolerance */
double onedimenmin(double xmin, double xguess, double xmax, double (*f)(double,void*), void *data,
double ftol, double atol,
/*OUT*/double *fx, /*OUT*/double *f2x);
double brent(double ax, double bx, double cx, double (*f)(double, void *), void *data,
double ftol, double atol,
double *foptx, double *f2optx, double fax, double fbx, double fcx);
/* Vector operations, either using SSE3 or not
Code assumes that vectors are a multiple of 4 in size
*/
void vector_multiply(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n, /*OUT*/numeric_t *fOut);
numeric_t vector_multiply_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n);
void vector_add_mult(/*IN/OUT*/numeric_t *f, /*IN*/numeric_t *add, numeric_t weight, int n);
/* multiply the transpose of a matrix by a vector */
void matrixt_by_vector4(/*IN*/numeric_t mat[4][MAXCODES], /*IN*/numeric_t vec[4], /*OUT*/numeric_t out[4]);
/* sum(f1*fBy)*sum(f2*fBy) */
numeric_t vector_dot_product_rot(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t* fBy, int n);
/* sum(f1*f2*f3) */
numeric_t vector_multiply3_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t* f3, int n);
numeric_t vector_sum(/*IN*/numeric_t *f1, int n);
void vector_multiply_by(/*IN/OUT*/numeric_t *f, /*IN*/numeric_t fBy, int n);
double clockDiff(/*IN*/struct timeval *clock_start);
int timeval_subtract (/*OUT*/struct timeval *result, /*IN*/struct timeval *x, /*IN*/struct timeval *y);
char *OpenMPString(void);
void ran_start(long seed);
double knuth_rand(); /* Random number between 0 and 1 */
void tred2 (double *a, const int n, const int np, double *d, double *e);
double pythag(double a, double b);
void tqli(double *d, double *e, int n, int np, double *z);
/* Like mymalloc; duplicates the input (returns NULL if given NULL) */
void *mymemdup(void *data, size_t sz);
void *myrealloc(void *data, size_t szOld, size_t szNew, bool bCopy);
double pnorm(double z); /* Probability(value <=z) */
/* Hashtable functions */
typedef struct
{
char *string;
int nCount; /* number of times this entry was seen */
int first; /* index of first entry with this value */
} hashbucket_t;
typedef struct {
int nBuckets;
/* hashvalue -> bucket. Or look in bucket + 1, +2, etc., till you hit a NULL string */
hashbucket_t *buckets;
} hashstrings_t;
typedef int hashiterator_t;
hashstrings_t *MakeHashtable(char **strings, int nStrings);
hashstrings_t *FreeHashtable(hashstrings_t* hash); /*returns NULL*/
hashiterator_t FindMatch(hashstrings_t *hash, char *string);
/* Return NULL if we have run out of values */
char *GetHashString(hashstrings_t *hash, hashiterator_t hi);
int HashCount(hashstrings_t *hash, hashiterator_t hi);
int HashFirst(hashstrings_t *hash, hashiterator_t hi);
void PrintNJ(/*WRITE*/FILE *, NJ_t *NJ, char **names, uniquify_t *unique, bool bShowSupport, bool bQuoteNames);
/* Print topology using node indices as node names */
void PrintNJInternal(/*WRITE*/FILE *, NJ_t *NJ, bool useLen);
uniquify_t *UniquifyAln(/*IN*/alignment_t *aln);
uniquify_t *FreeUniquify(uniquify_t *); /* returns NULL */
/* Convert a constraint alignment to a list of sequences. The returned array is indexed
by iUnique and points to values in the input alignment
*/
char **AlnToConstraints(alignment_t *constraints, uniquify_t *unique, hashstrings_t *hashnames);
/* ReadTree ignores non-unique leaves after the first instance.
At the end, it prunes the tree to ignore empty children and it
unroots the tree if necessary.
*/
void ReadTree(/*IN/OUT*/NJ_t *NJ,
/*IN*/uniquify_t *unique,
/*IN*/hashstrings_t *hashnames,
/*READ*/FILE *fpInTree);
char *ReadTreeToken(/*READ*/FILE *fp); /* returns a static array, or NULL on EOF */
void ReadTreeAddChild(int parent, int child, /*IN/OUT*/int *parents, /*IN/OUT*/children_t *children);
/* Do not add the leaf if we already set this unique-set to another parent */
void ReadTreeMaybeAddLeaf(int parent, char *name,
hashstrings_t *hashnames, uniquify_t *unique,
/*IN/OUT*/int *parents, /*IN/OUT*/children_t *children);
void ReadTreeRemove(/*IN/OUT*/int *parents, /*IN/OUT*/children_t *children, int node);
/* Routines to support tree traversal and prevent visiting a node >1 time
(esp. if topology changes).
*/
typedef bool *traversal_t;
traversal_t InitTraversal(NJ_t*);
void SkipTraversalInto(int node, /*IN/OUT*/traversal_t traversal);
traversal_t FreeTraversal(traversal_t, NJ_t*); /*returns NULL*/
/* returns new node, or -1 if nothing left to do. Use root for the first call.
Will return every node and then root.
Uses postorder tree traversal (depth-first search going down to leaves first)
Keeps track of which nodes are visited, so even after an NNI that swaps a
visited child with an unvisited uncle, the next call will visit the
was-uncle-now-child. (However, after SPR moves, there is no such guarantee.)
If pUp is not NULL, then, if going "back up" through a previously visited node
(presumably due to an NNI), then it will return the node another time,
with *pUp = true.
*/
int TraversePostorder(int lastnode, NJ_t *NJ, /*IN/OUT*/traversal_t,
/*OUT OPTIONAL*/bool *pUp);
/* Routines to support storing up-profiles during tree traversal
Eventually these should be smart enough to do weighted joins and
to minimize memory usage
*/
profile_t **UpProfiles(NJ_t *NJ);
profile_t *GetUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int node, bool useML);
profile_t *DeleteUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int node); /* returns NULL */
profile_t **FreeUpProfiles(profile_t **upProfiles, NJ_t *NJ); /* returns NULL */
/* Recomputes the profile for a node, presumably to reflect topology changes
If bionj is set, does a weighted join -- which requires using upProfiles
If useML is set, computes the posterior probability instead of averaging
*/
void RecomputeProfile(/*IN/OUT*/NJ_t *NJ, /*IN/OUT*/profile_t **upProfiles, int node, bool useML);
/* Recompute profiles going up from the leaves, using the provided distance matrix
and unweighted joins
*/
void RecomputeProfiles(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL*/distance_matrix_t *dmat);
void RecomputeMLProfiles(/*IN/OUT*/NJ_t *NJ);
/* If bionj is set, computes the weight to be given to A when computing the
profile for the ancestor of A and B. C and D are the other profiles in the quartet
If bionj is not set, returns -1 (which means unweighted in AverageProfile).
(A and B are the first two profiles in the array)
*/
double QuartetWeight(profile_t *profiles[4], distance_matrix_t *dmat, int nPos);
/* Returns a list of nodes, starting with node and ending with root */
int *PathToRoot(NJ_t *NJ, int node, /*OUT*/int *depth);
int *FreePath(int *path, NJ_t *NJ); /* returns NULL */
/* The default amino acid distance matrix, derived from the BLOSUM45 similarity matrix */
distance_matrix_t matrixBLOSUM45;
/* The default amino acid transition matrix (Jones Taylor Thorton 1992) */
double matrixJTT92[MAXCODES][MAXCODES];
double statJTT92[MAXCODES];
/* The Le-Gascuel 2008 amino acid transition matrix */
double matrixLG08[MAXCODES][MAXCODES];
double statLG08[MAXCODES];
/* The WAG amino acid transition matrix (Whelan-And-Goldman 2001) */
double matrixWAG01[MAXCODES][MAXCODES];
double statWAG01[MAXCODES];
int main(int argc, char **argv) {
int nAlign = 1; /* number of alignments to read */
int iArg;
char *matrixPrefix = NULL;
char *transitionFile = NULL;
distance_matrix_t *distance_matrix = NULL;
bool make_matrix = false;
char *constraintsFile = NULL;
char *intreeFile = NULL;
bool intree1 = false; /* the same starting tree each round */
int nni = -1; /* number of rounds of NNI, defaults to 4*log2(n) */
int spr = 2; /* number of rounds of SPR */
int maxSPRLength = 10; /* maximum distance to move a node */
int MLnni = -1; /* number of rounds of ML NNI, defaults to 2*log2(n) */
bool MLlen = false; /* optimize branch lengths; no topology changes */
int nBootstrap = 1000; /* If set, number of replicates of local bootstrap to do */
int nRateCats = nDefaultRateCats;
char *logfile = NULL;
bool bUseGtr = false;
bool bUseLg = false;
bool bUseWag = false;
bool bUseGtrRates = false;
double gtrrates[6] = {1,1,1,1,1,1};
bool bUseGtrFreq = false;
double gtrfreq[4] = {0.25,0.25,0.25,0.25};
bool bQuote = false;
FILE *fpOut = stdout;
if (isatty(STDIN_FILENO) && argc == 1) {
fprintf(stderr,"Usage for FastTree version %s %s%s:\n%s",
FT_VERSION, SSE_STRING, OpenMPString(), usage);
#if (defined _WIN32 || defined WIN32 || defined WIN64 || defined _WIN64)
fprintf(stderr, "Windows users: Please remember to run this inside a command shell\n");
fprintf(stderr,"Hit return to continue\n");
fgetc(stdin);
#endif
exit(0);
}
for (iArg = 1; iArg < argc; iArg++) {
if (strcmp(argv[iArg],"-makematrix") == 0) {
make_matrix = true;
} else if (strcmp(argv[iArg],"-logdist") == 0) {
fprintf(stderr, "Warning: logdist is now on by default and obsolete\n");
} else if (strcmp(argv[iArg],"-rawdist") == 0) {
logdist = false;
} else if (strcmp(argv[iArg],"-verbose") == 0 && iArg < argc-1) {
verbose = atoi(argv[++iArg]);
} else if (strcmp(argv[iArg],"-quiet") == 0) {
verbose = 0;
showProgress = 0;
} else if (strcmp(argv[iArg],"-nopr") == 0) {
showProgress = 0;
} else if (strcmp(argv[iArg],"-slow") == 0) {
slow = 1;
} else if (strcmp(argv[iArg],"-fastest") == 0) {
fastest = 1;
tophitsRefresh = 0.5;
useTopHits2nd = true;
} else if (strcmp(argv[iArg],"-2nd") == 0) {
useTopHits2nd = true;
} else if (strcmp(argv[iArg],"-no2nd") == 0) {
useTopHits2nd = false;
} else if (strcmp(argv[iArg],"-slownni") == 0) {
fastNNI = false;
} else if (strcmp(argv[iArg], "-matrix") == 0 && iArg < argc-1) {
iArg++;
matrixPrefix = argv[iArg];
} else if (strcmp(argv[iArg], "-nomatrix") == 0) {
useMatrix = false;
} else if (strcmp(argv[iArg], "-n") == 0 && iArg < argc-1) {
iArg++;
nAlign = atoi(argv[iArg]);
if (nAlign < 1) {
fprintf(stderr, "-n argument for #input alignments must be > 0 not %s\n", argv[iArg]);
exit(1);
}
} else if (strcmp(argv[iArg], "-quote") == 0) {
bQuote = true;
} else if (strcmp(argv[iArg], "-nt") == 0) {
nCodes = 4;
} else if (strcmp(argv[iArg], "-intree") == 0 && iArg < argc-1) {
iArg++;
intreeFile = argv[iArg];
} else if (strcmp(argv[iArg], "-intree1") == 0 && iArg < argc-1) {
iArg++;
intreeFile = argv[iArg];
intree1 = true;
} else if (strcmp(argv[iArg], "-nj") == 0) {
bionj = 0;
} else if (strcmp(argv[iArg], "-bionj") == 0) {
bionj = 1;
} else if (strcmp(argv[iArg], "-boot") == 0 && iArg < argc-1) {
iArg++;
nBootstrap = atoi(argv[iArg]);
} else if (strcmp(argv[iArg], "-noboot") == 0 || strcmp(argv[iArg], "-nosupport") == 0) {
nBootstrap = 0;
} else if (strcmp(argv[iArg], "-seed") == 0 && iArg < argc-1) {
iArg++;
long seed = atol(argv[iArg]);
ran_start(seed);
} else if (strcmp(argv[iArg],"-top") == 0) {
if(tophitsMult < 0.01)
tophitsMult = 1.0;
} else if (strcmp(argv[iArg],"-notop") == 0) {
tophitsMult = 0.0;
} else if (strcmp(argv[iArg], "-topm") == 0 && iArg < argc-1) {
iArg++;
tophitsMult = atof(argv[iArg]);
} else if (strcmp(argv[iArg], "-close") == 0 && iArg < argc-1) {
iArg++;
tophitsClose = atof(argv[iArg]);
if (tophitsMult <= 0) {
fprintf(stderr, "Cannot use -close unless -top is set above 0\n");
exit(1);
}
if (tophitsClose <= 0 || tophitsClose >= 1) {
fprintf(stderr, "-close argument must be between 0 and 1\n");
exit(1);
}
} else if (strcmp(argv[iArg], "-refresh") == 0 && iArg < argc-1) {
iArg++;
tophitsRefresh = atof(argv[iArg]);
if (tophitsMult <= 0) {
fprintf(stderr, "Cannot use -refresh unless -top is set above 0\n");
exit(1);
}
if (tophitsRefresh <= 0 || tophitsRefresh >= 1) {
fprintf(stderr, "-refresh argument must be between 0 and 1\n");
exit(1);
}
} else if (strcmp(argv[iArg],"-nni") == 0 && iArg < argc-1) {
iArg++;
nni = atoi(argv[iArg]);
if (nni == 0)
spr = 0;
} else if (strcmp(argv[iArg],"-spr") == 0 && iArg < argc-1) {
iArg++;
spr = atoi(argv[iArg]);
} else if (strcmp(argv[iArg],"-sprlength") == 0 && iArg < argc-1) {
iArg++;
maxSPRLength = atoi(argv[iArg]);
} else if (strcmp(argv[iArg],"-mlnni") == 0 && iArg < argc-1) {
iArg++;
MLnni = atoi(argv[iArg]);
} else if (strcmp(argv[iArg],"-noml") == 0) {
MLnni = 0;
} else if (strcmp(argv[iArg],"-mllen") == 0) {
MLnni = 0;
MLlen = true;
} else if (strcmp(argv[iArg],"-nome") == 0) {
spr = 0;
nni = 0;
} else if (strcmp(argv[iArg],"-help") == 0) {
fprintf(stderr,"FastTree %s %s%s:\n%s", FT_VERSION, SSE_STRING, OpenMPString(), usage);
exit(0);
} else if (strcmp(argv[iArg],"-expert") == 0) {
fprintf(stderr, "Detailed usage for FastTree %s %s%s:\n%s",
FT_VERSION, SSE_STRING, OpenMPString(), expertUsage);
exit(0);
} else if (strcmp(argv[iArg],"-pseudo") == 0) {
if (iArg < argc-1 && isdigit(argv[iArg+1][0])) {
iArg++;
pseudoWeight = atof(argv[iArg]);
if (pseudoWeight < 0.0) {
fprintf(stderr,"Illegal argument to -pseudo: %s\n", argv[iArg]);
exit(1);
}
} else {
pseudoWeight = 1.0;
}
} else if (strcmp(argv[iArg],"-constraints") == 0 && iArg < argc-1) {
iArg++;
constraintsFile = argv[iArg];
} else if (strcmp(argv[iArg],"-constraintWeight") == 0 && iArg < argc-1) {
iArg++;
constraintWeight = atof(argv[iArg]);
if (constraintWeight <= 0.0) {
fprintf(stderr, "Illegal argument to -constraintWeight (must be greater than zero): %s\n", argv[iArg]);
exit(1);
}
} else if (strcmp(argv[iArg],"-mlacc") == 0 && iArg < argc-1) {
iArg++;
mlAccuracy = atoi(argv[iArg]);
if (mlAccuracy < 1) {
fprintf(stderr, "Illlegal -mlacc argument: %s\n", argv[iArg]);
exit(1);
}
} else if (strcmp(argv[iArg],"-exactml") == 0 || strcmp(argv[iArg],"-mlexact") == 0) {
fprintf(stderr,"-exactml is not required -- exact posteriors is the default now\n");
} else if (strcmp(argv[iArg],"-approxml") == 0 || strcmp(argv[iArg],"-mlapprox") == 0) {
exactML = false;
} else if (strcmp(argv[iArg],"-cat") == 0 && iArg < argc-1) {
iArg++;
nRateCats = atoi(argv[iArg]);
if (nRateCats < 1) {
fprintf(stderr, "Illlegal argument to -ncat (must be greater than zero): %s\n", argv[iArg]);
exit(1);
}
} else if (strcmp(argv[iArg],"-nocat") == 0) {
nRateCats = 1;
} else if (strcmp(argv[iArg], "-lg") == 0) {
bUseLg = true;
} else if (strcmp(argv[iArg], "-wag") == 0) {
bUseWag = true;
} else if (strcmp(argv[iArg], "-gtr") == 0) {
bUseGtr = true;
} else if (strcmp(argv[iArg], "-trans") == 0 && iArg < argc-1) {
iArg++;
transitionFile = argv[iArg];
} else if (strcmp(argv[iArg], "-gtrrates") == 0 && iArg < argc-6) {
bUseGtr = true;
bUseGtrRates = true;
int i;
for (i = 0; i < 6; i++) {
gtrrates[i] = atof(argv[++iArg]);
if (gtrrates[i] < 1e-5) {
fprintf(stderr, "Illegal or too small value of GTR rate: %s\n", argv[iArg]);
exit(1);
}
}
} else if (strcmp(argv[iArg],"-gtrfreq") == 0 && iArg < argc-4) {
bUseGtr = true;
bUseGtrFreq = true;
int i;
double sum = 0;
for (i = 0; i < 4; i++) {
gtrfreq[i] = atof(argv[++iArg]);
sum += gtrfreq[i];
if (gtrfreq[i] < 1e-5) {
fprintf(stderr, "Illegal or too small value of GTR frequency: %s\n", argv[iArg]);
exit(1);
}
}
if (fabs(1.0-sum) > 0.01) {
fprintf(stderr, "-gtrfreq values do not sum to 1\n");
exit(1);
}
for (i = 0; i < 4; i++)
gtrfreq[i] /= sum;
} else if (strcmp(argv[iArg],"-log") == 0 && iArg < argc-1) {
iArg++;
logfile = argv[iArg];
} else if (strcmp(argv[iArg],"-gamma") == 0) {
gammaLogLk = true;
} else if (strcmp(argv[iArg],"-out") == 0 && iArg < argc-1) {
iArg++;
fpOut = fopen(argv[iArg],"w");
if(fpOut==NULL) {
fprintf(stderr,"Cannot write to %s\n",argv[iArg]);
exit(1);
}
} else if (argv[iArg][0] == '-') {
fprintf(stderr, "Unknown or incorrect use of option %s\n%s", argv[iArg], usage);
exit(1);
} else
break;
}
if(iArg < argc-1) {
fprintf(stderr, "%s", usage);
exit(1);
}
codesString = nCodes == 20 ? codesStringAA : codesStringNT;
if (nCodes == 4 && matrixPrefix == NULL)
useMatrix = false; /* no default nucleotide matrix */
if (transitionFile && nCodes != 20) {
fprintf(stderr, "The -trans option is only supported for amino acid alignments\n");
exit(1);
}
#ifndef USE_DOUBLE
if (transitionFile)
fprintf(stderr,
"Warning: custom matrices may create numerical problems for single-precision FastTree.\n"
"You may want to recompile with -DUSE_DOUBLE\n");
#endif
char *fileName = iArg == (argc-1) ? argv[argc-1] : NULL;
if (slow && fastest) {
fprintf(stderr,"Cannot be both slow and fastest\n");
exit(1);
}
if (slow && tophitsMult > 0) {
tophitsMult = 0.0;
}
FILE *fpLog = NULL;
if (logfile != NULL) {
fpLog = fopen(logfile, "w");
if (fpLog == NULL) {
fprintf(stderr, "Cannot write to: %s\n", logfile);
exit(1);
}
fprintf(fpLog, "Command:");
int i;
for (i=0; i < argc; i++)
fprintf(fpLog, " %s", argv[i]);
fprintf(fpLog,"\n");
fflush(fpLog);
}
int i;
FILE *fps[2] = {NULL,NULL};
int nFPs = 0;
if (verbose)
fps[nFPs++] = stderr;
if (fpLog != NULL)
fps[nFPs++] = fpLog;
if (!make_matrix) { /* Report settings */
char tophitString[100] = "no";
char tophitsCloseStr[100] = "default";
if(tophitsClose > 0) sprintf(tophitsCloseStr,"%.2f",tophitsClose);
if(tophitsMult>0) sprintf(tophitString,"%.2f*sqrtN close=%s refresh=%.2f",
tophitsMult, tophitsCloseStr, tophitsRefresh);
char supportString[100] = "none";
if (nBootstrap>0) {
if (MLnni != 0 || MLlen)
sprintf(supportString, "SH-like %d", nBootstrap);
else
sprintf(supportString,"Local boot %d",nBootstrap);
}
char nniString[100] = "(no NNI)";
if (nni > 0)
sprintf(nniString, "+NNI (%d rounds)", nni);
if (nni == -1)
strcpy(nniString, "+NNI");
char sprString[100] = "(no SPR)";
if (spr > 0)
sprintf(sprString, "+SPR (%d rounds range %d)", spr, maxSPRLength);
char mlnniString[100] = "(no ML-NNI)";
if(MLnni > 0)
sprintf(mlnniString, "+ML-NNI (%d rounds)", MLnni);
else if (MLnni == -1)
sprintf(mlnniString, "+ML-NNI");
else if (MLlen)
sprintf(mlnniString, "+ML branch lengths");
if ((MLlen || MLnni != 0) && !exactML)
strcat(mlnniString, " approx");
if (MLnni != 0)
sprintf(mlnniString+strlen(mlnniString), " opt-each=%d",mlAccuracy);
for (i = 0; i < nFPs; i++) {
FILE *fp = fps[i];
fprintf(fp,"FastTree Version %s %s%s\nAlignment: %s",
FT_VERSION, SSE_STRING, OpenMPString(), fileName != NULL ? fileName : "standard input");
if (nAlign>1)
fprintf(fp, " (%d alignments)", nAlign);
fprintf(fp,"\n%s distances: %s Joins: %s Support: %s\n",
nCodes == 20 ? "Amino acid" : "Nucleotide",
matrixPrefix ? matrixPrefix : (useMatrix? "BLOSUM45"
: (nCodes==4 && logdist ? "Jukes-Cantor" : "%different")),
bionj ? "weighted" : "balanced" ,
supportString);
if (intreeFile == NULL)
fprintf(fp, "Search: %s%s %s %s %s\nTopHits: %s\n",
slow?"Exhaustive (slow)" : (fastest ? "Fastest" : "Normal"),
useTopHits2nd ? "+2nd" : "",
nniString, sprString, mlnniString,
tophitString);
else
fprintf(fp, "Start at tree from %s %s %s\n", intreeFile, nniString, sprString);
if (MLnni != 0 || MLlen) {
fprintf(fp, "ML Model: %s,",
(nCodes == 4) ?
(bUseGtr ? "Generalized Time-Reversible" : "Jukes-Cantor") :
(transitionFile ? transitionFile :
(bUseLg ? "Le-Gascuel 2008" : (bUseWag ? "Whelan-And-Goldman" : "Jones-Taylor-Thorton"))));
if (nRateCats == 1)
fprintf(fp, " No rate variation across sites");
else
fprintf(fp, " CAT approximation with %d rate categories", nRateCats);
fprintf(fp, "\n");
if (nCodes == 4 && bUseGtrRates)
fprintf(fp, "GTR rates(ac ag at cg ct gt) %.4f %.4f %.4f %.4f %.4f %.4f\n",
gtrrates[0],gtrrates[1],gtrrates[2],gtrrates[3],gtrrates[4],gtrrates[5]);
if (nCodes == 4 && bUseGtrFreq)
fprintf(fp, "GTR frequencies(A C G T) %.4f %.4f %.4f %.4f\n",
gtrfreq[0],gtrfreq[1],gtrfreq[2],gtrfreq[3]);
}
if (constraintsFile != NULL)
fprintf(fp, "Constraints: %s Weight: %.3f\n", constraintsFile, constraintWeight);
if (pseudoWeight > 0)
fprintf(fp, "Pseudocount weight for comparing sequences with little overlap: %.3lf\n",pseudoWeight);
fflush(fp);
}
}
if (matrixPrefix != NULL) {
if (!useMatrix) {
fprintf(stderr,"Cannot use both -matrix and -nomatrix arguments!");
exit(1);
}
distance_matrix = ReadDistanceMatrix(matrixPrefix);
} else if (useMatrix) { /* use default matrix */
assert(nCodes==20);
distance_matrix = &matrixBLOSUM45;
SetupDistanceMatrix(distance_matrix);
} else {
distance_matrix = NULL;
}
int iAln;
FILE *fpIn = fileName != NULL ? fopen(fileName, "r") : stdin;
if (fpIn == NULL) {
fprintf(stderr, "Cannot read %s\n", fileName);
exit(1);
}
FILE *fpConstraints = NULL;
if (constraintsFile != NULL) {
fpConstraints = fopen(constraintsFile, "r");
if (fpConstraints == NULL) {
fprintf(stderr, "Cannot read %s\n", constraintsFile);
exit(1);
}
}
FILE *fpInTree = NULL;
if (intreeFile != NULL) {
fpInTree = fopen(intreeFile,"r");
if (fpInTree == NULL) {
fprintf(stderr, "Cannot read %s\n", intreeFile);
exit(1);
}
}
for(iAln = 0; iAln < nAlign; iAln++) {
alignment_t *aln = ReadAlignment(fpIn, bQuote);
if (aln->nSeq < 1) {
fprintf(stderr, "No alignment sequences\n");
exit(1);
}
if (fpLog) {
fprintf(fpLog, "Read %d sequences, %d positions\n", aln->nSeq, aln->nPos);
fflush(fpLog);
}
struct timeval clock_start;
gettimeofday(&clock_start,NULL);
ProgressReport("Read alignment",0,0,0,0);
/* Check that all names in alignment are unique */
hashstrings_t *hashnames = MakeHashtable(aln->names, aln->nSeq);
int i;
for (i=0; i<aln->nSeq; i++) {
hashiterator_t hi = FindMatch(hashnames,aln->names[i]);
if (HashCount(hashnames,hi) != 1) {
fprintf(stderr,"Non-unique name '%s' in the alignment\n",aln->names[i]);
exit(1);
}
}
/* Make a list of unique sequences -- note some lists are bigger than required */
ProgressReport("Hashed the names",0,0,0,0);
if (make_matrix) {
NJ_t *NJ = InitNJ(aln->seqs, aln->nSeq, aln->nPos,
/*constraintSeqs*/NULL, /*nConstraints*/0,
distance_matrix, /*transmat*/NULL);
printf(" %d\n",aln->nSeq);
int i,j;
for(i = 0; i < NJ->nSeq; i++) {
printf("%s",aln->names[i]);
for (j = 0; j < NJ->nSeq; j++) {
besthit_t hit;
SeqDist(NJ->profiles[i]->codes,NJ->profiles[j]->codes,NJ->nPos,NJ->distance_matrix,/*OUT*/&hit);
if (logdist)
hit.dist = LogCorrect(hit.dist);
/* Make sure -0 prints as 0 */
printf(" %f", hit.dist <= 0.0 ? 0.0 : hit.dist);
}
printf("\n");
}
} else {
/* reset counters*/
profileOps = 0;
outprofileOps = 0;
seqOps = 0;
profileAvgOps = 0;
nHillBetter = 0;
nCloseUsed = 0;
nClose2Used = 0;
nRefreshTopHits = 0;
nVisibleUpdate = 0;
nNNI = 0;
nML_NNI = 0;
nProfileFreqAlloc = 0;
nProfileFreqAvoid = 0;
szAllAlloc = 0;
mymallocUsed = 0;
maxmallocHeap = 0;
nLkCompute = 0;
nPosteriorCompute = 0;
nAAPosteriorExact = 0;
nAAPosteriorRough = 0;
nStarTests = 0;
uniquify_t *unique = UniquifyAln(aln);
ProgressReport("Identified unique sequences",0,0,0,0);
/* read constraints */
alignment_t *constraints = NULL;
char **uniqConstraints = NULL;
if (constraintsFile != NULL) {
constraints = ReadAlignment(fpConstraints, bQuote);
if (constraints->nSeq < 4) {
fprintf(stderr, "Warning: constraints file with less than 4 sequences ignored:\nalignment #%d in %s\n",
iAln+1, constraintsFile);
constraints = FreeAlignment(constraints);
} else {
uniqConstraints = AlnToConstraints(constraints, unique, hashnames);
ProgressReport("Read the constraints",0,0,0,0);
}
} /* end load constraints */
transition_matrix_t *transmat = NULL;
if (nCodes == 20) {
transmat = transitionFile? ReadAATransitionMatrix(transitionFile) :
(bUseLg? CreateTransitionMatrix(matrixLG08,statLG08) :
(bUseWag? CreateTransitionMatrix(matrixWAG01,statWAG01) :
CreateTransitionMatrix(matrixJTT92,statJTT92)));
} else if (nCodes == 4 && bUseGtr && (bUseGtrRates || bUseGtrFreq)) {
transmat = CreateGTR(gtrrates,gtrfreq);
}
NJ_t *NJ = InitNJ(unique->uniqueSeq, unique->nUnique, aln->nPos,
uniqConstraints,
uniqConstraints != NULL ? constraints->nPos : 0, /* nConstraints */
distance_matrix,
transmat);
if (verbose>2) fprintf(stderr, "read %s seqs %d (%d unique) positions %d nameLast %s seqLast %s\n",
fileName ? fileName : "standard input",
aln->nSeq, unique->nUnique, aln->nPos, aln->names[aln->nSeq-1], aln->seqs[aln->nSeq-1]);
FreeAlignmentSeqs(/*IN/OUT*/aln); /*no longer needed*/
if (fpInTree != NULL) {
if (intree1)
fseek(fpInTree, 0L, SEEK_SET);
ReadTree(/*IN/OUT*/NJ, /*IN*/unique, /*IN*/hashnames, /*READ*/fpInTree);
if (verbose > 2)
fprintf(stderr, "Read tree from %s\n", intreeFile);
if (verbose > 2)
PrintNJ(stderr, NJ, aln->names, unique, /*support*/false, bQuote);
} else {
FastNJ(NJ);
}
LogTree("NJ", 0, fpLog, NJ, aln->names, unique, bQuote);
/* profile-frequencies for the "up-profiles" in ReliabilityNJ take only diameter(Tree)*L*a
space not N*L*a space, because we can free them as we go.
And up-profile by their nature tend to be complicated.
So save the profile-frequency memory allocation counters now to exclude later results.
*/
#ifdef TRACK_MEMORY
long svProfileFreqAlloc = nProfileFreqAlloc;
long svProfileFreqAvoid = nProfileFreqAvoid;
#endif
int nniToDo = nni == -1 ? (int)(0.5 + 4.0 * log(NJ->nSeq)/log(2)) : nni;
int sprRemaining = spr;
int MLnniToDo = (MLnni != -1) ? MLnni : (int)(0.5 + 2.0*log(NJ->nSeq)/log(2));
if(verbose>0) {
if (fpInTree == NULL)
fprintf(stderr, "Initial topology in %.2f seconds\n", clockDiff(&clock_start));
if (spr > 0 || nniToDo > 0 || MLnniToDo > 0)
fprintf(stderr,"Refining topology: %d rounds ME-NNIs, %d rounds ME-SPRs, %d rounds ML-NNIs\n", nniToDo, spr, MLnniToDo);
}
if (nniToDo>0) {
int i;
bool bConverged = false;
nni_stats_t *nni_stats = InitNNIStats(NJ);
for (i=0; i < nniToDo; i++) {
double maxDelta;
if (!bConverged) {
int nChange = NNI(/*IN/OUT*/NJ, i, nniToDo, /*use ml*/false, /*IN/OUT*/nni_stats, /*OUT*/&maxDelta);
LogTree("ME_NNI%d",i+1, fpLog, NJ, aln->names, unique, bQuote);
if (nChange == 0) {
bConverged = true;
if (verbose>1)
fprintf(stderr, "Min_evolution NNIs converged at round %d -- skipping some rounds\n", i+1);
if (fpLog)
fprintf(fpLog, "Min_evolution NNIs converged at round %d -- skipping some rounds\n", i+1);
}
}
/* Interleave SPRs with NNIs (typically 1/3rd NNI, SPR, 1/3rd NNI, SPR, 1/3rd NNI */
if (sprRemaining > 0 && (nniToDo/(spr+1) > 0 && ((i+1) % (nniToDo/(spr+1))) == 0)) {
SPR(/*IN/OUT*/NJ, maxSPRLength, spr-sprRemaining, spr);
LogTree("ME_SPR%d",spr-sprRemaining+1, fpLog, NJ, aln->names, unique, bQuote);
sprRemaining--;
/* Restart the NNIs -- set all ages to 0, etc. */
bConverged = false;
nni_stats = FreeNNIStats(nni_stats, NJ);
nni_stats = InitNNIStats(NJ);
}
}
nni_stats = FreeNNIStats(nni_stats, NJ);
}
while(sprRemaining > 0) { /* do any remaining SPR rounds */
SPR(/*IN/OUT*/NJ, maxSPRLength, spr-sprRemaining, spr);
LogTree("ME_SPR%d",spr-sprRemaining+1, fpLog, NJ, aln->names, unique, bQuote);
sprRemaining--;
}
/* In minimum-evolution mode, update branch lengths, even if no NNIs or SPRs,
so that they are log-corrected, do not include penalties from constraints,
and avoid errors due to approximation of out-distances.
If doing maximum-likelihood NNIs, then we'll also use these
to get estimates of starting distances for quartets, etc.
*/
UpdateBranchLengths(/*IN/OUT*/NJ);
LogTree("ME_Lengths",0, fpLog, NJ, aln->names, unique, bQuote);
double total_len = 0;
int iNode;
for (iNode = 0; iNode < NJ->maxnode; iNode++)
total_len += fabs(NJ->branchlength[iNode]);
if (verbose>0) {
fprintf(stderr, "Total branch-length %.3f after %.2f sec\n",
total_len, clockDiff(&clock_start));
fflush(stderr);
}
if (fpLog) {
fprintf(fpLog, "Total branch-length %.3f after %.2f sec\n",
total_len, clockDiff(&clock_start));
fflush(stderr);
}
#ifdef TRACK_MEMORY
if (verbose>1) {
struct mallinfo mi = mallinfo();
fprintf(stderr, "Memory @ end of ME phase: %.2f MB (%.1f byte/pos) useful %.2f expected %.2f\n",
(mi.arena+mi.hblkhd)/1.0e6, (mi.arena+mi.hblkhd)/(double)(NJ->nSeq*(double)NJ->nPos),
mi.uordblks/1.0e6, mymallocUsed/1e6);
}
#endif
SplitCount_t splitcount = {0,0,0,0,0.0,0.0};
if (MLnniToDo > 0 || MLlen) {
bool warn_len = total_len/NJ->maxnode < 0.001 && MLMinBranchLengthTolerance > 1.0/aln->nPos;
bool warn = warn_len || (total_len/NJ->maxnode < 0.001 && aln->nPos >= 10000);
if (warn)
fprintf(stderr, "\nWARNING! This alignment consists of closely-related and very-long sequences.\n");
if (warn_len)
fprintf(stderr,
"This version of FastTree may not report reasonable branch lengths!\n"
#ifdef USE_DOUBLE
"Consider changing MLMinBranchLengthTolerance.\n"
#else
"Consider recompiling FastTree with -DUSE_DOUBLE.\n"
#endif
"For more information, visit\n"
"http://www.microbesonline.org/fasttree/#BranchLen\n\n");
if (warn)
fprintf(stderr, "WARNING! FastTree (or other standard maximum-likelihood tools)\n"
"may not be appropriate for aligments of very closely-related sequences\n"
"like this one, as FastTree does not account for recombination or gene conversion\n\n");
/* Do maximum-likelihood computations */
/* Convert profiles to use the transition matrix */
distance_matrix_t *tmatAsDist = TransMatToDistanceMat(/*OPTIONAL*/NJ->transmat);
RecomputeProfiles(NJ, /*OPTIONAL*/tmatAsDist);
tmatAsDist = myfree(tmatAsDist, sizeof(distance_matrix_t));
double lastloglk = -1e20;
nni_stats_t *nni_stats = InitNNIStats(NJ);
bool resetGtr = nCodes == 4 && bUseGtr && !bUseGtrRates;
if (MLlen) {
int iRound;
int maxRound = (int)(0.5 + log(NJ->nSeq)/log(2));
double dLastLogLk = -1e20;
for (iRound = 1; iRound <= maxRound; iRound++) {
int node;
numeric_t *oldlength = (numeric_t*)mymalloc(sizeof(numeric_t)*NJ->maxnodes);
for (node = 0; node < NJ->maxnode; node++)
oldlength[node] = NJ->branchlength[node];
OptimizeAllBranchLengths(/*IN/OUT*/NJ);
LogTree("ML_Lengths",iRound, fpLog, NJ, aln->names, unique, bQuote);
double dMaxChange = 0; /* biggest change in branch length */
for (node = 0; node < NJ->maxnode; node++) {
double d = fabs(oldlength[node] - NJ->branchlength[node]);
if (dMaxChange < d)
dMaxChange = d;
}
oldlength = myfree(oldlength, sizeof(numeric_t)*NJ->maxnodes);
double loglk = TreeLogLk(NJ, /*site_likelihoods*/NULL);
bool bConverged = iRound > 1 && (dMaxChange < 0.001 || loglk < (dLastLogLk+treeLogLkDelta));
if (verbose)
fprintf(stderr, "%d rounds ML lengths: LogLk %s= %.3lf Max-change %.4lf%s Time %.2f\n",
iRound,
exactML || nCodes != 20 ? "" : "~",
loglk,
dMaxChange,
bConverged ? " (converged)" : "",
clockDiff(&clock_start));
if (fpLog)
fprintf(fpLog, "TreeLogLk\tLength%d\t%.4lf\tMaxChange\t%.4lf\n",
iRound, loglk, dMaxChange);
if (iRound == 1) {
if (resetGtr)
SetMLGtr(/*IN/OUT*/NJ, bUseGtrFreq ? gtrfreq : NULL, fpLog);
SetMLRates(/*IN/OUT*/NJ, nRateCats);
LogMLRates(fpLog, NJ);
}
if (bConverged)
break;
}
}
if (MLnniToDo > 0) {
/* This may help us converge faster, and is fast */
OptimizeAllBranchLengths(/*IN/OUT*/NJ);
LogTree("ML_Lengths%d",1, fpLog, NJ, aln->names, unique, bQuote);
}
int iMLnni;
double maxDelta;
bool bConverged = false;
for (iMLnni = 0; iMLnni < MLnniToDo; iMLnni++) {
int changes = NNI(/*IN/OUT*/NJ, iMLnni, MLnniToDo, /*use ml*/true, /*IN/OUT*/nni_stats, /*OUT*/&maxDelta);
LogTree("ML_NNI%d",iMLnni+1, fpLog, NJ, aln->names, unique, bQuote);
double loglk = TreeLogLk(NJ, /*site_likelihoods*/NULL);
bool bConvergedHere = (iMLnni > 0) && ((loglk < lastloglk + treeLogLkDelta) || maxDelta < treeLogLkDelta);
if (verbose)
fprintf(stderr, "ML-NNI round %d: LogLk %s= %.3f NNIs %d max delta %.2f Time %.2f%s\n",
iMLnni+1,
exactML || nCodes != 20 ? "" : "~",
loglk, changes, maxDelta, clockDiff(&clock_start),
bConverged ? " (final)" : "");
if (fpLog)
fprintf(fpLog, "TreeLogLk\tML_NNI%d\t%.4lf\tMaxChange\t%.4lf\n", iMLnni+1, loglk, maxDelta);
if (bConverged)
break; /* we did our extra round */
if (bConvergedHere)
bConverged = true;
if (bConverged || iMLnni == MLnniToDo-2) {
/* last round uses high-accuracy seettings -- reset NNI stats to tone down heuristics */
nni_stats = FreeNNIStats(nni_stats, NJ);
nni_stats = InitNNIStats(NJ);
if (verbose)
fprintf(stderr, "Turning off heuristics for final round of ML NNIs%s\n",
bConvergedHere? " (converged)" : "");
if (fpLog)
fprintf(fpLog, "Turning off heuristics for final round of ML NNIs%s\n",
bConvergedHere? " (converged)" : "");
}
lastloglk = loglk;
if (iMLnni == 0 && NJ->rates.nRateCategories == 1) {
if (resetGtr)
SetMLGtr(/*IN/OUT*/NJ, bUseGtrFreq ? gtrfreq : NULL, fpLog);
SetMLRates(/*IN/OUT*/NJ, nRateCats);
LogMLRates(fpLog, NJ);
}
}
nni_stats = FreeNNIStats(nni_stats, NJ);
/* This does not take long and improves the results */
if (MLnniToDo > 0) {
OptimizeAllBranchLengths(/*IN/OUT*/NJ);
LogTree("ML_Lengths%d",2, fpLog, NJ, aln->names, unique, bQuote);
if (verbose || fpLog) {
double loglk = TreeLogLk(NJ, /*site_likelihoods*/NULL);
if (verbose)
fprintf(stderr, "Optimize all lengths: LogLk %s= %.3f Time %.2f\n",
exactML || nCodes != 20 ? "" : "~",
loglk,
clockDiff(&clock_start));
if (fpLog) {
fprintf(fpLog, "TreeLogLk\tML_Lengths%d\t%.4f\n", 2, loglk);
fflush(fpLog);
}
}
}
/* Count bad splits and compute SH-like supports if desired */
if ((MLnniToDo > 0 && !fastest) || nBootstrap > 0)
TestSplitsML(NJ, /*OUT*/&splitcount, nBootstrap);
/* Compute gamma-based likelihood? */
if (gammaLogLk && nRateCats > 1) {
numeric_t *rates = MLSiteRates(nRateCats);
double *site_loglk = MLSiteLikelihoodsByRate(NJ, rates, nRateCats);
double scale = RescaleGammaLogLk(NJ->nPos, nRateCats, rates, /*IN*/site_loglk, /*OPTIONAL*/fpLog);
rates = myfree(rates, sizeof(numeric_t) * nRateCats);
site_loglk = myfree(site_loglk, sizeof(double) * nRateCats * NJ->nPos);
for (i = 0; i < NJ->maxnodes; i++)
NJ->branchlength[i] *= scale;
}
} else {
/* Minimum evolution supports */
TestSplitsMinEvo(NJ, /*OUT*/&splitcount);
if (nBootstrap > 0)
ReliabilityNJ(NJ, nBootstrap);
}
for (i = 0; i < nFPs; i++) {
FILE *fp = fps[i];
fprintf(fp, "Total time: %.2f seconds Unique: %d/%d Bad splits: %d/%d",
clockDiff(&clock_start),
NJ->nSeq, aln->nSeq,
splitcount.nBadSplits, splitcount.nSplits);
if (splitcount.dWorstDeltaUnconstrained > 0)
fprintf(fp, " Worst %sdelta-%s %.3f",
uniqConstraints != NULL ? "unconstrained " : "",
(MLnniToDo > 0 || MLlen) ? "LogLk" : "Len",
splitcount.dWorstDeltaUnconstrained);
fprintf(fp,"\n");
if (NJ->nSeq > 3 && NJ->nConstraints > 0) {
fprintf(fp, "Violating constraints: %d both bad: %d",
splitcount.nConstraintViolations, splitcount.nBadBoth);
if (splitcount.dWorstDeltaConstrained > 0)
fprintf(fp, " Worst delta-%s due to constraints: %.3f",
(MLnniToDo > 0 || MLlen) ? "LogLk" : "Len",
splitcount.dWorstDeltaConstrained);
fprintf(fp,"\n");
}
if (verbose > 1 || fp == fpLog) {
double dN2 = NJ->nSeq*(double)NJ->nSeq;
fprintf(fp, "Dist/N**2: by-profile %.3f (out %.3f) by-leaf %.3f avg-prof %.3f\n",
profileOps/dN2, outprofileOps/dN2, seqOps/dN2, profileAvgOps/dN2);
if (nCloseUsed>0 || nClose2Used > 0 || nRefreshTopHits>0)
fprintf(fp, "Top hits: close neighbors %ld/%d 2nd-level %ld refreshes %ld",
nCloseUsed, NJ->nSeq, nClose2Used, nRefreshTopHits);
if(!slow) fprintf(fp, " Hill-climb: %ld Update-best: %ld\n", nHillBetter, nVisibleUpdate);
if (nniToDo > 0 || spr > 0 || MLnniToDo > 0)
fprintf(fp, "NNI: %ld SPR: %ld ML-NNI: %ld\n", nNNI, nSPR, nML_NNI);
if (MLnniToDo > 0) {
fprintf(fp, "Max-lk operations: lk %ld posterior %ld", nLkCompute, nPosteriorCompute);
if (nAAPosteriorExact > 0 || nAAPosteriorRough > 0)
fprintf(fp, " approximate-posteriors %.2f%%",
(100.0*nAAPosteriorRough)/(double)(nAAPosteriorExact+nAAPosteriorRough));
if (mlAccuracy < 2)
fprintf(fp, " star-only %ld", nStarTests);
fprintf(fp, "\n");
}
}
#ifdef TRACK_MEMORY
fprintf(fp, "Memory: %.2f MB (%.1f byte/pos) ",
maxmallocHeap/1.0e6, maxmallocHeap/(double)(aln->nSeq*(double)aln->nPos));
/* Only report numbers from before we do reliability estimates */
fprintf(fp, "profile-freq-alloc %ld avoided %.2f%%\n",
svProfileFreqAlloc,
svProfileFreqAvoid > 0 ?
100.0*svProfileFreqAvoid/(double)(svProfileFreqAlloc+svProfileFreqAvoid)
: 0);
#endif
fflush(fp);
}
PrintNJ(fpOut, NJ, aln->names, unique, /*support*/nBootstrap > 0, bQuote);
fflush(fpOut);
if (fpLog) {
fprintf(fpLog,"TreeCompleted\n");
fflush(fpLog);
}
FreeNJ(NJ);
if (uniqConstraints != NULL)
uniqConstraints = myfree(uniqConstraints, sizeof(char*) * unique->nUnique);
constraints = FreeAlignment(constraints);
unique = FreeUniquify(unique);
} /* end build tree */
hashnames = FreeHashtable(hashnames);
aln = FreeAlignment(aln);
} /* end loop over alignments */
if (fpLog != NULL)
fclose(fpLog);
if (fpOut != stdout) fclose(fpOut);
exit(0);
}
void ProgressReport(char *format, int i1, int i2, int i3, int i4) {
static bool time_set = false;
static struct timeval time_last;
static struct timeval time_begin;
if (!showProgress)
return;
static struct timeval time_now;
gettimeofday(&time_now,NULL);
if (!time_set) {
time_begin = time_last = time_now;
time_set = true;
}
static struct timeval elapsed;
timeval_subtract(&elapsed,&time_now,&time_last);
if (elapsed.tv_sec > 1 || elapsed.tv_usec > 100*1000 || verbose > 1) {
timeval_subtract(&elapsed,&time_now,&time_begin);
fprintf(stderr, "%7i.%2.2i seconds: ", (int)elapsed.tv_sec, (int)(elapsed.tv_usec/10000));
fprintf(stderr, format, i1, i2, i3, i4);
if (verbose > 1 || !isatty(STDERR_FILENO)) {
fprintf(stderr, "\n");
} else {
fprintf(stderr, " \r");
}
fflush(stderr);
time_last = time_now;
}
}
void LogMLRates(/*OPTIONAL WRITE*/FILE *fpLog, NJ_t *NJ) {
if (fpLog != NULL) {
rates_t *rates = &NJ->rates;
fprintf(fpLog, "NCategories\t%d\nRates",rates->nRateCategories);
assert(rates->nRateCategories > 0);
int iRate;
for (iRate = 0; iRate < rates->nRateCategories; iRate++)
fprintf(fpLog, " %f", rates->rates[iRate]);
fprintf(fpLog,"\nSiteCategories");
int iPos;
for (iPos = 0; iPos < NJ->nPos; iPos++) {
iRate = rates->ratecat[iPos];
fprintf(fpLog," %d",iRate+1);
}
fprintf(fpLog,"\n");
fflush(fpLog);
}
}
void LogTree(char *format, int i, /*OPTIONAL WRITE*/FILE *fpLog, NJ_t *NJ, char **names, uniquify_t *unique, bool bQuote) {
if(fpLog != NULL) {
fprintf(fpLog, format, i);
fprintf(fpLog, "\t");
PrintNJ(fpLog, NJ, names, unique, /*support*/false, bQuote);
fflush(fpLog);
}
}
NJ_t *InitNJ(char **sequences, int nSeq, int nPos,
/*OPTIONAL*/char **constraintSeqs, int nConstraints,
/*OPTIONAL*/distance_matrix_t *distance_matrix,
/*OPTIONAL*/transition_matrix_t *transmat) {
int iNode;
NJ_t *NJ = (NJ_t*)mymalloc(sizeof(NJ_t));
NJ->root = -1; /* set at end of FastNJ() */
NJ->maxnode = NJ->nSeq = nSeq;
NJ->nPos = nPos;
NJ->maxnodes = 2*nSeq;
NJ->seqs = sequences;
NJ->distance_matrix = distance_matrix;
NJ->transmat = transmat;
NJ->nConstraints = nConstraints;
NJ->constraintSeqs = constraintSeqs;
NJ->profiles = (profile_t **)mymalloc(sizeof(profile_t*) * NJ->maxnodes);
unsigned long counts[256];
int i;
for (i = 0; i < 256; i++)
counts[i] = 0;
for (iNode = 0; iNode < NJ->nSeq; iNode++) {
NJ->profiles[iNode] = SeqToProfile(NJ, NJ->seqs[iNode], nPos,
constraintSeqs != NULL ? constraintSeqs[iNode] : NULL,
nConstraints,
iNode,
/*IN/OUT*/counts);
}
unsigned long totCount = 0;
for (i = 0; i < 256; i++)
totCount += counts[i];
/* warnings about unknown characters */
for (i = 0; i < 256; i++) {
if (counts[i] == 0 || i == '.' || i == '-')
continue;
unsigned char *codesP;
bool bMatched = false;
for (codesP = codesString; *codesP != '\0'; codesP++) {
if (*codesP == i || tolower(*codesP) == i) {
bMatched = true;
break;
}
}
if (!bMatched)
fprintf(stderr, "Ignored unknown character %c (seen %lu times)\n", i, counts[i]);
}
/* warnings about the counts */
double fACGTUN = (counts['A'] + counts['C'] + counts['G'] + counts['T'] + counts['U'] + counts['N']
+ counts['a'] + counts['c'] + counts['g'] + counts['t'] + counts['u'] + counts['n'])
/ (double)(totCount - counts['-'] - counts['.']);
if (nCodes == 4 && fACGTUN < 0.9)
fprintf(stderr, "WARNING! ONLY %.1f%% NUCLEOTIDE CHARACTERS -- IS THIS REALLY A NUCLEOTIDE ALIGNMENT?\n",
100.0 * fACGTUN);
else if (nCodes == 20 && fACGTUN >= 0.9)
fprintf(stderr, "WARNING! %.1f%% NUCLEOTIDE CHARACTERS -- IS THIS REALLY A PROTEIN ALIGNMENT?\n",
100.0 * fACGTUN);
if(verbose>10) fprintf(stderr,"Made sequence profiles\n");
for (iNode = NJ->nSeq; iNode < NJ->maxnodes; iNode++)
NJ->profiles[iNode] = NULL; /* not yet exists */
NJ->outprofile = OutProfile(NJ->profiles, NJ->nSeq,
NJ->nPos, NJ->nConstraints,
NJ->distance_matrix);
if(verbose>10) fprintf(stderr,"Made out-profile\n");
NJ->totdiam = 0.0;
NJ->diameter = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->diameter[iNode] = 0;
NJ->varDiameter = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->varDiameter[iNode] = 0;
NJ->selfdist = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->selfdist[iNode] = 0;
NJ->selfweight = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->nSeq; iNode++)
NJ->selfweight[iNode] = NJ->nPos - NGaps(NJ,iNode);
NJ->outDistances = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes);
NJ->nOutDistActive = (int *)mymalloc(sizeof(int)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->maxnodes; iNode++)
NJ->nOutDistActive[iNode] = NJ->nSeq * 10; /* unreasonably high value */
NJ->parent = NULL; /* so SetOutDistance ignores it */
for (iNode = 0; iNode < NJ->nSeq; iNode++)
SetOutDistance(/*IN/UPDATE*/NJ, iNode, /*nActive*/NJ->nSeq);
if (verbose>2) {
for (iNode = 0; iNode < 4 && iNode < NJ->nSeq; iNode++)
fprintf(stderr, "Node %d outdist %f\n", iNode, NJ->outDistances[iNode]);
}
NJ->parent = (int *)mymalloc(sizeof(int)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->parent[iNode] = -1;
NJ->branchlength = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); /* distance to parent */
for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->branchlength[iNode] = 0;
NJ->support = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->support[iNode] = -1.0;
NJ->child = (children_t*)mymalloc(sizeof(children_t)*NJ->maxnodes);
for (iNode= 0; iNode < NJ->maxnode; iNode++) NJ->child[iNode].nChild = 0;
NJ->rates.nRateCategories = 0;
NJ->rates.rates = NULL;
NJ->rates.ratecat = NULL;
AllocRateCategories(&NJ->rates, 1, NJ->nPos);
return(NJ);
}
NJ_t *FreeNJ(NJ_t *NJ) {
if (NJ==NULL)
return(NJ);
int i;
for (i=0; i < NJ->maxnode; i++)
NJ->profiles[i] = FreeProfile(NJ->profiles[i], NJ->nPos, NJ->nConstraints);
NJ->profiles = myfree(NJ->profiles, sizeof(profile_t*) * NJ->maxnodes);
NJ->outprofile = FreeProfile(NJ->outprofile, NJ->nPos, NJ->nConstraints);
NJ->diameter = myfree(NJ->diameter, sizeof(numeric_t)*NJ->maxnodes);
NJ->varDiameter = myfree(NJ->varDiameter, sizeof(numeric_t)*NJ->maxnodes);
NJ->selfdist = myfree(NJ->selfdist, sizeof(numeric_t)*NJ->maxnodes);
NJ->selfweight = myfree(NJ->selfweight, sizeof(numeric_t)*NJ->maxnodes);
NJ->outDistances = myfree(NJ->outDistances, sizeof(numeric_t)*NJ->maxnodes);
NJ->nOutDistActive = myfree(NJ->nOutDistActive, sizeof(int)*NJ->maxnodes);
NJ->parent = myfree(NJ->parent, sizeof(int)*NJ->maxnodes);
NJ->branchlength = myfree(NJ->branchlength, sizeof(numeric_t)*NJ->maxnodes);
NJ->support = myfree(NJ->support, sizeof(numeric_t)*NJ->maxnodes);
NJ->child = myfree(NJ->child, sizeof(children_t)*NJ->maxnodes);
NJ->transmat = myfree(NJ->transmat, sizeof(transition_matrix_t));
AllocRateCategories(&NJ->rates, 0, NJ->nPos);
return(myfree(NJ, sizeof(NJ_t)));
}
/* Allocate or reallocate the rate categories, and set every position
to category 0 and every category's rate to 1.0
If nRateCategories=0, just deallocate
*/
void AllocRateCategories(/*IN/OUT*/rates_t *rates, int nRateCategories, int nPos) {
assert(nRateCategories >= 0);
rates->rates = myfree(rates->rates, sizeof(numeric_t)*rates->nRateCategories);
rates->ratecat = myfree(rates->ratecat, sizeof(unsigned int)*nPos);
rates->nRateCategories = nRateCategories;
if (rates->nRateCategories > 0) {
rates->rates = (numeric_t*)mymalloc(sizeof(numeric_t)*rates->nRateCategories);
int i;
for (i = 0; i < nRateCategories; i++)
rates->rates[i] = 1.0;
rates->ratecat = (unsigned int *)mymalloc(sizeof(unsigned int)*nPos);
for (i = 0; i < nPos; i++)
rates->ratecat[i] = 0;
}
}
void FastNJ(NJ_t *NJ) {
int iNode;
assert(NJ->nSeq >= 1);
if (NJ->nSeq < 3) {
NJ->root = NJ->maxnode++;
NJ->child[NJ->root].nChild = NJ->nSeq;
for (iNode = 0; iNode < NJ->nSeq; iNode++) {
NJ->parent[iNode] = NJ->root;
NJ->child[NJ->root].child[iNode] = iNode;
}
if (NJ->nSeq == 1) {
NJ->branchlength[0] = 0;
} else {
assert (NJ->nSeq == 2);
besthit_t hit;
SeqDist(NJ->profiles[0]->codes,NJ->profiles[1]->codes,NJ->nPos,NJ->distance_matrix,/*OUT*/&hit);
NJ->branchlength[0] = hit.dist/2.0;
NJ->branchlength[1] = hit.dist/2.0;
}
return;
}
/* else 3 or more sequences */
/* The visible set stores the best hit of each node (unless using top hits, in which case
it is handled by the top hits routines) */
besthit_t *visible = NULL; /* Not used if doing top hits */
besthit_t *besthitNew = NULL; /* All hits of new node -- not used if doing top-hits */
/* The top-hits lists, with the key parameter m = length of each top-hit list */
top_hits_t *tophits = NULL;
int m = 0; /* maximum length of a top-hits list */
if (tophitsMult > 0) {
m = (int)(0.5 + tophitsMult*sqrt(NJ->nSeq));
if(m<4 || 2*m >= NJ->nSeq) {
m=0;
if(verbose>1) fprintf(stderr,"Too few leaves, turning off top-hits\n");
} else {
if(verbose>2) fprintf(stderr,"Top-hit-list size = %d of %d\n", m, NJ->nSeq);
}
}
assert(!(slow && m>0));
/* Initialize top-hits or visible set */
if (m>0) {
tophits = InitTopHits(NJ, m);
SetAllLeafTopHits(/*IN/UPDATE*/NJ, /*OUT*/tophits);
ResetTopVisible(/*IN/UPDATE*/NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/tophits);
} else if (!slow) {
visible = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->maxnodes);
besthitNew = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->maxnodes);
for (iNode = 0; iNode < NJ->nSeq; iNode++)
SetBestHit(iNode, NJ, /*nActive*/NJ->nSeq, /*OUT*/&visible[iNode], /*OUT IGNORED*/NULL);
}
/* Iterate over joins */
int nActiveOutProfileReset = NJ->nSeq;
int nActive;
for (nActive = NJ->nSeq; nActive > 3; nActive--) {
int nJoinsDone = NJ->nSeq - nActive;
if (nJoinsDone > 0 && (nJoinsDone % 100) == 0)
ProgressReport("Joined %6d of %6d", nJoinsDone, NJ->nSeq-3, 0, 0);
besthit_t join; /* the join to do */
if (slow) {
ExhaustiveNJSearch(NJ,nActive,/*OUT*/&join);
} else if (m>0) {
TopHitNJSearch(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, /*OUT*/&join);
} else {
FastNJSearch(NJ, nActive, /*IN/OUT*/visible, /*OUT*/&join);
}
if (verbose>2) {
double penalty = constraintWeight
* (double)JoinConstraintPenalty(NJ, join.i, join.j);
if (penalty > 0.001) {
fprintf(stderr, "Constraint violation during neighbor-joining %d %d into %d penalty %.3f\n",
join.i, join.j, NJ->maxnode, penalty);
int iC;
for (iC = 0; iC < NJ->nConstraints; iC++) {
int local = JoinConstraintPenaltyPiece(NJ, join.i, join.j, iC);
if (local > 0)
fprintf(stderr, "Constraint %d piece %d %d/%d %d/%d %d/%d\n", iC, local,
NJ->profiles[join.i]->nOn[iC],
NJ->profiles[join.i]->nOff[iC],
NJ->profiles[join.j]->nOn[iC],
NJ->profiles[join.j]->nOff[iC],
NJ->outprofile->nOn[iC] - NJ->profiles[join.i]->nOn[iC] - NJ->profiles[join.j]->nOn[iC],
NJ->outprofile->nOff[iC] - NJ->profiles[join.i]->nOff[iC] - NJ->profiles[join.j]->nOff[iC]);
}
}
}
/* because of the stale out-distance heuristic, make sure that these are up-to-date */
SetOutDistance(NJ, join.i, nActive);
SetOutDistance(NJ, join.j, nActive);
/* Make sure weight is set and criterion is up to date */
SetDistCriterion(NJ, nActive, /*IN/OUT*/&join);
assert(NJ->nOutDistActive[join.i] == nActive);
assert(NJ->nOutDistActive[join.j] == nActive);
int newnode = NJ->maxnode++;
NJ->parent[join.i] = newnode;
NJ->parent[join.j] = newnode;
NJ->child[newnode].nChild = 2;
NJ->child[newnode].child[0] = join.i < join.j ? join.i : join.j;
NJ->child[newnode].child[1] = join.i > join.j ? join.i : join.j;
double rawIJ = join.dist + NJ->diameter[join.i] + NJ->diameter[join.j];
double distIJ = join.dist;
double deltaDist = (NJ->outDistances[join.i]-NJ->outDistances[join.j])/(double)(nActive-2);
NJ->branchlength[join.i] = (distIJ + deltaDist)/2;
NJ->branchlength[join.j] = (distIJ - deltaDist)/2;
double bionjWeight = 0.5; /* IJ = bionjWeight*I + (1-bionjWeight)*J */
double varIJ = rawIJ - NJ->varDiameter[join.i] - NJ->varDiameter[join.j];
if (bionj && join.weight > 0.01 && varIJ > 0.001) {
/* Set bionjWeight according to the BIONJ formula, where
the variance matrix is approximated by
Vij = ProfileVar(i,j) - varDiameter(i) - varDiameter(j)
ProfileVar(i,j) = distance(i,j) = top(i,j)/weight(i,j)
(The node's distance diameter does not affect the variances.)
The BIONJ formula is equation 9 from Gascuel 1997:
bionjWeight = 1/2 + sum(k!=i,j) (Vjk - Vik) / ((nActive-2)*Vij)
sum(k!=i,j) (Vjk - Vik) = sum(k!=i,j) Vik - varDiameter(j) + varDiameter(i)
= sum(k!=i,j) ProfileVar(j,k) - sum(k!=i,j) ProfileVar(i,k) + (nActive-2)*(varDiameter(i)-varDiameter(j))
sum(k!=i,j) ProfileVar(i,k)
~= (sum(k!=i,j) distance(i,k) * weight(i,k))/(mean(k!=i,j) weight(i,k))
~= (N-2) * top(i, Out-i-j) / weight(i, Out-i-j)
weight(i, Out-i-j) = N*weight(i,Out) - weight(i,i) - weight(i,j)
top(i, Out-i-j) = N*top(i,Out) - top(i,i) - top(i,j)
*/
besthit_t outI;
besthit_t outJ;
ProfileDist(NJ->profiles[join.i],NJ->outprofile,NJ->nPos,NJ->distance_matrix,/*OUT*/&outI);
ProfileDist(NJ->profiles[join.j],NJ->outprofile,NJ->nPos,NJ->distance_matrix,/*OUT*/&outJ);
outprofileOps += 2;
double varIWeight = (nActive * outI.weight - NJ->selfweight[join.i] - join.weight);
double varJWeight = (nActive * outJ.weight - NJ->selfweight[join.j] - join.weight);
double varITop = outI.dist * outI.weight * nActive
- NJ->selfdist[join.i] * NJ->selfweight[join.i] - rawIJ * join.weight;
double varJTop = outJ.dist * outJ.weight * nActive
- NJ->selfdist[join.j] * NJ->selfweight[join.j] - rawIJ * join.weight;
double deltaProfileVarOut = (nActive-2) * (varJTop/varJWeight - varITop/varIWeight);
double deltaVarDiam = (nActive-2)*(NJ->varDiameter[join.i] - NJ->varDiameter[join.j]);
if (varJWeight > 0.01 && varIWeight > 0.01)
bionjWeight = 0.5 + (deltaProfileVarOut+deltaVarDiam)/(2*(nActive-2)*varIJ);
if(bionjWeight<0) bionjWeight=0;
if(bionjWeight>1) bionjWeight=1;
if (verbose>2) fprintf(stderr,"dVarO %f dVarDiam %f varIJ %f from dist %f weight %f (pos %d) bionjWeight %f %f\n",
deltaProfileVarOut, deltaVarDiam,
varIJ, join.dist, join.weight, NJ->nPos,
bionjWeight, 1-bionjWeight);
if (verbose>3 && (newnode%5) == 0) {
/* Compare weight estimated from outprofiles from weight made by summing over other nodes */
double deltaProfileVarTot = 0;
for (iNode = 0; iNode < newnode; iNode++) {
if (NJ->parent[iNode] < 0) { /* excludes join.i, join.j */
besthit_t di, dj;
ProfileDist(NJ->profiles[join.i],NJ->profiles[iNode],NJ->nPos,NJ->distance_matrix,/*OUT*/&di);
ProfileDist(NJ->profiles[join.j],NJ->profiles[iNode],NJ->nPos,NJ->distance_matrix,/*OUT*/&dj);
deltaProfileVarTot += dj.dist - di.dist;
}
}
double lambdaTot = 0.5 + (deltaProfileVarTot+deltaVarDiam)/(2*(nActive-2)*varIJ);
if (lambdaTot < 0) lambdaTot = 0;
if (lambdaTot > 1) lambdaTot = 1;
if (fabs(bionjWeight-lambdaTot) > 0.01 || verbose > 4)
fprintf(stderr, "deltaProfileVar actual %.6f estimated %.6f lambda actual %.3f estimated %.3f\n",
deltaProfileVarTot,deltaProfileVarOut,lambdaTot,bionjWeight);
}
}
if (verbose > 2) fprintf(stderr, "Join\t%d\t%d\t%.6f\tlambda\t%.6f\tselfw\t%.3f\t%.3f\tnew\t%d\n",
join.i < join.j ? join.i : join.j,
join.i < join.j ? join.j : join.i,
join.criterion, bionjWeight,
NJ->selfweight[join.i < join.j ? join.i : join.j],
NJ->selfweight[join.i < join.j ? join.j : join.i],
newnode);
NJ->diameter[newnode] = bionjWeight * (NJ->branchlength[join.i] + NJ->diameter[join.i])
+ (1-bionjWeight) * (NJ->branchlength[join.j] + NJ->diameter[join.j]);
NJ->varDiameter[newnode] = bionjWeight * NJ->varDiameter[join.i]
+ (1-bionjWeight) * NJ->varDiameter[join.j]
+ bionjWeight * (1-bionjWeight) * varIJ;
NJ->profiles[newnode] = AverageProfile(NJ->profiles[join.i],NJ->profiles[join.j],
NJ->nPos, NJ->nConstraints,
NJ->distance_matrix,
bionj ? bionjWeight : /*noweight*/-1.0);
/* Update out-distances and total diameters */
int changedActiveOutProfile = nActiveOutProfileReset - (nActive-1);
if (changedActiveOutProfile >= nResetOutProfile
&& changedActiveOutProfile >= fResetOutProfile * nActiveOutProfileReset) {
/* Recompute the outprofile from scratch to avoid roundoff error */
profile_t **activeProfiles = (profile_t**)mymalloc(sizeof(profile_t*)*(nActive-1));
int nSaved = 0;
NJ->totdiam = 0;
for (iNode=0;iNode<NJ->maxnode;iNode++) {
if (NJ->parent[iNode]<0) {
assert(nSaved < nActive-1);
activeProfiles[nSaved++] = NJ->profiles[iNode];
NJ->totdiam += NJ->diameter[iNode];
}
}
assert(nSaved==nActive-1);
FreeProfile(NJ->outprofile, NJ->nPos, NJ->nConstraints);
if(verbose>2) fprintf(stderr,"Recomputing outprofile %d %d\n",nActiveOutProfileReset,nActive-1);
NJ->outprofile = OutProfile(activeProfiles, nSaved,
NJ->nPos, NJ->nConstraints,
NJ->distance_matrix);
activeProfiles = myfree(activeProfiles, sizeof(profile_t*)*(nActive-1));
nActiveOutProfileReset = nActive-1;
} else {
UpdateOutProfile(/*OUT*/NJ->outprofile,
NJ->profiles[join.i], NJ->profiles[join.j], NJ->profiles[newnode],
nActive,
NJ->nPos, NJ->nConstraints,
NJ->distance_matrix);
NJ->totdiam += NJ->diameter[newnode] - NJ->diameter[join.i] - NJ->diameter[join.j];
}
/* Store self-dist for use in other computations */
besthit_t selfdist;
ProfileDist(NJ->profiles[newnode],NJ->profiles[newnode],NJ->nPos,NJ->distance_matrix,/*OUT*/&selfdist);
NJ->selfdist[newnode] = selfdist.dist;
NJ->selfweight[newnode] = selfdist.weight;
/* Find the best hit of the joined node IJ */
if (m>0) {
TopHitJoin(newnode, /*IN/UPDATE*/NJ, nActive-1, /*IN/OUT*/tophits);
} else {
/* Not using top-hits, so we update all out-distances */
for (iNode = 0; iNode < NJ->maxnode; iNode++) {
if (NJ->parent[iNode] < 0) {
/* True nActive is now nActive-1 */
SetOutDistance(/*IN/UPDATE*/NJ, iNode, nActive-1);
}
}
if(visible != NULL) {
SetBestHit(newnode, NJ, nActive-1, /*OUT*/&visible[newnode], /*OUT OPTIONAL*/besthitNew);
if (verbose>2)
fprintf(stderr,"Visible %d %d %f %f\n",
visible[newnode].i, visible[newnode].j,
visible[newnode].dist, visible[newnode].criterion);
if (besthitNew != NULL) {
/* Use distances to new node to update visible set entries that are non-optimal */
for (iNode = 0; iNode < NJ->maxnode; iNode++) {
if (NJ->parent[iNode] >= 0 || iNode == newnode)
continue;
int iOldVisible = visible[iNode].j;
assert(iOldVisible>=0);
assert(visible[iNode].i == iNode);
/* Update the criterion; use nActive-1 because haven't decremented nActive yet */
if (NJ->parent[iOldVisible] < 0)
SetCriterion(/*IN/OUT*/NJ, nActive-1, &visible[iNode]);
if (NJ->parent[iOldVisible] >= 0
|| besthitNew[iNode].criterion < visible[iNode].criterion) {
if(verbose>3) fprintf(stderr,"Visible %d reset from %d to %d (%f vs. %f)\n",
iNode, iOldVisible,
newnode, visible[iNode].criterion, besthitNew[iNode].criterion);
if(NJ->parent[iOldVisible] < 0) nVisibleUpdate++;
visible[iNode].j = newnode;
visible[iNode].dist = besthitNew[iNode].dist;
visible[iNode].criterion = besthitNew[iNode].criterion;
}
} /* end loop over all nodes */
} /* end if recording all hits of new node */
} /* end if keeping a visible set */
} /* end else (m==0) */
} /* end loop over nActive */
#ifdef TRACK_MEMORY
if (verbose>1) {
struct mallinfo mi = mallinfo();
fprintf(stderr, "Memory @ end of FastNJ(): %.2f MB (%.1f byte/pos) useful %.2f expected %.2f\n",
(mi.arena+mi.hblkhd)/1.0e6, (mi.arena+mi.hblkhd)/(double)(NJ->nSeq*(double)NJ->nPos),
mi.uordblks/1.0e6, mymallocUsed/1e6);
}
#endif
/* We no longer need the tophits, visible set, etc. */
if (visible != NULL) visible = myfree(visible,sizeof(besthit_t)*NJ->maxnodes);
if (besthitNew != NULL) besthitNew = myfree(besthitNew,sizeof(besthit_t)*NJ->maxnodes);
tophits = FreeTopHits(tophits);
/* Add a root for the 3 remaining nodes */
int top[3];
int nTop = 0;
for (iNode = 0; iNode < NJ->maxnode; iNode++) {
if (NJ->parent[iNode] < 0) {
assert(nTop <= 2);
top[nTop++] = iNode;
}
}
assert(nTop==3);
NJ->root = NJ->maxnode++;
NJ->child[NJ->root].nChild = 3;
for (nTop = 0; nTop < 3; nTop++) {
NJ->parent[top[nTop]] = NJ->root;
NJ->child[NJ->root].child[nTop] = top[nTop];
}
besthit_t dist01, dist02, dist12;
ProfileDist(NJ->profiles[top[0]], NJ->profiles[top[1]], NJ->nPos, NJ->distance_matrix, /*OUT*/&dist01);
ProfileDist(NJ->profiles[top[0]], NJ->profiles[top[2]], NJ->nPos, NJ->distance_matrix, /*OUT*/&dist02);
ProfileDist(NJ->profiles[top[1]], NJ->profiles[top[2]], NJ->nPos, NJ->distance_matrix, /*OUT*/&dist12);
double d01 = dist01.dist - NJ->diameter[top[0]] - NJ->diameter[top[1]];
double d02 = dist02.dist - NJ->diameter[top[0]] - NJ->diameter[top[2]];
double d12 = dist12.dist - NJ->diameter[top[1]] - NJ->diameter[top[2]];
NJ->branchlength[top[0]] = (d01 + d02 - d12)/2;
NJ->branchlength[top[1]] = (d01 + d12 - d02)/2;
NJ->branchlength[top[2]] = (d02 + d12 - d01)/2;
/* Check how accurate the outprofile is */
if (verbose>2) {
profile_t *p[3] = {NJ->profiles[top[0]], NJ->profiles[top[1]], NJ->profiles[top[2]]};
profile_t *out = OutProfile(p, 3, NJ->nPos, NJ->nConstraints, NJ->distance_matrix);
int i;
double freqerror = 0;
double weighterror = 0;
for (i=0;i<NJ->nPos;i++) {
weighterror += fabs(out->weights[i] - NJ->outprofile->weights[i]);
int k;
for(k=0;k<nCodes;k++)
freqerror += fabs(out->vectors[nCodes*i+k] - NJ->outprofile->vectors[nCodes*i+k]);
}
fprintf(stderr,"Roundoff error in outprofile@end: WeightError %f FreqError %f\n", weighterror, freqerror);
FreeProfile(out, NJ->nPos, NJ->nConstraints);
}
return;
}
void ExhaustiveNJSearch(NJ_t *NJ, int nActive, /*OUT*/besthit_t *join) {
join->i = -1;
join->j = -1;
join->weight = 0;
join->dist = 1e20;
join->criterion = 1e20;
double bestCriterion = 1e20;
int i, j;
for (i = 0; i < NJ->maxnode-1; i++) {
if (NJ->parent[i] < 0) {
for (j = i+1; j < NJ->maxnode; j++) {
if (NJ->parent[j] < 0) {
besthit_t hit;
hit.i = i;
hit.j = j;
SetDistCriterion(NJ, nActive, /*IN/OUT*/&hit);
if (hit.criterion < bestCriterion) {
*join = hit;
bestCriterion = hit.criterion;
}
}
}
}
}
assert (join->i >= 0 && join->j >= 0);
}
void FastNJSearch(NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *besthits, /*OUT*/besthit_t *join) {
join->i = -1;
join->j = -1;
join->dist = 1e20;
join->weight = 0;
join->criterion = 1e20;
int iNode;
for (iNode = 0; iNode < NJ->maxnode; iNode++) {
int jNode = besthits[iNode].j;
if (NJ->parent[iNode] < 0 && NJ->parent[jNode] < 0) { /* both i and j still active */
/* recompute criterion to reflect the current out-distances */
SetCriterion(NJ, nActive, /*IN/OUT*/&besthits[iNode]);
if (besthits[iNode].criterion < join->criterion)
*join = besthits[iNode];
}
}
if(!fastest) {
int changed;
do {
changed = 0;
assert(join->i >= 0 && join->j >= 0);
SetBestHit(join->i, NJ, nActive, /*OUT*/&besthits[join->i], /*OUT IGNORED*/NULL);
if (besthits[join->i].j != join->j) {
changed = 1;
if (verbose>2)
fprintf(stderr,"BetterI\t%d\t%d\t%d\t%d\t%f\t%f\n",
join->i,join->j,besthits[join->i].i,besthits[join->i].j,
join->criterion,besthits[join->i].criterion);
}
/* Save the best hit either way, because the out-distance has probably changed
since we started the computation. */
join->j = besthits[join->i].j;
join->weight = besthits[join->i].weight;
join->dist = besthits[join->i].dist;
join->criterion = besthits[join->i].criterion;
SetBestHit(join->j, NJ, nActive, /*OUT*/&besthits[join->j], /*OUT IGNORE*/NULL);
if (besthits[join->j].j != join->i) {
changed = 1;
if (verbose>2)
fprintf(stderr,"BetterJ\t%d\t%d\t%d\t%d\t%f\t%f\n",
join->i,join->j,besthits[join->j].i,besthits[join->j].j,
join->criterion,besthits[join->j].criterion);
join->i = besthits[join->j].j;
join->weight = besthits[join->j].weight;
join->dist = besthits[join->j].dist;
join->criterion = besthits[join->j].criterion;
}
if(changed) nHillBetter++;
} while(changed);
}
}
/* A token is one of ():;, or an alphanumeric string without whitespace
Any whitespace between tokens is ignored */
char *ReadTreeToken(FILE *fp) {
static char buf[BUFFER_SIZE];
int len = 0;
int c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp)) {
if (c == '(' || c == ')' || c == ':' || c == ';' || c == ',') {
/* standalone token */
if (len == 0) {
buf[len++] = c;
buf[len] = '\0';
return(buf);
} else {
ungetc(c, fp);
buf[len] = '\0';
return(buf);
}
} else if (isspace(c)) {
if (len > 0) {
buf[len] = '\0';
return(buf);
}
/* else ignore whitespace at beginning of token */
} else {
/* not whitespace or standalone token */
buf[len++] = c;
if (len >= BUFFER_SIZE) {
buf[BUFFER_SIZE-1] = '\0';
fprintf(stderr, "Token too long in tree file, token begins with\n%s\n", buf);
exit(1);
}
}
}
if (len > 0) {
/* return the token we have so far */
buf[len] = '\0';
return(buf);
}
/* else */
return(NULL);
}
void ReadTreeError(char *err, char *token) {
fprintf(stderr, "Tree parse error: unexpected token '%s' -- %s\n",
token == NULL ? "(End of file)" : token,
err);
exit(1);
}
void ReadTreeAddChild(int parent, int child, /*IN/OUT*/int *parents, /*IN/OUT*/children_t *children) {
assert(parent >= 0);
assert(child >= 0);
assert(parents[child] < 0);
assert(children[parent].nChild < 3);
parents[child] = parent;
children[parent].child[children[parent].nChild++] = child;
}
void ReadTreeMaybeAddLeaf(int parent, char *name,
hashstrings_t *hashnames, uniquify_t *unique,
/*IN/OUT*/int *parents, /*IN/OUT*/children_t *children) {
hashiterator_t hi = FindMatch(hashnames,name);
if (HashCount(hashnames,hi) != 1)
ReadTreeError("not recognized as a sequence name", name);
int iSeqNonunique = HashFirst(hashnames,hi);
assert(iSeqNonunique >= 0 && iSeqNonunique < unique->nSeq);
int iSeqUnique = unique->alnToUniq[iSeqNonunique];
assert(iSeqUnique >= 0 && iSeqUnique < unique->nUnique);
/* Either record this leaves' parent (if it is -1) or ignore this leaf (if already seen) */
if (parents[iSeqUnique] < 0) {
ReadTreeAddChild(parent, iSeqUnique, /*IN/OUT*/parents, /*IN/OUT*/children);
if(verbose > 5)
fprintf(stderr, "Found leaf uniq%d name %s child of %d\n", iSeqUnique, name, parent);
} else {
if (verbose > 5)
fprintf(stderr, "Skipped redundant leaf uniq%d name %s\n", iSeqUnique, name);
}
}
void ReadTreeRemove(/*IN/OUT*/int *parents, /*IN/OUT*/children_t *children, int node) {
if(verbose > 5)
fprintf(stderr,"Removing node %d parent %d\n", node, parents[node]);
assert(parents[node] >= 0);
int parent = parents[node];
parents[node] = -1;
children_t *pc = &children[parent];
int oldn;
for (oldn = 0; oldn < pc->nChild; oldn++) {
if (pc->child[oldn] == node)
break;
}
assert(oldn < pc->nChild);
/* move successor nodes back in child list and shorten list */
int i;
for (i = oldn; i < pc->nChild-1; i++)
pc->child[i] = pc->child[i+1];
pc->nChild--;
/* add its children to parent's child list */
children_t *nc = &children[node];
if (nc->nChild > 0) {
assert(nc->nChild<=2);
assert(pc->nChild < 3);
assert(pc->nChild + nc->nChild <= 3);
int j;
for (j = 0; j < nc->nChild; j++) {
if(verbose > 5)
fprintf(stderr,"Repointing parent %d to child %d\n", parent, nc->child[j]);
pc->child[pc->nChild++] = nc->child[j];
parents[nc->child[j]] = parent;
}
nc->nChild = 0;
}
}
void ReadTree(/*IN/OUT*/NJ_t *NJ,
/*IN*/uniquify_t *unique,
/*IN*/hashstrings_t *hashnames,
/*READ*/FILE *fpInTree) {
assert(NJ->nSeq == unique->nUnique);
/* First, do a preliminary parse of the tree to with non-unique leaves ignored
We need to store this separately from NJ because it may have too many internal nodes
(matching sequences show up once in the NJ but could be in multiple places in the tree)
Will use iUnique as the index of nodes, as in the NJ structure
*/
int maxnodes = unique->nSeq*2;
int maxnode = unique->nSeq;
int *parent = (int*)mymalloc(sizeof(int)*maxnodes);
children_t *children = (children_t *)mymalloc(sizeof(children_t)*maxnodes);
int root = maxnode++;
int i;
for (i = 0; i < maxnodes; i++) {
parent[i] = -1;
children[i].nChild = 0;
}
/* The stack is the current path to the root, with the root at the first (top) position */
int stack_size = 1;
int *stack = (int*)mymalloc(sizeof(int)*maxnodes);
stack[0] = root;
int nDown = 0;
int nUp = 0;
char *token;
token = ReadTreeToken(fpInTree);
if (token == NULL || *token != '(')
ReadTreeError("No '(' at start", token);
/* nDown is still 0 because we have created the root */
while ((token = ReadTreeToken(fpInTree)) != NULL) {
if (nDown > 0) { /* In a stream of parentheses */
if (*token == '(')
nDown++;
else if (*token == ',' || *token == ';' || *token == ':' || *token == ')')
ReadTreeError("while reading parentheses", token);
else {
/* Add intermediate nodes if nDown was > 1 (for nDown=1, the only new node is the leaf) */
while (nDown-- > 0) {
int new = maxnode++;
assert(new < maxnodes);
ReadTreeAddChild(stack[stack_size-1], new, /*IN/OUT*/parent, /*IN/OUT*/children);
if(verbose > 5)
fprintf(stderr, "Added internal child %d of %d, stack size increase to %d\n",
new, stack[stack_size-1],stack_size+1);
stack[stack_size++] = new;
assert(stack_size < maxnodes);
}
ReadTreeMaybeAddLeaf(stack[stack_size-1], token,
hashnames, unique,
/*IN/OUT*/parent, /*IN/OUT*/children);
}
} else if (nUp > 0) {
if (*token == ';') { /* end the tree? */
if (nUp != stack_size)
ReadTreeError("unbalanced parentheses", token);
else
break;
} else if (*token == ')')
nUp++;
else if (*token == '(')
ReadTreeError("unexpected '(' after ')'", token);
else if (*token == ':') {
token = ReadTreeToken(fpInTree);
/* Read the branch length and ignore it */
if (token == NULL || (*token != '-' && !isdigit(*token)))
ReadTreeError("not recognized as a branch length", token);
} else if (*token == ',') {
/* Go back up the stack the correct #times */
while (nUp-- > 0) {
stack_size--;
if(verbose > 5)
fprintf(stderr, "Up to nUp=%d stack size %d at %d\n",
nUp, stack_size, stack[stack_size-1]);
if (stack_size <= 0)
ReadTreeError("too many ')'", token);
}
nUp = 0;
} else if (*token == '-' || isdigit(*token))
; /* ignore bootstrap value */
else
fprintf(stderr, "Warning while parsing tree: non-numeric label %s for internal node\n",
token);
} else if (*token == '(') {
nDown = 1;
} else if (*token == ')') {
nUp = 1;
} else if (*token == ':') {
token = ReadTreeToken(fpInTree);
if (token == NULL || (*token != '-' && !isdigit(*token)))
ReadTreeError("not recognized as a branch length", token);
} else if (*token == ',') {
; /* do nothing */
} else if (*token == ';')
ReadTreeError("unexpected token", token);
else
ReadTreeMaybeAddLeaf(stack[stack_size-1], token,
hashnames, unique,
/*IN/OUT*/parent, /*IN/OUT*/children);
}
/* Verify that all sequences were seen */
for (i = 0; i < unique->nUnique; i++) {
if (parent[i] < 0) {
fprintf(stderr, "Alignment sequence %d (unique %d) absent from input tree\n"
"The starting tree (the argument to -intree) must include all sequences in the alignment!\n",
unique->uniqueFirst[i], i);
exit(1);
}
}
/* Simplify the tree -- remove all internal nodes with < 2 children
Keep trying until no nodes get removed
*/
int nRemoved;
do {
nRemoved = 0;
/* Here stack is the list of nodes we haven't visited yet while doing
a tree traversal */
stack_size = 1;
stack[0] = root;
while (stack_size > 0) {
int node = stack[--stack_size];
if (node >= unique->nUnique) { /* internal node */
if (children[node].nChild <= 1) {
if (node != root) {
ReadTreeRemove(/*IN/OUT*/parent,/*IN/OUT*/children,node);
nRemoved++;
} else if (node == root && children[node].nChild == 1) {
int newroot = children[node].child[0];
parent[newroot] = -1;
children[root].nChild = 0;
nRemoved++;
if(verbose > 5)
fprintf(stderr,"Changed root from %d to %d\n",root,newroot);
root = newroot;
stack[stack_size++] = newroot;
}
} else {
int j;
for (j = 0; j < children[node].nChild; j++) {
assert(stack_size < maxnodes);
stack[stack_size++] = children[node].child[j];
if(verbose > 5)
fprintf(stderr,"Added %d to stack\n", stack[stack_size-1]);
}
}
}
}
} while (nRemoved > 0);
/* Simplify the root node to 3 children if it has 2 */
if (children[root].nChild == 2) {
for (i = 0; i < 2; i++) {
int child = children[root].child[i];
assert(child >= 0 && child < maxnodes);
if (children[child].nChild == 2) {
ReadTreeRemove(parent,children,child); /* replace root -> child -> A,B with root->A,B */
break;
}
}
}
for (i = 0; i < maxnodes; i++)
if(verbose > 5)
fprintf(stderr,"Simplfied node %d has parent %d nchild %d\n",
i, parent[i], children[i].nChild);
/* Map the remaining internal nodes to NJ nodes */
int *map = (int*)mymalloc(sizeof(int)*maxnodes);
for (i = 0; i < unique->nUnique; i++)
map[i] = i;
for (i = unique->nUnique; i < maxnodes; i++)
map[i] = -1;
stack_size = 1;
stack[0] = root;
while (stack_size > 0) {
int node = stack[--stack_size];
if (node >= unique->nUnique) { /* internal node */
assert(node == root || children[node].nChild > 1);
map[node] = NJ->maxnode++;
for (i = 0; i < children[node].nChild; i++) {
assert(stack_size < maxnodes);
stack[stack_size++] = children[node].child[i];
}
}
}
for (i = 0; i < maxnodes; i++)
if(verbose > 5)
fprintf(stderr,"Map %d to %d (parent %d nchild %d)\n",
i, map[i], parent[i], children[i].nChild);
/* Set NJ->parent, NJ->children, NJ->root */
NJ->root = map[root];
int node;
for (node = 0; node < maxnodes; node++) {
int njnode = map[node];
if (njnode >= 0) {
NJ->child[njnode].nChild = children[node].nChild;
for (i = 0; i < children[node].nChild; i++) {
assert(children[node].child[i] >= 0 && children[node].child[i] < maxnodes);
NJ->child[njnode].child[i] = map[children[node].child[i]];
}
if (parent[node] >= 0)
NJ->parent[njnode] = map[parent[node]];
}
}
/* Make sure that parent/child relationships match */
for (i = 0; i < NJ->maxnode; i++) {
children_t *c = &NJ->child[i];
int j;
for (j = 0; j < c->nChild;j++)
assert(c->child[j] >= 0 && c->child[j] < NJ->maxnode && NJ->parent[c->child[j]] == i);
}
assert(NJ->parent[NJ->root] < 0);
map = myfree(map,sizeof(int)*maxnodes);
stack = myfree(stack,sizeof(int)*maxnodes);
children = myfree(children,sizeof(children_t)*maxnodes);
parent = myfree(parent,sizeof(int)*maxnodes);
/* Compute profiles as balanced -- the NNI stage will recompute these
profiles anyway
*/
traversal_t traversal = InitTraversal(NJ);
node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
if (node >= NJ->nSeq && node != NJ->root)
SetProfile(/*IN/OUT*/NJ, node, /*noweight*/-1.0);
}
traversal = FreeTraversal(traversal,NJ);
}
/* Print topology using node indices as node names */
void PrintNJInternal(FILE *fp, NJ_t *NJ, bool useLen) {
if (NJ->nSeq < 4) {
return;
}
typedef struct { int node; int end; } stack_t;
stack_t *stack = (stack_t *)mymalloc(sizeof(stack_t)*NJ->maxnodes);
int stackSize = 1;
stack[0].node = NJ->root;
stack[0].end = 0;
while(stackSize>0) {
stack_t *last = &stack[stackSize-1];
stackSize--;
/* Save last, as we are about to overwrite it */
int node = last->node;
int end = last->end;
if (node < NJ->nSeq) {
if (NJ->child[NJ->parent[node]].child[0] != node) fputs(",",fp);
fprintf(fp, "%d", node);
if (useLen)
fprintf(fp, ":%.4f", NJ->branchlength[node]);
} else if (end) {
fprintf(fp, ")%d", node);
if (useLen)
fprintf(fp, ":%.4f", NJ->branchlength[node]);
} else {
if (node != NJ->root && NJ->child[NJ->parent[node]].child[0] != node) fprintf(fp, ",");
fprintf(fp, "(");
stackSize++;
stack[stackSize-1].node = node;
stack[stackSize-1].end = 1;
children_t *c = &NJ->child[node];
/* put children on in reverse order because we use the last one first */
int i;
for (i = c->nChild-1; i >=0; i--) {
stackSize++;
stack[stackSize-1].node = c->child[i];
stack[stackSize-1].end = 0;
}
}
}
fprintf(fp, ";\n");
stack = myfree(stack, sizeof(stack_t)*NJ->maxnodes);
}
void PrintNJ(FILE *fp, NJ_t *NJ, char **names, uniquify_t *unique, bool bShowSupport, bool bQuote) {
/* And print the tree: depth first search
* The stack contains
* list of remaining children with their depth
* parent node, with a flag of -1 so I know to print right-paren
*/
if (NJ->nSeq==1 && unique->alnNext[unique->uniqueFirst[0]] >= 0) {
/* Special case -- otherwise we end up with double parens */
int first = unique->uniqueFirst[0];
assert(first >= 0 && first < unique->nSeq);
fprintf(fp, bQuote ? "('%s':0.0" : "(%s:0.0", names[first]);
int iName = unique->alnNext[first];
while (iName >= 0) {
assert(iName < unique->nSeq);
fprintf(fp, bQuote ? ",'%s':0.0" : ",%s:0.0", names[iName]);
iName = unique->alnNext[iName];
}
fprintf(fp,");\n");
return;
}
typedef struct { int node; int end; } stack_t;
stack_t *stack = (stack_t *)mymalloc(sizeof(stack_t)*NJ->maxnodes);
int stackSize = 1;
stack[0].node = NJ->root;
stack[0].end = 0;
while(stackSize>0) {
stack_t *last = &stack[stackSize-1];
stackSize--;
/* Save last, as we are about to overwrite it */
int node = last->node;
int end = last->end;
if (node < NJ->nSeq) {
if (NJ->child[NJ->parent[node]].child[0] != node) fputs(",",fp);
int first = unique->uniqueFirst[node];
assert(first >= 0 && first < unique->nSeq);
/* Print the name, or the subtree of duplicate names */
if (unique->alnNext[first] == -1) {
fprintf(fp, bQuote ? "'%s'" : "%s", names[first]);
} else {
fprintf(fp, bQuote ? "('%s':0.0" : "(%s:0.0", names[first]);
int iName = unique->alnNext[first];
while (iName >= 0) {
assert(iName < unique->nSeq);
fprintf(fp, bQuote ? ",'%s':0.0" : ",%s:0.0", names[iName]);
iName = unique->alnNext[iName];
}
fprintf(fp,")");
}
/* Print the branch length */
#ifdef USE_DOUBLE
#define FP_FORMAT "%.9f"
#else
#define FP_FORMAT "%.5f"
#endif
fprintf(fp, ":" FP_FORMAT, NJ->branchlength[node]);
} else if (end) {
if (node == NJ->root)
fprintf(fp, ")");
else if (bShowSupport)
fprintf(fp, ")%.3f:" FP_FORMAT, NJ->support[node], NJ->branchlength[node]);
else
fprintf(fp, "):" FP_FORMAT, NJ->branchlength[node]);
} else {
if (node != NJ->root && NJ->child[NJ->parent[node]].child[0] != node) fprintf(fp, ",");
fprintf(fp, "(");
stackSize++;
stack[stackSize-1].node = node;
stack[stackSize-1].end = 1;
children_t *c = &NJ->child[node];
/* put children on in reverse order because we use the last one first */
int i;
for (i = c->nChild-1; i >=0; i--) {
stackSize++;
stack[stackSize-1].node = c->child[i];
stack[stackSize-1].end = 0;
}
}
}
fprintf(fp, ";\n");
stack = myfree(stack, sizeof(stack_t)*NJ->maxnodes);
}
alignment_t *ReadAlignment(/*IN*/FILE *fp, bool bQuote) {
/* bQuote supports the -quote option */
int nSeq = 0;
int nPos = 0;
char **names = NULL;
char **seqs = NULL;
char buf[BUFFER_SIZE] = "";
if (fgets(buf,sizeof(buf),fp) == NULL) {
fprintf(stderr, "Error reading header line\n");
exit(1);
}
int nSaved = 100;
if (buf[0] == '>') {
/* FASTA, truncate names at any of these */
char *nameStop = bQuote ? "'\t\r\n" : "(),: \t\r\n";
char *seqSkip = " \t\r\n"; /* skip these characters in the sequence */
seqs = (char**)mymalloc(sizeof(char*) * nSaved);
names = (char**)mymalloc(sizeof(char*) * nSaved);
do {
/* loop over lines */
if (buf[0] == '>') {
/* truncate the name */
char *p, *q;
for (p = buf+1; *p != '\0'; p++) {
for (q = nameStop; *q != '\0'; q++) {
if (*p == *q) {
*p = '\0';
break;
}
}
if (*p == '\0') break;
}
/* allocate space for another sequence */
nSeq++;
if (nSeq > nSaved) {
int nNewSaved = nSaved*2;
seqs = myrealloc(seqs,sizeof(char*)*nSaved,sizeof(char*)*nNewSaved, /*copy*/false);
names = myrealloc(names,sizeof(char*)*nSaved,sizeof(char*)*nNewSaved, /*copy*/false);
nSaved = nNewSaved;
}
names[nSeq-1] = (char*)mymemdup(buf+1,strlen(buf));
seqs[nSeq-1] = NULL;
} else {
/* count non-space characters and append to sequence */
int nKeep = 0;
char *p, *q;
for (p=buf; *p != '\0'; p++) {
for (q=seqSkip; *q != '\0'; q++) {
if (*p == *q)
break;
}
if (*p != *q)
nKeep++;
}
int nOld = (seqs[nSeq-1] == NULL) ? 0 : strlen(seqs[nSeq-1]);
seqs[nSeq-1] = (char*)myrealloc(seqs[nSeq-1], nOld, nOld+nKeep+1, /*copy*/false);
if (nOld+nKeep > nPos)
nPos = nOld + nKeep;
char *out = seqs[nSeq-1] + nOld;
for (p=buf; *p != '\0'; p++) {
for (q=seqSkip; *q != '\0'; q++) {
if (*p == *q)
break;
}
if (*p != *q) {
*out = *p;
out++;
}
}
assert(out-seqs[nSeq-1] == nKeep + nOld);
*out = '\0';
}
} while(fgets(buf,sizeof(buf),fp) != NULL);
if (seqs[nSeq-1] == NULL) {
fprintf(stderr, "No sequence data for last entry %s\n",names[nSeq-1]);
exit(1);
}
names = myrealloc(names,sizeof(char*)*nSaved,sizeof(char*)*nSeq, /*copy*/false);
seqs = myrealloc(seqs,sizeof(char*)*nSaved,sizeof(char*)*nSeq, /*copy*/false);
} else {
/* PHYLIP interleaved-like format
Allow arbitrary length names, require spaces between names and sequences
Allow multiple alignments, either separated by a single empty line (e.g. seqboot output)
or not.
*/
if (buf[0] == '\n' || buf[0] == '\r') {
if (fgets(buf,sizeof(buf),fp) == NULL) {
fprintf(stderr, "Empty header line followed by EOF\n");
exit(1);
}
}
if (sscanf(buf, "%d%d", &nSeq, &nPos) != 2
|| nSeq < 1 || nPos < 1) {
fprintf(stderr, "Error parsing header line:%s\n", buf);
exit(1);
}
names = (char **)mymalloc(sizeof(char*) * nSeq);
seqs = (char **)mymalloc(sizeof(char*) * nSeq);
nSaved = nSeq;
int i;
for (i = 0; i < nSeq; i++) {
names[i] = NULL;
seqs[i] = (char *)mymalloc(nPos+1); /* null-terminate */
seqs[i][0] = '\0';
}
int iSeq = 0;
while(fgets(buf,sizeof(buf),fp)) {
if ((buf[0] == '\n' || buf[0] == '\r') && (iSeq == nSeq || iSeq == 0)) {
iSeq = 0;
} else {
int j = 0; /* character just past end of name */
if (buf[0] == ' ') {
if (names[iSeq] == NULL) {
fprintf(stderr, "No name in phylip line %s", buf);
exit(1);
}
} else {
while (buf[j] != '\n' && buf[j] != '\0' && buf[j] != ' ')
j++;
if (buf[j] != ' ' || j == 0) {
fprintf(stderr, "No sequence in phylip line %s", buf);
exit(1);
}
if (iSeq >= nSeq) {
fprintf(stderr, "No empty line between sequence blocks (is the sequence count wrong?)\n");
exit(1);
}
if (names[iSeq] == NULL) {
/* save the name */
names[iSeq] = (char *)mymalloc(j+1);
int k;
for (k = 0; k < j; k++) names[iSeq][k] = buf[k];
names[iSeq][j] = '\0';
} else {
/* check the name */
int k;
int match = 1;
for (k = 0; k < j; k++) {
if (names[iSeq][k] != buf[k]) {
match = 0;
break;
}
}
if (!match || names[iSeq][j] != '\0') {
fprintf(stderr, "Wrong name in phylip line %s\nExpected %s\n", buf, names[iSeq]);
exit(1);
}
}
}
int seqlen = strlen(seqs[iSeq]);
for (; buf[j] != '\n' && buf[j] != '\0'; j++) {
if (buf[j] != ' ') {
if (seqlen >= nPos) {
fprintf(stderr, "Too many characters (expected %d) for sequence named %s\nSo far have:\n%s\n",
nPos, names[iSeq], seqs[iSeq]);
exit(1);
}
seqs[iSeq][seqlen++] = toupper(buf[j]);
}
}
seqs[iSeq][seqlen] = '\0'; /* null-terminate */
if(verbose>10) fprintf(stderr,"Read iSeq %d name %s seqsofar %s\n", iSeq, names[iSeq], seqs[iSeq]);
iSeq++;
if (iSeq == nSeq && strlen(seqs[0]) == nPos)
break; /* finished alignment */
} /* end else non-empty phylip line */
}
if (iSeq != nSeq && iSeq != 0) {
fprintf(stderr, "Wrong number of sequences: expected %d\n", nSeq);
exit(1);
}
}
/* Check lengths of sequences */
int i;
for (i = 0; i < nSeq; i++) {
int seqlen = strlen(seqs[i]);
if (seqlen != nPos) {
fprintf(stderr, "Wrong number of characters for %s: expected %d but have %d instead.\n"
"This sequence may be truncated, or another sequence may be too long.\n",
names[i], nPos, seqlen);
exit(1);
}
}
/* Replace "." with "-" and warn if we find any */
/* If nucleotide sequences, replace U with T and N with X */
bool findDot = false;
for (i = 0; i < nSeq; i++) {
char *p;
for (p = seqs[i]; *p != '\0'; p++) {
if (*p == '.') {
findDot = true;
*p = '-';
}
if (nCodes == 4 && *p == 'U')
*p = 'T';
if (nCodes == 4 && *p == 'N')
*p = 'X';
}
}
if (findDot)
fprintf(stderr, "Warning! Found \".\" character(s). These are treated as gaps\n");
if (ferror(fp)) {
fprintf(stderr, "Error reading input file\n");
exit(1);
}
alignment_t *align = (alignment_t*)mymalloc(sizeof(alignment_t));
align->nSeq = nSeq;
align->nPos = nPos;
align->names = names;
align->seqs = seqs;
align->nSaved = nSaved;
return(align);
}
void FreeAlignmentSeqs(/*IN/OUT*/alignment_t *aln) {
assert(aln != NULL);
int i;
for (i = 0; i < aln->nSeq; i++)
aln->seqs[i] = myfree(aln->seqs[i], aln->nPos+1);
}
alignment_t *FreeAlignment(alignment_t *aln) {
if(aln==NULL)
return(NULL);
int i;
for (i = 0; i < aln->nSeq; i++) {
aln->names[i] = myfree(aln->names[i],strlen(aln->names[i])+1);
aln->seqs[i] = myfree(aln->seqs[i], aln->nPos+1);
}
aln->names = myfree(aln->names, sizeof(char*)*aln->nSaved);
aln->seqs = myfree(aln->seqs, sizeof(char*)*aln->nSaved);
myfree(aln, sizeof(alignment_t));
return(NULL);
}
char **AlnToConstraints(alignment_t *constraints, uniquify_t *unique, hashstrings_t *hashnames) {
/* look up constraints as names and map to unique-space */
char ** uniqConstraints = (char**)mymalloc(sizeof(char*) * unique->nUnique);
int i;
for (i = 0; i < unique->nUnique; i++)
uniqConstraints[i] = NULL;
for (i = 0; i < constraints->nSeq; i++) {
char *name = constraints->names[i];
char *constraintSeq = constraints->seqs[i];
hashiterator_t hi = FindMatch(hashnames,name);
if (HashCount(hashnames,hi) != 1) {
fprintf(stderr, "Sequence %s from constraints file is not in the alignment\n", name);
exit(1);
}
int iSeqNonunique = HashFirst(hashnames,hi);
assert(iSeqNonunique >= 0 && iSeqNonunique < unique->nSeq);
int iSeqUnique = unique->alnToUniq[iSeqNonunique];
assert(iSeqUnique >= 0 && iSeqUnique < unique->nUnique);
if (uniqConstraints[iSeqUnique] != NULL) {
/* Already set a constraint for this group of sequences!
Warn that we are ignoring this one unless the constraints match */
if (strcmp(uniqConstraints[iSeqUnique],constraintSeq) != 0) {
fprintf(stderr,
"Warning: ignoring constraints for %s:\n%s\n"
"Another sequence has the same sequence but different constraints\n",
name, constraintSeq);
}
} else {
uniqConstraints[iSeqUnique] = constraintSeq;
}
}
return(uniqConstraints);
}
profile_t *SeqToProfile(/*IN/OUT*/NJ_t *NJ,
char *seq, int nPos,
/*OPTIONAL*/char *constraintSeq, int nConstraints,
int iNode,
unsigned long counts[256]) {
static unsigned char charToCode[256];
static int codeSet = 0;
int c, i;
if (!codeSet) {
for (c = 0; c < 256; c++) {
charToCode[c] = nCodes;
}
for (i = 0; codesString[i]; i++) {
charToCode[codesString[i]] = i;
charToCode[tolower(codesString[i])] = i;
}
charToCode['-'] = NOCODE;
codeSet=1;
}
assert(strlen(seq) == nPos);
profile_t *profile = NewProfile(nPos,nConstraints);
for (i = 0; i < nPos; i++) {
unsigned int character = (unsigned int) seq[i];
counts[character]++;
c = charToCode[character];
if(verbose>10 && i < 2) fprintf(stderr,"pos %d char %c code %d\n", i, seq[i], c);
/* treat unknowns as gaps */
if (c == nCodes || c == NOCODE) {
profile->codes[i] = NOCODE;
profile->weights[i] = 0.0;
} else {
profile->codes[i] = c;
profile->weights[i] = 1.0;
}
}
if (nConstraints > 0) {
for (i = 0; i < nConstraints; i++) {
profile->nOn[i] = 0;
profile->nOff[i] = 0;
}
bool bWarn = false;
if (constraintSeq != NULL) {
assert(strlen(constraintSeq) == nConstraints);
for (i = 0; i < nConstraints; i++) {
if (constraintSeq[i] == '1') {
profile->nOn[i] = 1;
} else if (constraintSeq[i] == '0') {
profile->nOff[i] = 1;
} else if (constraintSeq[i] != '-') {
if (!bWarn) {
fprintf(stderr, "Constraint characters in unique sequence %d replaced with gap:", iNode+1);
bWarn = true;
}
fprintf(stderr, " %c%d", constraintSeq[i], i+1);
/* For the benefit of ConstraintSequencePenalty -- this is a bit of a hack, as
this modifies the value read from the alignment
*/
constraintSeq[i] = '-';
}
}
if (bWarn)
fprintf(stderr, "\n");
}
}
return profile;
}
void SeqDist(unsigned char *codes1, unsigned char *codes2, int nPos,
distance_matrix_t *dmat,
/*OUT*/besthit_t *hit) {
double top = 0; /* summed over positions */
int nUse = 0;
int i;
if (dmat==NULL) {
int nDiff = 0;
for (i = 0; i < nPos; i++) {
if (codes1[i] != NOCODE && codes2[i] != NOCODE) {
nUse++;
if (codes1[i] != codes2[i]) nDiff++;
}
}
top = (double)nDiff;
} else {
for (i = 0; i < nPos; i++) {
if (codes1[i] != NOCODE && codes2[i] != NOCODE) {
nUse++;
top += dmat->distances[(unsigned int)codes1[i]][(unsigned int)codes2[i]];
}
}
}
hit->weight = (double)nUse;
hit->dist = nUse > 0 ? top/(double)nUse : 1.0;
seqOps++;
}
void CorrectedPairDistances(profile_t **profiles, int nProfiles,
/*OPTIONAL*/distance_matrix_t *distance_matrix,
int nPos,
/*OUT*/double *distances) {
assert(distances != NULL);
assert(profiles != NULL);
assert(nProfiles>1 && nProfiles <= 4);
besthit_t hit[6];
int iHit,i,j;
for (iHit=0, i=0; i < nProfiles; i++) {
for (j=i+1; j < nProfiles; j++, iHit++) {
ProfileDist(profiles[i],profiles[j],nPos,distance_matrix,/*OUT*/&hit[iHit]);
distances[iHit] = hit[iHit].dist;
}
}
if (pseudoWeight > 0) {
/* Estimate the prior distance */
double dTop = 0;
double dBottom = 0;
for (iHit=0; iHit < (nProfiles*(nProfiles-1))/2; iHit++) {
dTop += hit[iHit].dist * hit[iHit].weight;
dBottom += hit[iHit].weight;
}
double prior = (dBottom > 0.01) ? dTop/dBottom : 3.0;
for (iHit=0; iHit < (nProfiles*(nProfiles-1))/2; iHit++)
distances[iHit] = (distances[iHit] * hit[iHit].weight + prior * pseudoWeight)
/ (hit[iHit].weight + pseudoWeight);
}
if (logdist) {
for (iHit=0; iHit < (nProfiles*(nProfiles-1))/2; iHit++)
distances[iHit] = LogCorrect(distances[iHit]);
}
}
/* During the neighbor-joining phase, a join only violates our constraints if
node1, node2, and other are all represented in the constraint
and if one of the 3 is split and the other two do not agree
*/
int JoinConstraintPenalty(/*IN*/NJ_t *NJ, int node1, int node2) {
if (NJ->nConstraints == 0)
return(0.0);
int penalty = 0;
int iC;
for (iC = 0; iC < NJ->nConstraints; iC++)
penalty += JoinConstraintPenaltyPiece(NJ, node1, node2, iC);
return(penalty);
}
int JoinConstraintPenaltyPiece(NJ_t *NJ, int node1, int node2, int iC) {
profile_t *pOut = NJ->outprofile;
profile_t *p1 = NJ->profiles[node1];
profile_t *p2 = NJ->profiles[node2];
int nOn1 = p1->nOn[iC];
int nOff1 = p1->nOff[iC];
int nOn2 = p2->nOn[iC];
int nOff2 = p2->nOff[iC];
int nOnOut = pOut->nOn[iC] - nOn1 - nOn2;
int nOffOut = pOut->nOff[iC] - nOff1 - nOff2;
if ((nOn1+nOff1) > 0 && (nOn2+nOff2) > 0 && (nOnOut+nOffOut) > 0) {
/* code is -1 for split, 0 for off, 1 for on */
int code1 = (nOn1 > 0 && nOff1 > 0) ? -1 : (nOn1 > 0 ? 1 : 0);
int code2 = (nOn2 > 0 && nOff2 > 0) ? -1 : (nOn2 > 0 ? 1 : 0);
int code3 = (nOnOut > 0 && nOffOut) > 0 ? -1 : (nOnOut > 0 ? 1 : 0);
int nSplit = (code1 == -1 ? 1 : 0) + (code2 == -1 ? 1 : 0) + (code3 == -1 ? 1 : 0);
int nOn = (code1 == 1 ? 1 : 0) + (code2 == 1 ? 1 : 0) + (code3 == 1 ? 1 : 0);
if (nSplit == 1 && nOn == 1)
return(SplitConstraintPenalty(nOn1+nOn2, nOff1+nOff2, nOnOut, nOffOut));
}
/* else */
return(0);
}
void QuartetConstraintPenalties(profile_t *profiles[4], int nConstraints, /*OUT*/double penalty[3]) {
int i;
for (i=0; i < 3; i++)
penalty[i] = 0.0;
if(nConstraints == 0)
return;
int iC;
for (iC = 0; iC < nConstraints; iC++) {
double part[3];
if (QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/part)) {
for (i=0;i<3;i++)
penalty[i] += part[i];
if (verbose>2
&& (fabs(part[ABvsCD]-part[ACvsBD]) > 0.001 || fabs(part[ABvsCD]-part[ADvsBC]) > 0.001))
fprintf(stderr, "Constraint Penalties at %d: ABvsCD %.3f ACvsBD %.3f ADvsBC %.3f %d/%d %d/%d %d/%d %d/%d\n",
iC, part[ABvsCD], part[ACvsBD], part[ADvsBC],
profiles[0]->nOn[iC], profiles[0]->nOff[iC],
profiles[1]->nOn[iC], profiles[1]->nOff[iC],
profiles[2]->nOn[iC], profiles[2]->nOff[iC],
profiles[3]->nOn[iC], profiles[3]->nOff[iC]);
}
}
if (verbose>2)
fprintf(stderr, "Total Constraint Penalties: ABvsCD %.3f ACvsBD %.3f ADvsBC %.3f\n",
penalty[ABvsCD], penalty[ACvsBD], penalty[ADvsBC]);
}
double PairConstraintDistance(int nOn1, int nOff1, int nOn2, int nOff2) {
double f1 = nOn1/(double)(nOn1+nOff1);
double f2 = nOn2/(double)(nOn2+nOff2);
/* 1 - f1 * f2 - (1-f1)*(1-f2) = 1 - f1 * f2 - 1 + f1 + f2 - f1 * f2 */
return(f1 + f2 - 2.0 * f1 * f2);
}
bool QuartetConstraintPenaltiesPiece(profile_t *profiles[4], int iC, /*OUT*/double piece[3]) {
int nOn[4];
int nOff[4];
int i;
int nSplit = 0;
int nPlus = 0;
int nMinus = 0;
for (i=0; i < 4; i++) {
nOn[i] = profiles[i]->nOn[iC];
nOff[i] = profiles[i]->nOff[iC];
if (nOn[i] + nOff[i] == 0)
return(false); /* ignore */
else if (nOn[i] > 0 && nOff[i] > 0)
nSplit++;
else if (nOn[i] > 0)
nPlus++;
else
nMinus++;
}
/* If just one of them is split or on the other side and the others all agree, also ignore */
if (nPlus >= 3 || nMinus >= 3)
return(false);
piece[ABvsCD] = constraintWeight
* (PairConstraintDistance(nOn[0],nOff[0],nOn[1],nOff[1])
+ PairConstraintDistance(nOn[2],nOff[2],nOn[3],nOff[3]));
piece[ACvsBD] = constraintWeight
* (PairConstraintDistance(nOn[0],nOff[0],nOn[2],nOff[2])
+ PairConstraintDistance(nOn[1],nOff[1],nOn[3],nOff[3]));
piece[ADvsBC] = constraintWeight
* (PairConstraintDistance(nOn[0],nOff[0],nOn[3],nOff[3])
+ PairConstraintDistance(nOn[2],nOff[2],nOn[1],nOff[1]));
return(true);
}
/* Minimum number of constrained leaves that need to be moved
to satisfy the constraint (or 0 if constraint is satisfied)
Defining it this way should ensure that SPR moves that break
constraints get a penalty
*/
int SplitConstraintPenalty(int nOn1, int nOff1, int nOn2, int nOff2) {
return(nOn1 + nOff2 < nOn2 + nOff1 ?
(nOn1 < nOff2 ? nOn1 : nOff2)
: (nOn2 < nOff1 ? nOn2 : nOff1));
}
bool SplitViolatesConstraint(profile_t *profiles[4], int iConstraint) {
int i;
int codes[4]; /* 0 for off, 1 for on, -1 for split (quit if not constrained at all) */
for (i = 0; i < 4; i++) {
if (profiles[i]->nOn[iConstraint] + profiles[i]->nOff[iConstraint] == 0)
return(false);
else if (profiles[i]->nOn[iConstraint] > 0 && profiles[i]->nOff[iConstraint] == 0)
codes[i] = 1;
else if (profiles[i]->nOn[iConstraint] == 0 && profiles[i]->nOff[iConstraint] > 0)
codes[i] = 0;
else
codes[i] = -1;
}
int n0 = 0;
int n1 = 0;
for (i = 0; i < 4; i++) {
if (codes[i] == 0)
n0++;
else if (codes[i] == 1)
n1++;
}
/* 3 on one side means no violation, even if other is code -1
otherwise must have code != -1 and agreement on the split
*/
if (n0 >= 3 || n1 >= 3)
return(false);
if (n0==2 && n1==2 && codes[0] == codes[1] && codes[2] == codes[3])
return(false);
return(true);
}
double LogCorrect(double dist) {
const double maxscore = 3.0;
if (nCodes == 4 && !useMatrix) { /* Jukes-Cantor */
dist = dist < 0.74 ? -0.75*log(1.0 - dist * 4.0/3.0) : maxscore;
} else { /* scoredist-like */
dist = dist < 0.99 ? -1.3*log(1.0 - dist) : maxscore;
}
return (dist < maxscore ? dist : maxscore);
}
/* A helper function -- f1 and f2 can be NULL if the corresponding code != NOCODE
*/
double ProfileDistPiece(unsigned int code1, unsigned int code2,
numeric_t *f1, numeric_t *f2,
/*OPTIONAL*/distance_matrix_t *dmat,
/*OPTIONAL*/numeric_t *codeDist2) {
if (dmat) {
if (code1 != NOCODE && code2 != NOCODE) { /* code1 vs code2 */
return(dmat->distances[code1][code2]);
} else if (codeDist2 != NULL && code1 != NOCODE) { /* code1 vs. codeDist2 */
return(codeDist2[code1]);
} else { /* f1 vs f2 */
if (f1 == NULL) {
if(code1 == NOCODE) return(10.0);
f1 = &dmat->codeFreq[code1][0];
}
if (f2 == NULL) {
if(code2 == NOCODE) return(10.0);
f2 = &dmat->codeFreq[code2][0];
}
return(vector_multiply3_sum(f1,f2,dmat->eigenval,nCodes));
}
} else {
/* no matrix */
if (code1 != NOCODE) {
if (code2 != NOCODE) {
return(code1 == code2 ? 0.0 : 1.0); /* code1 vs code2 */
} else {
if(f2 == NULL) return(10.0);
return(1.0 - f2[code1]); /* code1 vs. f2 */
}
} else {
if (code2 != NOCODE) {
if(f1 == NULL) return(10.0);
return(1.0 - f1[code2]); /* f1 vs code2 */
} else { /* f1 vs. f2 */
if (f1 == NULL || f2 == NULL) return(10.0);
double piece = 1.0;
int k;
for (k = 0; k < nCodes; k++) {
piece -= f1[k] * f2[k];
}
return(piece);
}
}
}
assert(0);
}
/* E.g. GET_FREQ(profile,iPos,iVector)
Gets the next element of the vectors (and updates iVector), or
returns NULL if we didn't store a vector
*/
#define GET_FREQ(P,I,IVECTOR) \
(P->weights[I] > 0 && P->codes[I] == NOCODE ? &P->vectors[nCodes*(IVECTOR++)] : NULL)
void ProfileDist(profile_t *profile1, profile_t *profile2, int nPos,
/*OPTIONAL*/distance_matrix_t *dmat,
/*OUT*/besthit_t *hit) {
double top = 0;
double denom = 0;
int iFreq1 = 0;
int iFreq2 = 0;
int i = 0;
for (i = 0; i < nPos; i++) {
numeric_t *f1 = GET_FREQ(profile1,i,/*IN/OUT*/iFreq1);
numeric_t *f2 = GET_FREQ(profile2,i,/*IN/OUT*/iFreq2);
if (profile1->weights[i] > 0 && profile2->weights[i] > 0) {
double weight = profile1->weights[i] * profile2->weights[i];
denom += weight;
double piece = ProfileDistPiece(profile1->codes[i],profile2->codes[i],f1,f2,dmat,
profile2->codeDist ? &profile2->codeDist[i*nCodes] : NULL);
top += weight * piece;
}
}
assert(iFreq1 == profile1->nVectors);
assert(iFreq2 == profile2->nVectors);
hit->weight = denom > 0 ? denom : 0.01; /* 0.01 is an arbitrarily low value of weight (normally >>1) */
hit->dist = denom > 0 ? top/denom : 1;
profileOps++;
}
/* This should not be called if the update weight is 0, as
in that case code==NOCODE and in=NULL is possible, and then
it will fail.
*/
void AddToFreq(/*IN/OUT*/numeric_t *fOut,
double weight,
unsigned int codeIn, /*OPTIONAL*/numeric_t *fIn,
/*OPTIONAL*/distance_matrix_t *dmat) {
assert(fOut != NULL);
if (fIn != NULL) {
vector_add_mult(fOut, fIn, weight, nCodes);
} else if (dmat) {
assert(codeIn != NOCODE);
vector_add_mult(fOut, dmat->codeFreq[codeIn], weight, nCodes);
} else {
assert(codeIn != NOCODE);
fOut[codeIn] += weight;
}
}
void SetProfile(/*IN/OUT*/NJ_t *NJ, int node, double weight1) {
children_t *c = &NJ->child[node];
assert(c->nChild == 2);
assert(NJ->profiles[c->child[0]] != NULL);
assert(NJ->profiles[c->child[1]] != NULL);
if (NJ->profiles[node] != NULL)
FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints);
NJ->profiles[node] = AverageProfile(NJ->profiles[c->child[0]],
NJ->profiles[c->child[1]],
NJ->nPos, NJ->nConstraints,
NJ->distance_matrix,
weight1);
}
/* bionjWeight is the weight of the first sequence (between 0 and 1),
or -1 to do the average.
*/
profile_t *AverageProfile(profile_t *profile1, profile_t *profile2,
int nPos, int nConstraints,
distance_matrix_t *dmat,
double bionjWeight) {
int i;
if (bionjWeight < 0) {
bionjWeight = 0.5;
}
/* First, set codes and weights and see how big vectors will be */
profile_t *out = NewProfile(nPos, nConstraints);
for (i = 0; i < nPos; i++) {
out->weights[i] = bionjWeight * profile1->weights[i]
+ (1-bionjWeight) * profile2->weights[i];
out->codes[i] = NOCODE;
if (out->weights[i] > 0) {
if (profile1->weights[i] > 0 && profile1->codes[i] != NOCODE
&& (profile2->weights[i] <= 0 || profile1->codes[i] == profile2->codes[i])) {
out->codes[i] = profile1->codes[i];
} else if (profile1->weights[i] <= 0
&& profile2->weights[i] > 0
&& profile2->codes[i] != NOCODE) {
out->codes[i] = profile2->codes[i];
}
if (out->codes[i] == NOCODE) out->nVectors++;
}
}
/* Allocate and set the vectors */
out->vectors = (numeric_t*)mymalloc(sizeof(numeric_t)*nCodes*out->nVectors);
for (i = 0; i < nCodes * out->nVectors; i++) out->vectors[i] = 0;
nProfileFreqAlloc += out->nVectors;
nProfileFreqAvoid += nPos - out->nVectors;
int iFreqOut = 0;
int iFreq1 = 0;
int iFreq2 = 0;
for (i=0; i < nPos; i++) {
numeric_t *f = GET_FREQ(out,i,/*IN/OUT*/iFreqOut);
numeric_t *f1 = GET_FREQ(profile1,i,/*IN/OUT*/iFreq1);
numeric_t *f2 = GET_FREQ(profile2,i,/*IN/OUT*/iFreq2);
if (f != NULL) {
if (profile1->weights[i] > 0)
AddToFreq(/*IN/OUT*/f, profile1->weights[i] * bionjWeight,
profile1->codes[i], f1, dmat);
if (profile2->weights[i] > 0)
AddToFreq(/*IN/OUT*/f, profile2->weights[i] * (1.0-bionjWeight),
profile2->codes[i], f2, dmat);
NormalizeFreq(/*IN/OUT*/f, dmat);
} /* end if computing f */
if (verbose > 10 && i < 5) {
fprintf(stderr,"Average profiles: pos %d in-w1 %f in-w2 %f bionjWeight %f to weight %f code %d\n",
i, profile1->weights[i], profile2->weights[i], bionjWeight,
out->weights[i], out->codes[i]);
if (f!= NULL) {
int k;
for (k = 0; k < nCodes; k++)
fprintf(stderr, "\t%c:%f", codesString[k], f ? f[k] : -1.0);
fprintf(stderr,"\n");
}
}
} /* end loop over positions */
assert(iFreq1 == profile1->nVectors);
assert(iFreq2 == profile2->nVectors);
assert(iFreqOut == out->nVectors);
/* compute total constraints */
for (i = 0; i < nConstraints; i++) {
out->nOn[i] = profile1->nOn[i] + profile2->nOn[i];
out->nOff[i] = profile1->nOff[i] + profile2->nOff[i];
}
profileAvgOps++;
return(out);
}
/* Make the (unrotated) frequencies sum to 1
Simply dividing by total_weight is not ideal because of roundoff error
So compute total_freq instead
*/
void NormalizeFreq(/*IN/OUT*/numeric_t *freq, distance_matrix_t *dmat) {
double total_freq = 0;
int k;
if (dmat != NULL) {
/* The total frequency is dot_product(true_frequencies, 1)
So we rotate the 1 vector by eigeninv (stored in eigentot)
*/
total_freq = vector_multiply_sum(freq, dmat->eigentot, nCodes);
} else {
for (k = 0; k < nCodes; k++)
total_freq += freq[k];
}
if (total_freq > fPostTotalTolerance) {
numeric_t inverse_weight = 1.0/total_freq;
vector_multiply_by(/*IN/OUT*/freq, inverse_weight, nCodes);
} else {
/* This can happen if we are in a very low-weight region, e.g. if a mostly-gap position gets weighted down
repeatedly; just set them all to arbitrary but legal values */
if (dmat == NULL) {
for (k = 0; k < nCodes; k++)
freq[k] = 1.0/nCodes;
} else {
for (k = 0; k < nCodes; k++)
freq[k] = dmat->codeFreq[0][k];
}
}
}
/* OutProfile() computes the out-profile */
profile_t *OutProfile(profile_t **profiles, int nProfiles,
int nPos, int nConstraints,
distance_matrix_t *dmat) {
int i; /* position */
int in; /* profile */
profile_t *out = NewProfile(nPos, nConstraints);
double inweight = 1.0/(double)nProfiles; /* The maximal output weight is 1.0 */
/* First, set weights -- code is always NOCODE, prevent weight=0 */
for (i = 0; i < nPos; i++) {
out->weights[i] = 0;
for (in = 0; in < nProfiles; in++)
out->weights[i] += profiles[in]->weights[i] * inweight;
if (out->weights[i] <= 0) out->weights[i] = 1e-20; /* always store a vector */
out->nVectors++;
out->codes[i] = NOCODE; /* outprofile is normally complicated */
}
/* Initialize the frequencies to 0 */
out->vectors = (numeric_t*)mymalloc(sizeof(numeric_t)*nCodes*out->nVectors);
for (i = 0; i < nCodes*out->nVectors; i++)
out->vectors[i] = 0;
/* Add up the weights, going through each sequence in turn */
for (in = 0; in < nProfiles; in++) {
int iFreqOut = 0;
int iFreqIn = 0;
for (i = 0; i < nPos; i++) {
numeric_t *fIn = GET_FREQ(profiles[in],i,/*IN/OUT*/iFreqIn);
numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut);
if (profiles[in]->weights[i] > 0)
AddToFreq(/*IN/OUT*/fOut, profiles[in]->weights[i],
profiles[in]->codes[i], fIn, dmat);
}
assert(iFreqOut == out->nVectors);
assert(iFreqIn == profiles[in]->nVectors);
}
/* And normalize the frequencies to sum to 1 */
int iFreqOut = 0;
for (i = 0; i < nPos; i++) {
numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut);
if (fOut)
NormalizeFreq(/*IN/OUT*/fOut, dmat);
}
assert(iFreqOut == out->nVectors);
if (verbose > 10) fprintf(stderr,"Average %d profiles\n", nProfiles);
if(dmat)
SetCodeDist(/*IN/OUT*/out, nPos, dmat);
/* Compute constraints */
for (i = 0; i < nConstraints; i++) {
out->nOn[i] = 0;
out->nOff[i] = 0;
for (in = 0; in < nProfiles; in++) {
out->nOn[i] += profiles[in]->nOn[i];
out->nOff[i] += profiles[in]->nOff[i];
}
}
return(out);
}
void UpdateOutProfile(/*IN/OUT*/profile_t *out, profile_t *old1, profile_t *old2,
profile_t *new, int nActiveOld,
int nPos, int nConstraints,
distance_matrix_t *dmat) {
int i, k;
int iFreqOut = 0;
int iFreq1 = 0;
int iFreq2 = 0;
int iFreqNew = 0;
assert(nActiveOld > 0);
for (i = 0; i < nPos; i++) {
numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut);
numeric_t *fOld1 = GET_FREQ(old1,i,/*IN/OUT*/iFreq1);
numeric_t *fOld2 = GET_FREQ(old2,i,/*IN/OUT*/iFreq2);
numeric_t *fNew = GET_FREQ(new,i,/*IN/OUT*/iFreqNew);
assert(out->codes[i] == NOCODE && fOut != NULL); /* No no-vector optimization for outprofiles */
if (verbose > 3 && i < 3) {
fprintf(stderr,"Updating out-profile position %d weight %f (mult %f)\n",
i, out->weights[i], out->weights[i]*nActiveOld);
}
double originalMult = out->weights[i]*nActiveOld;
double newMult = originalMult + new->weights[i] - old1->weights[i] - old2->weights[i];
out->weights[i] = newMult/(nActiveOld-1);
if (out->weights[i] <= 0) out->weights[i] = 1e-20; /* always use the vector */
for (k = 0; k < nCodes; k++) fOut[k] *= originalMult;
if (old1->weights[i] > 0)
AddToFreq(/*IN/OUT*/fOut, -old1->weights[i], old1->codes[i], fOld1, dmat);
if (old2->weights[i] > 0)
AddToFreq(/*IN/OUT*/fOut, -old2->weights[i], old2->codes[i], fOld2, dmat);
if (new->weights[i] > 0)
AddToFreq(/*IN/OUT*/fOut, new->weights[i], new->codes[i], fNew, dmat);
/* And renormalize */
NormalizeFreq(/*IN/OUT*/fOut, dmat);
if (verbose > 2 && i < 3) {
fprintf(stderr,"Updated out-profile position %d weight %f (mult %f)",
i, out->weights[i], out->weights[i]*nActiveOld);
if(out->weights[i] > 0)
for (k=0;k<nCodes;k++)
fprintf(stderr, " %c:%f", dmat?'?':codesString[k], fOut[k]);
fprintf(stderr,"\n");
}
}
assert(iFreqOut == out->nVectors);
assert(iFreq1 == old1->nVectors);
assert(iFreq2 == old2->nVectors);
assert(iFreqNew == new->nVectors);
if(dmat)
SetCodeDist(/*IN/OUT*/out,nPos,dmat);
/* update constraints -- note in practice this should be a no-op */
for (i = 0; i < nConstraints; i++) {
out->nOn[i] += new->nOn[i] - old1->nOn[i] - old2->nOn[i];
out->nOff[i] += new->nOff[i] - old1->nOff[i] - old2->nOff[i];
}
}
void SetCodeDist(/*IN/OUT*/profile_t *profile, int nPos,
distance_matrix_t *dmat) {
if (profile->codeDist == NULL)
profile->codeDist = (numeric_t*)mymalloc(sizeof(numeric_t)*nPos*nCodes);
int i;
int iFreq = 0;
for (i = 0; i < nPos; i++) {
numeric_t *f = GET_FREQ(profile,i,/*IN/OUT*/iFreq);
int k;
for (k = 0; k < nCodes; k++)
profile->codeDist[i*nCodes+k] = ProfileDistPiece(/*code1*/profile->codes[i], /*code2*/k,
/*f1*/f, /*f2*/NULL,
dmat, NULL);
}
assert(iFreq==profile->nVectors);
}
void SetBestHit(int node, NJ_t *NJ, int nActive,
/*OUT*/besthit_t *bestjoin, /*OUT OPTIONAL*/besthit_t *allhits) {
assert(NJ->parent[node] < 0);
bestjoin->i = node;
bestjoin->j = -1;
bestjoin->dist = 1e20;
bestjoin->criterion = 1e20;
int j;
besthit_t tmp;
#ifdef OPENMP
/* Note -- if we are already in a parallel region, this will be ignored */
#pragma omp parallel for schedule(dynamic, 50)
#endif
for (j = 0; j < NJ->maxnode; j++) {
besthit_t *sv = allhits != NULL ? &allhits[j] : &tmp;
sv->i = node;
sv->j = j;
if (NJ->parent[j] >= 0) {
sv->i = -1; /* illegal/empty join */
sv->weight = 0.0;
sv->criterion = sv->dist = 1e20;
continue;
}
/* Note that we compute self-distances (allow j==node) because the top-hit heuristic
expects self to be within its top hits, but we exclude those from the bestjoin
that we return...
*/
SetDistCriterion(NJ, nActive, /*IN/OUT*/sv);
if (sv->criterion < bestjoin->criterion && node != j)
*bestjoin = *sv;
}
if (verbose>5) {
fprintf(stderr, "SetBestHit %d %d %f %f\n", bestjoin->i, bestjoin->j, bestjoin->dist, bestjoin->criterion);
}
}
void ReadMatrix(char *filename, /*OUT*/numeric_t codes[MAXCODES][MAXCODES], bool checkCodes) {
char buf[BUFFER_SIZE] = "";
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Cannot read %s\n",filename);
exit(1);
}
if (fgets(buf,sizeof(buf),fp) == NULL) {
fprintf(stderr, "Error reading header line for %s:\n%s\n", filename, buf);
exit(1);
}
if (checkCodes) {
int i;
int iBufPos;
for (iBufPos=0,i=0;i<nCodes;i++,iBufPos++) {
if(buf[iBufPos] != codesString[i]) {
fprintf(stderr,"Header line\n%s\nin file %s does not have expected code %c # %d in %s\n",
buf, filename, codesString[i], i, codesString);
exit(1);
}
iBufPos++;
if(buf[iBufPos] != '\n' && buf[iBufPos] != '\r' && buf[iBufPos] != '\0' && buf[iBufPos] != '\t') {
fprintf(stderr, "Header line in %s should be tab-delimited\n", filename);
exit(1);
}
if (buf[iBufPos] == '\0' && i < nCodes-1) {
fprintf(stderr, "Header line in %s ends prematurely\n",filename);
exit(1);
}
} /* end loop over codes */
/* Should be at end, but allow \n because of potential DOS \r\n */
if(buf[iBufPos] != '\0' && buf[iBufPos] != '\n' && buf[iBufPos] != '\r') {
fprintf(stderr, "Header line in %s has too many entries\n", filename);
exit(1);
}
}
int iLine;
for (iLine = 0; iLine < nCodes; iLine++) {
buf[0] = '\0';
if (fgets(buf,sizeof(buf),fp) == NULL) {
fprintf(stderr, "Cannot read line %d from file %s\n", iLine+2, filename);
exit(1);
}
char *field = strtok(buf,"\t\r\n");
field = strtok(NULL, "\t"); /* ignore first column */
int iColumn;
for (iColumn = 0; iColumn < nCodes && field != NULL; iColumn++, field = strtok(NULL,"\t")) {
if(sscanf(field,ScanNumericSpec,&codes[iLine][iColumn]) != 1) {
fprintf(stderr,"Cannot parse field %s in file %s\n", field, filename);
exit(1);
}
}
}
}
void ReadVector(char *filename, /*OUT*/numeric_t codes[MAXCODES]) {
FILE *fp = fopen(filename,"r");
if (fp == NULL) {
fprintf(stderr, "Cannot read %s\n",filename);
exit(1);
}
int i;
for (i = 0; i < nCodes; i++) {
if (fscanf(fp,ScanNumericSpec,&codes[i]) != 1) {
fprintf(stderr,"Cannot read %d entry of %s\n",i+1,filename);
exit(1);
}
}
if (fclose(fp) != 0) {
fprintf(stderr, "Error reading %s\n",filename);
exit(1);
}
}
distance_matrix_t *ReadDistanceMatrix(char *prefix) {
char buffer[BUFFER_SIZE];
distance_matrix_t *dmat = (distance_matrix_t*)mymalloc(sizeof(distance_matrix_t));
if(strlen(prefix) > BUFFER_SIZE-20) {
fprintf(stderr,"Filename %s too long\n", prefix);
exit(1);
}
strcpy(buffer, prefix);
strcat(buffer, ".distances");
ReadMatrix(buffer, /*OUT*/dmat->distances, /*checkCodes*/true);
strcpy(buffer, prefix);
strcat(buffer, ".inverses");
ReadMatrix(buffer, /*OUT*/dmat->eigeninv, /*checkCodes*/false);
strcpy(buffer, prefix);
strcat(buffer, ".eigenvalues");
ReadVector(buffer, /*OUT*/dmat->eigenval);
if(verbose>1) fprintf(stderr, "Read distance matrix from %s\n",prefix);
SetupDistanceMatrix(/*IN/OUT*/dmat);
return(dmat);
}
void SetupDistanceMatrix(/*IN/OUT*/distance_matrix_t *dmat) {
/* Check that the eigenvalues and eigen-inverse are consistent with the
distance matrix and that the matrix is symmetric */
int i,j,k;
for (i = 0; i < nCodes; i++) {
for (j = 0; j < nCodes; j++) {
if(fabs(dmat->distances[i][j]-dmat->distances[j][i]) > 1e-6) {
fprintf(stderr,"Distance matrix not symmetric for %d,%d: %f vs %f\n",
i+1,j+1,
dmat->distances[i][j],
dmat->distances[j][i]);
exit(1);
}
double total = 0.0;
for (k = 0; k < nCodes; k++)
total += dmat->eigenval[k] * dmat->eigeninv[k][i] * dmat->eigeninv[k][j];
if(fabs(total - dmat->distances[i][j]) > 1e-6) {
fprintf(stderr,"Distance matrix entry %d,%d should be %f but eigen-representation gives %f\n",
i+1,j+1,dmat->distances[i][j],total);
exit(1);
}
}
}
/* And compute eigentot */
for (k = 0; k < nCodes; k++) {
dmat->eigentot[k] = 0.;
int j;
for (j = 0; j < nCodes; j++)
dmat->eigentot[k] += dmat->eigeninv[k][j];
}
/* And compute codeFreq */
int code;
for(code = 0; code < nCodes; code++) {
for (k = 0; k < nCodes; k++) {
dmat->codeFreq[code][k] = dmat->eigeninv[k][code];
}
}
/* And gapFreq */
for(code = 0; code < nCodes; code++) {
double gapFreq = 0.0;
for (k = 0; k < nCodes; k++)
gapFreq += dmat->codeFreq[k][code];
dmat->gapFreq[code] = gapFreq / nCodes;
}
if(verbose>10) fprintf(stderr, "Made codeFreq\n");
}
nni_t ChooseNNI(profile_t *profiles[4],
/*OPTIONAL*/distance_matrix_t *dmat,
int nPos, int nConstraints,
/*OUT*/double criteria[3]) {
double d[6];
CorrectedPairDistances(profiles, 4, dmat, nPos, /*OUT*/d);
double penalty[3]; /* indexed as nni_t */
QuartetConstraintPenalties(profiles, nConstraints, /*OUT*/penalty);
criteria[ABvsCD] = d[qAB] + d[qCD] + penalty[ABvsCD];
criteria[ACvsBD] = d[qAC] + d[qBD] + penalty[ACvsBD];
criteria[ADvsBC] = d[qAD] + d[qBC] + penalty[ADvsBC];
nni_t choice = ABvsCD;
if (criteria[ACvsBD] < criteria[ABvsCD] && criteria[ACvsBD] <= criteria[ADvsBC]) {
choice = ACvsBD;
} else if (criteria[ADvsBC] < criteria[ABvsCD] && criteria[ADvsBC] <= criteria[ACvsBD]) {
choice = ADvsBC;
}
if (verbose > 1 && penalty[choice] > penalty[ABvsCD] + 1e-6) {
fprintf(stderr, "Worsen constraint: from %.3f to %.3f distance %.3f to %.3f: ",
penalty[ABvsCD], penalty[choice],
criteria[ABvsCD], choice == ACvsBD ? criteria[ACvsBD] : criteria[ADvsBC]);
int iC;
for (iC = 0; iC < nConstraints; iC++) {
double ppart[3];
if (QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/ppart)) {
double old_penalty = ppart[ABvsCD];
double new_penalty = ppart[choice];
if (new_penalty > old_penalty + 1e-6)
fprintf(stderr, " %d (%d/%d %d/%d %d/%d %d/%d)", iC,
profiles[0]->nOn[iC], profiles[0]->nOff[iC],
profiles[1]->nOn[iC], profiles[1]->nOff[iC],
profiles[2]->nOn[iC], profiles[2]->nOff[iC],
profiles[3]->nOn[iC], profiles[3]->nOff[iC]);
}
}
fprintf(stderr,"\n");
}
if (verbose > 3)
fprintf(stderr, "NNI scores ABvsCD %.5f ACvsBD %.5f ADvsBC %.5f choice %s\n",
criteria[ABvsCD], criteria[ACvsBD], criteria[ADvsBC],
choice == ABvsCD ? "AB|CD" : (choice == ACvsBD ? "AC|BD" : "AD|BC"));
return(choice);
}
profile_t *PosteriorProfile(profile_t *p1, profile_t *p2,
double len1, double len2,
/*OPTIONAL*/transition_matrix_t *transmat,
rates_t *rates,
int nPos, int nConstraints) {
if (len1 < MLMinBranchLength)
len1 = MLMinBranchLength;
if (len2 < MLMinBranchLength)
len2 = MLMinBranchLength;
int i,j,k;
profile_t *out = NewProfile(nPos, nConstraints);
for (i = 0; i < nPos; i++) {
out->codes[i] = NOCODE;
out->weights[i] = 1.0;
}
out->nVectors = nPos;
out->vectors = (numeric_t*)mymalloc(sizeof(numeric_t)*nCodes*out->nVectors);
for (i = 0; i < nCodes * out->nVectors; i++) out->vectors[i] = 0;
int iFreqOut = 0;
int iFreq1 = 0;
int iFreq2 = 0;
numeric_t *expeigenRates1 = NULL, *expeigenRates2 = NULL;
if (transmat != NULL) {
expeigenRates1 = ExpEigenRates(len1, transmat, rates);
expeigenRates2 = ExpEigenRates(len2, transmat, rates);
}
if (transmat == NULL) { /* Jukes-Cantor */
assert(nCodes == 4);
double *PSame1 = PSameVector(len1, rates);
double *PDiff1 = PDiffVector(PSame1, rates);
double *PSame2 = PSameVector(len2, rates);
double *PDiff2 = PDiffVector(PSame2, rates);
numeric_t mix1[4], mix2[4];
for (i=0; i < nPos; i++) {
int iRate = rates->ratecat[i];
double w1 = p1->weights[i];
double w2 = p2->weights[i];
int code1 = p1->codes[i];
int code2 = p2->codes[i];
numeric_t *f1 = GET_FREQ(p1,i,/*IN/OUT*/iFreq1);
numeric_t *f2 = GET_FREQ(p2,i,/*IN/OUT*/iFreq2);
/* First try to store a simple profile */
if (f1 == NULL && f2 == NULL) {
if (code1 == NOCODE && code2 == NOCODE) {
out->codes[i] = NOCODE;
out->weights[i] = 0.0;
continue;
} else if (code1 == NOCODE) {
/* Posterior(parent | character & gap, len1, len2) = Posterior(parent | character, len1)
= PSame() for matching characters and 1-PSame() for the rest
= (pSame - pDiff) * character + (1-(pSame-pDiff)) * gap
*/
out->codes[i] = code2;
out->weights[i] = w2 * (PSame2[iRate] - PDiff2[iRate]);
continue;
} else if (code2 == NOCODE) {
out->codes[i] = code1;
out->weights[i] = w1 * (PSame1[iRate] - PDiff1[iRate]);
continue;
} else if (code1 == code2) {
out->codes[i] = code1;
double f12code = (w1*PSame1[iRate] + (1-w1)*0.25) * (w2*PSame2[iRate] + (1-w2)*0.25);
double f12other = (w1*PDiff1[iRate] + (1-w1)*0.25) * (w2*PDiff2[iRate] + (1-w2)*0.25);
/* posterior probability of code1/code2 after scaling */
double pcode = f12code/(f12code+3*f12other);
/* Now f = w * (code ? 1 : 0) + (1-w) * 0.25, so to get pcode we need
fcode = 1/4 + w1*3/4 or w = (f-1/4)*4/3
*/
out->weights[i] = (pcode - 0.25) * 4.0/3.0;
/* This can be zero because of numerical problems, I think */
if (out->weights[i] < 1e-6) {
if (verbose > 1)
fprintf(stderr, "Replaced weight %f with %f from w1 %f w2 %f PSame %f %f f12code %f f12other %f\n",
out->weights[i], 1e-6,
w1, w2,
PSame1[iRate], PSame2[iRate],
f12code, f12other);
out->weights[i] = 1e-6;
}
continue;
}
}
/* if we did not compute a simple profile, then do the full computation and
store the full vector
*/
if (f1 == NULL) {
for (j = 0; j < 4; j++)
mix1[j] = (1-w1)*0.25;
if(code1 != NOCODE)
mix1[code1] += w1;
f1 = mix1;
}
if (f2 == NULL) {
for (j = 0; j < 4; j++)
mix2[j] = (1-w2)*0.25;
if(code2 != NOCODE)
mix2[code2] += w2;
f2 = mix2;
}
out->codes[i] = NOCODE;
out->weights[i] = 1.0;
numeric_t *f = GET_FREQ(out,i,/*IN/OUT*/iFreqOut);
double lkAB = 0;
for (j = 0; j < 4; j++) {
f[j] = (f1[j] * PSame1[iRate] + (1.0-f1[j]) * PDiff1[iRate])
* (f2[j] * PSame2[iRate] + (1.0-f2[j]) * PDiff2[iRate]);
lkAB += f[j];
}
double lkABInv = 1.0/lkAB;
for (j = 0; j < 4; j++)
f[j] *= lkABInv;
}
PSame1 = myfree(PSame1, sizeof(double) * rates->nRateCategories);
PSame2 = myfree(PSame2, sizeof(double) * rates->nRateCategories);
PDiff1 = myfree(PDiff1, sizeof(double) * rates->nRateCategories);
PDiff2 = myfree(PDiff2, sizeof(double) * rates->nRateCategories);
} else if (nCodes == 4) { /* matrix model on nucleotides */
numeric_t *fGap = &transmat->codeFreq[NOCODE][0];
numeric_t f1mix[4], f2mix[4];
for (i=0; i < nPos; i++) {
if (p1->codes[i] == NOCODE && p2->codes[i] == NOCODE
&& p1->weights[i] == 0 && p2->weights[i] == 0) {
/* aligning gap with gap -- just output a gap
out->codes[i] is already set to NOCODE so need not set that */
out->weights[i] = 0;
continue;
}
int iRate = rates->ratecat[i];
numeric_t *expeigen1 = &expeigenRates1[iRate*4];
numeric_t *expeigen2 = &expeigenRates2[iRate*4];
numeric_t *f1 = GET_FREQ(p1,i,/*IN/OUT*/iFreq1);
numeric_t *f2 = GET_FREQ(p2,i,/*IN/OUT*/iFreq2);
numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut);
assert(fOut != NULL);
if (f1 == NULL) {
f1 = &transmat->codeFreq[p1->codes[i]][0]; /* codeFreq includes an entry for NOCODE */
double w = p1->weights[i];
if (w > 0.0 && w < 1.0) {
for (j = 0; j < 4; j++)
f1mix[j] = w * f1[j] + (1.0-w) * fGap[j];
f1 = f1mix;
}
}
if (f2 == NULL) {
f2 = &transmat->codeFreq[p2->codes[i]][0];
double w = p2->weights[i];
if (w > 0.0 && w < 1.0) {
for (j = 0; j < 4; j++)
f2mix[j] = w * f2[j] + (1.0-w) * fGap[j];
f2 = f2mix;
}
}
numeric_t fMult1[4] ALIGNED; /* rotated1 * expeigen1 */
numeric_t fMult2[4] ALIGNED; /* rotated2 * expeigen2 */
#if 0 /* SSE3 is slower */
vector_multiply(f1, expeigen1, 4, /*OUT*/fMult1);
vector_multiply(f2, expeigen2, 4, /*OUT*/fMult2);
#else
for (j = 0; j < 4; j++) {
fMult1[j] = f1[j]*expeigen1[j];
fMult2[j] = f2[j]*expeigen2[j];
}
#endif
numeric_t fPost[4] ALIGNED; /* in unrotated space */
for (j = 0; j < 4; j++) {
#if 0 /* SSE3 is slower */
fPost[j] = vector_dot_product_rot(fMult1, fMult2, &transmat->codeFreq[j][0], 4)
* transmat->statinv[j]; */
#else
double out1 = 0;
double out2 = 0;
for (k = 0; k < 4; k++) {
out1 += fMult1[k] * transmat->codeFreq[j][k];
out2 += fMult2[k] * transmat->codeFreq[j][k];
}
fPost[j] = out1*out2*transmat->statinv[j];
#endif
}
double fPostTot = 0;
for (j = 0; j < 4; j++)
fPostTot += fPost[j];
assert(fPostTot > fPostTotalTolerance);
double fPostInv = 1.0/fPostTot;
#if 0 /* SSE3 is slower */
vector_multiply_by(fPost, fPostInv, 4);
#else
for (j = 0; j < 4; j++)
fPost[j] *= fPostInv;
#endif
/* and finally, divide by stat again & rotate to give the new frequencies */
matrixt_by_vector4(transmat->eigeninvT, fPost, /*OUT*/fOut);
} /* end loop over position i */
} else if (nCodes == 20) { /* matrix model on amino acids */
numeric_t *fGap = &transmat->codeFreq[NOCODE][0];
numeric_t f1mix[20] ALIGNED;
numeric_t f2mix[20] ALIGNED;
for (i=0; i < nPos; i++) {
if (p1->codes[i] == NOCODE && p2->codes[i] == NOCODE
&& p1->weights[i] == 0 && p2->weights[i] == 0) {
/* aligning gap with gap -- just output a gap
out->codes[i] is already set to NOCODE so need not set that */
out->weights[i] = 0;
continue;
}
int iRate = rates->ratecat[i];
numeric_t *expeigen1 = &expeigenRates1[iRate*20];
numeric_t *expeigen2 = &expeigenRates2[iRate*20];
numeric_t *f1 = GET_FREQ(p1,i,/*IN/OUT*/iFreq1);
numeric_t *f2 = GET_FREQ(p2,i,/*IN/OUT*/iFreq2);
numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut);
assert(fOut != NULL);
if (f1 == NULL) {
f1 = &transmat->codeFreq[p1->codes[i]][0]; /* codeFreq includes an entry for NOCODE */
double w = p1->weights[i];
if (w > 0.0 && w < 1.0) {
for (j = 0; j < 20; j++)
f1mix[j] = w * f1[j] + (1.0-w) * fGap[j];
f1 = f1mix;
}
}
if (f2 == NULL) {
f2 = &transmat->codeFreq[p2->codes[i]][0];
double w = p2->weights[i];
if (w > 0.0 && w < 1.0) {
for (j = 0; j < 20; j++)
f2mix[j] = w * f2[j] + (1.0-w) * fGap[j];
f2 = f2mix;
}
}
numeric_t fMult1[20] ALIGNED; /* rotated1 * expeigen1 */
numeric_t fMult2[20] ALIGNED; /* rotated2 * expeigen2 */
vector_multiply(f1, expeigen1, 20, /*OUT*/fMult1);
vector_multiply(f2, expeigen2, 20, /*OUT*/fMult2);
numeric_t fPost[20] ALIGNED; /* in unrotated space */
for (j = 0; j < 20; j++) {
numeric_t value = vector_dot_product_rot(fMult1, fMult2, &transmat->codeFreq[j][0], 20)
* transmat->statinv[j];
/* Added this logic try to avoid rare numerical problems */
fPost[j] = value >= 0 ? value : 0;
}
double fPostTot = vector_sum(fPost, 20);
assert(fPostTot > fPostTotalTolerance);
double fPostInv = 1.0/fPostTot;
vector_multiply_by(/*IN/OUT*/fPost, fPostInv, 20);
int ch = -1; /* the dominant character, if any */
if (!exactML) {
for (j = 0; j < 20; j++) {
if (fPost[j] >= approxMLminf) {
ch = j;
break;
}
}
}
/* now, see if we can use the approximation
fPost ~= (1 or 0) * w + nearP * (1-w)
to avoid rotating */
double w = 0;
if (ch >= 0) {
w = (fPost[ch] - transmat->nearP[ch][ch]) / (1.0 - transmat->nearP[ch][ch]);
for (j = 0; j < 20; j++) {
if (j != ch) {
double fRough = (1.0-w) * transmat->nearP[ch][j];
if (fRough < fPost[j] * approxMLminratio) {
ch = -1; /* give up on the approximation */
break;
}
}
}
}
if (ch >= 0) {
nAAPosteriorRough++;
double wInvStat = w * transmat->statinv[ch];
for (j = 0; j < 20; j++)
fOut[j] = wInvStat * transmat->codeFreq[ch][j] + (1.0-w) * transmat->nearFreq[ch][j];
} else {
/* and finally, divide by stat again & rotate to give the new frequencies */
nAAPosteriorExact++;
for (j = 0; j < 20; j++)
fOut[j] = vector_multiply_sum(fPost, &transmat->eigeninv[j][0], 20);
}
} /* end loop over position i */
} else {
assert(0); /* illegal nCodes */
}
if (transmat != NULL) {
expeigenRates1 = myfree(expeigenRates1, sizeof(numeric_t) * rates->nRateCategories * nCodes);
expeigenRates2 = myfree(expeigenRates2, sizeof(numeric_t) * rates->nRateCategories * nCodes);
}
/* Reallocate out->vectors to be the right size */
out->nVectors = iFreqOut;
if (out->nVectors == 0)
out->vectors = (numeric_t*)myfree(out->vectors, sizeof(numeric_t)*nCodes*nPos);
else
out->vectors = (numeric_t*)myrealloc(out->vectors,
/*OLDSIZE*/sizeof(numeric_t)*nCodes*nPos,
/*NEWSIZE*/sizeof(numeric_t)*nCodes*out->nVectors,
/*copy*/true); /* try to save space */
nProfileFreqAlloc += out->nVectors;
nProfileFreqAvoid += nPos - out->nVectors;
/* compute total constraints */
for (i = 0; i < nConstraints; i++) {
out->nOn[i] = p1->nOn[i] + p2->nOn[i];
out->nOff[i] = p1->nOff[i] + p2->nOff[i];
}
nPosteriorCompute++;
return(out);
}
double *PSameVector(double length, rates_t *rates) {
double *pSame = mymalloc(sizeof(double) * rates->nRateCategories);
int iRate;
for (iRate = 0; iRate < rates->nRateCategories; iRate++)
pSame[iRate] = 0.25 + 0.75 * exp((-4.0/3.0) * fabs(length*rates->rates[iRate]));
return(pSame);
}
double *PDiffVector(double *pSame, rates_t *rates) {
double *pDiff = mymalloc(sizeof(double) * rates->nRateCategories);
int iRate;
for (iRate = 0; iRate < rates->nRateCategories; iRate++)
pDiff[iRate] = (1.0 - pSame[iRate])/3.0;
return(pDiff);
}
numeric_t *ExpEigenRates(double length, transition_matrix_t *transmat, rates_t *rates) {
numeric_t *expeigen = mymalloc(sizeof(numeric_t) * nCodes * rates->nRateCategories);
int iRate, j;
for (iRate = 0; iRate < rates->nRateCategories; iRate++) {
for (j = 0; j < nCodes; j++) {
double relLen = length * rates->rates[iRate];
/* very short branch lengths lead to numerical problems so prevent them */
if (relLen < MLMinRelBranchLength)
relLen = MLMinRelBranchLength;
expeigen[iRate*nCodes + j] = exp(relLen * transmat->eigenval[j]);
}
}
return(expeigen);
}
double PairLogLk(profile_t *pA, profile_t *pB, double length, int nPos,
/*OPTIONAL*/transition_matrix_t *transmat,
rates_t *rates,
/*OPTIONAL IN/OUT*/double *site_likelihoods) {
double lk = 1.0;
double loglk = 0.0; /* stores underflow of lk during the loop over positions */
int i,j;
assert(rates != NULL && rates->nRateCategories > 0);
numeric_t *expeigenRates = NULL;
if (transmat != NULL)
expeigenRates = ExpEigenRates(length, transmat, rates);
if (transmat == NULL) { /* Jukes-Cantor */
assert (nCodes == 4);
double *pSame = PSameVector(length, rates);
double *pDiff = PDiffVector(pSame, rates);
int iFreqA = 0;
int iFreqB = 0;
for (i = 0; i < nPos; i++) {
int iRate = rates->ratecat[i];
double wA = pA->weights[i];
double wB = pB->weights[i];
int codeA = pA->codes[i];
int codeB = pB->codes[i];
numeric_t *fA = GET_FREQ(pA,i,/*IN/OUT*/iFreqA);
numeric_t *fB = GET_FREQ(pB,i,/*IN/OUT*/iFreqB);
double lkAB = 0;
if (fA == NULL && fB == NULL) {
if (codeA == NOCODE) { /* A is all gaps */
/* gap to gap is sum(j) 0.25 * (0.25 * pSame + 0.75 * pDiff) = sum(i) 0.25*0.25 = 0.25
gap to any character gives the same result
*/
lkAB = 0.25;
} else if (codeB == NOCODE) { /* B is all gaps */
lkAB = 0.25;
} else if (codeA == codeB) { /* A and B match */
lkAB = pSame[iRate] * wA*wB + 0.25 * (1-wA*wB);
} else { /* codeA != codeB */
lkAB = pDiff[iRate] * wA*wB + 0.25 * (1-wA*wB);
}
} else if (fA == NULL) {
/* Compare codeA to profile of B */
if (codeA == NOCODE)
lkAB = 0.25;
else
lkAB = wA * (pDiff[iRate] + fB[codeA] * (pSame[iRate]-pDiff[iRate])) + (1.0-wA) * 0.25;
/* because lkAB = wA * P(codeA->B) + (1-wA) * 0.25
P(codeA -> B) = sum(j) P(B==j) * (j==codeA ? pSame : pDiff)
= sum(j) P(B==j) * pDiff +
= pDiff + P(B==codeA) * (pSame-pDiff)
*/
} else if (fB == NULL) { /* Compare codeB to profile of A */
if (codeB == NOCODE)
lkAB = 0.25;
else
lkAB = wB * (pDiff[iRate] + fA[codeB] * (pSame[iRate]-pDiff[iRate])) + (1.0-wB) * 0.25;
} else { /* both are full profiles */
for (j = 0; j < 4; j++)
lkAB += fB[j] * (fA[j] * pSame[iRate] + (1-fA[j])* pDiff[iRate]); /* P(A|B) */
}
assert(lkAB > 0);
lk *= lkAB;
while (lk < LkUnderflow) {
lk *= LkUnderflowInv;
loglk -= LogLkUnderflow;
}
if (site_likelihoods != NULL)
site_likelihoods[i] *= lkAB;
}
pSame = myfree(pSame, sizeof(double) * rates->nRateCategories);
pDiff = myfree(pDiff, sizeof(double) * rates->nRateCategories);
} else if (nCodes == 4) { /* matrix model on nucleotides */
int iFreqA = 0;
int iFreqB = 0;
numeric_t fAmix[4], fBmix[4];
numeric_t *fGap = &transmat->codeFreq[NOCODE][0];
for (i = 0; i < nPos; i++) {
int iRate = rates->ratecat[i];
numeric_t *expeigen = &expeigenRates[iRate*4];
double wA = pA->weights[i];
double wB = pB->weights[i];
if (wA == 0 && wB == 0 && pA->codes[i] == NOCODE && pB->codes[i] == NOCODE) {
/* Likelihood of A vs B is 1, so nothing changes
Do not need to advance iFreqA or iFreqB */
continue;
}
numeric_t *fA = GET_FREQ(pA,i,/*IN/OUT*/iFreqA);
numeric_t *fB = GET_FREQ(pB,i,/*IN/OUT*/iFreqB);
if (fA == NULL)
fA = &transmat->codeFreq[pA->codes[i]][0];
if (wA > 0.0 && wA < 1.0) {
for (j = 0; j < 4; j++)
fAmix[j] = wA*fA[j] + (1.0-wA)*fGap[j];
fA = fAmix;
}
if (fB == NULL)
fB = &transmat->codeFreq[pB->codes[i]][0];
if (wB > 0.0 && wB < 1.0) {
for (j = 0; j < 4; j++)
fBmix[j] = wB*fB[j] + (1.0-wB)*fGap[j];
fB = fBmix;
}
/* SSE3 instructions do not speed this step up:
numeric_t lkAB = vector_multiply3_sum(expeigen, fA, fB); */
// dsp this is where check for <=0 was added in 2.1.1.LG
double lkAB = 0;
for (j = 0; j < 4; j++)
lkAB += expeigen[j]*fA[j]*fB[j];
assert(lkAB > 0);
if (site_likelihoods != NULL)
site_likelihoods[i] *= lkAB;
lk *= lkAB;
while (lk < LkUnderflow) {
lk *= LkUnderflowInv;
loglk -= LogLkUnderflow;
}
while (lk > LkUnderflowInv) {
lk *= LkUnderflow;
loglk += LogLkUnderflow;
}
}
} else if (nCodes == 20) { /* matrix model on amino acids */
int iFreqA = 0;
int iFreqB = 0;
numeric_t fAmix[20], fBmix[20];
numeric_t *fGap = &transmat->codeFreq[NOCODE][0];
for (i = 0; i < nPos; i++) {
int iRate = rates->ratecat[i];
numeric_t *expeigen = &expeigenRates[iRate*20];
double wA = pA->weights[i];
double wB = pB->weights[i];
if (wA == 0 && wB == 0 && pA->codes[i] == NOCODE && pB->codes[i] == NOCODE) {
/* Likelihood of A vs B is 1, so nothing changes
Do not need to advance iFreqA or iFreqB */
continue;
}
numeric_t *fA = GET_FREQ(pA,i,/*IN/OUT*/iFreqA);
numeric_t *fB = GET_FREQ(pB,i,/*IN/OUT*/iFreqB);
if (fA == NULL)
fA = &transmat->codeFreq[pA->codes[i]][0];
if (wA > 0.0 && wA < 1.0) {
for (j = 0; j < 20; j++)
fAmix[j] = wA*fA[j] + (1.0-wA)*fGap[j];
fA = fAmix;
}
if (fB == NULL)
fB = &transmat->codeFreq[pB->codes[i]][0];
if (wB > 0.0 && wB < 1.0) {
for (j = 0; j < 20; j++)
fBmix[j] = wB*fB[j] + (1.0-wB)*fGap[j];
fB = fBmix;
}
numeric_t lkAB = vector_multiply3_sum(expeigen, fA, fB, 20);
if (!(lkAB > 0)) {
/* If this happens, it indicates a numerical problem that needs to be addressed elsewhere,
so report all the details */
fprintf(stderr, "# FastTree.c::PairLogLk -- numerical problem!\n");
fprintf(stderr, "# This block is intended for loading into R\n");
fprintf(stderr, "lkAB = %.8g\n", lkAB);
fprintf(stderr, "Branch_length= %.8g\nalignment_position=%d\nnCodes=%d\nrate_category=%d\nrate=%.8g\n",
length, i, nCodes, iRate, rates->rates[iRate]);
fprintf(stderr, "wA=%.8g\nwB=%.8g\n", wA, wB);
fprintf(stderr, "codeA = %d\ncodeB = %d\n", pA->codes[i], pB->codes[i]);
fprintf(stderr, "fA = c(");
for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", fA[j]);
fprintf(stderr,")\n");
fprintf(stderr, "fB = c(");
for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", fB[j]);
fprintf(stderr,")\n");
fprintf(stderr, "stat = c(");
for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", transmat->stat[j]);
fprintf(stderr,")\n");
fprintf(stderr, "eigenval = c(");
for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", transmat->eigenval[j]);
fprintf(stderr,")\n");
fprintf(stderr, "expeigen = c(");
for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", expeigen[j]);
fprintf(stderr,")\n");
int k;
fprintf(stderr, "codeFreq = c(");
for (j = 0; j < nCodes; j++) for(k = 0; k < nCodes; k++) fprintf(stderr, "%s %.8g", j==0 && k==0?"":",",
transmat->codeFreq[j][k]);
fprintf(stderr,")\n");
fprintf(stderr, "eigeninv = c(");
for (j = 0; j < nCodes; j++) for(k = 0; k < nCodes; k++) fprintf(stderr, "%s %.8g", j==0 && k==0?"":",",
transmat->eigeninv[j][k]);
fprintf(stderr,")\n");
fprintf(stderr, "# Transform into matrices and compute un-rotated vectors for profiles A and B\n");
fprintf(stderr, "codeFreq = matrix(codeFreq,nrow=20);\n");
fprintf(stderr, "eigeninv = matrix(eigeninv,nrow=20);\n");
fputs("unrotA = stat * (eigeninv %*% fA)\n", stderr);
fputs("unrotB = stat * (eigeninv %*% fB)\n", stderr);
fprintf(stderr,"# End of R block\n");
}
assert(lkAB > 0);
if (site_likelihoods != NULL)
site_likelihoods[i] *= lkAB;
lk *= lkAB;
while (lk < LkUnderflow) {
lk *= LkUnderflowInv;
loglk -= LogLkUnderflow;
}
while (lk > LkUnderflowInv) {
lk *= LkUnderflow;
loglk += LogLkUnderflow;
}
}
} else {
assert(0); /* illegal nCodes */
}
if (transmat != NULL)
expeigenRates = myfree(expeigenRates, sizeof(numeric_t) * rates->nRateCategories * 20);
loglk += log(lk);
nLkCompute++;
return(loglk);
}
double MLQuartetLogLk(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD,
int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
/*IN*/double branch_lengths[5],
/*OPTIONAL OUT*/double *site_likelihoods) {
profile_t *pAB = PosteriorProfile(pA, pB,
branch_lengths[0], branch_lengths[1],
transmat,
rates,
nPos, /*nConstraints*/0);
profile_t *pCD = PosteriorProfile(pC, pD,
branch_lengths[2], branch_lengths[3],
transmat,
rates,
nPos, /*nConstraints*/0);
if (site_likelihoods != NULL) {
int i;
for (i = 0; i < nPos; i++)
site_likelihoods[i] = 1.0;
}
/* Roughly, P(A,B,C,D) = P(A) P(B|A) P(D|C) P(AB | CD) */
double loglk = PairLogLk(pA, pB, branch_lengths[0]+branch_lengths[1],
nPos, transmat, rates, /*OPTIONAL IN/OUT*/site_likelihoods)
+ PairLogLk(pC, pD, branch_lengths[2]+branch_lengths[3],
nPos, transmat, rates, /*OPTIONAL IN/OUT*/site_likelihoods)
+ PairLogLk(pAB, pCD, branch_lengths[4],
nPos, transmat, rates, /*OPTIONAL IN/OUT*/site_likelihoods);
pAB = FreeProfile(pAB, nPos, /*nConstraints*/0);
pCD = FreeProfile(pCD, nPos, /*nConstraints*/0);
return(loglk);
}
double PairNegLogLk(double x, void *data) {
quartet_opt_t *qo = (quartet_opt_t *)data;
assert(qo != NULL);
assert(qo->pair1 != NULL && qo->pair2 != NULL);
qo->nEval++;
double loglk = PairLogLk(qo->pair1, qo->pair2, x, qo->nPos, qo->transmat, qo->rates, /*site_lk*/NULL);
assert(loglk < 1e100);
if (verbose > 5)
fprintf(stderr, "PairLogLk(%.4f) = %.4f\n", x, loglk);
return(-loglk);
}
double MLQuartetOptimize(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD,
int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
/*IN/OUT*/double branch_lengths[5],
/*OPTIONAL OUT*/bool *pStarTest,
/*OPTIONAL OUT*/double *site_likelihoods) {
int j;
double start_length[5];
for (j = 0; j < 5; j++) {
start_length[j] = branch_lengths[j];
if (branch_lengths[j] < MLMinBranchLength)
branch_lengths[j] = MLMinBranchLength;
}
quartet_opt_t qopt = { nPos, transmat, rates, /*nEval*/0,
/*pair1*/NULL, /*pair2*/NULL };
double f2x, negloglk;
if (pStarTest != NULL)
*pStarTest = false;
/* First optimize internal branch, then branch to A, B, C, D, in turn
May use star test to quit after internal branch
*/
profile_t *pAB = PosteriorProfile(pA, pB,
branch_lengths[LEN_A], branch_lengths[LEN_B],
transmat, rates, nPos, /*nConstraints*/0);
profile_t *pCD = PosteriorProfile(pC, pD,
branch_lengths[LEN_C], branch_lengths[LEN_D],
transmat, rates, nPos, /*nConstraints*/0);
qopt.pair1 = pAB;
qopt.pair2 = pCD;
branch_lengths[LEN_I] = onedimenmin(/*xmin*/MLMinBranchLength,
/*xguess*/branch_lengths[LEN_I],
/*xmax*/6.0,
PairNegLogLk,
/*data*/&qopt,
/*ftol*/MLFTolBranchLength,
/*atol*/MLMinBranchLengthTolerance,
/*OUT*/&negloglk,
/*OUT*/&f2x);
if (pStarTest != NULL) {
assert(site_likelihoods == NULL);
double loglkStar = -PairNegLogLk(MLMinBranchLength, &qopt);
if (loglkStar < -negloglk - closeLogLkLimit) {
*pStarTest = true;
double off = PairLogLk(pA, pB,
branch_lengths[LEN_A] + branch_lengths[LEN_B],
qopt.nPos, qopt.transmat, qopt.rates, /*site_lk*/NULL)
+ PairLogLk(pC, pD,
branch_lengths[LEN_C] + branch_lengths[LEN_D],
qopt.nPos, qopt.transmat, qopt.rates, /*site_lk*/NULL);
pAB = FreeProfile(pAB, nPos, /*nConstraints*/0);
pCD = FreeProfile(pCD, nPos, /*nConstraints*/0);
return (-negloglk + off);
}
}
pAB = FreeProfile(pAB, nPos, /*nConstraints*/0);
profile_t *pBCD = PosteriorProfile(pB, pCD,
branch_lengths[LEN_B], branch_lengths[LEN_I],
transmat, rates, nPos, /*nConstraints*/0);
qopt.pair1 = pA;
qopt.pair2 = pBCD;
branch_lengths[LEN_A] = onedimenmin(/*xmin*/MLMinBranchLength,
/*xguess*/branch_lengths[LEN_A],
/*xmax*/6.0,
PairNegLogLk,
/*data*/&qopt,
/*ftol*/MLFTolBranchLength,
/*atol*/MLMinBranchLengthTolerance,
/*OUT*/&negloglk,
/*OUT*/&f2x);
pBCD = FreeProfile(pBCD, nPos, /*nConstraints*/0);
profile_t *pACD = PosteriorProfile(pA, pCD,
branch_lengths[LEN_A], branch_lengths[LEN_I],
transmat, rates, nPos, /*nConstraints*/0);
qopt.pair1 = pB;
qopt.pair2 = pACD;
branch_lengths[LEN_B] = onedimenmin(/*xmin*/MLMinBranchLength,
/*xguess*/branch_lengths[LEN_B],
/*xmax*/6.0,
PairNegLogLk,
/*data*/&qopt,
/*ftol*/MLFTolBranchLength,
/*atol*/MLMinBranchLengthTolerance,
/*OUT*/&negloglk,
/*OUT*/&f2x);
pACD = FreeProfile(pACD, nPos, /*nConstraints*/0);
pCD = FreeProfile(pCD, nPos, /*nConstraints*/0);
pAB = PosteriorProfile(pA, pB,
branch_lengths[LEN_A], branch_lengths[LEN_B],
transmat, rates, nPos, /*nConstraints*/0);
profile_t *pABD = PosteriorProfile(pAB, pD,
branch_lengths[LEN_I], branch_lengths[LEN_D],
transmat, rates, nPos, /*nConstraints*/0);
qopt.pair1 = pC;
qopt.pair2 = pABD;
branch_lengths[LEN_C] = onedimenmin(/*xmin*/MLMinBranchLength,
/*xguess*/branch_lengths[LEN_C],
/*xmax*/6.0,
PairNegLogLk,
/*data*/&qopt,
/*ftol*/MLFTolBranchLength,
/*atol*/MLMinBranchLengthTolerance,
/*OUT*/&negloglk,
/*OUT*/&f2x);
pABD = FreeProfile(pABD, nPos, /*nConstraints*/0);
profile_t *pABC = PosteriorProfile(pAB, pC,
branch_lengths[LEN_I], branch_lengths[LEN_C],
transmat, rates, nPos, /*nConstraints*/0);
qopt.pair1 = pD;
qopt.pair2 = pABC;
branch_lengths[LEN_D] = onedimenmin(/*xmin*/MLMinBranchLength,
/*xguess*/branch_lengths[LEN_D],
/*xmax*/6.0,
PairNegLogLk,
/*data*/&qopt,
/*ftol*/MLFTolBranchLength,
/*atol*/MLMinBranchLengthTolerance,
/*OUT*/&negloglk,
/*OUT*/&f2x);
/* Compute the total quartet likelihood
PairLogLk(ABC,D) + PairLogLk(AB,C) + PairLogLk(A,B)
*/
double loglkABCvsD = -negloglk;
if (site_likelihoods) {
for (j = 0; j < nPos; j++)
site_likelihoods[j] = 1.0;
PairLogLk(pABC, pD, branch_lengths[LEN_D],
qopt.nPos, qopt.transmat, qopt.rates, /*IN/OUT*/site_likelihoods);
}
double quartetloglk = loglkABCvsD
+ PairLogLk(pAB, pC, branch_lengths[LEN_I] + branch_lengths[LEN_C],
qopt.nPos, qopt.transmat, qopt.rates,
/*IN/OUT*/site_likelihoods)
+ PairLogLk(pA, pB, branch_lengths[LEN_A] + branch_lengths[LEN_B],
qopt.nPos, qopt.transmat, qopt.rates,
/*IN/OUT*/site_likelihoods);
pABC = FreeProfile(pABC, nPos, /*nConstraints*/0);
pAB = FreeProfile(pAB, nPos, /*nConstraints*/0);
if (verbose > 3) {
double loglkStart = MLQuartetLogLk(pA, pB, pC, pD, nPos, transmat, rates, start_length, /*site_lk*/NULL);
fprintf(stderr, "Optimize loglk from %.5f to %.5f eval %d lengths from\n"
" %.5f %.5f %.5f %.5f %.5f to\n"
" %.5f %.5f %.5f %.5f %.5f\n",
loglkStart, quartetloglk, qopt.nEval,
start_length[0], start_length[1], start_length[2], start_length[3], start_length[4],
branch_lengths[0], branch_lengths[1], branch_lengths[2], branch_lengths[3], branch_lengths[4]);
}
return(quartetloglk);
}
nni_t MLQuartetNNI(profile_t *profiles[4],
/*OPTIONAL*/transition_matrix_t *transmat,
rates_t *rates,
int nPos, int nConstraints,
/*OUT*/double criteria[3], /* The three potential quartet log-likelihoods */
/*IN/OUT*/numeric_t len[5],
bool bFast)
{
int i;
double lenABvsCD[5] = {len[LEN_A], len[LEN_B], len[LEN_C], len[LEN_D], len[LEN_I]};
double lenACvsBD[5] = {len[LEN_A], len[LEN_C], len[LEN_B], len[LEN_D], len[LEN_I]}; /* Swap B & C */
double lenADvsBC[5] = {len[LEN_A], len[LEN_D], len[LEN_C], len[LEN_B], len[LEN_I]}; /* Swap B & D */
bool bConsiderAC = true;
bool bConsiderAD = true;
int iRound;
int nRounds = mlAccuracy < 2 ? 2 : mlAccuracy;
double penalty[3];
QuartetConstraintPenalties(profiles, nConstraints, /*OUT*/penalty);
if (penalty[ABvsCD] > penalty[ACvsBD] || penalty[ABvsCD] > penalty[ADvsBC])
bFast = false;
#ifdef OPENMP
bFast = false; /* turn off star topology test */
#endif
for (iRound = 0; iRound < nRounds; iRound++) {
bool bStarTest = false;
{
#ifdef OPENMP
#pragma omp parallel
#pragma omp sections
#endif
{
#ifdef OPENMP
#pragma omp section
#endif
{
criteria[ABvsCD] = MLQuartetOptimize(profiles[0], profiles[1], profiles[2], profiles[3],
nPos, transmat, rates,
/*IN/OUT*/lenABvsCD,
bFast ? &bStarTest : NULL,
/*site_likelihoods*/NULL)
- penalty[ABvsCD]; /* subtract penalty b/c we are trying to maximize log lk */
}
#ifdef OPENMP
#pragma omp section
#else
if (bStarTest) {
nStarTests++;
criteria[ACvsBD] = -1e20;
criteria[ADvsBC] = -1e20;
len[LEN_I] = lenABvsCD[LEN_I];
return(ABvsCD);
}
#endif
{
if (bConsiderAC)
criteria[ACvsBD] = MLQuartetOptimize(profiles[0], profiles[2], profiles[1], profiles[3],
nPos, transmat, rates,
/*IN/OUT*/lenACvsBD, NULL, /*site_likelihoods*/NULL)
- penalty[ACvsBD];
}
#ifdef OPENMP
#pragma omp section
#endif
{
if (bConsiderAD)
criteria[ADvsBC] = MLQuartetOptimize(profiles[0], profiles[3], profiles[2], profiles[1],
nPos, transmat, rates,
/*IN/OUT*/lenADvsBC, NULL, /*site_likelihoods*/NULL)
- penalty[ADvsBC];
}
}
} /* end parallel sections */
if (mlAccuracy < 2) {
/* If clearly worse then ABvsCD, or have short internal branch length and worse, then
give up */
if (criteria[ACvsBD] < criteria[ABvsCD] - closeLogLkLimit
|| (lenACvsBD[LEN_I] <= 2.0*MLMinBranchLength && criteria[ACvsBD] < criteria[ABvsCD]))
bConsiderAC = false;
if (criteria[ADvsBC] < criteria[ABvsCD] - closeLogLkLimit
|| (lenADvsBC[LEN_I] <= 2.0*MLMinBranchLength && criteria[ADvsBC] < criteria[ABvsCD]))
bConsiderAD = false;
if (!bConsiderAC && !bConsiderAD)
break;
/* If clearly better than either alternative, then give up
(Comparison is probably biased in favor of ABvsCD anyway) */
if (criteria[ACvsBD] > criteria[ABvsCD] + closeLogLkLimit
&& criteria[ACvsBD] > criteria[ADvsBC] + closeLogLkLimit)
break;
if (criteria[ADvsBC] > criteria[ABvsCD] + closeLogLkLimit
&& criteria[ADvsBC] > criteria[ACvsBD] + closeLogLkLimit)
break;
}
} /* end loop over rounds */
if (verbose > 2) {
fprintf(stderr, "Optimized quartet for %d rounds: ABvsCD %.5f ACvsBD %.5f ADvsBC %.5f\n",
iRound, criteria[ABvsCD], criteria[ACvsBD], criteria[ADvsBC]);
}
if (criteria[ACvsBD] > criteria[ABvsCD] && criteria[ACvsBD] > criteria[ADvsBC]) {
for (i = 0; i < 5; i++) len[i] = lenACvsBD[i];
return(ACvsBD);
} else if (criteria[ADvsBC] > criteria[ABvsCD] && criteria[ADvsBC] > criteria[ACvsBD]) {
for (i = 0; i < 5; i++) len[i] = lenADvsBC[i];
return(ADvsBC);
} else {
for (i = 0; i < 5; i++) len[i] = lenABvsCD[i];
return(ABvsCD);
}
}
double TreeLength(/*IN/OUT*/NJ_t *NJ, bool recomputeProfiles) {
if (recomputeProfiles) {
traversal_t traversal2 = InitTraversal(NJ);
int j = NJ->root;
while((j = TraversePostorder(j, NJ, /*IN/OUT*/traversal2, /*pUp*/NULL)) >= 0) {
/* nothing to do for leaves or root */
if (j >= NJ->nSeq && j != NJ->root)
SetProfile(/*IN/OUT*/NJ, j, /*noweight*/-1.0);
}
traversal2 = FreeTraversal(traversal2,NJ);
}
UpdateBranchLengths(/*IN/OUT*/NJ);
double total_len = 0;
int iNode;
for (iNode = 0; iNode < NJ->maxnode; iNode++)
total_len += NJ->branchlength[iNode];
return(total_len);
}
double TreeLogLk(/*IN*/NJ_t *NJ, /*OPTIONAL OUT*/double *site_loglk) {
int i;
if (NJ->nSeq < 2)
return(0.0);
double loglk = 0.0;
double *site_likelihood = NULL;
if (site_loglk != NULL) {
site_likelihood = mymalloc(sizeof(double)*NJ->nPos);
for (i = 0; i < NJ->nPos; i++) {
site_likelihood[i] = 1.0;
site_loglk[i] = 0.0;
}
}
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
int nChild = NJ->child[node].nChild;
if (nChild == 0)
continue;
assert(nChild >= 2);
int *children = NJ->child[node].child;
double loglkchild = PairLogLk(NJ->profiles[children[0]], NJ->profiles[children[1]],
NJ->branchlength[children[0]]+NJ->branchlength[children[1]],
NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/site_likelihood);
loglk += loglkchild;
if (site_likelihood != NULL) {
/* prevent underflows */
for (i = 0; i < NJ->nPos; i++) {
while(site_likelihood[i] < LkUnderflow) {
site_likelihood[i] *= LkUnderflowInv;
site_loglk[i] -= LogLkUnderflow;
}
}
}
if (verbose > 2)
fprintf(stderr, "At %d: LogLk(%d:%.4f,%d:%.4f) = %.3f\n",
node,
children[0], NJ->branchlength[children[0]],
children[1], NJ->branchlength[children[1]],
loglkchild);
if (NJ->child[node].nChild == 3) {
assert(node == NJ->root);
/* Infer the common parent of the 1st two to define the third... */
profile_t *pAB = PosteriorProfile(NJ->profiles[children[0]],
NJ->profiles[children[1]],
NJ->branchlength[children[0]],
NJ->branchlength[children[1]],
NJ->transmat, &NJ->rates,
NJ->nPos, /*nConstraints*/0);
double loglkup = PairLogLk(pAB, NJ->profiles[children[2]],
NJ->branchlength[children[2]],
NJ->nPos, NJ->transmat, &NJ->rates,
/*IN/OUT*/site_likelihood);
loglk += loglkup;
if (verbose > 2)
fprintf(stderr, "At root %d: LogLk((%d/%d),%d:%.3f) = %.3f\n",
node, children[0], children[1], children[2],
NJ->branchlength[children[2]],
loglkup);
pAB = FreeProfile(pAB, NJ->nPos, NJ->nConstraints);
}
}
traversal = FreeTraversal(traversal,NJ);
if (site_likelihood != NULL) {
for (i = 0; i < NJ->nPos; i++) {
site_loglk[i] += log(site_likelihood[i]);
}
site_likelihood = myfree(site_likelihood, sizeof(double)*NJ->nPos);
}
/* For Jukes-Cantor, with a tree of size 4, if the children of the root are
(A,B), C, and D, then
P(ABCD) = P(A) P(B|A) P(C|AB) P(D|ABC)
Above we compute P(B|A) P(C|AB) P(D|ABC) -- note P(B|A) is at the child of root
and P(C|AB) P(D|ABC) is at root.
Similarly if the children of the root are C, D, and (A,B), then
P(ABCD) = P(C|D) P(A|B) P(AB|CD) P(D), and above we compute that except for P(D)
So we need to multiply by P(A) = 0.25, so we pay log(4) at each position
(if ungapped). Each gapped position in any sequence reduces the payment by log(4)
For JTT or GTR, we are computing P(A & B) and the posterior profiles are scaled to take
the prior into account, so we do not need any correction.
codeFreq[NOCODE] is scaled x higher so that P(-) = 1 not P(-)=1/nCodes, so gaps
do not need to be corrected either.
*/
if (nCodes == 4 && NJ->transmat == NULL) {
int nGaps = 0;
double logNCodes = log((double)nCodes);
for (i = 0; i < NJ->nPos; i++) {
int nGapsThisPos = 0;
for (node = 0; node < NJ->nSeq; node++) {
unsigned char *codes = NJ->profiles[node]->codes;
if (codes[i] == NOCODE)
nGapsThisPos++;
}
nGaps += nGapsThisPos;
if (site_loglk != NULL) {
site_loglk[i] += nGapsThisPos * logNCodes;
if (nCodes == 4 && NJ->transmat == NULL)
site_loglk[i] -= logNCodes;
}
}
loglk -= NJ->nPos * logNCodes;
loglk += nGaps * logNCodes; /* do not pay for gaps -- only Jukes-Cantor */
}
return(loglk);
}
void SetMLGtr(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL IN*/double *freq_in, /*OPTIONAL WRITE*/FILE *fpLog) {
int i;
assert(nCodes==4);
gtr_opt_t gtr;
gtr.NJ = NJ;
gtr.fpLog = fpLog;
if (freq_in != NULL) {
for (i=0; i<4; i++)
gtr.freq[i]=freq_in[i];
} else {
/* n[] and sum were int in FastTree 2.1.9 and earlier -- this
caused gtr analyses to fail on analyses with >2e9 positions */
long n[4] = {1,1,1,1}; /* pseudocounts */
for (i=0; i<NJ->nSeq; i++) {
unsigned char *codes = NJ->profiles[i]->codes;
int iPos;
for (iPos=0; iPos<NJ->nPos; iPos++)
if (codes[iPos] < 4)
n[codes[iPos]]++;
}
long sum = n[0]+n[1]+n[2]+n[3];
for (i=0; i<4; i++)
gtr.freq[i] = n[i]/(double)sum;
}
for (i=0; i<6; i++)
gtr.rates[i] = 1.0;
int nRounds = mlAccuracy < 2 ? 2 : mlAccuracy;
for (i = 0; i < nRounds; i++) {
for (gtr.iRate = 0; gtr.iRate < 6; gtr.iRate++) {
ProgressReport("Optimizing GTR model, step %d of %d", i*6+gtr.iRate+1, 12, 0, 0);
double negloglk, f2x;
gtr.rates[gtr.iRate] = onedimenmin(/*xmin*/0.05,
/*xguess*/gtr.rates[gtr.iRate],
/*xmax*/20.0,
GTRNegLogLk,
/*data*/>r,
/*ftol*/0.001,
/*atol*/0.0001,
/*OUT*/&negloglk,
/*OUT*/&f2x);
}
}
/* normalize gtr so last rate is 1 -- specifying that rate separately is useful for optimization only */
for (i = 0; i < 5; i++)
gtr.rates[i] /= gtr.rates[5];
gtr.rates[5] = 1.0;
if (verbose) {
fprintf(stderr, "GTR Frequencies: %.4f %.4f %.4f %.4f\n", gtr.freq[0], gtr.freq[1], gtr.freq[2], gtr.freq[3]);
fprintf(stderr, "GTR rates(ac ag at cg ct gt) %.4f %.4f %.4f %.4f %.4f %.4f\n",
gtr.rates[0],gtr.rates[1],gtr.rates[2],gtr.rates[3],gtr.rates[4],gtr.rates[5]);
}
if (fpLog != NULL) {
fprintf(fpLog, "GTRFreq\t%.4f\t%.4f\t%.4f\t%.4f\n", gtr.freq[0], gtr.freq[1], gtr.freq[2], gtr.freq[3]);
fprintf(fpLog, "GTRRates\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\n",
gtr.rates[0],gtr.rates[1],gtr.rates[2],gtr.rates[3],gtr.rates[4],gtr.rates[5]);
}
myfree(NJ->transmat, sizeof(transition_matrix_t));
NJ->transmat = CreateGTR(gtr.rates, gtr.freq);
RecomputeMLProfiles(/*IN/OUT*/NJ);
OptimizeAllBranchLengths(/*IN/OUT*/NJ);
}
double GTRNegLogLk(double x, void *data) {
gtr_opt_t *gtr = (gtr_opt_t*)data;
assert(nCodes == 4);
assert(gtr->NJ != NULL);
assert(gtr->iRate >= 0 && gtr->iRate < 6);
assert(x > 0);
transition_matrix_t *old = gtr->NJ->transmat;
double rates[6];
int i;
for (i = 0; i < 6; i++)
rates[i] = gtr->rates[i];
rates[gtr->iRate] = x;
FILE *fpLog = gtr->fpLog;
if (fpLog)
fprintf(fpLog, "GTR_Opt\tfreq %.5f %.5f %.5f %.5f rates %.5f %.5f %.5f %.5f %.5f %.5f\n",
gtr->freq[0], gtr->freq[1], gtr->freq[2], gtr->freq[3],
rates[0], rates[1], rates[2], rates[3], rates[4], rates[5]);
gtr->NJ->transmat = CreateGTR(rates, gtr->freq);
RecomputeMLProfiles(/*IN/OUT*/gtr->NJ);
double loglk = TreeLogLk(gtr->NJ, /*site_loglk*/NULL);
myfree(gtr->NJ->transmat, sizeof(transition_matrix_t));
gtr->NJ->transmat = old;
/* Do not recompute profiles -- assume the caller will do that */
if (verbose > 2)
fprintf(stderr, "GTR LogLk(%.5f %.5f %.5f %.5f %.5f %.5f) = %f\n",
rates[0], rates[1], rates[2], rates[3], rates[4], rates[5], loglk);
if (fpLog)
fprintf(fpLog, "GTR_Opt\tGTR LogLk(%.5f %.5f %.5f %.5f %.5f %.5f) = %f\n",
rates[0], rates[1], rates[2], rates[3], rates[4], rates[5], loglk);
return(-loglk);
}
/* Caller must free the resulting vector of n rates */
numeric_t *MLSiteRates(int nRateCategories) {
/* Even spacing from 1/nRate to nRate */
double logNCat = log((double)nRateCategories);
double logMinRate = -logNCat;
double logMaxRate = logNCat;
double logd = (logMaxRate-logMinRate)/(double)(nRateCategories-1);
numeric_t *rates = mymalloc(sizeof(numeric_t)*nRateCategories);
int i;
for (i = 0; i < nRateCategories; i++)
rates[i] = exp(logMinRate + logd*(double)i);
return(rates);
}
double *MLSiteLikelihoodsByRate(/*IN*/NJ_t *NJ, /*IN*/numeric_t *rates, int nRateCategories) {
double *site_loglk = mymalloc(sizeof(double)*NJ->nPos*nRateCategories);
/* save the original rates */
assert(NJ->rates.nRateCategories > 0);
numeric_t *oldRates = NJ->rates.rates;
NJ->rates.rates = mymalloc(sizeof(numeric_t) * NJ->rates.nRateCategories);
/* Compute site likelihood for each rate */
int iPos;
int iRate;
for (iRate = 0; iRate < nRateCategories; iRate++) {
int i;
for (i = 0; i < NJ->rates.nRateCategories; i++)
NJ->rates.rates[i] = rates[iRate];
RecomputeMLProfiles(/*IN/OUT*/NJ);
double loglk = TreeLogLk(NJ, /*OUT*/&site_loglk[NJ->nPos*iRate]);
ProgressReport("Site likelihoods with rate category %d of %d", iRate+1, nRateCategories, 0, 0);
if(verbose > 2) {
fprintf(stderr, "Rate %.3f Loglk %.3f SiteLogLk", rates[iRate], loglk);
for (iPos = 0; iPos < NJ->nPos; iPos++)
fprintf(stderr,"\t%.3f", site_loglk[NJ->nPos*iRate + iPos]);
fprintf(stderr,"\n");
}
}
/* restore original rates and profiles */
myfree(NJ->rates.rates, sizeof(numeric_t) * NJ->rates.nRateCategories);
NJ->rates.rates = oldRates;
RecomputeMLProfiles(/*IN/OUT*/NJ);
return(site_loglk);
}
void SetMLRates(/*IN/OUT*/NJ_t *NJ, int nRateCategories) {
assert(nRateCategories > 0);
AllocRateCategories(/*IN/OUT*/&NJ->rates, 1, NJ->nPos); /* set to 1 category of rate 1 */
if (nRateCategories == 1) {
RecomputeMLProfiles(/*IN/OUT*/NJ);
return;
}
numeric_t *rates = MLSiteRates(nRateCategories);
double *site_loglk = MLSiteLikelihoodsByRate(/*IN*/NJ, /*IN*/rates, nRateCategories);
/* Select best rate for each site, correcting for the prior
For a prior, use a gamma distribution with shape parameter 3, scale 1/3, so
Prior(rate) ~ rate**2 * exp(-3*rate)
log Prior(rate) = C + 2 * log(rate) - 3 * rate
*/
double sumRates = 0;
int iPos;
int iRate;
for (iPos = 0; iPos < NJ->nPos; iPos++) {
int iBest = -1;
double dBest = -1e20;
for (iRate = 0; iRate < nRateCategories; iRate++) {
double site_loglk_with_prior = site_loglk[NJ->nPos*iRate + iPos]
+ 2.0 * log(rates[iRate]) - 3.0 * rates[iRate];
if (site_loglk_with_prior > dBest) {
iBest = iRate;
dBest = site_loglk_with_prior;
}
}
if (verbose > 2)
fprintf(stderr, "Selected rate category %d rate %.3f for position %d\n",
iBest, rates[iBest], iPos+1);
NJ->rates.ratecat[iPos] = iBest;
sumRates += rates[iBest];
}
site_loglk = myfree(site_loglk, sizeof(double)*NJ->nPos*nRateCategories);
/* Force the rates to average to 1 */
double avgRate = sumRates/NJ->nPos;
for (iRate = 0; iRate < nRateCategories; iRate++)
rates[iRate] /= avgRate;
/* Save the rates */
NJ->rates.rates = myfree(NJ->rates.rates, sizeof(numeric_t) * NJ->rates.nRateCategories);
NJ->rates.rates = rates;
NJ->rates.nRateCategories = nRateCategories;
/* Update profiles based on rates */
RecomputeMLProfiles(/*IN/OUT*/NJ);
if (verbose) {
fprintf(stderr, "Switched to using %d rate categories (CAT approximation)\n", nRateCategories);
fprintf(stderr, "Rate categories were divided by %.3f so that average rate = 1.0\n", avgRate);
fprintf(stderr, "CAT-based log-likelihoods may not be comparable across runs\n");
if (!gammaLogLk)
fprintf(stderr, "Use -gamma for approximate but comparable Gamma(20) log-likelihoods\n");
}
}
double GammaLogLk(/*IN*/siteratelk_t *s, /*OPTIONAL OUT*/double *gamma_loglk_sites) {
int iRate, iPos;
double *dRate = mymalloc(sizeof(double) * s->nRateCats);
for (iRate = 0; iRate < s->nRateCats; iRate++) {
/* The probability density for each rate is approximated by the total
density between the midpoints */
double pMin = iRate == 0 ? 0.0 :
PGamma(s->mult * (s->rates[iRate-1] + s->rates[iRate])/2.0, s->alpha);
double pMax = iRate == s->nRateCats-1 ? 1.0 :
PGamma(s->mult * (s->rates[iRate]+s->rates[iRate+1])/2.0, s->alpha);
dRate[iRate] = pMax-pMin;
}
double loglk = 0.0;
for (iPos = 0; iPos < s->nPos; iPos++) {
/* Prevent underflow on large trees by comparing to maximum loglk */
double maxloglk = -1e20;
for (iRate = 0; iRate < s->nRateCats; iRate++) {
double site_loglk = s->site_loglk[s->nPos*iRate + iPos];
if (site_loglk > maxloglk)
maxloglk = site_loglk;
}
double rellk = 0; /* likelihood scaled by exp(maxloglk) */
for (iRate = 0; iRate < s->nRateCats; iRate++) {
double lk = exp(s->site_loglk[s->nPos*iRate + iPos] - maxloglk);
rellk += lk * dRate[iRate];
}
double loglk_site = maxloglk + log(rellk);
loglk += loglk_site;
if (gamma_loglk_sites != NULL)
gamma_loglk_sites[iPos] = loglk_site;
}
dRate = myfree(dRate, sizeof(double)*s->nRateCats);
return(loglk);
}
double OptAlpha(double alpha, void *data) {
siteratelk_t *s = (siteratelk_t *)data;
s->alpha = alpha;
return(-GammaLogLk(s, NULL));
}
double OptMult(double mult, void *data) {
siteratelk_t *s = (siteratelk_t *)data;
s->mult = mult;
return(-GammaLogLk(s, NULL));
}
/* Input site_loglk must be for each rate */
double RescaleGammaLogLk(int nPos, int nRateCats, /*IN*/numeric_t *rates, /*IN*/double *site_loglk,
/*OPTIONAL*/FILE *fpLog) {
siteratelk_t s = { /*mult*/1.0, /*alpha*/1.0, nPos, nRateCats, rates, site_loglk };
double fx, f2x;
int i;
fx = -GammaLogLk(&s, NULL);
if (verbose>2)
fprintf(stderr, "Optimizing alpha, starting at loglk %.3f\n", -fx);
for (i = 0; i < 10; i++) {
ProgressReport("Optimizing alpha round %d", i+1, 0, 0, 0);
double start = fx;
s.alpha = onedimenmin(0.01, s.alpha, 10.0, OptAlpha, &s, 0.001, 0.001, &fx, &f2x);
if (verbose>2)
fprintf(stderr, "Optimize alpha round %d to %.3f lk %.3f\n", i+1, s.alpha, -fx);
s.mult = onedimenmin(0.01, s.mult, 10.0, OptMult, &s, 0.001, 0.001, &fx, &f2x);
if (verbose>2)
fprintf(stderr, "Optimize mult round %d to %.3f lk %.3f\n", i+1, s.mult, -fx);
if (fx > start - 0.001) {
if (verbose>2)
fprintf(stderr, "Optimizing alpha & mult converged\n");
break;
}
}
double *gamma_loglk_sites = mymalloc(sizeof(double) * nPos);
double gammaLogLk = GammaLogLk(&s, /*OUT*/gamma_loglk_sites);
if (verbose > 0)
fprintf(stderr, "Gamma(%d) LogLk = %.3f alpha = %.3f rescaling lengths by %.3f\n",
nRateCats, gammaLogLk, s.alpha, 1/s.mult);
if (fpLog) {
int iPos;
int iRate;
fprintf(fpLog, "Gamma%dLogLk\t%.3f\tApproximate\tAlpha\t%.3f\tRescale\t%.3f\n",
nRateCats, gammaLogLk, s.alpha, 1/s.mult);
fprintf(fpLog, "Gamma%d\tSite\tLogLk", nRateCats);
for (iRate = 0; iRate < nRateCats; iRate++)
fprintf(fpLog, "\tr=%.3f", rates[iRate]/s.mult);
fprintf(fpLog,"\n");
for (iPos = 0; iPos < nPos; iPos++) {
fprintf(fpLog, "Gamma%d\t%d\t%.3f", nRateCats, iPos, gamma_loglk_sites[iPos]);
for (iRate = 0; iRate < nRateCats; iRate++)
fprintf(fpLog, "\t%.3f", site_loglk[nPos*iRate + iPos]);
fprintf(fpLog,"\n");
}
}
gamma_loglk_sites = myfree(gamma_loglk_sites, sizeof(double) * nPos);
return(1.0/s.mult);
}
double MLPairOptimize(profile_t *pA, profile_t *pB,
int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates,
/*IN/OUT*/double *branch_length) {
quartet_opt_t qopt = { nPos, transmat, rates,
/*nEval*/0, /*pair1*/pA, /*pair2*/pB };
double f2x,negloglk;
*branch_length = onedimenmin(/*xmin*/MLMinBranchLength,
/*xguess*/*branch_length,
/*xmax*/6.0,
PairNegLogLk,
/*data*/&qopt,
/*ftol*/MLFTolBranchLength,
/*atol*/MLMinBranchLengthTolerance,
/*OUT*/&negloglk,
/*OUT*/&f2x);
return(-negloglk); /* the log likelihood */
}
void OptimizeAllBranchLengths(/*IN/OUT*/NJ_t *NJ) {
if (NJ->nSeq < 2)
return;
if (NJ->nSeq == 2) {
int parent = NJ->root;
assert(NJ->child[parent].nChild==2);
int nodes[2] = { NJ->child[parent].child[0], NJ->child[parent].child[1] };
double length = 1.0;
(void)MLPairOptimize(NJ->profiles[nodes[0]], NJ->profiles[nodes[1]],
NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/&length);
NJ->branchlength[nodes[0]] = length/2.0;
NJ->branchlength[nodes[1]] = length/2.0;
return;
};
traversal_t traversal = InitTraversal(NJ);
profile_t **upProfiles = UpProfiles(NJ);
int node = NJ->root;
int iDone = 0;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
int nChild = NJ->child[node].nChild;
if (nChild > 0) {
if ((iDone % 100) == 0)
ProgressReport("ML Lengths %d of %d splits", iDone+1, NJ->maxnode - NJ->nSeq, 0, 0);
iDone++;
/* optimize the branch lengths between self, parent, and children,
with two iterations
*/
assert(nChild == 2 || nChild == 3);
int nodes[3] = { NJ->child[node].child[0],
NJ->child[node].child[1],
nChild == 3 ? NJ->child[node].child[2] : node };
profile_t *profiles[3] = { NJ->profiles[nodes[0]],
NJ->profiles[nodes[1]],
nChild == 3 ? NJ->profiles[nodes[2]]
: GetUpProfile(/*IN/OUT*/upProfiles, NJ, node, /*useML*/true) };
int iter;
for (iter = 0; iter < 2; iter++) {
int i;
for (i = 0; i < 3; i++) {
profile_t *pA = profiles[i];
int b1 = (i+1) % 3;
int b2 = (i+2) % 3;
profile_t *pB = PosteriorProfile(profiles[b1], profiles[b2],
NJ->branchlength[nodes[b1]],
NJ->branchlength[nodes[b2]],
NJ->transmat, &NJ->rates, NJ->nPos, /*nConstraints*/0);
double len = NJ->branchlength[nodes[i]];
if (len < MLMinBranchLength)
len = MLMinBranchLength;
(void)MLPairOptimize(pA, pB, NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/&len);
NJ->branchlength[nodes[i]] = len;
pB = FreeProfile(pB, NJ->nPos, /*nConstraints*/0);
if (verbose>3)
fprintf(stderr, "Optimize length for %d to %.3f\n",
nodes[i], NJ->branchlength[nodes[i]]);
}
}
if (node != NJ->root) {
RecomputeProfile(/*IN/OUT*/NJ, /*IN/OUT*/upProfiles, node, /*useML*/true);
DeleteUpProfile(upProfiles, NJ, node);
}
}
}
traversal = FreeTraversal(traversal,NJ);
upProfiles = FreeUpProfiles(upProfiles,NJ);
}
void RecomputeMLProfiles(/*IN/OUT*/NJ_t *NJ) {
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
if (NJ->child[node].nChild == 2) {
NJ->profiles[node] = FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints);
int *children = NJ->child[node].child;
NJ->profiles[node] = PosteriorProfile(NJ->profiles[children[0]], NJ->profiles[children[1]],
NJ->branchlength[children[0]], NJ->branchlength[children[1]],
NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints);
}
}
traversal = FreeTraversal(traversal, NJ);
}
void RecomputeProfiles(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL*/distance_matrix_t *dmat) {
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
if (NJ->child[node].nChild == 2) {
int *child = NJ->child[node].child;
NJ->profiles[node] = FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints);
NJ->profiles[node] = AverageProfile(NJ->profiles[child[0]], NJ->profiles[child[1]],
NJ->nPos, NJ->nConstraints,
dmat, /*unweighted*/-1.0);
}
}
traversal = FreeTraversal(traversal,NJ);
}
int NNI(/*IN/OUT*/NJ_t *NJ, int iRound, int nRounds, bool useML,
/*IN/OUT*/nni_stats_t *stats,
/*OUT*/double *dMaxDelta) {
/* For each non-root node N, with children A,B, sibling C, and uncle D,
we compare the current topology AB|CD to the alternate topologies
AC|BD and AD|BC, by using the 4 relevant profiles.
If useML is true, it uses quartet maximum likelihood, and it
updates branch lengths as it goes.
If useML is false, it uses the minimum-evolution criterion with
log-corrected distances on profiles. (If logdist is false, then
the log correction is not done.) If useML is false, then NNI()
does NOT modify the branch lengths.
Regardless of whether it changes the topology, it recomputes the
profile for the node, using the pairwise distances and BIONJ-like
weightings (if bionj is set). The parent's profile has changed,
but recomputing it is not necessary because we will visit it
before we need it (we use postorder, so we may visit the sibling
and its children before we visit the parent, but we never
consider an ancestor's profile, so that is OK). When we change
the parent's profile, this alters the uncle's up-profile, so we
remove that. Finally, if the topology has changed, we remove the
up-profiles of the nodes.
If we do an NNI during post-order traversal, the result is a bit
tricky. E.g. if we are at node N, and have visited its children A
and B but not its uncle C, and we do an NNI that swaps B & C,
then the post-order traversal will visit C, and its children, but
then on the way back up, it will skip N, as it has already
visited it. So, the profile of N will not be recomputed: any
changes beneath C will not be reflected in the profile of N, and
the profile of N will be slightly stale. This will be corrected
on the next round of NNIs.
*/
double supportThreshold = useML ? treeLogLkDelta : MEMinDelta;
int i;
*dMaxDelta = 0.0;
int nNNIThisRound = 0;
if (NJ->nSeq <= 3)
return(0); /* nothing to do */
if (verbose > 2) {
fprintf(stderr, "Beginning round %d of NNIs with ml? %d\n", iRound, useML?1:0);
PrintNJInternal(/*WRITE*/stderr, NJ, /*useLen*/useML && iRound > 0 ? 1 : 0);
}
/* For each node the upProfile or NULL */
profile_t **upProfiles = UpProfiles(NJ);
traversal_t traversal = InitTraversal(NJ);
/* Identify nodes we can skip traversing into */
int node;
if (fastNNI) {
for (node = 0; node < NJ->maxnode; node++) {
if (node != NJ->root
&& node >= NJ->nSeq
&& stats[node].age >= 2
&& stats[node].subtreeAge >= 2
&& stats[node].support > supportThreshold) {
int nodeABCD[4];
SetupABCD(NJ, node, NULL, NULL, /*OUT*/nodeABCD, useML);
for (i = 0; i < 4; i++)
if (stats[nodeABCD[i]].age == 0 && stats[nodeABCD[i]].support > supportThreshold)
break;
if (i == 4) {
SkipTraversalInto(node, /*IN/OUT*/traversal);
if (verbose > 2)
fprintf(stderr, "Skipping subtree at %d: child %d %d parent %d age %d subtreeAge %d support %.3f\n",
node, nodeABCD[0], nodeABCD[1], NJ->parent[node],
stats[node].age, stats[node].subtreeAge, stats[node].support);
}
}
}
}
int iDone = 0;
bool bUp;
node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, &bUp)) >= 0) {
if (node < NJ->nSeq || node == NJ->root)
continue; /* nothing to do for leaves or root */
if (bUp) {
if(verbose > 2)
fprintf(stderr, "Going up back to node %d\n", node);
/* No longer needed */
for (i = 0; i < NJ->child[node].nChild; i++)
DeleteUpProfile(upProfiles, NJ, NJ->child[node].child[i]);
DeleteUpProfile(upProfiles, NJ, node);
RecomputeProfile(/*IN/OUT*/NJ, /*IN/OUT*/upProfiles, node, useML);
continue;
}
if ((iDone % 100) == 0) {
char buf[100];
sprintf(buf, "%s NNI round %%d of %%d, %%d of %%d splits", useML ? "ML" : "ME");
if (iDone > 0)
sprintf(buf+strlen(buf), ", %d changes", nNNIThisRound);
if (nNNIThisRound > 0)
sprintf(buf+strlen(buf), " (max delta %.3f)", *dMaxDelta);
ProgressReport(buf, iRound+1, nRounds, iDone+1, NJ->maxnode - NJ->nSeq);
}
iDone++;
profile_t *profiles[4];
int nodeABCD[4];
/* Note -- during the first round of ML NNIs, we use the min-evo-based branch lengths,
which may be suboptimal */
SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, useML);
/* Given our 4 profiles, consider doing a swap */
int nodeA = nodeABCD[0];
int nodeB = nodeABCD[1];
int nodeC = nodeABCD[2];
int nodeD = nodeABCD[3];
nni_t choice = ABvsCD;
if (verbose > 2)
fprintf(stderr,"Considering NNI around %d: Swap A=%d B=%d C=%d D=up(%d) or parent %d\n",
node, nodeA, nodeB, nodeC, nodeD, NJ->parent[node]);
if (verbose > 3 && useML) {
double len[5] = { NJ->branchlength[nodeA], NJ->branchlength[nodeB], NJ->branchlength[nodeC], NJ->branchlength[nodeD],
NJ->branchlength[node] };
for (i=0; i < 5; i++)
if (len[i] < MLMinBranchLength)
len[i] = MLMinBranchLength;
fprintf(stderr, "Starting quartet likelihood %.3f len %.3f %.3f %.3f %.3f %.3f\n",
MLQuartetLogLk(profiles[0],profiles[1],profiles[2],profiles[3],NJ->nPos,NJ->transmat,&NJ->rates,len, /*site_lk*/NULL),
len[0], len[1], len[2], len[3], len[4]);
}
numeric_t newlength[5];
double criteria[3];
if (useML) {
for (i = 0; i < 4; i++)
newlength[i] = NJ->branchlength[nodeABCD[i]];
newlength[4] = NJ->branchlength[node];
bool bFast = mlAccuracy < 2 && stats[node].age > 0;
choice = MLQuartetNNI(profiles, NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints,
/*OUT*/criteria, /*IN/OUT*/newlength, bFast);
} else {
choice = ChooseNNI(profiles, NJ->distance_matrix, NJ->nPos, NJ->nConstraints,
/*OUT*/criteria);
/* invert criteria so that higher is better, as in ML case, to simplify code below */
for (i = 0; i < 3; i++)
criteria[i] = -criteria[i];
}
if (choice == ACvsBD) {
/* swap B and C */
ReplaceChild(/*IN/OUT*/NJ, node, nodeB, nodeC);
ReplaceChild(/*IN/OUT*/NJ, NJ->parent[node], nodeC, nodeB);
} else if (choice == ADvsBC) {
/* swap A and C */
ReplaceChild(/*IN/OUT*/NJ, node, nodeA, nodeC);
ReplaceChild(/*IN/OUT*/NJ, NJ->parent[node], nodeC, nodeA);
}
if (useML) {
/* update branch length for the internal branch, and of any
branches that lead to leaves, b/c those will not are not
the internal branch for NNI and would not otherwise be set.
*/
if (choice == ADvsBC) {
/* For ADvsBC, MLQuartetNNI swaps B with D, but we swap A with C */
double length2[5] = { newlength[LEN_C], newlength[LEN_D],
newlength[LEN_A], newlength[LEN_B],
newlength[LEN_I] };
int i;
for (i = 0; i < 5; i++) newlength[i] = length2[i];
/* and swap A and C */
double tmp = newlength[LEN_A];
newlength[LEN_A] = newlength[LEN_C];
newlength[LEN_C] = tmp;
} else if (choice == ACvsBD) {
/* swap B and C */
double tmp = newlength[LEN_B];
newlength[LEN_B] = newlength[LEN_C];
newlength[LEN_C] = tmp;
}
NJ->branchlength[node] = newlength[LEN_I];
NJ->branchlength[nodeA] = newlength[LEN_A];
NJ->branchlength[nodeB] = newlength[LEN_B];
NJ->branchlength[nodeC] = newlength[LEN_C];
NJ->branchlength[nodeD] = newlength[LEN_D];
}
if (verbose>2 && (choice != ABvsCD || verbose > 2))
fprintf(stderr,"NNI around %d: Swap A=%d B=%d C=%d D=out(C) -- choose %s %s %.4f\n",
node, nodeA, nodeB, nodeC,
choice == ACvsBD ? "AC|BD" : (choice == ABvsCD ? "AB|CD" : "AD|BC"),
useML ? "delta-loglk" : "-deltaLen",
criteria[choice] - criteria[ABvsCD]);
if(verbose >= 3 && slow && useML)
fprintf(stderr, "Old tree lk -- %.4f\n", TreeLogLk(NJ, /*site_likelihoods*/NULL));
/* update stats, *dMaxDelta, etc. */
if (choice == ABvsCD) {
stats[node].age++;
} else {
if (useML)
nML_NNI++;
else
nNNI++;
nNNIThisRound++;
stats[node].age = 0;
stats[nodeA].age = 0;
stats[nodeB].age = 0;
stats[nodeC].age = 0;
stats[nodeD].age = 0;
}
stats[node].delta = criteria[choice] - criteria[ABvsCD]; /* 0 if ABvsCD */
if (stats[node].delta > *dMaxDelta)
*dMaxDelta = stats[node].delta;
/* support is improvement of score for self over better of alternatives */
stats[node].support = 1e20;
for (i = 0; i < 3; i++)
if (choice != i && criteria[choice]-criteria[i] < stats[node].support)
stats[node].support = criteria[choice]-criteria[i];
/* subtreeAge is the number of rounds since self or descendent had a significant improvement */
if (stats[node].delta > supportThreshold)
stats[node].subtreeAge = 0;
else {
stats[node].subtreeAge++;
for (i = 0; i < 2; i++) {
int child = NJ->child[node].child[i];
if (stats[node].subtreeAge > stats[child].subtreeAge)
stats[node].subtreeAge = stats[child].subtreeAge;
}
}
/* update profiles and free up unneeded up-profiles */
if (choice == ABvsCD) {
/* No longer needed */
DeleteUpProfile(upProfiles, NJ, nodeA);
DeleteUpProfile(upProfiles, NJ, nodeB);
DeleteUpProfile(upProfiles, NJ, nodeC);
RecomputeProfile(/*IN/OUT*/NJ, /*IN/OUT*/upProfiles, node, useML);
if(slow && useML)
UpdateForNNI(NJ, node, upProfiles, useML);
} else {
UpdateForNNI(NJ, node, upProfiles, useML);
}
if(verbose > 2 && slow && useML) {
/* Note we recomputed profiles back up to root already if slow */
PrintNJInternal(/*WRITE*/stderr, NJ, /*useLen*/true);
fprintf(stderr, "New tree lk -- %.4f\n", TreeLogLk(NJ, /*site_likelihoods*/NULL));
}
} /* end postorder traversal */
traversal = FreeTraversal(traversal,NJ);
if (verbose>=2) {
int nUp = 0;
for (i = 0; i < NJ->maxnodes; i++)
if (upProfiles[i] != NULL)
nUp++;
fprintf(stderr, "N up profiles at end of NNI: %d\n", nUp);
}
upProfiles = FreeUpProfiles(upProfiles,NJ);
return(nNNIThisRound);
}
nni_stats_t *InitNNIStats(NJ_t *NJ) {
nni_stats_t *stats = mymalloc(sizeof(nni_stats_t)*NJ->maxnode);
const int LargeAge = 1000000;
int i;
for (i = 0; i < NJ->maxnode; i++) {
stats[i].delta = 0;
stats[i].support = 0;
if (i == NJ->root || i < NJ->nSeq) {
stats[i].age = LargeAge;
stats[i].subtreeAge = LargeAge;
} else {
stats[i].age = 0;
stats[i].subtreeAge = 0;
}
}
return(stats);
}
nni_stats_t *FreeNNIStats(nni_stats_t *stats, NJ_t *NJ) {
return(myfree(stats, sizeof(nni_stats_t)*NJ->maxnode));
}
int FindSPRSteps(/*IN/OUT*/NJ_t *NJ,
int nodeMove, /* the node to move multiple times */
int nodeAround, /* sibling or parent of node to NNI to start the chain */
/*IN/OUT*/profile_t **upProfiles,
/*OUT*/spr_step_t *steps,
int maxSteps,
bool bFirstAC) {
int iStep;
for (iStep = 0; iStep < maxSteps; iStep++) {
if (NJ->child[nodeAround].nChild != 2)
break; /* no further to go */
/* Consider the NNIs around nodeAround */
profile_t *profiles[4];
int nodeABCD[4];
SetupABCD(NJ, nodeAround, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false);
double criteria[3];
(void) ChooseNNI(profiles, NJ->distance_matrix, NJ->nPos, NJ->nConstraints,
/*OUT*/criteria);
/* Do & save the swap */
spr_step_t *step = &steps[iStep];
if (iStep == 0 ? bFirstAC : criteria[ACvsBD] < criteria[ADvsBC]) {
/* swap B & C to put AC together */
step->deltaLength = criteria[ACvsBD] - criteria[ABvsCD];
step->nodes[0] = nodeABCD[1];
step->nodes[1] = nodeABCD[2];
} else {
/* swap AC to put AD together */
step->deltaLength = criteria[ADvsBC] - criteria[ABvsCD];
step->nodes[0] = nodeABCD[0];
step->nodes[1] = nodeABCD[2];
}
if (verbose>3) {
fprintf(stderr, "SPR chain step %d for %d around %d swap %d %d deltaLen %.5f\n",
iStep+1, nodeAround, nodeMove, step->nodes[0], step->nodes[1], step->deltaLength);
if (verbose>4)
PrintNJInternal(stderr, NJ, /*useLen*/false);
}
ReplaceChild(/*IN/OUT*/NJ, nodeAround, step->nodes[0], step->nodes[1]);
ReplaceChild(/*IN/OUT*/NJ, NJ->parent[nodeAround], step->nodes[1], step->nodes[0]);
UpdateForNNI(/*IN/OUT*/NJ, nodeAround, /*IN/OUT*/upProfiles, /*useML*/false);
/* set the new nodeAround -- either parent(nodeMove) or sibling(nodeMove) --
so that it different from current nodeAround
*/
int newAround[2] = { NJ->parent[nodeMove], Sibling(NJ, nodeMove) };
if (NJ->parent[nodeMove] == NJ->root)
RootSiblings(NJ, nodeMove, /*OUT*/newAround);
assert(newAround[0] == nodeAround || newAround[1] == nodeAround);
assert(newAround[0] != newAround[1]);
nodeAround = newAround[newAround[0] == nodeAround ? 1 : 0];
}
return(iStep);
}
void UnwindSPRStep(/*IN/OUT*/NJ_t *NJ,
/*IN*/spr_step_t *step,
/*IN/OUT*/profile_t **upProfiles) {
int parents[2];
int i;
for (i = 0; i < 2; i++) {
assert(step->nodes[i] >= 0 && step->nodes[i] < NJ->maxnodes);
parents[i] = NJ->parent[step->nodes[i]];
assert(parents[i] >= 0);
}
assert(parents[0] != parents[1]);
ReplaceChild(/*IN/OUT*/NJ, parents[0], step->nodes[0], step->nodes[1]);
ReplaceChild(/*IN/OUT*/NJ, parents[1], step->nodes[1], step->nodes[0]);
int iYounger = 0;
if (NJ->parent[parents[0]] == parents[1]) {
iYounger = 0;
} else {
assert(NJ->parent[parents[1]] == parents[0]);
iYounger = 1;
}
UpdateForNNI(/*IN/OUT*/NJ, parents[iYounger], /*IN/OUT*/upProfiles, /*useML*/false);
}
/* Update the profile of node and its ancestor, and delete nearby out-profiles */
void UpdateForNNI(/*IN/OUT*/NJ_t *NJ, int node, /*IN/OUT*/profile_t **upProfiles,
bool useML) {
int i;
if (slow) {
/* exhaustive update */
for (i = 0; i < NJ->maxnodes; i++)
DeleteUpProfile(upProfiles, NJ, i);
/* update profiles back to root */
int ancestor;
for (ancestor = node; ancestor >= 0; ancestor = NJ->parent[ancestor])
RecomputeProfile(/*IN/OUT*/NJ, upProfiles, ancestor, useML);
/* remove any up-profiles made while doing that*/
for (i = 0; i < NJ->maxnodes; i++)
DeleteUpProfile(upProfiles, NJ, i);
} else {
/* if fast, only update around self
note that upProfile(parent) is still OK after an NNI, but
up-profiles of uncles may not be
*/
DeleteUpProfile(upProfiles, NJ, node);
for (i = 0; i < NJ->child[node].nChild; i++)
DeleteUpProfile(upProfiles, NJ, NJ->child[node].child[i]);
assert(node != NJ->root);
int parent = NJ->parent[node];
int neighbors[2] = { parent, Sibling(NJ, node) };
if (parent == NJ->root)
RootSiblings(NJ, node, /*OUT*/neighbors);
DeleteUpProfile(upProfiles, NJ, neighbors[0]);
DeleteUpProfile(upProfiles, NJ, neighbors[1]);
int uncle = Sibling(NJ, parent);
if (uncle >= 0)
DeleteUpProfile(upProfiles, NJ, uncle);
RecomputeProfile(/*IN/OUT*/NJ, upProfiles, node, useML);
RecomputeProfile(/*IN/OUT*/NJ, upProfiles, parent, useML);
}
}
void SPR(/*IN/OUT*/NJ_t *NJ, int maxSPRLength, int iRound, int nRounds) {
/* Given a non-root node N with children A,B, sibling C, and uncle D,
we can try to move A by doing three types of moves (4 choices):
"down" -- swap A with a child of B (if B is not a leaf) [2 choices]
"over" -- swap B with C
"up" -- swap A with D
We follow down moves with down moves, over moves with down moves, and
up moves with either up or over moves. (Other choices are just backing
up and hence useless.)
As with NNIs, we keep track of up-profiles as we go. However, some of the regular
profiles may also become "stale" so it is a bit trickier.
We store the traversal before we do SPRs to avoid any possible infinite loop
*/
double last_tot_len = 0.0;
if (NJ->nSeq <= 3 || maxSPRLength < 1)
return;
if (slow)
last_tot_len = TreeLength(NJ, /*recomputeLengths*/true);
int *nodeList = mymalloc(sizeof(int) * NJ->maxnodes);
int nodeListLen = 0;
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
nodeList[nodeListLen++] = node;
}
assert(nodeListLen == NJ->maxnode);
traversal = FreeTraversal(traversal,NJ);
profile_t **upProfiles = UpProfiles(NJ);
spr_step_t *steps = mymalloc(sizeof(spr_step_t) * maxSPRLength); /* current chain of SPRs */
int i;
for (i = 0; i < nodeListLen; i++) {
node = nodeList[i];
if ((i % 100) == 0)
ProgressReport("SPR round %3d of %3d, %d of %d nodes",
iRound+1, nRounds, i+1, nodeListLen);
if (node == NJ->root)
continue; /* nothing to do for root */
/* The nodes to NNI around */
int nodeAround[2] = { NJ->parent[node], Sibling(NJ, node) };
if (NJ->parent[node] == NJ->root) {
/* NNI around both siblings instead */
RootSiblings(NJ, node, /*OUT*/nodeAround);
}
bool bChanged = false;
int iAround;
for (iAround = 0; iAround < 2 && bChanged == false; iAround++) {
int ACFirst;
for (ACFirst = 0; ACFirst < 2 && bChanged == false; ACFirst++) {
if(verbose > 3)
PrintNJInternal(stderr, NJ, /*useLen*/false);
int chainLength = FindSPRSteps(/*IN/OUT*/NJ, node, nodeAround[iAround],
upProfiles, /*OUT*/steps, maxSPRLength, (bool)ACFirst);
double dMinDelta = 0.0;
int iCBest = -1;
double dTotDelta = 0.0;
int iC;
for (iC = 0; iC < chainLength; iC++) {
dTotDelta += steps[iC].deltaLength;
if (dTotDelta < dMinDelta) {
dMinDelta = dTotDelta;
iCBest = iC;
}
}
if (verbose>3) {
fprintf(stderr, "SPR %s %d around %d chainLength %d of %d deltaLength %.5f swaps:",
iCBest >= 0 ? "move" : "abandoned",
node,nodeAround[iAround],iCBest+1,chainLength,dMinDelta);
for (iC = 0; iC < chainLength; iC++)
fprintf(stderr, " (%d,%d)%.4f", steps[iC].nodes[0], steps[iC].nodes[1], steps[iC].deltaLength);
fprintf(stderr,"\n");
}
for (iC = chainLength - 1; iC > iCBest; iC--)
UnwindSPRStep(/*IN/OUT*/NJ, /*IN*/&steps[iC], /*IN/OUT*/upProfiles);
if(verbose > 3)
PrintNJInternal(stderr, NJ, /*useLen*/false);
while (slow && iCBest >= 0) {
double expected_tot_len = last_tot_len + dMinDelta;
double new_tot_len = TreeLength(NJ, /*recompute*/true);
if (verbose > 2)
fprintf(stderr, "Total branch-length is now %.4f was %.4f expected %.4f\n",
new_tot_len, last_tot_len, expected_tot_len);
if (new_tot_len < last_tot_len) {
last_tot_len = new_tot_len;
break; /* no rewinding necessary */
}
if (verbose > 2)
fprintf(stderr, "Rewinding SPR to %d\n",iCBest);
UnwindSPRStep(/*IN/OUT*/NJ, /*IN*/&steps[iCBest], /*IN/OUT*/upProfiles);
dMinDelta -= steps[iCBest].deltaLength;
iCBest--;
}
if (iCBest >= 0)
bChanged = true;
} /* loop over which step to take at 1st NNI */
} /* loop over which node to pivot around */
if (bChanged) {
nSPR++; /* the SPR move is OK */
/* make sure all the profiles are OK */
int j;
for (j = 0; j < NJ->maxnodes; j++)
DeleteUpProfile(upProfiles, NJ, j);
int ancestor;
for (ancestor = NJ->parent[node]; ancestor >= 0; ancestor = NJ->parent[ancestor])
RecomputeProfile(/*IN/OUT*/NJ, upProfiles, ancestor, /*useML*/false);
}
} /* end loop over subtrees to prune & regraft */
steps = myfree(steps, sizeof(spr_step_t) * maxSPRLength);
upProfiles = FreeUpProfiles(upProfiles,NJ);
nodeList = myfree(nodeList, sizeof(int) * NJ->maxnodes);
}
void RecomputeProfile(/*IN/OUT*/NJ_t *NJ, /*IN/OUT*/profile_t **upProfiles, int node,
bool useML) {
if (node < NJ->nSeq || node == NJ->root)
return; /* no profile to compute */
assert(NJ->child[node].nChild==2);
profile_t *profiles[4];
double weight = 0.5;
if (useML || !bionj) {
profiles[0] = NJ->profiles[NJ->child[node].child[0]];
profiles[1] = NJ->profiles[NJ->child[node].child[1]];
} else {
int nodeABCD[4];
SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, useML);
weight = QuartetWeight(profiles, NJ->distance_matrix, NJ->nPos);
}
if (verbose>3) {
if (useML) {
fprintf(stderr, "Recompute %d from %d %d lengths %.4f %.4f\n",
node,
NJ->child[node].child[0],
NJ->child[node].child[1],
NJ->branchlength[NJ->child[node].child[0]],
NJ->branchlength[NJ->child[node].child[1]]);
} else {
fprintf(stderr, "Recompute %d from %d %d weight %.3f\n",
node, NJ->child[node].child[0], NJ->child[node].child[1], weight);
}
}
NJ->profiles[node] = FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints);
if (useML) {
NJ->profiles[node] = PosteriorProfile(profiles[0], profiles[1],
NJ->branchlength[NJ->child[node].child[0]],
NJ->branchlength[NJ->child[node].child[1]],
NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints);
} else {
NJ->profiles[node] = AverageProfile(profiles[0], profiles[1],
NJ->nPos, NJ->nConstraints,
NJ->distance_matrix, weight);
}
}
/* The BIONJ-like formula for the weight of A when building a profile for AB is
1/2 + (avgD(B,CD) - avgD(A,CD))/(2*d(A,B))
*/
double QuartetWeight(profile_t *profiles[4], distance_matrix_t *dmat, int nPos) {
if (!bionj)
return(-1.0); /* even weighting */
double d[6];
CorrectedPairDistances(profiles, 4, dmat, nPos, /*OUT*/d);
if (d[qAB] < 0.01)
return -1.0;
double weight = 0.5 + ((d[qBC]+d[qBD])-(d[qAC]+d[qAD]))/(4*d[qAB]);
if (weight < 0)
weight = 0;
if (weight > 1)
weight = 1;
return (weight);
}
/* Resets the children entry of parent and also the parent entry of newchild */
void ReplaceChild(/*IN/OUT*/NJ_t *NJ, int parent, int oldchild, int newchild) {
NJ->parent[newchild] = parent;
int iChild;
for (iChild = 0; iChild < NJ->child[parent].nChild; iChild++) {
if (NJ->child[parent].child[iChild] == oldchild) {
NJ->child[parent].child[iChild] = newchild;
return;
}
}
assert(0);
}
/* Recomputes all branch lengths
For internal branches such as (A,B) vs. (C,D), uses the formula
length(AB|CD) = (d(A,C)+d(A,D)+d(B,C)+d(B,D))/4 - d(A,B)/2 - d(C,D)/2
(where all distances are profile distances - diameters).
For external branches (e.g. to leaves) A vs. (B,C), use the formula
length(A|BC) = (d(A,B)+d(A,C)-d(B,C))/2
*/
void UpdateBranchLengths(/*IN/OUT*/NJ_t *NJ) {
if (NJ->nSeq < 2)
return;
else if (NJ->nSeq == 2) {
int root = NJ->root;
int nodeA = NJ->child[root].child[0];
int nodeB = NJ->child[root].child[1];
besthit_t h;
ProfileDist(NJ->profiles[nodeA],NJ->profiles[nodeB],
NJ->nPos, NJ->distance_matrix, /*OUT*/&h);
if (logdist)
h.dist = LogCorrect(h.dist);
NJ->branchlength[nodeA] = h.dist/2.0;
NJ->branchlength[nodeB] = h.dist/2.0;
return;
}
profile_t **upProfiles = UpProfiles(NJ);
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
/* reset branch length of node (distance to its parent) */
if (node == NJ->root)
continue; /* no branch length to set */
if (node < NJ->nSeq) { /* a leaf */
profile_t *profileA = NJ->profiles[node];
profile_t *profileB = NULL;
profile_t *profileC = NULL;
int sib = Sibling(NJ,node);
if (sib == -1) { /* at root, have 2 siblings */
int sibs[2];
RootSiblings(NJ, node, /*OUT*/sibs);
profileB = NJ->profiles[sibs[0]];
profileC = NJ->profiles[sibs[1]];
} else {
profileB = NJ->profiles[sib];
profileC = GetUpProfile(/*IN/OUT*/upProfiles, NJ, NJ->parent[node], /*useML*/false);
}
profile_t *profiles[3] = {profileA,profileB,profileC};
double d[3]; /*AB,AC,BC*/
CorrectedPairDistances(profiles, 3, NJ->distance_matrix, NJ->nPos, /*OUT*/d);
/* d(A,BC) = (dAB+dAC-dBC)/2 */
NJ->branchlength[node] = (d[0]+d[1]-d[2])/2.0;
} else {
profile_t *profiles[4];
int nodeABCD[4];
SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false);
double d[6];
CorrectedPairDistances(profiles, 4, NJ->distance_matrix, NJ->nPos, /*OUT*/d);
NJ->branchlength[node] = (d[qAC]+d[qAD]+d[qBC]+d[qBD])/4.0 - (d[qAB]+d[qCD])/2.0;
/* no longer needed */
DeleteUpProfile(upProfiles, NJ, nodeABCD[0]);
DeleteUpProfile(upProfiles, NJ, nodeABCD[1]);
}
}
traversal = FreeTraversal(traversal,NJ);
upProfiles = FreeUpProfiles(upProfiles,NJ);
}
/* Pick columns for resampling, stored as returned_vector[iBoot*nPos + j] */
int *ResampleColumns(int nPos, int nBootstrap) {
long lPos = nPos; /* to prevent overflow on very long alignments when multiplying nPos * nBootstrap */
int *col = (int*)mymalloc(sizeof(int)*lPos*(size_t)nBootstrap);
int i;
for (i = 0; i < nBootstrap; i++) {
int j;
for (j = 0; j < nPos; j++) {
int pos = (int)(knuth_rand() * nPos);
if (pos<0)
pos = 0;
else if (pos == nPos)
pos = nPos-1;
col[i*lPos + j] = pos;
}
}
if (verbose > 5) {
for (i=0; i < 3 && i < nBootstrap; i++) {
fprintf(stderr,"Boot%d",i);
int j;
for (j = 0; j < nPos; j++) {
fprintf(stderr,"\t%d",col[i*lPos+j]);
}
fprintf(stderr,"\n");
}
}
return(col);
}
void ReliabilityNJ(/*IN/OUT*/NJ_t *NJ, int nBootstrap) {
/* For each non-root node N, with children A,B, parent P, sibling C, and grandparent G,
we test the reliability of the split (A,B) versus rest by comparing the profiles
of A, B, C, and the "up-profile" of P.
Each node's upProfile is the average of its sibling's (down)-profile + its parent's up-profile
(If node's parent is the root, then there are two siblings and we don't need an up-profile)
To save memory, we do depth-first-search down from the root, and we only keep
up-profiles for nodes in the active path.
*/
if (NJ->nSeq <= 3 || nBootstrap <= 0)
return; /* nothing to do */
int *col = ResampleColumns(NJ->nPos, nBootstrap);
profile_t **upProfiles = UpProfiles(NJ);
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
int iNodesDone = 0;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
if (node < NJ->nSeq || node == NJ->root)
continue; /* nothing to do for leaves or root */
if(iNodesDone > 0 && (iNodesDone % 100) == 0)
ProgressReport("Local bootstrap for %6d of %6d internal splits", iNodesDone, NJ->nSeq-3, 0, 0);
iNodesDone++;
profile_t *profiles[4];
int nodeABCD[4];
SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false);
NJ->support[node] = SplitSupport(profiles[0], profiles[1], profiles[2], profiles[3],
NJ->distance_matrix,
NJ->nPos,
nBootstrap,
col);
/* no longer needed */
DeleteUpProfile(upProfiles, NJ, nodeABCD[0]);
DeleteUpProfile(upProfiles, NJ, nodeABCD[1]);
DeleteUpProfile(upProfiles, NJ, nodeABCD[2]);
}
traversal = FreeTraversal(traversal,NJ);
upProfiles = FreeUpProfiles(upProfiles,NJ);
col = myfree(col, sizeof(int)*((size_t)NJ->nPos)*nBootstrap);
}
profile_t *NewProfile(int nPos, int nConstraints) {
profile_t *profile = (profile_t *)mymalloc(sizeof(profile_t));
profile->weights = mymalloc(sizeof(numeric_t)*nPos);
profile->codes = mymalloc(sizeof(unsigned char)*nPos);
profile->vectors = NULL;
profile->nVectors = 0;
profile->codeDist = NULL;
if (nConstraints == 0) {
profile->nOn = NULL;
profile->nOff = NULL;
} else {
profile->nOn = mymalloc(sizeof(int)*nConstraints);
profile->nOff = mymalloc(sizeof(int)*nConstraints);
}
return(profile);
}
profile_t *FreeProfile(profile_t *profile, int nPos, int nConstraints) {
if(profile==NULL) return(NULL);
myfree(profile->codes, nPos);
myfree(profile->weights, nPos);
myfree(profile->vectors, sizeof(numeric_t)*nCodes*profile->nVectors);
myfree(profile->codeDist, sizeof(numeric_t)*nCodes*nPos);
if (nConstraints > 0) {
myfree(profile->nOn, sizeof(int)*nConstraints);
myfree(profile->nOff, sizeof(int)*nConstraints);
}
return(myfree(profile, sizeof(profile_t)));
}
void SetupABCD(NJ_t *NJ, int node,
/* the 4 profiles; the last one is an outprofile */
/*OPTIONAL OUT*/profile_t *profiles[4],
/*OPTIONAL IN/OUT*/profile_t **upProfiles,
/*OUT*/int nodeABCD[4],
bool useML) {
int parent = NJ->parent[node];
assert(parent >= 0);
assert(NJ->child[node].nChild == 2);
nodeABCD[0] = NJ->child[node].child[0]; /*A*/
nodeABCD[1] = NJ->child[node].child[1]; /*B*/
profile_t *profile4 = NULL;
if (parent == NJ->root) {
int sibs[2];
RootSiblings(NJ, node, /*OUT*/sibs);
nodeABCD[2] = sibs[0];
nodeABCD[3] = sibs[1];
if (profiles == NULL)
return;
profile4 = NJ->profiles[sibs[1]];
} else {
nodeABCD[2] = Sibling(NJ,node);
assert(nodeABCD[2] >= 0);
nodeABCD[3] = parent;
if (profiles == NULL)
return;
profile4 = GetUpProfile(upProfiles,NJ,parent,useML);
}
assert(upProfiles != NULL);
int i;
for (i = 0; i < 3; i++)
profiles[i] = NJ->profiles[nodeABCD[i]];
profiles[3] = profile4;
}
int Sibling(NJ_t *NJ, int node) {
int parent = NJ->parent[node];
if (parent < 0 || parent == NJ->root)
return(-1);
int iChild;
for(iChild=0;iChild<NJ->child[parent].nChild;iChild++) {
if(NJ->child[parent].child[iChild] != node)
return (NJ->child[parent].child[iChild]);
}
assert(0);
return(-1);
}
void RootSiblings(NJ_t *NJ, int node, /*OUT*/int sibs[2]) {
assert(NJ->parent[node] == NJ->root);
assert(NJ->child[NJ->root].nChild == 3);
int nSibs = 0;
int iChild;
for(iChild=0; iChild < NJ->child[NJ->root].nChild; iChild++) {
int child = NJ->child[NJ->root].child[iChild];
if (child != node) sibs[nSibs++] = child;
}
assert(nSibs==2);
}
void TestSplitsML(/*IN/OUT*/NJ_t *NJ, /*OUT*/SplitCount_t *splitcount, int nBootstrap) {
const double tolerance = 1e-6;
splitcount->nBadSplits = 0;
splitcount->nConstraintViolations = 0;
splitcount->nBadBoth = 0;
splitcount->nSplits = 0;
splitcount->dWorstDeltaUnconstrained = 0;
splitcount->dWorstDeltaConstrained = 0;
profile_t **upProfiles = UpProfiles(NJ);
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
int *col = nBootstrap > 0 ? ResampleColumns(NJ->nPos, nBootstrap) : NULL;
double *site_likelihoods[3];
int choice;
for (choice = 0; choice < 3; choice++)
site_likelihoods[choice] = mymalloc(sizeof(double)*NJ->nPos);
int iNodesDone = 0;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
if (node < NJ->nSeq || node == NJ->root)
continue; /* nothing to do for leaves or root */
if(iNodesDone > 0 && (iNodesDone % 100) == 0)
ProgressReport("ML split tests for %6d of %6d internal splits", iNodesDone, NJ->nSeq-3, 0, 0);
iNodesDone++;
profile_t *profiles[4];
int nodeABCD[4];
SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/true);
double loglk[3];
double len[5];
int i;
for (i = 0; i < 4; i++)
len[i] = NJ->branchlength[nodeABCD[i]];
len[4] = NJ->branchlength[node];
double lenABvsCD[5] = {len[LEN_A], len[LEN_B], len[LEN_C], len[LEN_D], len[LEN_I]};
double lenACvsBD[5] = {len[LEN_A], len[LEN_C], len[LEN_B], len[LEN_D], len[LEN_I]}; /* Swap B & C */
double lenADvsBC[5] = {len[LEN_A], len[LEN_D], len[LEN_C], len[LEN_B], len[LEN_I]}; /* Swap B & D */
{
#ifdef OPENMP
#pragma omp parallel
#pragma omp sections
#endif
{
#ifdef OPENMP
#pragma omp section
#endif
{
/* Lengths are already optimized for ABvsCD */
loglk[ABvsCD] = MLQuartetLogLk(profiles[0], profiles[1], profiles[2], profiles[3],
NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenABvsCD,
/*OUT*/site_likelihoods[ABvsCD]);
}
#ifdef OPENMP
#pragma omp section
#endif
{
loglk[ACvsBD] = MLQuartetOptimize(profiles[0], profiles[2], profiles[1], profiles[3],
NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenACvsBD, /*pStarTest*/NULL,
/*OUT*/site_likelihoods[ACvsBD]);
}
#ifdef OPENMP
#pragma omp section
#endif
{
loglk[ADvsBC] = MLQuartetOptimize(profiles[0], profiles[3], profiles[2], profiles[1],
NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenADvsBC, /*pStarTest*/NULL,
/*OUT*/site_likelihoods[ADvsBC]);
}
}
}
/* do a second pass on the better alternative if it is close */
if (loglk[ACvsBD] > loglk[ADvsBC]) {
if (mlAccuracy > 1 || loglk[ACvsBD] > loglk[ABvsCD] - closeLogLkLimit) {
loglk[ACvsBD] = MLQuartetOptimize(profiles[0], profiles[2], profiles[1], profiles[3],
NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenACvsBD, /*pStarTest*/NULL,
/*OUT*/site_likelihoods[ACvsBD]);
}
} else {
if (mlAccuracy > 1 || loglk[ADvsBC] > loglk[ABvsCD] - closeLogLkLimit) {
loglk[ADvsBC] = MLQuartetOptimize(profiles[0], profiles[3], profiles[2], profiles[1],
NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenADvsBC, /*pStarTest*/NULL,
/*OUT*/site_likelihoods[ADvsBC]);
}
}
if (loglk[ABvsCD] >= loglk[ACvsBD] && loglk[ABvsCD] >= loglk[ADvsBC])
choice = ABvsCD;
else if (loglk[ACvsBD] >= loglk[ABvsCD] && loglk[ACvsBD] >= loglk[ADvsBC])
choice = ACvsBD;
else
choice = ADvsBC;
bool badSplit = loglk[choice] > loglk[ABvsCD] + treeLogLkDelta; /* ignore small changes in likelihood */
/* constraint penalties, indexed by nni_t (lower is better) */
double p[3];
QuartetConstraintPenalties(profiles, NJ->nConstraints, /*OUT*/p);
bool bBadConstr = p[ABvsCD] > p[ACvsBD] + tolerance || p[ABvsCD] > p[ADvsBC] + tolerance;
bool violateConstraint = false;
int iC;
for (iC=0; iC < NJ->nConstraints; iC++) {
if (SplitViolatesConstraint(profiles, iC)) {
violateConstraint = true;
break;
}
}
splitcount->nSplits++;
if (violateConstraint)
splitcount->nConstraintViolations++;
if (badSplit)
splitcount->nBadSplits++;
if (badSplit && bBadConstr)
splitcount->nBadBoth++;
if (badSplit) {
double delta = loglk[choice] - loglk[ABvsCD];
/* If ABvsCD is favored over the more likely NNI by constraints,
then this is probably a bad split because of the constraint */
if (p[choice] > p[ABvsCD] + tolerance)
splitcount->dWorstDeltaConstrained = MAX(delta, splitcount->dWorstDeltaConstrained);
else
splitcount->dWorstDeltaUnconstrained = MAX(delta, splitcount->dWorstDeltaUnconstrained);
}
if (nBootstrap>0)
NJ->support[node] = badSplit ? 0.0 : SHSupport(NJ->nPos, nBootstrap, col, loglk, site_likelihoods);
/* No longer needed */
DeleteUpProfile(upProfiles, NJ, nodeABCD[0]);
DeleteUpProfile(upProfiles, NJ, nodeABCD[1]);
DeleteUpProfile(upProfiles, NJ, nodeABCD[2]);
}
traversal = FreeTraversal(traversal,NJ);
upProfiles = FreeUpProfiles(upProfiles,NJ);
if (nBootstrap>0)
col = myfree(col, sizeof(int)*((size_t)NJ->nPos)*nBootstrap);
for (choice = 0; choice < 3; choice++)
site_likelihoods[choice] = myfree(site_likelihoods[choice], sizeof(double)*NJ->nPos);
}
void TestSplitsMinEvo(NJ_t *NJ, /*OUT*/SplitCount_t *splitcount) {
const double tolerance = 1e-6;
splitcount->nBadSplits = 0;
splitcount->nConstraintViolations = 0;
splitcount->nBadBoth = 0;
splitcount->nSplits = 0;
splitcount->dWorstDeltaUnconstrained = 0.0;
splitcount->dWorstDeltaConstrained = 0.0;
profile_t **upProfiles = UpProfiles(NJ);
traversal_t traversal = InitTraversal(NJ);
int node = NJ->root;
while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) {
if (node < NJ->nSeq || node == NJ->root)
continue; /* nothing to do for leaves or root */
profile_t *profiles[4];
int nodeABCD[4];
SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false);
if (verbose>2)
fprintf(stderr,"Testing Split around %d: A=%d B=%d C=%d D=up(%d) or node parent %d\n",
node, nodeABCD[0], nodeABCD[1], nodeABCD[2], nodeABCD[3], NJ->parent[node]);
double d[6]; /* distances, perhaps log-corrected distances, no constraint penalties */
CorrectedPairDistances(profiles, 4, NJ->distance_matrix, NJ->nPos, /*OUT*/d);
/* alignment-based scores for each split (lower is better) */
double sABvsCD = d[qAB] + d[qCD];
double sACvsBD = d[qAC] + d[qBD];
double sADvsBC = d[qAD] + d[qBC];
/* constraint penalties, indexed by nni_t (lower is better) */
double p[3];
QuartetConstraintPenalties(profiles, NJ->nConstraints, /*OUT*/p);
int nConstraintsViolated = 0;
int iC;
for (iC=0; iC < NJ->nConstraints; iC++) {
if (SplitViolatesConstraint(profiles, iC)) {
nConstraintsViolated++;
if (verbose > 2) {
double penalty[3] = {0.0,0.0,0.0};
(void)QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/penalty);
fprintf(stderr, "Violate constraint %d at %d (children %d %d) penalties %.3f %.3f %.3f %d/%d %d/%d %d/%d %d/%d\n",
iC, node, NJ->child[node].child[0], NJ->child[node].child[1],
penalty[ABvsCD], penalty[ACvsBD], penalty[ADvsBC],
profiles[0]->nOn[iC], profiles[0]->nOff[iC],
profiles[1]->nOn[iC], profiles[1]->nOff[iC],
profiles[2]->nOn[iC], profiles[2]->nOff[iC],
profiles[3]->nOn[iC], profiles[3]->nOff[iC]);
}
}
}
double delta = sABvsCD - MIN(sACvsBD,sADvsBC);
bool bBadDist = delta > tolerance;
bool bBadConstr = p[ABvsCD] > p[ACvsBD] + tolerance || p[ABvsCD] > p[ADvsBC] + tolerance;
splitcount->nSplits++;
if (bBadDist) {
nni_t choice = sACvsBD < sADvsBC ? ACvsBD : ADvsBC;
/* If ABvsCD is favored over the shorter NNI by constraints,
then this is probably a bad split because of the constraint */
if (p[choice] > p[ABvsCD] + tolerance)
splitcount->dWorstDeltaConstrained = MAX(delta, splitcount->dWorstDeltaConstrained);
else
splitcount->dWorstDeltaUnconstrained = MAX(delta, splitcount->dWorstDeltaUnconstrained);
}
if (nConstraintsViolated > 0)
splitcount->nConstraintViolations++; /* count splits with any violations, not #constraints in a splits */
if (bBadDist)
splitcount->nBadSplits++;
if (bBadDist && bBadConstr)
splitcount->nBadBoth++;
if (bBadConstr && verbose > 2) {
/* Which NNI would be better */
double dist_advantage = 0;
double constraint_penalty = 0;
if (p[ACvsBD] < p[ADvsBC]) {
dist_advantage = sACvsBD - sABvsCD;
constraint_penalty = p[ABvsCD] - p[ACvsBD];
} else {
dist_advantage = sADvsBC - sABvsCD;
constraint_penalty = p[ABvsCD] - p[ADvsBC];
}
fprintf(stderr, "Violate constraints %d distance_advantage %.3f constraint_penalty %.3f (children %d %d):",
node, dist_advantage, constraint_penalty,
NJ->child[node].child[0], NJ->child[node].child[1]);
/* list the constraints with a penalty, meaning that ABCD all have non-zero
values and that AB|CD worse than others */
for (iC = 0; iC < NJ->nConstraints; iC++) {
double ppart[6];
if (QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/ppart)) {
if (ppart[qAB] + ppart[qCD] > ppart[qAD] + ppart[qBC] + tolerance
|| ppart[qAB] + ppart[qCD] > ppart[qAC] + ppart[qBD] + tolerance)
fprintf(stderr, " %d (%d/%d %d/%d %d/%d %d/%d)", iC,
profiles[0]->nOn[iC], profiles[0]->nOff[iC],
profiles[1]->nOn[iC], profiles[1]->nOff[iC],
profiles[2]->nOn[iC], profiles[2]->nOff[iC],
profiles[3]->nOn[iC], profiles[3]->nOff[iC]);
}
}
fprintf(stderr, "\n");
}
/* no longer needed */
DeleteUpProfile(upProfiles, NJ, nodeABCD[0]);
DeleteUpProfile(upProfiles, NJ, nodeABCD[1]);
}
traversal = FreeTraversal(traversal,NJ);
upProfiles = FreeUpProfiles(upProfiles,NJ);
}
/* Computes support for (A,B),(C,D) compared to that for (A,C),(B,D) and (A,D),(B,C) */
double SplitSupport(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD,
/*OPTIONAL*/distance_matrix_t *dmat,
int nPos,
int nBootstrap,
int *col) {
int i,j;
long lPos = nPos; /* to avoid overflow when multiplying */
/* Note distpieces are weighted */
double *distpieces[6];
double *weights[6];
for (j = 0; j < 6; j++) {
distpieces[j] = (double*)mymalloc(sizeof(double)*nPos);
weights[j] = (double*)mymalloc(sizeof(double)*nPos);
}
int iFreqA = 0;
int iFreqB = 0;
int iFreqC = 0;
int iFreqD = 0;
for (i = 0; i < nPos; i++) {
numeric_t *fA = GET_FREQ(pA, i, /*IN/OUT*/iFreqA);
numeric_t *fB = GET_FREQ(pB, i, /*IN/OUT*/iFreqB);
numeric_t *fC = GET_FREQ(pC, i, /*IN/OUT*/iFreqC);
numeric_t *fD = GET_FREQ(pD, i, /*IN/OUT*/iFreqD);
weights[qAB][i] = pA->weights[i] * pB->weights[i];
weights[qAC][i] = pA->weights[i] * pC->weights[i];
weights[qAD][i] = pA->weights[i] * pD->weights[i];
weights[qBC][i] = pB->weights[i] * pC->weights[i];
weights[qBD][i] = pB->weights[i] * pD->weights[i];
weights[qCD][i] = pC->weights[i] * pD->weights[i];
distpieces[qAB][i] = weights[qAB][i] * ProfileDistPiece(pA->codes[i], pB->codes[i], fA, fB, dmat, NULL);
distpieces[qAC][i] = weights[qAC][i] * ProfileDistPiece(pA->codes[i], pC->codes[i], fA, fC, dmat, NULL);
distpieces[qAD][i] = weights[qAD][i] * ProfileDistPiece(pA->codes[i], pD->codes[i], fA, fD, dmat, NULL);
distpieces[qBC][i] = weights[qBC][i] * ProfileDistPiece(pB->codes[i], pC->codes[i], fB, fC, dmat, NULL);
distpieces[qBD][i] = weights[qBD][i] * ProfileDistPiece(pB->codes[i], pD->codes[i], fB, fD, dmat, NULL);
distpieces[qCD][i] = weights[qCD][i] * ProfileDistPiece(pC->codes[i], pD->codes[i], fC, fD, dmat, NULL);
}
assert(iFreqA == pA->nVectors);
assert(iFreqB == pB->nVectors);
assert(iFreqC == pC->nVectors);
assert(iFreqD == pD->nVectors);
double totpieces[6];
double totweights[6];
double dists[6];
for (j = 0; j < 6; j++) {
totpieces[j] = 0.0;
totweights[j] = 0.0;
for (i = 0; i < nPos; i++) {
totpieces[j] += distpieces[j][i];
totweights[j] += weights[j][i];
}
dists[j] = totweights[j] > 0.01 ? totpieces[j]/totweights[j] : 3.0;
if (logdist)
dists[j] = LogCorrect(dists[j]);
}
/* Support1 = Support(AB|CD over AC|BD) = d(A,C)+d(B,D)-d(A,B)-d(C,D)
Support2 = Support(AB|CD over AD|BC) = d(A,D)+d(B,C)-d(A,B)-d(C,D)
*/
double support1 = dists[qAC] + dists[qBD] - dists[qAB] - dists[qCD];
double support2 = dists[qAD] + dists[qBC] - dists[qAB] - dists[qCD];
if (support1 < 0 || support2 < 0) {
nSuboptimalSplits++; /* Another split seems superior */
}
assert(nBootstrap > 0);
int nSupport = 0;
int iBoot;
for (iBoot=0;iBoot<nBootstrap;iBoot++) {
int *colw = &col[lPos*iBoot];
for (j = 0; j < 6; j++) {
double totp = 0;
double totw = 0;
double *d = distpieces[j];
double *w = weights[j];
for (i=0; i<nPos; i++) {
int c = colw[i];
totp += d[c];
totw += w[c];
}
dists[j] = totw > 0.01 ? totp/totw : 3.0;
if (logdist)
dists[j] = LogCorrect(dists[j]);
}
support1 = dists[qAC] + dists[qBD] - dists[qAB] - dists[qCD];
support2 = dists[qAD] + dists[qBC] - dists[qAB] - dists[qCD];
if (support1 > 0 && support2 > 0)
nSupport++;
} /* end loop over bootstrap replicates */
for (j = 0; j < 6; j++) {
distpieces[j] = myfree(distpieces[j], sizeof(double)*nPos);
weights[j] = myfree(weights[j], sizeof(double)*nPos);
}
return( nSupport/(double)nBootstrap );
}
double SHSupport(int nPos, int nBootstrap, int *col, double loglk[3], double *site_likelihoods[3]) {
long lPos = nPos; /* to avoid overflow when multiplying */
assert(nBootstrap>0);
double delta1 = loglk[0]-loglk[1];
double delta2 = loglk[0]-loglk[2];
double delta = delta1 < delta2 ? delta1 : delta2;
double *siteloglk[3];
int i,j;
for (i = 0; i < 3; i++) {
siteloglk[i] = mymalloc(sizeof(double)*nPos);
for (j = 0; j < nPos; j++)
siteloglk[i][j] = log(site_likelihoods[i][j]);
}
int nSupport = 0;
int iBoot;
for (iBoot = 0; iBoot < nBootstrap; iBoot++) {
double resampled[3];
for (i = 0; i < 3; i++)
resampled[i] = -loglk[i];
for (j = 0; j < nPos; j++) {
int pos = col[iBoot*lPos+j];
for (i = 0; i < 3; i++)
resampled[i] += siteloglk[i][pos];
}
int iBest = 0;
for (i = 1; i < 3; i++)
if (resampled[i] > resampled[iBest])
iBest = i;
double resample1 = resampled[iBest] - resampled[(iBest+1)%3];
double resample2 = resampled[iBest] - resampled[(iBest+2)%3];
double resampleDelta = resample1 < resample2 ? resample1 : resample2;
if (resampleDelta < delta)
nSupport++;
}
for (i=0;i<3;i++)
siteloglk[i] = myfree(siteloglk[i], sizeof(double)*nPos);
return(nSupport/(double)nBootstrap);
}
void SetDistCriterion(/*IN/OUT*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *hit) {
if (hit->i < NJ->nSeq && hit->j < NJ->nSeq) {
SeqDist(NJ->profiles[hit->i]->codes,
NJ->profiles[hit->j]->codes,
NJ->nPos, NJ->distance_matrix, /*OUT*/hit);
} else {
ProfileDist(NJ->profiles[hit->i],
NJ->profiles[hit->j],
NJ->nPos, NJ->distance_matrix, /*OUT*/hit);
hit->dist -= (NJ->diameter[hit->i] + NJ->diameter[hit->j]);
}
hit->dist += constraintWeight
* (double)JoinConstraintPenalty(NJ, hit->i, hit->j);
SetCriterion(NJ,nActive,/*IN/OUT*/hit);
}
void SetCriterion(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join) {
if(join->i < 0
|| join->j < 0
|| NJ->parent[join->i] >= 0
|| NJ->parent[join->j] >= 0)
return;
assert(NJ->nOutDistActive[join->i] >= nActive);
assert(NJ->nOutDistActive[join->j] >= nActive);
int nDiffAllow = tophitsMult > 0 ? (int)(nActive*staleOutLimit) : 0;
if (NJ->nOutDistActive[join->i] - nActive > nDiffAllow)
SetOutDistance(NJ, join->i, nActive);
if (NJ->nOutDistActive[join->j] - nActive > nDiffAllow)
SetOutDistance(NJ, join->j, nActive);
double outI = NJ->outDistances[join->i];
if (NJ->nOutDistActive[join->i] != nActive)
outI *= (nActive-1)/(double)(NJ->nOutDistActive[join->i]-1);
double outJ = NJ->outDistances[join->j];
if (NJ->nOutDistActive[join->j] != nActive)
outJ *= (nActive-1)/(double)(NJ->nOutDistActive[join->j]-1);
join->criterion = join->dist - (outI+outJ)/(double)(nActive-2);
if (verbose > 2 && nActive <= 5) {
fprintf(stderr, "Set Criterion to join %d %d with nActive=%d dist+penalty %.3f criterion %.3f\n",
join->i, join->j, nActive, join->dist, join->criterion);
}
}
void SetOutDistance(NJ_t *NJ, int iNode, int nActive) {
if (NJ->nOutDistActive[iNode] == nActive)
return;
/* May be called by InitNJ before we have parents */
assert(iNode>=0 && (NJ->parent == NULL || NJ->parent[iNode]<0));
besthit_t dist;
ProfileDist(NJ->profiles[iNode], NJ->outprofile, NJ->nPos, NJ->distance_matrix, &dist);
outprofileOps++;
/* out(A) = sum(X!=A) d(A,X)
= sum(X!=A) (profiledist(A,X) - diam(A) - diam(X))
= sum(X!=A) profiledist(A,X) - (N-1)*diam(A) - (totdiam - diam(A))
in the absence of gaps:
profiledist(A,out) = mean profiledist(A, all active nodes)
sum(X!=A) profiledist(A,X) = N * profiledist(A,out) - profiledist(A,A)
With gaps, we need to take the weights of the comparisons into account, where
w(Ai) is the weight of position i in profile A:
w(A,B) = sum_i w(Ai) * w(Bi)
d(A,B) = sum_i w(Ai) * w(Bi) * d(Ai,Bi) / w(A,B)
sum(X!=A) profiledist(A,X) ~= (N-1) * profiledist(A, Out w/o A)
profiledist(A, Out w/o A) = sum_X!=A sum_i d(Ai,Xi) * w(Ai) * w(Bi) / ( sum_X!=A sum_i w(Ai) * w(Bi) )
d(A, Out) = sum_A sum_i d(Ai,Xi) * w(Ai) * w(Bi) / ( sum_X sum_i w(Ai) * w(Bi) )
and so we get
profiledist(A,out w/o A) = (top of d(A,Out) - top of d(A,A)) / (weight of d(A,Out) - weight of d(A,A))
top = dist * weight
with another correction of nActive because the weight of the out-profile is the average
weight not the total weight.
*/
double top = (nActive-1)
* (dist.dist * dist.weight * nActive - NJ->selfweight[iNode] * NJ->selfdist[iNode]);
double bottom = (dist.weight * nActive - NJ->selfweight[iNode]);
double pdistOutWithoutA = top/bottom;
NJ->outDistances[iNode] = bottom > 0.01 ?
pdistOutWithoutA - NJ->diameter[iNode] * (nActive-1) - (NJ->totdiam - NJ->diameter[iNode])
: 3.0;
NJ->nOutDistActive[iNode] = nActive;
if(verbose>3 && iNode < 5)
fprintf(stderr,"NewOutDist for %d %f from dist %f selfd %f diam %f totdiam %f newActive %d\n",
iNode, NJ->outDistances[iNode], dist.dist, NJ->selfdist[iNode], NJ->diameter[iNode],
NJ->totdiam, nActive);
if (verbose>6 && (iNode % 10) == 0) {
/* Compute the actual out-distance and compare */
double total = 0.0;
double total_pd = 0.0;
int j;
for (j=0;j<NJ->maxnode;j++) {
if (j!=iNode && (NJ->parent==NULL || NJ->parent[j]<0)) {
besthit_t bh;
ProfileDist(NJ->profiles[iNode], NJ->profiles[j], NJ->nPos, NJ->distance_matrix, /*OUT*/&bh);
total_pd += bh.dist;
total += bh.dist - (NJ->diameter[iNode] + NJ->diameter[j]);
}
}
fprintf(stderr,"OutDist for Node %d %f truth %f profiled %f truth %f pd_err %f\n",
iNode, NJ->outDistances[iNode], total, pdistOutWithoutA, total_pd,fabs(pdistOutWithoutA-total_pd));
}
}
top_hits_t *FreeTopHits(top_hits_t *tophits) {
if (tophits == NULL)
return(NULL);
int iNode;
for (iNode = 0; iNode < tophits->maxnodes; iNode++) {
top_hits_list_t *l = &tophits->top_hits_lists[iNode];
if (l->hits != NULL)
l->hits = myfree(l->hits, sizeof(hit_t) * l->nHits);
}
tophits->top_hits_lists = myfree(tophits->top_hits_lists, sizeof(top_hits_list_t) * tophits->maxnodes);
tophits->visible = myfree(tophits->visible, sizeof(hit_t*) * tophits->maxnodes);
tophits->topvisible = myfree(tophits->topvisible, sizeof(int) * tophits->nTopVisible);
#ifdef OPENMP
for (iNode = 0; iNode < tophits->maxnodes; iNode++)
omp_destroy_lock(&tophits->locks[iNode]);
tophits->locks = myfree(tophits->locks, sizeof(omp_lock_t) * tophits->maxnodes);
#endif
return(myfree(tophits, sizeof(top_hits_t)));
}
top_hits_t *InitTopHits(NJ_t *NJ, int m) {
int iNode;
assert(m > 0);
top_hits_t *tophits = mymalloc(sizeof(top_hits_t));
tophits->m = m;
tophits->q = (int)(0.5 + tophits2Mult * sqrt(tophits->m));
if (!useTopHits2nd || tophits->q >= tophits->m)
tophits->q = 0;
tophits->maxnodes = NJ->maxnodes;
tophits->top_hits_lists = mymalloc(sizeof(top_hits_list_t) * tophits->maxnodes);
tophits->visible = mymalloc(sizeof(hit_t) * tophits->maxnodes);
tophits->nTopVisible = (int)(0.5 + topvisibleMult*m);
tophits->topvisible = mymalloc(sizeof(int) * tophits->nTopVisible);
#ifdef OPENMP
tophits->locks = mymalloc(sizeof(omp_lock_t) * tophits->maxnodes);
for (iNode = 0; iNode < tophits->maxnodes; iNode++)
omp_init_lock(&tophits->locks[iNode]);
#endif
int i;
for (i = 0; i < tophits->nTopVisible; i++)
tophits->topvisible[i] = -1; /* empty */
tophits->topvisibleAge = 0;
for (iNode = 0; iNode < tophits->maxnodes; iNode++) {
top_hits_list_t *l = &tophits->top_hits_lists[iNode];
l->nHits = 0;
l->hits = NULL;
l->hitSource = -1;
l->age = 0;
hit_t *v = &tophits->visible[iNode];
v->j = -1;
v->dist = 1e20;
}
return(tophits);
}
/* Helper function for sorting in SetAllLeafTopHits,
and the global variables it needs
*/
NJ_t *CompareSeedNJ = NULL;
int *CompareSeedGaps = NULL;
int CompareSeeds(const void *c1, const void *c2) {
int seed1 = *(int *)c1;
int seed2 = *(int *)c2;
int gapdiff = CompareSeedGaps[seed1] - CompareSeedGaps[seed2];
if (gapdiff != 0) return(gapdiff); /* fewer gaps is better */
double outdiff = CompareSeedNJ->outDistances[seed1] - CompareSeedNJ->outDistances[seed2];
if(outdiff < 0) return(-1); /* closer to more nodes is better */
if(outdiff > 0) return(1);
return(0);
}
/* Using the seed heuristic and the close global variable */
void SetAllLeafTopHits(/*IN/UPDATE*/NJ_t *NJ, /*IN/OUT*/top_hits_t *tophits) {
double close = tophitsClose;
if (close < 0) {
if (fastest && NJ->nSeq >= 50000) {
close = 0.99;
} else {
double logN = log((double)NJ->nSeq)/log(2.0);
close = logN/(logN+2.0);
}
}
/* Sort the potential seeds, by a combination of nGaps and NJ->outDistances
We don't store nGaps so we need to compute that
*/
int *nGaps = (int*)mymalloc(sizeof(int)*NJ->nSeq);
int iNode;
for(iNode=0; iNode<NJ->nSeq; iNode++) {
nGaps[iNode] = (int)(0.5 + NJ->nPos - NJ->selfweight[iNode]);
}
int *seeds = (int*)mymalloc(sizeof(int)*NJ->nSeq);
for (iNode=0; iNode<NJ->nSeq; iNode++) seeds[iNode] = iNode;
CompareSeedNJ = NJ;
CompareSeedGaps = nGaps;
qsort(/*IN/OUT*/seeds, NJ->nSeq, sizeof(int), CompareSeeds);
CompareSeedNJ = NULL;
CompareSeedGaps = NULL;
/* For each seed, save its top 2*m hits and then look for close neighbors */
assert(2 * tophits->m <= NJ->nSeq);
int iSeed;
int nHasTopHits = 0;
#ifdef OPENMP
#pragma omp parallel for schedule(dynamic, 50)
#endif
for(iSeed=0; iSeed < NJ->nSeq; iSeed++) {
int seed = seeds[iSeed];
if (iSeed > 0 && (iSeed % 100) == 0) {
#ifdef OPENMP
#pragma omp critical
#endif
ProgressReport("Top hits for %6d of %6d seqs (at seed %6d)",
nHasTopHits, NJ->nSeq,
iSeed, 0);
}
if (tophits->top_hits_lists[seed].nHits > 0) {
if(verbose>2) fprintf(stderr, "Skipping seed %d\n", seed);
continue;
}
besthit_t *besthitsSeed = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->nSeq);
besthit_t *besthitsNeighbor = (besthit_t*)mymalloc(sizeof(besthit_t) * 2 * tophits->m);
besthit_t bestjoin;
if(verbose>2) fprintf(stderr,"Trying seed %d\n", seed);
SetBestHit(seed, NJ, /*nActive*/NJ->nSeq, /*OUT*/&bestjoin, /*OUT*/besthitsSeed);
/* sort & save top hits of self. besthitsSeed is now sorted. */
SortSaveBestHits(seed, /*IN/SORT*/besthitsSeed, /*IN-SIZE*/NJ->nSeq,
/*OUT-SIZE*/tophits->m, /*IN/OUT*/tophits);
nHasTopHits++;
/* find "close" neighbors and compute their top hits */
double neardist = besthitsSeed[2 * tophits->m - 1].dist * close;
/* must have at least average weight, rem higher is better
and allow a bit more than average, e.g. if we are looking for within 30% away,
20% more gaps than usual seems OK
Alternatively, have a coverage requirement in case neighbor is short
If fastest, consider the top q/2 hits to be close neighbors, regardless
*/
double nearweight = 0;
int iClose;
for (iClose = 0; iClose < 2 * tophits->m; iClose++)
nearweight += besthitsSeed[iClose].weight;
nearweight = nearweight/(2.0 * tophits->m); /* average */
nearweight *= (1.0-2.0*neardist/3.0);
double nearcover = 1.0 - neardist/2.0;
if(verbose>2) fprintf(stderr,"Distance limit for close neighbors %f weight %f ungapped %d\n",
neardist, nearweight, NJ->nPos-nGaps[seed]);
for (iClose = 0; iClose < tophits->m; iClose++) {
besthit_t *closehit = &besthitsSeed[iClose];
int closeNode = closehit->j;
if (tophits->top_hits_lists[closeNode].nHits > 0)
continue;
/* If within close-distance, or identical, use as close neighbor */
bool close = closehit->dist <= neardist
&& (closehit->weight >= nearweight
|| closehit->weight >= (NJ->nPos-nGaps[closeNode])*nearcover);
bool identical = closehit->dist < 1e-6
&& fabs(closehit->weight - (NJ->nPos - nGaps[seed])) < 1e-5
&& fabs(closehit->weight - (NJ->nPos - nGaps[closeNode])) < 1e-5;
if (useTopHits2nd && iClose < tophits->q && (close || identical)) {
nHasTopHits++;
nClose2Used++;
int nUse = MIN(tophits->q * tophits2Safety, 2 * tophits->m);
besthit_t *besthitsClose = mymalloc(sizeof(besthit_t) * nUse);
TransferBestHits(NJ, /*nActive*/NJ->nSeq,
closeNode,
/*IN*/besthitsSeed, /*SIZE*/nUse,
/*OUT*/besthitsClose,
/*updateDistance*/true);
SortSaveBestHits(closeNode, /*IN/SORT*/besthitsClose,
/*IN-SIZE*/nUse, /*OUT-SIZE*/tophits->q,
/*IN/OUT*/tophits);
tophits->top_hits_lists[closeNode].hitSource = seed;
besthitsClose = myfree(besthitsClose, sizeof(besthit_t) * nUse);
} else if (close || identical || (fastest && iClose < (tophits->q+1)/2)) {
nHasTopHits++;
nCloseUsed++;
if(verbose>2) fprintf(stderr, "Near neighbor %d (rank %d weight %f ungapped %d %d)\n",
closeNode, iClose, besthitsSeed[iClose].weight,
NJ->nPos-nGaps[seed],
NJ->nPos-nGaps[closeNode]);
/* compute top 2*m hits */
TransferBestHits(NJ, /*nActive*/NJ->nSeq,
closeNode,
/*IN*/besthitsSeed, /*SIZE*/2 * tophits->m,
/*OUT*/besthitsNeighbor,
/*updateDistance*/true);
SortSaveBestHits(closeNode, /*IN/SORT*/besthitsNeighbor,
/*IN-SIZE*/2 * tophits->m, /*OUT-SIZE*/tophits->m,
/*IN/OUT*/tophits);
/* And then try for a second level of transfer. We assume we
are in a good area, because of the 1st
level of transfer, and in a small neighborhood, because q is
small (32 for 1 million sequences), so we do not make any close checks.
*/
int iClose2;
for (iClose2 = 0; iClose2 < tophits->q && iClose2 < 2 * tophits->m; iClose2++) {
int closeNode2 = besthitsNeighbor[iClose2].j;
assert(closeNode2 >= 0);
if (tophits->top_hits_lists[closeNode2].hits == NULL) {
nClose2Used++;
nHasTopHits++;
int nUse = MIN(tophits->q * tophits2Safety, 2 * tophits->m);
besthit_t *besthitsClose2 = mymalloc(sizeof(besthit_t) * nUse);
TransferBestHits(NJ, /*nActive*/NJ->nSeq,
closeNode2,
/*IN*/besthitsNeighbor, /*SIZE*/nUse,
/*OUT*/besthitsClose2,
/*updateDistance*/true);
SortSaveBestHits(closeNode2, /*IN/SORT*/besthitsClose2,
/*IN-SIZE*/nUse, /*OUT-SIZE*/tophits->q,
/*IN/OUT*/tophits);
tophits->top_hits_lists[closeNode2].hitSource = closeNode;
besthitsClose2 = myfree(besthitsClose2, sizeof(besthit_t) * nUse);
} /* end if should do 2nd-level transfer */
}
}
} /* end loop over close candidates */
besthitsSeed = myfree(besthitsSeed, sizeof(besthit_t)*NJ->nSeq);
besthitsNeighbor = myfree(besthitsNeighbor, sizeof(besthit_t) * 2 * tophits->m);
} /* end loop over seeds */
for (iNode=0; iNode<NJ->nSeq; iNode++) {
top_hits_list_t *l = &tophits->top_hits_lists[iNode];
assert(l->hits != NULL);
assert(l->hits[0].j >= 0);
assert(l->hits[0].j < NJ->nSeq);
assert(l->hits[0].j != iNode);
tophits->visible[iNode] = l->hits[0];
}
if (verbose >= 2) fprintf(stderr, "#Close neighbors among leaves: 1st-level %ld 2nd-level %ld seeds %ld\n",
nCloseUsed, nClose2Used, NJ->nSeq-nCloseUsed-nClose2Used);
nGaps = myfree(nGaps, sizeof(int)*NJ->nSeq);
seeds = myfree(seeds, sizeof(int)*NJ->nSeq);
/* Now add a "checking phase" where we ensure that the q or 2*sqrt(m) hits
of i are represented in j (if they should be)
*/
long lReplace = 0;
int nCheck = tophits->q > 0 ? tophits->q : (int)(0.5 + 2.0*sqrt(tophits->m));
for (iNode = 0; iNode < NJ->nSeq; iNode++) {
if ((iNode % 100) == 0)
ProgressReport("Checking top hits for %6d of %6d seqs",
iNode+1, NJ->nSeq, 0, 0);
top_hits_list_t *lNode = &tophits->top_hits_lists[iNode];
int iHit;
for (iHit = 0; iHit < nCheck && iHit < lNode->nHits; iHit++) {
besthit_t bh = HitToBestHit(iNode, lNode->hits[iHit]);
SetCriterion(NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/&bh);
top_hits_list_t *lTarget = &tophits->top_hits_lists[bh.j];
/* If this criterion is worse than the nCheck-1 entry of the target,
then skip the check.
This logic is based on assuming that the list is sorted,
which is true initially but may not be true later.
Still, is a good heuristic.
*/
assert(nCheck > 0);
assert(nCheck <= lTarget->nHits);
besthit_t bhCheck = HitToBestHit(bh.j, lTarget->hits[nCheck-1]);
SetCriterion(NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/&bhCheck);
if (bhCheck.criterion < bh.criterion)
continue; /* no check needed */
/* Check if this is present in the top-hit list */
int iHit2;
bool bFound = false;
for (iHit2 = 0; iHit2 < lTarget->nHits && !bFound; iHit2++)
if (lTarget->hits[iHit2].j == iNode)
bFound = true;
if (!bFound) {
/* Find the hit with the worst criterion and replace it with this one */
int iWorst = -1;
double dWorstCriterion = -1e20;
for (iHit2 = 0; iHit2 < lTarget->nHits; iHit2++) {
besthit_t bh2 = HitToBestHit(bh.j, lTarget->hits[iHit2]);
SetCriterion(NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/&bh2);
if (bh2.criterion > dWorstCriterion) {
iWorst = iHit2;
dWorstCriterion = bh2.criterion;
}
}
if (dWorstCriterion > bh.criterion) {
assert(iWorst >= 0);
lTarget->hits[iWorst].j = iNode;
lTarget->hits[iWorst].dist = bh.dist;
lReplace++;
/* and perhaps update visible */
besthit_t v;
bool bSuccess = GetVisible(NJ, /*nActive*/NJ->nSeq, tophits, bh.j, /*OUT*/&v);
assert(bSuccess);
if (bh.criterion < v.criterion)
tophits->visible[bh.j] = lTarget->hits[iWorst];
}
}
}
}
if (verbose >= 2)
fprintf(stderr, "Replaced %ld top hit entries\n", lReplace);
}
/* Updates out-distances but does not reset or update visible set */
void GetBestFromTopHits(int iNode,
/*IN/UPDATE*/NJ_t *NJ,
int nActive,
/*IN*/top_hits_t *tophits,
/*OUT*/besthit_t *bestjoin) {
assert(iNode >= 0);
assert(NJ->parent[iNode] < 0);
top_hits_list_t *l = &tophits->top_hits_lists[iNode];
assert(l->nHits > 0);
assert(l->hits != NULL);
if(!fastest)
SetOutDistance(NJ, iNode, nActive); /* ensure out-distances are not stale */
bestjoin->i = -1;
bestjoin->j = -1;
bestjoin->dist = 1e20;
bestjoin->criterion = 1e20;
int iBest;
for(iBest=0; iBest < l->nHits; iBest++) {
besthit_t bh = HitToBestHit(iNode, l->hits[iBest]);
if (UpdateBestHit(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/&bh, /*update dist*/true)) {
SetCriterion(/*IN/OUT*/NJ, nActive, /*IN/OUT*/&bh); /* make sure criterion is correct */
if (bh.criterion < bestjoin->criterion)
*bestjoin = bh;
}
}
assert(bestjoin->j >= 0); /* a hit was found */
assert(bestjoin->i == iNode);
}
int ActiveAncestor(/*IN*/NJ_t *NJ, int iNode) {
if (iNode < 0)
return(iNode);
while(NJ->parent[iNode] >= 0)
iNode = NJ->parent[iNode];
return(iNode);
}
bool UpdateBestHit(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *hit,
bool bUpdateDist) {
int i = ActiveAncestor(/*IN*/NJ, hit->i);
int j = ActiveAncestor(/*IN*/NJ, hit->j);
if (i < 0 || j < 0 || i == j) {
hit->i = -1;
hit->j = -1;
hit->weight = 0;
hit->dist = 1e20;
hit->criterion = 1e20;
return(false);
}
if (i != hit->i || j != hit->j) {
hit->i = i;
hit->j = j;
if (bUpdateDist) {
SetDistCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit);
} else {
hit->dist = -1e20;
hit->criterion = 1e20;
}
}
return(true);
}
bool GetVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN/OUT*/top_hits_t *tophits,
int iNode, /*OUT*/besthit_t *visible) {
if (iNode < 0 || NJ->parent[iNode] >= 0)
return(false);
hit_t *v = &tophits->visible[iNode];
if (v->j < 0 || NJ->parent[v->j] >= 0)
return(false);
*visible = HitToBestHit(iNode, *v);
SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/visible);
return(true);
}
besthit_t *UniqueBestHits(/*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN/SORT*/besthit_t *combined, int nCombined,
/*OUT*/int *nUniqueOut) {
int iHit;
for (iHit = 0; iHit < nCombined; iHit++) {
besthit_t *hit = &combined[iHit];
UpdateBestHit(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit, /*update*/false);
}
qsort(/*IN/OUT*/combined, nCombined, sizeof(besthit_t), CompareHitsByIJ);
besthit_t *uniqueList = (besthit_t*)mymalloc(sizeof(besthit_t)*nCombined);
int nUnique = 0;
int iSavedLast = -1;
/* First build the new list */
for (iHit = 0; iHit < nCombined; iHit++) {
besthit_t *hit = &combined[iHit];
if (hit->i < 0 || hit->j < 0)
continue;
if (iSavedLast >= 0) {
/* toss out duplicates */
besthit_t *saved = &combined[iSavedLast];
if (saved->i == hit->i && saved->j == hit->j)
continue;
}
assert(nUnique < nCombined);
assert(hit->j >= 0 && NJ->parent[hit->j] < 0);
uniqueList[nUnique++] = *hit;
iSavedLast = iHit;
}
*nUniqueOut = nUnique;
/* Then do any updates to the criterion or the distances in parallel */
#ifdef OPENMP
#pragma omp parallel for schedule(dynamic, 50)
#endif
for (iHit = 0; iHit < nUnique; iHit++) {
besthit_t *hit = &uniqueList[iHit];
if (hit->dist < 0.0)
SetDistCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit);
else
SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit);
}
return(uniqueList);
}
/*
Create a top hit list for the new node, either
from children (if there are enough best hits left) or by a "refresh"
Also set visible set for newnode
Also update visible set for other nodes if we stumble across a "better" hit
*/
void TopHitJoin(int newnode,
/*IN/UPDATE*/NJ_t *NJ,
int nActive,
/*IN/OUT*/top_hits_t *tophits) {
long startProfileOps = profileOps;
long startOutProfileOps = outprofileOps;
assert(NJ->child[newnode].nChild == 2);
top_hits_list_t *lNew = &tophits->top_hits_lists[newnode];
assert(lNew->hits == NULL);
/* Copy the hits */
int i;
top_hits_list_t *lChild[2];
for (i = 0; i< 2; i++) {
lChild[i] = &tophits->top_hits_lists[NJ->child[newnode].child[i]];
assert(lChild[i]->hits != NULL && lChild[i]->nHits > 0);
}
int nCombined = lChild[0]->nHits + lChild[1]->nHits;
besthit_t *combinedList = (besthit_t*)mymalloc(sizeof(besthit_t)*nCombined);
HitsToBestHits(lChild[0]->hits, lChild[0]->nHits, NJ->child[newnode].child[0],
/*OUT*/combinedList);
HitsToBestHits(lChild[1]->hits, lChild[1]->nHits, NJ->child[newnode].child[1],
/*OUT*/combinedList + lChild[0]->nHits);
int nUnique;
/* UniqueBestHits() replaces children (used in the calls to HitsToBestHits)
with active ancestors, so all distances & criteria will be recomputed */
besthit_t *uniqueList = UniqueBestHits(/*IN/UPDATE*/NJ, nActive,
/*IN/SORT*/combinedList,
nCombined,
/*OUT*/&nUnique);
int nUniqueAlloc = nCombined;
combinedList = myfree(combinedList, sizeof(besthit_t)*nCombined);
/* Forget the top-hit lists of the joined nodes */
for (i = 0; i < 2; i++) {
lChild[i]->hits = myfree(lChild[i]->hits, sizeof(hit_t) * lChild[i]->nHits);
lChild[i]->nHits = 0;
}
/* Use the average age, rounded up, by 1 Versions 2.0 and earlier
used the maximum age, which leads to more refreshes without
improving the accuracy of the NJ phase. Intuitively, if one of
them was just refreshed then another refresh is unlikely to help.
*/
lNew->age = (lChild[0]->age+lChild[1]->age+1)/2 + 1;
/* If top hit ages always match (perfectly balanced), then a
limit of log2(m) would mean a refresh after
m joins, which is about what we want.
*/
int tophitAgeLimit = MAX(1, (int)(0.5 + log((double)tophits->m)/log(2.0)));
/* Either use the merged list as candidate top hits, or
move from 2nd level to 1st level, or do a refresh
UniqueBestHits eliminates hits to self, so if nUnique==nActive-1,
we've already done the exhaustive search.
Either way, we set tophits, visible(newnode), update visible of its top hits,
and modify topvisible: if we do a refresh, then we reset it, otherwise we update
*/
bool bSecondLevel = lChild[0]->hitSource >= 0 && lChild[1]->hitSource >= 0;
bool bUseUnique = nUnique==nActive-1
|| (lNew->age <= tophitAgeLimit
&& nUnique >= (bSecondLevel ? (int)(0.5 + tophits2Refresh * tophits->q)
: (int)(0.5 + tophits->m * tophitsRefresh) ));
if (bUseUnique && verbose > 2)
fprintf(stderr,"Top hits for %d from combined %d nActive=%d tophitsage %d %s\n",
newnode,nUnique,nActive,lNew->age,
bSecondLevel ? "2ndlevel" : "1stlevel");
if (!bUseUnique
&& bSecondLevel
&& lNew->age <= tophitAgeLimit) {
int source = ActiveAncestor(NJ, lChild[0]->hitSource);
if (source == newnode)
source = ActiveAncestor(NJ, lChild[1]->hitSource);
/* In parallel mode, it is possible that we would select a node as the
hit-source and then over-write that top hit with a short list.
So we need this sanity check.
*/
if (source != newnode
&& source >= 0
&& tophits->top_hits_lists[source].hitSource < 0) {
/* switch from 2nd-level to 1st-level top hits -- compute top hits list
of node from what we have so far plus the active source plus its top hits */
top_hits_list_t *lSource = &tophits->top_hits_lists[source];
assert(lSource->hitSource < 0);
assert(lSource->nHits > 0);
int nMerge = 1 + lSource->nHits + nUnique;
besthit_t *mergeList = mymalloc(sizeof(besthit_t) * nMerge);
memcpy(/*to*/mergeList, /*from*/uniqueList, nUnique * sizeof(besthit_t));
int iMerge = nUnique;
mergeList[iMerge].i = newnode;
mergeList[iMerge].j = source;
SetDistCriterion(NJ, nActive, /*IN/OUT*/&mergeList[iMerge]);
iMerge++;
HitsToBestHits(lSource->hits, lSource->nHits, newnode, /*OUT*/mergeList+iMerge);
for (i = 0; i < lSource->nHits; i++) {
SetDistCriterion(NJ, nActive, /*IN/OUT*/&mergeList[iMerge]);
iMerge++;
}
assert(iMerge == nMerge);
uniqueList = myfree(uniqueList, nUniqueAlloc * sizeof(besthit_t));
uniqueList = UniqueBestHits(/*IN/UPDATE*/NJ, nActive,
/*IN/SORT*/mergeList,
nMerge,
/*OUT*/&nUnique);
nUniqueAlloc = nMerge;
mergeList = myfree(mergeList, sizeof(besthit_t)*nMerge);
assert(nUnique > 0);
bUseUnique = nUnique >= (int)(0.5 + tophits->m * tophitsRefresh);
bSecondLevel = false;
if (bUseUnique && verbose > 2)
fprintf(stderr, "Top hits for %d from children and source %d's %d hits, nUnique %d\n",
newnode, source, lSource->nHits, nUnique);
}
}
if (bUseUnique) {
if (bSecondLevel) {
/* pick arbitrarily */
lNew->hitSource = lChild[0]->hitSource;
}
int nSave = MIN(nUnique, bSecondLevel ? tophits->q : tophits->m);
assert(nSave>0);
if (verbose > 2)
fprintf(stderr, "Combined %d ops so far %ld\n", nUnique, profileOps - startProfileOps);
SortSaveBestHits(newnode, /*IN/SORT*/uniqueList, /*nIn*/nUnique,
/*nOut*/nSave, /*IN/OUT*/tophits);
assert(lNew->hits != NULL); /* set by sort/save */
tophits->visible[newnode] = lNew->hits[0];
UpdateTopVisible(/*IN*/NJ, nActive, newnode, &tophits->visible[newnode],
/*IN/OUT*/tophits);
UpdateVisible(/*IN/UPDATE*/NJ, nActive, /*IN*/uniqueList, nSave, /*IN/OUT*/tophits);
} else {
/* need to refresh: set top hits for node and for its top hits */
if(verbose > 2) fprintf(stderr,"Top hits for %d by refresh (%d unique age %d) nActive=%d\n",
newnode,nUnique,lNew->age,nActive);
nRefreshTopHits++;
lNew->age = 0;
int iNode;
/* ensure all out-distances are up to date ahead of time
to avoid any data overwriting issues.
*/
#ifdef OPENMP
#pragma omp parallel for schedule(dynamic, 50)
#endif
for (iNode = 0; iNode < NJ->maxnode; iNode++) {
if (NJ->parent[iNode] < 0) {
if (fastest) {
besthit_t bh;
bh.i = iNode;
bh.j = iNode;
bh.dist = 0;
SetCriterion(/*IN/UPDATE*/NJ, nActive, &bh);
} else {
SetOutDistance(/*IN/UDPATE*/NJ, iNode, nActive);
}
}
}
/* exhaustively get the best 2*m hits for newnode, set visible, and save the top m */
besthit_t *allhits = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->maxnode);
assert(2 * tophits->m <= NJ->maxnode);
besthit_t bh;
SetBestHit(newnode, NJ, nActive, /*OUT*/&bh, /*OUT*/allhits);
qsort(/*IN/OUT*/allhits, NJ->maxnode, sizeof(besthit_t), CompareHitsByCriterion);
SortSaveBestHits(newnode, /*IN/SORT*/allhits, /*nIn*/NJ->maxnode,
/*nOut*/tophits->m, /*IN/OUT*/tophits);
/* Do not need to call UpdateVisible because we set visible below */
/* And use the top 2*m entries to expand other best-hit lists, but only for top m */
int iHit;
#ifdef OPENMP
#pragma omp parallel for schedule(dynamic, 50)
#endif
for (iHit=0; iHit < tophits->m; iHit++) {
if (allhits[iHit].i < 0) continue;
int iNode = allhits[iHit].j;
assert(iNode>=0);
if (NJ->parent[iNode] >= 0) continue;
top_hits_list_t *l = &tophits->top_hits_lists[iNode];
int nHitsOld = l->nHits;
assert(nHitsOld <= tophits->m);
l->age = 0;
/* Merge: old hits into 0->nHitsOld and hits from iNode above that */
besthit_t *bothList = (besthit_t*)mymalloc(sizeof(besthit_t) * 3 * tophits->m);
HitsToBestHits(/*IN*/l->hits, nHitsOld, iNode, /*OUT*/bothList); /* does not compute criterion */
for (i = 0; i < nHitsOld; i++)
SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/&bothList[i]);
if (nActive <= 2 * tophits->m)
l->hitSource = -1; /* abandon the 2nd-level top-hits heuristic */
int nNewHits = l->hitSource >= 0 ? tophits->q : tophits->m;
assert(nNewHits > 0);
TransferBestHits(/*IN/UPDATE*/NJ, nActive, iNode,
/*IN*/allhits, /*nOldHits*/2 * nNewHits,
/*OUT*/&bothList[nHitsOld],
/*updateDist*/false); /* rely on UniqueBestHits to update dist and/or criterion */
int nUnique2;
besthit_t *uniqueList2 = UniqueBestHits(/*IN/UPDATE*/NJ, nActive,
/*IN/SORT*/bothList, nHitsOld + 2 * nNewHits,
/*OUT*/&nUnique2);
assert(nUnique2 > 0);
bothList = myfree(bothList,3 * tophits->m * sizeof(besthit_t));
/* Note this will overwrite l, but we saved nHitsOld */
SortSaveBestHits(iNode, /*IN/SORT*/uniqueList2, /*nIn*/nUnique2,
/*nOut*/nNewHits, /*IN/OUT*/tophits);
/* will update topvisible below */
tophits->visible[iNode] = tophits->top_hits_lists[iNode].hits[0];
uniqueList2 = myfree(uniqueList2, (nHitsOld + 2 * tophits->m) * sizeof(besthit_t));
}
ResetTopVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits); /* outside of the parallel phase */
allhits = myfree(allhits,sizeof(besthit_t)*NJ->maxnode);
}
uniqueList = myfree(uniqueList, nUniqueAlloc * sizeof(besthit_t));
if (verbose > 2) {
fprintf(stderr, "New top-hit list for %d profile-ops %ld (out-ops %ld): source %d age %d members ",
newnode,
profileOps - startProfileOps,
outprofileOps - startOutProfileOps,
lNew->hitSource, lNew->age);
int i;
for (i = 0; i < lNew->nHits; i++)
fprintf(stderr, " %d", lNew->hits[i].j);
fprintf(stderr,"\n");
}
}
void UpdateVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN*/besthit_t *tophitsNode,
int nTopHits,
/*IN/OUT*/top_hits_t *tophits) {
int iHit;
for(iHit = 0; iHit < nTopHits; iHit++) {
besthit_t *hit = &tophitsNode[iHit];
if (hit->i < 0) continue; /* possible empty entries */
assert(NJ->parent[hit->i] < 0);
assert(hit->j >= 0 && NJ->parent[hit->j] < 0);
besthit_t visible;
bool bSuccess = GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, hit->j, /*OUT*/&visible);
if (!bSuccess || hit->criterion < visible.criterion) {
if (bSuccess)
nVisibleUpdate++;
hit_t *v = &tophits->visible[hit->j];
v->j = hit->i;
v->dist = hit->dist;
UpdateTopVisible(NJ, nActive, hit->j, v, /*IN/OUT*/tophits);
if(verbose>5) fprintf(stderr,"NewVisible %d %d %f\n",
hit->j,v->j,v->dist);
}
} /* end loop over hits */
}
/* Update the top-visible list to perhaps include visible[iNode] */
void UpdateTopVisible(/*IN*/NJ_t * NJ, int nActive,
int iIn, /*IN*/hit_t *hit,
/*IN/OUT*/top_hits_t *tophits) {
assert(tophits != NULL);
bool bIn = false; /* placed in the list */
int i;
/* First, if the list is not full, put it in somewhere */
for (i = 0; i < tophits->nTopVisible && !bIn; i++) {
int iNode = tophits->topvisible[i];
if (iNode == iIn) {
/* this node is already in the top hit list */
bIn = true;
} else if (iNode < 0 || NJ->parent[iNode] >= 0) {
/* found an empty spot */
bIn = true;
tophits->topvisible[i] = iIn;
}
}
int iPosWorst = -1;
double dCriterionWorst = -1e20;
if (!bIn) {
/* Search for the worst hit */
for (i = 0; i < tophits->nTopVisible && !bIn; i++) {
int iNode = tophits->topvisible[i];
assert(iNode >= 0 && NJ->parent[iNode] < 0 && iNode != iIn);
besthit_t visible;
if (!GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, iNode, /*OUT*/&visible)) {
/* found an empty spot */
tophits->topvisible[i] = iIn;
bIn = true;
} else if (visible.i == hit->j && visible.j == iIn) {
/* the reverse hit is already in the top hit list */
bIn = true;
} else if (visible.criterion >= dCriterionWorst) {
iPosWorst = i;
dCriterionWorst = visible.criterion;
}
}
}
if (!bIn && iPosWorst >= 0) {
besthit_t visible = HitToBestHit(iIn, *hit);
SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/&visible);
if (visible.criterion < dCriterionWorst) {
if (verbose > 2) {
int iOld = tophits->topvisible[iPosWorst];
fprintf(stderr, "TopVisible replace %d=>%d with %d=>%d\n",
iOld, tophits->visible[iOld].j, visible.i, visible.j);
}
tophits->topvisible[iPosWorst] = iIn;
}
}
if (verbose > 2) {
fprintf(stderr, "Updated TopVisible: ");
for (i = 0; i < tophits->nTopVisible; i++) {
int iNode = tophits->topvisible[i];
if (iNode >= 0 && NJ->parent[iNode] < 0) {
besthit_t bh = HitToBestHit(iNode, tophits->visible[iNode]);
SetDistCriterion(NJ, nActive, &bh);
fprintf(stderr, " %d=>%d:%.4f", bh.i, bh.j, bh.criterion);
}
}
fprintf(stderr,"\n");
}
}
/* Recompute the topvisible list */
void ResetTopVisible(/*IN/UPDATE*/NJ_t *NJ,
int nActive,
/*IN/OUT*/top_hits_t *tophits) {
besthit_t *visibleSorted = mymalloc(sizeof(besthit_t)*nActive);
int nVisible = 0; /* #entries in visibleSorted */
int iNode;
for (iNode = 0; iNode < NJ->maxnode; iNode++) {
/* skip joins involving stale nodes */
if (NJ->parent[iNode] >= 0)
continue;
besthit_t v;
if (GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, iNode, /*OUT*/&v)) {
assert(nVisible < nActive);
visibleSorted[nVisible++] = v;
}
}
assert(nVisible > 0);
qsort(/*IN/OUT*/visibleSorted,nVisible,sizeof(besthit_t),CompareHitsByCriterion);
/* Only keep the top m items, and try to avoid duplicating i->j with j->i
Note that visible(i) -> j does not necessarily imply visible(j) -> i,
so we store what the pairing was (or -1 for not used yet)
*/
int *inTopVisible = malloc(sizeof(int) * NJ->maxnodes);
int i;
for (i = 0; i < NJ->maxnodes; i++)
inTopVisible[i] = -1;
if (verbose > 2)
fprintf(stderr, "top-hit search: nActive %d nVisible %d considering up to %d items\n",
nActive, nVisible, tophits->m);
/* save the sorted indices in topvisible */
int iSave = 0;
for (i = 0; i < nVisible && iSave < tophits->nTopVisible; i++) {
besthit_t *v = &visibleSorted[i];
if (inTopVisible[v->i] != v->j) { /* not seen already */
tophits->topvisible[iSave++] = v->i;
inTopVisible[v->i] = v->j;
inTopVisible[v->j] = v->i;
}
}
while(iSave < tophits->nTopVisible)
tophits->topvisible[iSave++] = -1;
myfree(visibleSorted, sizeof(besthit_t)*nActive);
myfree(inTopVisible, sizeof(int) * NJ->maxnodes);
tophits->topvisibleAge = 0;
if (verbose > 2) {
fprintf(stderr, "Reset TopVisible: ");
for (i = 0; i < tophits->nTopVisible; i++) {
int iNode = tophits->topvisible[i];
if (iNode < 0)
break;
fprintf(stderr, " %d=>%d", iNode, tophits->visible[iNode].j);
}
fprintf(stderr,"\n");
}
}
/*
Find best hit to do in O(N*log(N) + m*L*log(N)) time, by
copying and sorting the visible list
updating out-distances for the top (up to m) candidates
selecting the best hit
if !fastest then
local hill-climbing for a better join,
using best-hit lists only, and updating
all out-distances in every best-hit list
*/
void TopHitNJSearch(/*IN/UPDATE*/NJ_t *NJ, int nActive,
/*IN/OUT*/top_hits_t *tophits,
/*OUT*/besthit_t *join) {
/* first, do we have at least m/2 candidates in topvisible?
And remember the best one */
int nCandidate = 0;
int iNodeBestCandidate = -1;
double dBestCriterion = 1e20;
int i;
for (i = 0; i < tophits->nTopVisible; i++) {
int iNode = tophits->topvisible[i];
besthit_t visible;
if (GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, iNode, /*OUT*/&visible)) {
nCandidate++;
if (iNodeBestCandidate < 0 || visible.criterion < dBestCriterion) {
iNodeBestCandidate = iNode;
dBestCriterion = visible.criterion;
}
}
}
tophits->topvisibleAge++;
/* Note we may have only nActive/2 joins b/c we try to store them once */
if (2 * tophits->topvisibleAge > tophits->m
|| (3*nCandidate < tophits->nTopVisible && 3*nCandidate < nActive)) {
/* recompute top visible */
if (verbose > 2)
fprintf(stderr, "Resetting the top-visible list at nActive=%d\n",nActive);
/* If age is low, then our visible set is becoming too sparse, because we have
recently recomputed the top visible subset. This is very rare but can happen
with -fastest. A quick-and-dirty solution is to walk up
the parents to get additional entries in top hit lists. To ensure that the
visible set becomes full, pick an arbitrary node if walking up terminates at self.
*/
if (tophits->topvisibleAge <= 2) {
if (verbose > 2)
fprintf(stderr, "Expanding visible set by walking up to active nodes at nActive=%d\n", nActive);
int iNode;
for (iNode = 0; iNode < NJ->maxnode; iNode++) {
if (NJ->parent[iNode] >= 0)
continue;
hit_t *v = &tophits->visible[iNode];
int newj = ActiveAncestor(NJ, v->j);
if (newj >= 0 && newj != v->j) {
if (newj == iNode) {
/* pick arbitrarily */
newj = 0;
while (NJ->parent[newj] >= 0 || newj == iNode)
newj++;
}
assert(newj >= 0 && newj < NJ->maxnodes
&& newj != iNode
&& NJ->parent[newj] < 0);
/* Set v to point to newj */
besthit_t bh = { iNode, newj, -1e20, -1e20, -1e20 };
SetDistCriterion(NJ, nActive, /*IN/OUT*/&bh);
v->j = newj;
v->dist = bh.dist;
}
}
}
ResetTopVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits);
/* and recurse to try again */
TopHitNJSearch(NJ, nActive, tophits, join);
return;
}
if (verbose > 2)
fprintf(stderr, "Top-visible list size %d (nActive %d m %d)\n",
nCandidate, nActive, tophits->m);
assert(iNodeBestCandidate >= 0 && NJ->parent[iNodeBestCandidate] < 0);
bool bSuccess = GetVisible(NJ, nActive, tophits, iNodeBestCandidate, /*OUT*/join);
assert(bSuccess);
assert(join->i >= 0 && NJ->parent[join->i] < 0);
assert(join->j >= 0 && NJ->parent[join->j] < 0);
if(fastest)
return;
int changed;
do {
changed = 0;
besthit_t bestI;
GetBestFromTopHits(join->i, NJ, nActive, tophits, /*OUT*/&bestI);
assert(bestI.i == join->i);
if (bestI.j != join->j && bestI.criterion < join->criterion) {
changed = 1;
if (verbose>2)
fprintf(stderr,"BetterI\t%d\t%d\t%d\t%d\t%f\t%f\n",
join->i,join->j,bestI.i,bestI.j,
join->criterion,bestI.criterion);
*join = bestI;
}
besthit_t bestJ;
GetBestFromTopHits(join->j, NJ, nActive, tophits, /*OUT*/&bestJ);
assert(bestJ.i == join->j);
if (bestJ.j != join->i && bestJ.criterion < join->criterion) {
changed = 1;
if (verbose>2)
fprintf(stderr,"BetterJ\t%d\t%d\t%d\t%d\t%f\t%f\n",
join->i,join->j,bestJ.i,bestJ.j,
join->criterion,bestJ.criterion);
*join = bestJ;
}
if(changed) nHillBetter++;
} while(changed);
}
int NGaps(/*IN*/NJ_t *NJ, int iNode) {
assert(iNode < NJ->nSeq);
int nGaps = 0;
int p;
for(p=0; p<NJ->nPos; p++) {
if (NJ->profiles[iNode]->codes[p] == NOCODE)
nGaps++;
}
return(nGaps);
}
int CompareHitsByCriterion(const void *c1, const void *c2) {
const besthit_t *hit1 = (besthit_t*)c1;
const besthit_t *hit2 = (besthit_t*)c2;
if (hit1->criterion < hit2->criterion) return(-1);
if (hit1->criterion > hit2->criterion) return(1);
return(0);
}
int CompareHitsByIJ(const void *c1, const void *c2) {
const besthit_t *hit1 = (besthit_t*)c1;
const besthit_t *hit2 = (besthit_t*)c2;
return hit1->i != hit2->i ? hit1->i - hit2->i : hit1->j - hit2->j;
}
void SortSaveBestHits(int iNode, /*IN/SORT*/besthit_t *besthits,
int nIn, int nOut,
/*IN/OUT*/top_hits_t *tophits) {
assert(nIn > 0);
assert(nOut > 0);
top_hits_list_t *l = &tophits->top_hits_lists[iNode];
/* */
qsort(/*IN/OUT*/besthits,nIn,sizeof(besthit_t),CompareHitsByCriterion);
/* First count how many we will save
Not sure if removing duplicates is actually necessary.
*/
int nSave = 0;
int jLast = -1;
int iBest;
for (iBest = 0; iBest < nIn && nSave < nOut; iBest++) {
if (besthits[iBest].i < 0)
continue;
assert(besthits[iBest].i == iNode);
int j = besthits[iBest].j;
if (j != iNode && j != jLast && j >= 0) {
nSave++;
jLast = j;
}
}
assert(nSave > 0);
#ifdef OPENMP
omp_set_lock(&tophits->locks[iNode]);
#endif
if (l->hits != NULL) {
l->hits = myfree(l->hits, l->nHits * sizeof(hit_t));
l->nHits = 0;
}
l->hits = mymalloc(sizeof(hit_t) * nSave);
l->nHits = nSave;
int iSave = 0;
jLast = -1;
for (iBest = 0; iBest < nIn && iSave < nSave; iBest++) {
int j = besthits[iBest].j;
if (j != iNode && j != jLast && j >= 0) {
l->hits[iSave].j = j;
l->hits[iSave].dist = besthits[iBest].dist;
iSave++;
jLast = j;
}
}
#ifdef OPENMP
omp_unset_lock(&tophits->locks[iNode]);
#endif
assert(iSave == nSave);
}
void TransferBestHits(/*IN/UPDATE*/NJ_t *NJ,
int nActive,
int iNode,
/*IN*/besthit_t *oldhits,
int nOldHits,
/*OUT*/besthit_t *newhits,
bool updateDistances) {
assert(iNode >= 0);
assert(NJ->parent[iNode] < 0);
int iBest;
for(iBest = 0; iBest < nOldHits; iBest++) {
besthit_t *old = &oldhits[iBest];
besthit_t *new = &newhits[iBest];
new->i = iNode;
new->j = ActiveAncestor(/*IN*/NJ, old->j);
new->dist = old->dist; /* may get reset below */
new->weight = old->weight;
new->criterion = old->criterion;
if(new->j < 0 || new->j == iNode) {
new->weight = 0;
new->dist = -1e20;
new->criterion = 1e20;
} else if (new->i != old->i || new->j != old->j) {
if (updateDistances)
SetDistCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/new);
else {
new->dist = -1e20;
new->criterion = 1e20;
}
} else {
if (updateDistances)
SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/new);
else
new->criterion = 1e20; /* leave dist alone */
}
}
}
void HitsToBestHits(/*IN*/hit_t *hits, int nHits, int iNode, /*OUT*/besthit_t *newhits) {
int i;
for (i = 0; i < nHits; i++) {
hit_t *hit = &hits[i];
besthit_t *bh = &newhits[i];
bh->i = iNode;
bh->j = hit->j;
bh->dist = hit->dist;
bh->criterion = 1e20;
bh->weight = -1; /* not the true value -- we compute these directly when needed */
}
}
besthit_t HitToBestHit(int i, hit_t hit) {
besthit_t bh;
bh.i = i;
bh.j = hit.j;
bh.dist = hit.dist;
bh.criterion = 1e20;
bh.weight = -1;
return(bh);
}
char *OpenMPString(void) {
#ifdef OPENMP
static char buf[100];
sprintf(buf, ", OpenMP (%d threads)", omp_get_max_threads());
return(buf);
#else
return("");
#endif
}
/* Algorithm 26.2.17 from Abromowitz and Stegun, Handbook of Mathematical Functions
Absolute accuracy of only about 1e-7, which is enough for us
*/
double pnorm(double x)
{
double b1 = 0.319381530;
double b2 = -0.356563782;
double b3 = 1.781477937;
double b4 = -1.821255978;
double b5 = 1.330274429;
double p = 0.2316419;
double c = 0.39894228;
if(x >= 0.0) {
double t = 1.0 / ( 1.0 + p * x );
return (1.0 - c * exp( -x * x / 2.0 ) * t *
( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 ));
}
/*else*/
double t = 1.0 / ( 1.0 - p * x );
return ( c * exp( -x * x / 2.0 ) * t *
( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 ));
}
void *mymalloc(size_t sz) {
if (sz == 0) return(NULL);
void *new = malloc(sz);
if (new == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
szAllAlloc += sz;
mymallocUsed += sz;
#ifdef TRACK_MEMORY
struct mallinfo mi = mallinfo();
if (mi.arena+mi.hblkhd > maxmallocHeap)
maxmallocHeap = mi.arena+mi.hblkhd;
#endif
/* gcc malloc should always return 16-byte-aligned values... */
assert(IS_ALIGNED(new));
return (new);
}
void *mymemdup(void *data, size_t sz) {
if(data==NULL) return(NULL);
void *new = mymalloc(sz);
memcpy(/*to*/new, /*from*/data, sz);
return(new);
}
void *myrealloc(void *data, size_t szOld, size_t szNew, bool bCopy) {
if (data == NULL && szOld == 0)
return(mymalloc(szNew));
if (data == NULL || szOld == 0 || szNew == 0) {
fprintf(stderr,"Empty myrealloc\n");
exit(1);
}
if (szOld == szNew)
return(data);
void *new = NULL;
if (bCopy) {
/* Try to reduce memory fragmentation by allocating anew and copying
Seems to help in practice */
new = mymemdup(data, szNew);
myfree(data, szOld);
} else {
new = realloc(data,szNew);
if (new == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
assert(IS_ALIGNED(new));
szAllAlloc += (szNew-szOld);
mymallocUsed += (szNew-szOld);
#ifdef TRACK_MEMORY
struct mallinfo mi = mallinfo();
if (mi.arena+mi.hblkhd > maxmallocHeap)
maxmallocHeap = mi.arena+mi.hblkhd;
#endif
}
return(new);
}
void *myfree(void *p, size_t sz) {
if(p==NULL) return(NULL);
free(p);
mymallocUsed -= sz;
return(NULL);
}
/******************************************************************************/
/* Minimization of a 1-dimensional function by Brent's method (Numerical Recipes)
* Borrowed from Tree-Puzzle 5.1 util.c under GPL
* Modified by M.N.P to pass in the accessory data for the optimization function,
* to use 2x bounds around the starting guess and expand them if necessary,
* and to use both a fractional and an absolute tolerance
*/
#define ITMAX 100
#define CGOLD 0.3819660
#define TINY 1.0e-20
#define ZEPS 1.0e-10
#define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
/* Brents method in one dimension */
double brent(double ax, double bx, double cx, double (*f)(double, void *), void *data,
double ftol, double atol,
double *foptx, double *f2optx, double fax, double fbx, double fcx)
{
int iter;
double a,b,d=0,etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm;
double xw,wv,vx;
double e=0.0;
a=(ax < cx ? ax : cx);
b=(ax > cx ? ax : cx);
x=bx;
fx=fbx;
if (fax < fcx) {
w=ax;
fw=fax;
v=cx;
fv=fcx;
} else {
w=cx;
fw=fcx;
v=ax;
fv=fax;
}
for (iter=1;iter<=ITMAX;iter++) {
xm=0.5*(a+b);
tol1=ftol*fabs(x);
tol2=2.0*(tol1+ZEPS);
if (fabs(x-xm) <= (tol2-0.5*(b-a))
|| fabs(a-b) < atol) {
*foptx = fx;
xw = x-w;
wv = w-v;
vx = v-x;
*f2optx = 2.0*(fv*xw + fx*wv + fw*vx)/
(v*v*xw + x*x*wv + w*w*vx);
return x;
}
if (fabs(e) > tol1) {
r=(x-w)*(fx-fv);
q=(x-v)*(fx-fw);
p=(x-v)*q-(x-w)*r;
q=2.0*(q-r);
if (q > 0.0) p = -p;
q=fabs(q);
etemp=e;
e=d;
if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
d=CGOLD*(e=(x >= xm ? a-x : b-x));
else {
d=p/q;
u=x+d;
if (u-a < tol2 || b-u < tol2)
d=SIGN(tol1,xm-x);
}
} else {
d=CGOLD*(e=(x >= xm ? a-x : b-x));
}
u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
fu=(*f)(u,data);
if (fu <= fx) {
if (u >= x) a=x; else b=x;
SHFT(v,w,x,u)
SHFT(fv,fw,fx,fu)
} else {
if (u < x) a=u; else b=u;
if (fu <= fw || w == x) {
v=w;
w=u;
fv=fw;
fw=fu;
} else if (fu <= fv || v == x || v == w) {
v=u;
fv=fu;
}
}
}
*foptx = fx;
xw = x-w;
wv = w-v;
vx = v-x;
*f2optx = 2.0*(fv*xw + fx*wv + fw*vx)/
(v*v*xw + x*x*wv + w*w*vx);
return x;
} /* brent */
#undef ITMAX
#undef CGOLD
#undef ZEPS
#undef SHFT
#undef SIGN
/* one-dimensional minimization - as input a lower and an upper limit and a trial
value for the minimum is needed: xmin < xguess < xmax
the function and a fractional tolerance has to be specified
onedimenmin returns the optimal x value and the value of the function
and its second derivative at this point
*/
double onedimenmin(double xmin, double xguess, double xmax, double (*f)(double,void*), void *data,
double ftol, double atol,
/*OUT*/double *fx, /*OUT*/double *f2x)
{
double optx, ax, bx, cx, fa, fb, fc;
/* first attempt to bracketize minimum */
if (xguess == xmin) {
ax = xmin;
bx = 2.0*xguess;
cx = 10.0*xguess;
} else if (xguess <= 2.0 * xmin) {
ax = xmin;
bx = xguess;
cx = 5.0*xguess;
} else {
ax = 0.5*xguess;
bx = xguess;
cx = 2.0*xguess;
}
if (cx > xmax)
cx = xmax;
if (bx >= cx)
bx = 0.5*(ax+cx);
if (verbose > 4)
fprintf(stderr, "onedimenmin lo %.4f guess %.4f hi %.4f range %.4f %.4f\n",
ax, bx, cx, xmin, xmax);
/* ideally this range includes the true minimum, i.e.,
fb < fa and fb < fc
if not, we gradually expand the boundaries until it does,
or we near the boundary of the allowed range and use that
*/
fa = (*f)(ax,data);
fb = (*f)(bx,data);
fc = (*f)(cx,data);
while(fa < fb && ax > xmin) {
ax = (ax+xmin)/2.0;
if (ax < 2.0*xmin) /* give up on shrinking the region */
ax = xmin;
fa = (*f)(ax,data);
}
while(fc < fb && cx < xmax) {
cx = (cx+xmax)/2.0;
if (cx > xmax * 0.95)
cx = xmax;
fc = (*f)(cx,data);
}
optx = brent(ax, bx, cx, f, data, ftol, atol, fx, f2x, fa, fb, fc);
if (verbose > 4)
fprintf(stderr, "onedimenmin reaches optimum f(%.4f) = %.4f f2x %.4f\n", optx, *fx, *f2x);
return optx; /* return optimal x */
} /* onedimenmin */
/* Numerical code for the gamma distribution is modified from the PhyML 3 code
(GNU public license) of Stephane Guindon
*/
double LnGamma (double alpha)
{
/* returns ln(gamma(alpha)) for alpha>0, accurate to 10 decimal places.
Stirling's formula is used for the central polynomial part of the procedure.
Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma function.
Communications of the Association for Computing Machinery, 9:684
*/
double x=alpha, f=0, z;
if (x<7) {
f=1; z=x-1;
while (++z<7) f*=z;
x=z; f=-(double)log(f);
}
z = 1/(x*x);
return f + (x-0.5)*(double)log(x) - x + .918938533204673
+ (((-.000595238095238*z+.000793650793651)*z-.002777777777778)*z
+.083333333333333)/x;
}
double IncompleteGamma(double x, double alpha, double ln_gamma_alpha)
{
/* returns the incomplete gamma ratio I(x,alpha) where x is the upper
limit of the integration and alpha is the shape parameter.
returns (-1) if in error
ln_gamma_alpha = ln(Gamma(alpha)), is almost redundant.
(1) series expansion if (alpha>x || x<=1)
(2) continued fraction otherwise
RATNEST FORTRAN by
Bhattacharjee GP (1970) The incomplete gamma integral. Applied Statistics,
19: 285-287 (AS32)
*/
int i;
double p=alpha, g=ln_gamma_alpha;
double accurate=1e-8, overflow=1e30;
double factor, gin=0, rn=0, a=0,b=0,an=0,dif=0, term=0, pn[6];
if (x==0) return (0);
if (x<0 || p<=0) return (-1);
factor=(double)exp(p*(double)log(x)-x-g);
if (x>1 && x>=p) goto l30;
/* (1) series expansion */
gin=1; term=1; rn=p;
l20:
rn++;
term*=x/rn; gin+=term;
if (term > accurate) goto l20;
gin*=factor/p;
goto l50;
l30:
/* (2) continued fraction */
a=1-p; b=a+x+1; term=0;
pn[0]=1; pn[1]=x; pn[2]=x+1; pn[3]=x*b;
gin=pn[2]/pn[3];
l32:
a++; b+=2; term++; an=a*term;
for (i=0; i<2; i++) pn[i+4]=b*pn[i+2]-an*pn[i];
if (pn[5] == 0) goto l35;
rn=pn[4]/pn[5]; dif=fabs(gin-rn);
if (dif>accurate) goto l34;
if (dif<=accurate*rn) goto l42;
l34:
gin=rn;
l35:
for (i=0; i<4; i++) pn[i]=pn[i+2];
if (fabs(pn[4]) < overflow) goto l32;
for (i=0; i<4; i++) pn[i]/=overflow;
goto l32;
l42:
gin=1-factor*gin;
l50:
return (gin);
}
double PGamma(double x, double alpha)
{
/* scale = 1/alpha */
return IncompleteGamma(x*alpha,alpha,LnGamma(alpha));
}
/* helper function to subtract timval structures */
/* 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;
}
double clockDiff(/*IN*/struct timeval *clock_start) {
struct timeval time_now, elapsed;
gettimeofday(/*OUT*/&time_now,NULL);
timeval_subtract(/*OUT*/&elapsed,/*IN*/&time_now,/*IN*/clock_start);
return(elapsed.tv_sec + elapsed.tv_usec*1e-6);
}
/* The random number generator is taken from D E Knuth
http://www-cs-faculty.stanford.edu/~knuth/taocp.html
*/
/* This program by D E Knuth is in the public domain and freely copyable.
* It is explained in Seminumerical Algorithms, 3rd edition, Section 3.6
* (or in the errata to the 2nd edition --- see
* http://www-cs-faculty.stanford.edu/~knuth/taocp.html
* in the changes to Volume 2 on pages 171 and following). */
/* N.B. The MODIFICATIONS introduced in the 9th printing (2002) are
included here; there's no backwards compatibility with the original. */
/* This version also adopts Brendan McKay's suggestion to
accommodate naive users who forget to call ran_start(seed). */
/* If you find any bugs, please report them immediately to
* taocp@cs.stanford.edu
* (and you will be rewarded if the bug is genuine). Thanks! */
/************ see the book for explanations and caveats! *******************/
/************ in particular, you need two's complement arithmetic **********/
#define KK 100 /* the long lag */
#define LL 37 /* the short lag */
#define MM (1L<<30) /* the modulus */
#define mod_diff(x,y) (((x)-(y))&(MM-1)) /* subtraction mod MM */
long ran_x[KK]; /* the generator state */
#ifdef __STDC__
void ran_array(long aa[],int n)
#else
void ran_array(aa,n) /* put n new random numbers in aa */
long *aa; /* destination */
int n; /* array length (must be at least KK) */
#endif
{
register int i,j;
for (j=0;j<KK;j++) aa[j]=ran_x[j];
for (;j<n;j++) aa[j]=mod_diff(aa[j-KK],aa[j-LL]);
for (i=0;i<LL;i++,j++) ran_x[i]=mod_diff(aa[j-KK],aa[j-LL]);
for (;i<KK;i++,j++) ran_x[i]=mod_diff(aa[j-KK],ran_x[i-LL]);
}
/* the following routines are from exercise 3.6--15 */
/* after calling ran_start, get new randoms by, e.g., "x=ran_arr_next()" */
#define QUALITY 1009 /* recommended quality level for high-res use */
long ran_arr_buf[QUALITY];
long ran_arr_dummy=-1, ran_arr_started=-1;
long *ran_arr_ptr=&ran_arr_dummy; /* the next random number, or -1 */
#define TT 70 /* guaranteed separation between streams */
#define is_odd(x) ((x)&1) /* units bit of x */
#ifdef __STDC__
void ran_start(long seed)
#else
void ran_start(seed) /* do this before using ran_array */
long seed; /* selector for different streams */
#endif
{
register int t,j;
long x[KK+KK-1]; /* the preparation buffer */
register long ss=(seed+2)&(MM-2);
for (j=0;j<KK;j++) {
x[j]=ss; /* bootstrap the buffer */
ss<<=1; if (ss>=MM) ss-=MM-2; /* cyclic shift 29 bits */
}
x[1]++; /* make x[1] (and only x[1]) odd */
for (ss=seed&(MM-1),t=TT-1; t; ) {
for (j=KK-1;j>0;j--) x[j+j]=x[j], x[j+j-1]=0; /* "square" */
for (j=KK+KK-2;j>=KK;j--)
x[j-(KK-LL)]=mod_diff(x[j-(KK-LL)],x[j]),
x[j-KK]=mod_diff(x[j-KK],x[j]);
if (is_odd(ss)) { /* "multiply by z" */
for (j=KK;j>0;j--) x[j]=x[j-1];
x[0]=x[KK]; /* shift the buffer cyclically */
x[LL]=mod_diff(x[LL],x[KK]);
}
if (ss) ss>>=1; else t--;
}
for (j=0;j<LL;j++) ran_x[j+KK-LL]=x[j];
for (;j<KK;j++) ran_x[j-LL]=x[j];
for (j=0;j<10;j++) ran_array(x,KK+KK-1); /* warm things up */
ran_arr_ptr=&ran_arr_started;
}
#define ran_arr_next() (*ran_arr_ptr>=0? *ran_arr_ptr++: ran_arr_cycle())
long ran_arr_cycle()
{
if (ran_arr_ptr==&ran_arr_dummy)
ran_start(314159L); /* the user forgot to initialize */
ran_array(ran_arr_buf,QUALITY);
ran_arr_buf[KK]=-1;
ran_arr_ptr=ran_arr_buf+1;
return ran_arr_buf[0];
}
/* end of code from Knuth */
double knuth_rand() {
return(9.31322574615479e-10 * ran_arr_next()); /* multiply by 2**-30 */
}
hashstrings_t *MakeHashtable(char **strings, int nStrings) {
hashstrings_t *hash = (hashstrings_t*)mymalloc(sizeof(hashstrings_t));
hash->nBuckets = 8*nStrings;
hash->buckets = (hashbucket_t*)mymalloc(sizeof(hashbucket_t) * hash->nBuckets);
int i;
for (i=0; i < hash->nBuckets; i++) {
hash->buckets[i].string = NULL;
hash->buckets[i].nCount = 0;
hash->buckets[i].first = -1;
}
for (i=0; i < nStrings; i++) {
hashiterator_t hi = FindMatch(hash, strings[i]);
if (hash->buckets[hi].string == NULL) {
/* save a unique entry */
assert(hash->buckets[hi].nCount == 0);
hash->buckets[hi].string = strings[i];
hash->buckets[hi].nCount = 1;
hash->buckets[hi].first = i;
} else {
/* record a duplicate entry */
assert(hash->buckets[hi].string != NULL);
assert(strcmp(hash->buckets[hi].string, strings[i]) == 0);
assert(hash->buckets[hi].first >= 0);
hash->buckets[hi].nCount++;
}
}
return(hash);
}
hashstrings_t *FreeHashtable(hashstrings_t* hash) {
if (hash != NULL) {
myfree(hash->buckets, sizeof(hashbucket_t) * hash->nBuckets);
myfree(hash, sizeof(hashstrings_t));
}
return(NULL);
}
#define MAXADLER 65521
hashiterator_t FindMatch(hashstrings_t *hash, char *string) {
/* Adler-32 checksum */
unsigned int hashA = 1;
unsigned int hashB = 0;
char *p;
for (p = string; *p != '\0'; p++) {
hashA = ((unsigned int)*p + hashA);
hashB = hashA+hashB;
}
hashA %= MAXADLER;
hashB %= MAXADLER;
hashiterator_t hi = (hashB*65536+hashA) % hash->nBuckets;
while(hash->buckets[hi].string != NULL
&& strcmp(hash->buckets[hi].string, string) != 0) {
hi++;
if (hi >= hash->nBuckets)
hi = 0;
}
return(hi);
}
char *GetHashString(hashstrings_t *hash, hashiterator_t hi) {
return(hash->buckets[hi].string);
}
int HashCount(hashstrings_t *hash, hashiterator_t hi) {
return(hash->buckets[hi].nCount);
}
int HashFirst(hashstrings_t *hash, hashiterator_t hi) {
return(hash->buckets[hi].first);
}
uniquify_t *UniquifyAln(alignment_t *aln) {
int nUniqueSeq = 0;
char **uniqueSeq = (char**)mymalloc(aln->nSeq * sizeof(char*)); /* iUnique -> seq */
int *uniqueFirst = (int*)mymalloc(aln->nSeq * sizeof(int)); /* iUnique -> iFirst in aln */
int *alnNext = (int*)mymalloc(aln->nSeq * sizeof(int)); /* i in aln -> next, or -1 */
int *alnToUniq = (int*)mymalloc(aln->nSeq * sizeof(int)); /* i in aln -> iUnique; many -> -1 */
int i;
for (i = 0; i < aln->nSeq; i++) {
uniqueSeq[i] = NULL;
uniqueFirst[i] = -1;
alnNext[i] = -1;
alnToUniq[i] = -1;
}
hashstrings_t *hashseqs = MakeHashtable(aln->seqs, aln->nSeq);
for (i=0; i<aln->nSeq; i++) {
hashiterator_t hi = FindMatch(hashseqs,aln->seqs[i]);
int first = HashFirst(hashseqs,hi);
if (first == i) {
uniqueSeq[nUniqueSeq] = aln->seqs[i];
uniqueFirst[nUniqueSeq] = i;
alnToUniq[i] = nUniqueSeq;
nUniqueSeq++;
} else {
int last = first;
while (alnNext[last] != -1)
last = alnNext[last];
assert(last>=0);
alnNext[last] = i;
assert(alnToUniq[last] >= 0 && alnToUniq[last] < nUniqueSeq);
alnToUniq[i] = alnToUniq[last];
}
}
assert(nUniqueSeq>0);
hashseqs = FreeHashtable(hashseqs);
uniquify_t *uniquify = (uniquify_t*)mymalloc(sizeof(uniquify_t));
uniquify->nSeq = aln->nSeq;
uniquify->nUnique = nUniqueSeq;
uniquify->uniqueFirst = uniqueFirst;
uniquify->alnNext = alnNext;
uniquify->alnToUniq = alnToUniq;
uniquify->uniqueSeq = uniqueSeq;
return(uniquify);
}
uniquify_t *FreeUniquify(uniquify_t *unique) {
if (unique != NULL) {
myfree(unique->uniqueFirst, sizeof(int)*unique->nSeq);
myfree(unique->alnNext, sizeof(int)*unique->nSeq);
myfree(unique->alnToUniq, sizeof(int)*unique->nSeq);
myfree(unique->uniqueSeq, sizeof(char*)*unique->nSeq);
myfree(unique,sizeof(uniquify_t));
unique = NULL;
}
return(unique);
}
traversal_t InitTraversal(NJ_t *NJ) {
traversal_t worked = (bool*)mymalloc(sizeof(bool)*NJ->maxnodes);
int i;
for (i=0; i<NJ->maxnodes; i++)
worked[i] = false;
return(worked);
}
void SkipTraversalInto(int node, /*IN/OUT*/traversal_t traversal) {
traversal[node] = true;
}
int TraversePostorder(int node, NJ_t *NJ, /*IN/OUT*/traversal_t traversal,
/*OPTIONAL OUT*/bool *pUp) {
if (pUp)
*pUp = false;
while(1) {
assert(node >= 0);
/* move to a child if possible */
bool found = false;
int iChild;
for (iChild=0; iChild < NJ->child[node].nChild; iChild++) {
int child = NJ->child[node].child[iChild];
if (!traversal[child]) {
node = child;
found = true;
break;
}
}
if (found)
continue; /* keep moving down */
if (!traversal[node]) {
traversal[node] = true;
return(node);
}
/* If we've already done this node, need to move up */
if (node == NJ->root)
return(-1); /* nowhere to go -- done traversing */
node = NJ->parent[node];
/* If we go up to someplace that was already marked as visited, this is due
to a change in topology, so return it marked as "up" */
if (pUp && traversal[node]) {
*pUp = true;
return(node);
}
}
}
traversal_t FreeTraversal(traversal_t traversal, NJ_t *NJ) {
myfree(traversal, sizeof(bool)*NJ->maxnodes);
return(NULL);
}
profile_t **UpProfiles(NJ_t *NJ) {
profile_t **upProfiles = (profile_t**)mymalloc(sizeof(profile_t*)*NJ->maxnodes);
int i;
for (i=0; i<NJ->maxnodes; i++) upProfiles[i] = NULL;
return(upProfiles);
}
profile_t *GetUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int outnode, bool useML) {
assert(outnode != NJ->root && outnode >= NJ->nSeq); /* not for root or leaves */
if (upProfiles[outnode] != NULL)
return(upProfiles[outnode]);
int depth;
int *pathToRoot = PathToRoot(NJ, outnode, /*OUT*/&depth);
int i;
/* depth-1 is root */
for (i = depth-2; i>=0; i--) {
int node = pathToRoot[i];
if (upProfiles[node] == NULL) {
/* Note -- SetupABCD may call GetUpProfile, but it should do it farther
up in the path to the root
*/
profile_t *profiles[4];
int nodeABCD[4];
SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, useML);
if (useML) {
/* If node is a child of root, then the 4th profile is of the 2nd root-sibling of node
Otherwise, the 4th profile is the up-profile of the parent of node, and that
is the branch-length we need
*/
double lenC = NJ->branchlength[nodeABCD[2]];
double lenD = NJ->branchlength[nodeABCD[3]];
if (verbose > 3) {
fprintf(stderr, "Computing UpProfile for node %d with lenC %.4f lenD %.4f pair-loglk %.3f\n",
node, lenC, lenD,
PairLogLk(profiles[2],profiles[3],lenC+lenD,NJ->nPos,NJ->transmat,&NJ->rates, /*site_lk*/NULL));
PrintNJInternal(stderr, NJ, /*useLen*/true);
}
upProfiles[node] = PosteriorProfile(/*C*/profiles[2], /*D*/profiles[3],
lenC, lenD,
NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints);
} else {
profile_t *profilesCDAB[4] = { profiles[2], profiles[3], profiles[0], profiles[1] };
double weight = QuartetWeight(profilesCDAB, NJ->distance_matrix, NJ->nPos);
if (verbose>3)
fprintf(stderr, "Compute upprofile of %d from %d and parents (vs. children %d %d) with weight %.3f\n",
node, nodeABCD[2], nodeABCD[0], nodeABCD[1], weight);
upProfiles[node] = AverageProfile(profiles[2], profiles[3],
NJ->nPos, NJ->nConstraints,
NJ->distance_matrix,
weight);
}
}
}
FreePath(pathToRoot,NJ);
assert(upProfiles[outnode] != NULL);
return(upProfiles[outnode]);
}
profile_t *DeleteUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int node) {
assert(node>=0 && node < NJ->maxnodes);
if (upProfiles[node] != NULL)
upProfiles[node] = FreeProfile(upProfiles[node], NJ->nPos, NJ->nConstraints); /* returns NULL */
return(NULL);
}
profile_t **FreeUpProfiles(profile_t **upProfiles, NJ_t *NJ) {
int i;
int nUsed = 0;
for (i=0; i < NJ->maxnodes; i++) {
if (upProfiles[i] != NULL)
nUsed++;
DeleteUpProfile(upProfiles, NJ, i);
}
myfree(upProfiles, sizeof(profile_t*)*NJ->maxnodes);
if (verbose >= 3)
fprintf(stderr,"FreeUpProfiles -- freed %d\n", nUsed);
return(NULL);
}
int *PathToRoot(NJ_t *NJ, int node, /*OUT*/int *outDepth) {
int *pathToRoot = (int*)mymalloc(sizeof(int)*NJ->maxnodes);
int depth = 0;
int ancestor = node;
while(ancestor >= 0) {
pathToRoot[depth] = ancestor;
ancestor = NJ->parent[ancestor];
depth++;
}
*outDepth = depth;
return(pathToRoot);
}
int *FreePath(int *path, NJ_t *NJ) {
myfree(path, sizeof(int)*NJ->maxnodes);
return(NULL);
}
transition_matrix_t *CreateGTR(double *r/*ac ag at cg ct gt*/, double *f/*acgt*/) {
double matrix[4][MAXCODES];
assert(nCodes==4);
int i, j;
/* Place rates onto a symmetric matrix, but correct by f(target), so that
stationary distribution f[] is maintained
Leave diagonals as 0 (CreateTransitionMatrix will fix them)
*/
int imat = 0;
for (i = 0; i < nCodes; i++) {
matrix[i][i] = 0;
for (j = i+1; j < nCodes; j++) {
double rate = r[imat++];
assert(rate > 0);
/* Want t(matrix) * f to be 0 */
matrix[i][j] = rate * f[i];
matrix[j][i] = rate * f[j];
}
}
/* Compute average mutation rate */
double total_rate = 0;
for (i = 0; i < nCodes; i++)
for (j = 0; j < nCodes; j++)
total_rate += f[i] * matrix[i][j];
assert(total_rate > 1e-6);
double inv = 1.0/total_rate;
for (i = 0; i < nCodes; i++)
for (j = 0; j < nCodes; j++)
matrix[i][j] *= inv;
return(CreateTransitionMatrix(matrix,f));
}
transition_matrix_t *CreateTransitionMatrix(/*IN*/double matrix[MAXCODES][MAXCODES],
/*IN*/double stat[MAXCODES]) {
int i,j,k;
transition_matrix_t *transmat = mymalloc(sizeof(transition_matrix_t));
double sqrtstat[20];
for (i = 0; i < nCodes; i++) {
transmat->stat[i] = stat[i];
transmat->statinv[i] = 1.0/stat[i];
sqrtstat[i] = sqrt(stat[i]);
}
double sym[20*20]; /* symmetrized matrix M' */
/* set diagonals so columns sums are 0 before symmetrization */
for (i = 0; i < nCodes; i++)
for (j = 0; j < nCodes; j++)
sym[nCodes*i+j] = matrix[i][j];
for (j = 0; j < nCodes; j++) {
double sum = 0;
sym[nCodes*j+j] = 0;
for (i = 0; i < nCodes; i++)
sum += sym[nCodes*i+j];
sym[nCodes*j+j] = -sum;
}
/* M' = S**-1 M S */
for (i = 0; i < nCodes; i++)
for (j = 0; j < nCodes; j++)
sym[nCodes*i+j] *= sqrtstat[j]/sqrtstat[i];
/* eigen decomposition of M' -- note that eigenW is the transpose of what we want,
which is eigenvectors in columns */
double eigenW[20*20], eval[20], e[20];
for (i = 0; i < nCodes*nCodes; i++)
eigenW[i] = sym[i];
tred2(eigenW, nCodes, nCodes, eval, e);
tqli(eval, e, nCodes , nCodes, eigenW);
/* save eigenvalues */
for (i = 0; i < nCodes; i++)
transmat->eigenval[i] = eval[i];
/* compute eigen decomposition of M into t(codeFreq): V = S*W */
/* compute inverse of V in eigeninv: V**-1 = t(W) S**-1 */
for (i = 0; i < nCodes; i++) {
for (j = 0; j < nCodes; j++) {
transmat->eigeninv[i][j] = eigenW[nCodes*i+j] / sqrtstat[j];
transmat->eigeninvT[j][i] = transmat->eigeninv[i][j];
}
}
for (i = 0; i < nCodes; i++)
for (j = 0; j < nCodes; j++)
transmat->codeFreq[i][j] = eigenW[j*nCodes+i] * sqrtstat[i];
/* codeFreq[NOCODE] is the rotation of (1,1,...) not (1/nCodes,1/nCodes,...), which
gives correct posterior probabilities
*/
for (j = 0; j < nCodes; j++) {
transmat->codeFreq[NOCODE][j] = 0.0;
for (i = 0; i < nCodes; i++)
transmat->codeFreq[NOCODE][j] += transmat->codeFreq[i][j];
}
/* save some posterior probabilities for approximating later:
first, we compute P(B | A, t) for t = approxMLnearT, by using
V * exp(L*t) * V**-1 */
double expvalues[MAXCODES];
for (i = 0; i < nCodes; i++)
expvalues[i] = exp(approxMLnearT * transmat->eigenval[i]);
double LVinv[MAXCODES][MAXCODES]; /* exp(L*t) * V**-1 */
for (i = 0; i < nCodes; i++) {
for (j = 0; j < nCodes; j++)
LVinv[i][j] = transmat->eigeninv[i][j] * expvalues[i];
}
/* matrix transform for converting A -> B given t: transt[i][j] = P(j->i | t) */
double transt[MAXCODES][MAXCODES];
for (i = 0; i < nCodes; i++) {
for (j = 0; j < nCodes; j++) {
transt[i][j] = 0;
for (k = 0; k < nCodes; k++)
transt[i][j] += transmat->codeFreq[i][k] * LVinv[k][j];
}
}
/* nearP[i][j] = P(parent = j | both children are i) = P(j | i,i) ~ stat(j) * P(j->i | t)**2 */
for (i = 0; i < nCodes; i++) {
double nearP[MAXCODES];
double tot = 0;
for (j = 0; j < nCodes; j++) {
assert(transt[j][i] > 0);
assert(transmat->stat[j] > 0);
nearP[j] = transmat->stat[j] * transt[i][j] * transt[i][j];
tot += nearP[j];
}
assert(tot > 0);
for (j = 0; j < nCodes; j++)
nearP[j] *= 1.0/tot;
/* save nearP in transmat->nearP[i][] */
for (j = 0; j < nCodes; j++)
transmat->nearP[i][j] = nearP[j];
/* multiply by 1/stat and rotate nearP */
for (j = 0; j < nCodes; j++)
nearP[j] /= transmat->stat[j];
for (j = 0; j < nCodes; j++) {
double rot = 0;
for (k = 0; k < nCodes; k++)
rot += nearP[k] * transmat->codeFreq[i][j];
transmat->nearFreq[i][j] = rot;
}
}
return(transmat);
assert(0);
}
distance_matrix_t *TransMatToDistanceMat(transition_matrix_t *transmat) {
if (transmat == NULL)
return(NULL);
distance_matrix_t *dmat = mymalloc(sizeof(distance_matrix_t));
int i, j;
for (i=0; i<nCodes; i++) {
for (j=0; j<nCodes; j++) {
dmat->distances[i][j] = 0; /* never actually used */
dmat->eigeninv[i][j] = transmat->eigeninv[i][j];
dmat->codeFreq[i][j] = transmat->codeFreq[i][j];
}
}
/* eigentot . rotated-vector is the total frequency of the unrotated vector
(used to normalize in NormalizeFreq()
For transition matrices, we rotate by transpose of eigenvectors, so
we need to multiply by the inverse matrix by 1....1 to get this vector,
or in other words, sum the columns
*/
for(i = 0; i<nCodes; i++) {
dmat->eigentot[i] = 0.0;
for (j = 0; j<nCodes; j++)
dmat->eigentot[i] += transmat->eigeninv[i][j];
}
return(dmat);
}
/* Numerical recipes code for eigen decomposition (actually taken from RAxML rev_functions.c) */
void tred2 (double *a, const int n, const int np, double *d, double *e)
{
#define a(i,j) a[(j-1)*np + (i-1)]
#define e(i) e[i-1]
#define d(i) d[i-1]
int i, j, k, l;
double f, g, h, hh, scale;
for (i = n; i > 1; i--) {
l = i-1;
h = 0;
scale = 0;
if ( l > 1 ) {
for ( k = 1; k <= l; k++ )
scale += fabs(a(i,k));
if (scale == 0)
e(i) = a(i,l);
else {
for (k = 1; k <= l; k++) {
a(i,k) /= scale;
h += a(i,k) * a(i,k);
}
f = a(i,l);
g = -sqrt(h);
if (f < 0) g = -g;
e(i) = scale *g;
h -= f*g;
a(i,l) = f-g;
f = 0;
for (j = 1; j <=l ; j++) {
a(j,i) = a(i,j) / h;
g = 0;
for (k = 1; k <= j; k++)
g += a(j,k)*a(i,k);
for (k = j+1; k <= l; k++)
g += a(k,j)*a(i,k);
e(j) = g/h;
f += e(j)*a(i,j);
}
hh = f/(h+h);
for (j = 1; j <= l; j++) {
f = a(i,j);
g = e(j) - hh * f;
e(j) = g;
for (k = 1; k <= j; k++)
a(j,k) -= f*e(k) + g*a(i,k);
}
}
} else
e(i) = a(i,l);
d(i) = h;
}
d(1) = 0;
e(1) = 0;
for (i = 1; i <= n; i++) {
l = i-1;
if (d(i) != 0) {
for (j = 1; j <=l; j++) {
g = 0;
for (k = 1; k <= l; k++)
g += a(i,k)*a(k,j);
for (k=1; k <=l; k++)
a(k,j) -= g * a(k,i);
}
}
d(i) = a(i,i);
a(i,i) = 1;
for (j=1; j<=l; j++)
a(i,j) = a(j,i) = 0;
}
return;
#undef a
#undef e
#undef d
}
double pythag(double a, double b) {
double absa = fabs(a), absb = fabs(b);
return (absa > absb) ?
absa * sqrt(1+ (absb/absa)*(absb/absa)) :
absb == 0 ?
0 :
absb * sqrt(1+ (absa/absb)*(absa/absb));
}
void tqli(double *d, double *e, int n, int np, double *z)
{
#define z(i,j) z[(j-1)*np + (i-1)]
#define e(i) e[i-1]
#define d(i) d[i-1]
int i = 0, iter = 0, k = 0, l = 0, m = 0;
double b = 0, c = 0, dd = 0, f = 0, g = 0, p = 0, r = 0, s = 0;
for(i=2; i<=n; i++)
e(i-1) = e(i);
e(n) = 0;
for (l = 1; l <= n; l++)
{
iter = 0;
labelExtra:
for (m = l; (m < n); m++)
{
dd = fabs(d(m))+fabs(d(m+1));
if (fabs(e(m))+dd == dd)
break;
}
if (m != l)
{
assert(iter < 30);
iter++;
g = (d(l+1)-d(l))/(2*e(l));
r = pythag(g,1.);
g = d(m)-d(l)+e(l)/(g+(g<0?-r:r));
s = 1;
c = 1;
p = 0;
for (i = m-1; i>=l; i--)
{
f = s*e(i);
b = c*e(i);
r = pythag(f,g);
e(i+1) = r;
if (r == 0)
{
d (i+1) -= p;
e (m) = 0;
goto labelExtra;
}
s = f/r;
c = g/r;
g = d(i+1)-p;
r = (d(i)-g)*s + 2*c*b;
p = s*r;
d(i+1) = g + p;
g = c*r - b;
for (k=1; k <= n; k++)
{
f = z(k,i+1);
z(k,i+1) = s * z(k,i) + c*f;
z(k,i) = c * z(k,i) - s*f;
}
}
d(l) -= p;
e(l) = g;
e(m) = 0;
goto labelExtra;
}
}
return;
#undef z
#undef e
#undef d
}
#ifdef USE_SSE3
inline float mm_sum(register __m128 sum) {
#if 1
/* stupider but faster */
float f[4] ALIGNED;
_mm_store_ps(f,sum);
return(f[0]+f[1]+f[2]+f[3]);
#else
/* first we get sum[0]+sum[1], sum[2]+sum[3] by selecting 0/1 and 2/3 */
sum = _mm_add_ps(sum,_mm_shuffle_ps(sum,sum,_MM_SHUFFLE(0,1,2,3)));
/* then get sum[0]+sum[1]+sum[2]+sum[3] by selecting 0/1 and 0/1 */
sum = _mm_add_ps(sum,_mm_shuffle_ps(sum,sum,_MM_SHUFFLE(0,1,0,1)));
float f;
_mm_store_ss(&f, sum); /* save the lowest word */
return(f);
#endif
}
#endif
void vector_multiply(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n, /*OUT*/numeric_t *fOut) {
#ifdef USE_SSE3
int i;
for (i = 0; i < n; i += 4) {
__m128 a, b, c;
a = _mm_load_ps(f1+i);
b = _mm_load_ps(f2+i);
c = _mm_mul_ps(a, b);
_mm_store_ps(fOut+i,c);
}
#else
int i;
for (i = 0; i < n; i++)
fOut[i] = f1[i]*f2[i];
#endif
}
numeric_t vector_multiply_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n) {
#ifdef USE_SSE3
if (n == 4)
return(f1[0]*f2[0]+f1[1]*f2[1]+f1[2]*f2[2]+f1[3]*f2[3]);
__m128 sum = _mm_setzero_ps();
int i;
for (i = 0; i < n; i += 4) {
__m128 a, b, c;
a = _mm_load_ps(f1+i);
b = _mm_load_ps(f2+i);
c = _mm_mul_ps(a, b);
sum = _mm_add_ps(c, sum);
}
return(mm_sum(sum));
#else
int i;
numeric_t out = 0.0;
for (i=0; i < n; i++)
out += f1[i]*f2[i];
return(out);
#endif
}
/* sum(f1*f2*f3) */
numeric_t vector_multiply3_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t* f3, int n) {
#ifdef USE_SSE3
__m128 sum = _mm_setzero_ps();
int i;
for (i = 0; i < n; i += 4) {
__m128 a1, a2, a3;
a1 = _mm_load_ps(f1+i);
a2 = _mm_load_ps(f2+i);
a3 = _mm_load_ps(f3+i);
sum = _mm_add_ps(_mm_mul_ps(_mm_mul_ps(a1,a2),a3),sum);
}
return(mm_sum(sum));
#else
int i;
numeric_t sum = 0.0;
for (i = 0; i < n; i++)
sum += f1[i]*f2[i]*f3[i];
return(sum);
#endif
}
numeric_t vector_dot_product_rot(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t *fBy, int n) {
#ifdef USE_SSE3
__m128 sum1 = _mm_setzero_ps();
__m128 sum2 = _mm_setzero_ps();
int i;
for (i = 0; i < n; i += 4) {
__m128 a1, a2, aBy;
a1 = _mm_load_ps(f1+i);
a2 = _mm_load_ps(f2+i);
aBy = _mm_load_ps(fBy+i);
sum1 = _mm_add_ps(_mm_mul_ps(a1, aBy), sum1);
sum2 = _mm_add_ps(_mm_mul_ps(a2, aBy), sum2);
}
return(mm_sum(sum1)*mm_sum(sum2));
#else
int i;
numeric_t out1 = 0.0;
numeric_t out2 = 0.0;
for (i=0; i < n; i++) {
out1 += f1[i]*fBy[i];
out2 += f2[i]*fBy[i];
}
return(out1*out2);
#endif
}
numeric_t vector_sum(/*IN*/numeric_t *f1, int n) {
#ifdef USE_SSE3
if (n==4)
return(f1[0]+f1[1]+f1[2]+f1[3]);
__m128 sum = _mm_setzero_ps();
int i;
for (i = 0; i < n; i+=4) {
__m128 a;
a = _mm_load_ps(f1+i);
sum = _mm_add_ps(a, sum);
}
return(mm_sum(sum));
#else
numeric_t out = 0.0;
int i;
for (i = 0; i < n; i++)
out += f1[i];
return(out);
#endif
}
void vector_multiply_by(/*IN/OUT*/numeric_t *f, /*IN*/numeric_t fBy, int n) {
int i;
#ifdef USE_SSE3
__m128 c = _mm_set1_ps(fBy);
for (i = 0; i < n; i += 4) {
__m128 a, b;
a = _mm_load_ps(f+i);
b = _mm_mul_ps(a,c);
_mm_store_ps(f+i,b);
}
#else
for (i = 0; i < n; i++)
f[i] *= fBy;
#endif
}
void vector_add_mult(/*IN/OUT*/numeric_t *fTot, /*IN*/numeric_t *fAdd, numeric_t weight, int n) {
#ifdef USE_SSE3
int i;
__m128 w = _mm_set1_ps(weight);
for (i = 0; i < n; i += 4) {
__m128 tot, add;
tot = _mm_load_ps(fTot+i);
add = _mm_load_ps(fAdd+i);
_mm_store_ps(fTot+i, _mm_add_ps(tot, _mm_mul_ps(add,w)));
}
#else
int i;
for (i = 0; i < n; i++)
fTot[i] += fAdd[i] * weight;
#endif
}
void matrixt_by_vector4(/*IN*/numeric_t mat[4][MAXCODES], /*IN*/numeric_t vec[4], /*OUT*/numeric_t out[4]) {
#ifdef USE_SSE3
/*__m128 v = _mm_load_ps(vec);*/
__m128 o = _mm_setzero_ps();
int j;
/* result is a sum of vectors: sum(k) v[k] * mat[k][] */
for (j = 0; j < 4; j++) {
__m128 m = _mm_load_ps(&mat[j][0]);
__m128 vj = _mm_load1_ps(&vec[j]); /* is it faster to shuffle v? */
o = _mm_add_ps(o, _mm_mul_ps(vj,m));
}
_mm_store_ps(out, o);
#else
int j,k;
for (j = 0; j < 4; j++) {
double sum = 0;
for (k = 0; k < 4; k++)
sum += vec[k] * mat[k][j];
out[j] = sum;
}
#endif
}
transition_matrix_t *ReadAATransitionMatrix(/*IN*/char *filename) {
assert(nCodes==20);
double stat[20];
static double matrix[MAXCODES][MAXCODES];
static char buf[BUFFER_SIZE];
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Cannot read transition matrix file %s\n", filename);
exit(1);
}
char expected[2*MAXCODES+20];
int posE = 0;
int i, j;
for (i = 0; i < 20; i++) {
expected[posE++] = codesStringAA[i];
expected[posE++] = '\t';
}
expected[posE++] = '*';
expected[posE++] = '\n';
expected[posE++] = '\0';
if (fgets(buf, sizeof(buf), fp) == NULL) {
fprintf(stderr, "Error reading header line from transition matrix file\n");
exit(1);
}
if (strcmp(buf, expected) != 0) {
fprintf(stderr, "Invalid header line in transition matrix file, it must match:\n%s\n", expected);
exit(1);
}
for (i = 0; i < 20; i++) {
if (fgets(buf, sizeof(buf), fp) == NULL) {
fprintf(stderr, "Error reading matrix line\n");
exit(1);
}
char *field = strtok(buf,"\t\r\n");
if (field == NULL || strlen(field) != 1 || field[0] != codesStringAA[i]) {
fprintf(stderr, "Line for amino acid %c does not have the expected beginning\n", codesStringAA[i]);
exit(1);
}
for (j = 0; j < 20; j++) {
field = strtok(NULL, "\t\r\n");
if (field == NULL) {
fprintf(stderr, "Not enough fields for amino acid %c\n", codesStringAA[i]);
exit(1);
}
matrix[i][j] = atof(field);
}
field = strtok(NULL, "\t\r\n");
if (field == NULL) {
fprintf(stderr, "Not enough fields for amino acid %c\n", codesStringAA[i]);
exit(1);
}
stat[i] = atof(field);
}
double tol = 1e-5;
/* Verify that stat is positive and sums to 1 */
double statTot = 0;
for (i = 0; i < 20; i++) {
if (stat[i] < tol) {
fprintf(stderr, "stationary frequency for amino acid %c must be positive\n", codesStringAA[i]);
exit(1);
}
statTot += stat[i];
}
if (fabs(statTot - 1) > tol) {
fprintf(stderr, "stationary frequencies must sum to 1 -- actual sum is %g\n", statTot);
exit(1);
}
/* Verify that diagonals are negative and dot product of stat and diagonals is -1 */
double totRate = 0;
for (i = 0; i < 20; i++) {
double diag = matrix[i][i];
if (diag > -tol) {
fprintf(stderr, "transition rate(%c,%c) must be negative\n",
codesStringAA[i], codesStringAA[i]);
exit(1);
}
totRate += stat[i] * diag;
}
if (fabs(totRate + 1) > tol) {
fprintf(stderr, "Dot product of matrix diagonal and stationary frequencies must be -1 -- actual dot product is %g\n",
totRate);
exit(1);
}
/* Verify that each off-diagonal entry is nonnegative and that each column sums to 0 */
for (j = 0; j < 20; j++) {
double colSum = 0;
for (i = 0; i < 20; i++) {
double value = matrix[i][j];
colSum += value;
if (i != j && value < 0) {
fprintf(stderr, "Off-diagonal matrix entry for (%c,%c) is negative\n",
codesStringAA[i], codesStringAA[j]);
exit(1);
}
}
if (fabs(colSum) > tol) {
fprintf(stderr, "Sum of column %c must be zero -- actual sum is %g\n",
codesStringAA[j], colSum);
exit(1);
}
}
return CreateTransitionMatrix(matrix, stat);
}
distance_matrix_t matrixBLOSUM45 =
{
/*distances*/
{
{0, 1.31097856157468, 1.06573001937323, 1.2682782988532, 0.90471293383305, 1.05855446876905, 1.05232790675508, 0.769574440593014, 1.27579668305679, 0.964604099952603, 0.987178199640556, 1.05007594438157, 1.05464162250736, 1.1985987403937, 0.967404475245526, 0.700490199584332, 0.880060189098976, 1.09748548316685, 1.28141710375267, 0.800038509951648},
{1.31097856157468, 0, 0.8010890222701, 0.953340718498495, 1.36011107208122, 0.631543775840481, 0.791014908659279, 1.15694899265629, 0.761152570032029, 1.45014917711188, 1.17792001455227, 0.394661075648738, 0.998807558909651, 1.135143404599, 1.15432562628921, 1.05309036790541, 1.05010474413616, 1.03938321130789, 0.963216908696184, 1.20274751778601},
{1.06573001937323, 0.8010890222701, 0, 0.488217214273568, 1.10567116937273, 0.814970207038261, 0.810176440932339, 0.746487413974582, 0.61876156253224, 1.17886558630004, 1.52003670190022, 0.808442678243754, 1.2889025816028, 1.16264109995678, 1.18228799147301, 0.679475681649858, 0.853658619686283, 1.68988558988005, 1.24297493464833, 1.55207513886163},
{1.2682782988532, 0.953340718498495, 0.488217214273568, 0, 1.31581050011876, 0.769778474953791, 0.482077627352988, 0.888361752320536, 0.736360849050364, 1.76756333403346, 1.43574761894039, 0.763612910719347, 1.53386612356483, 1.74323672079854, 0.886347403928663, 0.808614044804528, 1.01590147813779, 1.59617804551619, 1.1740494822217, 1.46600946033173},
{0.90471293383305, 1.36011107208122, 1.10567116937273, 1.31581050011876, 0, 1.3836789310481, 1.37553994252576, 1.26740695314856, 1.32361065635259, 1.26087264215993, 1.02417540515351, 1.37259631233791, 1.09416720447891, 0.986982088723923, 1.59321190226694, 0.915638787768407, 0.913042853922533, 1.80744143643002, 1.3294417177004, 0.830022143283238},
{1.05855446876905, 0.631543775840481, 0.814970207038261, 0.769778474953791, 1.3836789310481, 0, 0.506942797642807, 1.17699648087288, 0.614595446514896, 1.17092829494457, 1.19833088638994, 0.637341078675405, 0.806490842729072, 1.83315144709714, 0.932064479113502, 0.850321696813199, 1.06830084665916, 1.05739353225849, 0.979907428113788, 1.5416250309563},
{1.05232790675508, 0.791014908659279, 0.810176440932339, 0.482077627352988, 1.37553994252576, 0.506942797642807, 0, 1.17007322676118, 0.769786956320484, 1.46659942462342, 1.19128214039009, 0.633592151371708, 1.27269395724349, 1.44641491621774, 0.735428579892476, 0.845319988414402, 1.06201695511881, 1.324395996498, 1.22734387448031, 1.53255698189437},
{0.769574440593014, 1.15694899265629, 0.746487413974582, 0.888361752320536, 1.26740695314856, 1.17699648087288, 1.17007322676118, 0, 1.1259007054424, 1.7025415585924, 1.38293205218175, 1.16756929156758, 1.17264582493965, 1.33271035269688, 1.07564768421292, 0.778868281341681, 1.23287107008366, 0.968539655354582, 1.42479529031801, 1.41208067821187},
{1.27579668305679, 0.761152570032029, 0.61876156253224, 0.736360849050364, 1.32361065635259, 0.614595446514896, 0.769786956320484, 1.1259007054424, 0, 1.4112324673522, 1.14630894167097, 0.967795284542623, 0.771479459384692, 1.10468029976148, 1.12334774065132, 1.02482926701639, 1.28754326478771, 1.27439749294131, 0.468683841672724, 1.47469999960758},
{0.964604099952603, 1.45014917711188, 1.17886558630004, 1.76756333403346, 1.26087264215993, 1.17092829494457, 1.46659942462342, 1.7025415585924, 1.4112324673522, 0, 0.433350517223017, 1.463460928818, 0.462965544381851, 0.66291968000662, 1.07010201755441, 1.23000200130049, 0.973485453109068, 0.963546200571036, 0.708724769805536, 0.351200119909572},
{0.987178199640556, 1.17792001455227, 1.52003670190022, 1.43574761894039, 1.02417540515351, 1.19833088638994, 1.19128214039009, 1.38293205218175, 1.14630894167097, 0.433350517223017, 0, 1.49770950074319, 0.473800072611076, 0.538473125003292, 1.37979627224964, 1.5859723170438, 0.996267398224516, 0.986095542821092, 0.725310666139274, 0.570542199221932},
{1.05007594438157, 0.394661075648738, 0.808442678243754, 0.763612910719347, 1.37259631233791, 0.637341078675405, 0.633592151371708, 1.16756929156758, 0.967795284542623, 1.463460928818, 1.49770950074319, 0, 1.0079761868248, 1.44331961488922, 0.924599080166146, 1.06275728888356, 1.05974425835993, 1.04892430642749, 0.972058829603409, 1.21378822764856},
{1.05464162250736, 0.998807558909651, 1.2889025816028, 1.53386612356483, 1.09416720447891, 0.806490842729072, 1.27269395724349, 1.17264582493965, 0.771479459384692, 0.462965544381851, 0.473800072611076, 1.0079761868248, 0, 0.72479754849538, 1.1699868662153, 1.34481214251794, 1.06435197383538, 1.05348497728858, 0.774878150710318, 0.609532859331199},
{1.1985987403937, 1.135143404599, 1.16264109995678, 1.74323672079854, 0.986982088723923, 1.83315144709714, 1.44641491621774, 1.33271035269688, 1.10468029976148, 0.66291968000662, 0.538473125003292, 1.44331961488922, 0.72479754849538, 0, 1.32968844979665, 1.21307373491949, 0.960087571600877, 0.475142555482979, 0.349485367759138, 0.692733248746636},
{0.967404475245526, 1.15432562628921, 1.18228799147301, 0.886347403928663, 1.59321190226694, 0.932064479113502, 0.735428579892476, 1.07564768421292, 1.12334774065132, 1.07010201755441, 1.37979627224964, 0.924599080166146, 1.1699868662153, 1.32968844979665, 0, 0.979087429691819, 0.97631161216338, 1.21751652292503, 1.42156458605332, 1.40887880416009},
{0.700490199584332, 1.05309036790541, 0.679475681649858, 0.808614044804528, 0.915638787768407, 0.850321696813199, 0.845319988414402, 0.778868281341681, 1.02482926701639, 1.23000200130049, 1.5859723170438, 1.06275728888356, 1.34481214251794, 1.21307373491949, 0.979087429691819, 0, 0.56109848274013, 1.76318885009194, 1.29689226231656, 1.02015839286433},
{0.880060189098976, 1.05010474413616, 0.853658619686283, 1.01590147813779, 0.913042853922533, 1.06830084665916, 1.06201695511881, 1.23287107008366, 1.28754326478771, 0.973485453109068, 0.996267398224516, 1.05974425835993, 1.06435197383538, 0.960087571600877, 0.97631161216338, 0.56109848274013, 0, 1.39547634461879, 1.02642577026706, 0.807404666228614},
{1.09748548316685, 1.03938321130789, 1.68988558988005, 1.59617804551619, 1.80744143643002, 1.05739353225849, 1.324395996498, 0.968539655354582, 1.27439749294131, 0.963546200571036, 0.986095542821092, 1.04892430642749, 1.05348497728858, 0.475142555482979, 1.21751652292503, 1.76318885009194, 1.39547634461879, 0, 0.320002937404137, 1.268589159299},
{1.28141710375267, 0.963216908696184, 1.24297493464833, 1.1740494822217, 1.3294417177004, 0.979907428113788, 1.22734387448031, 1.42479529031801, 0.468683841672724, 0.708724769805536, 0.725310666139274, 0.972058829603409, 0.774878150710318, 0.349485367759138, 1.42156458605332, 1.29689226231656, 1.02642577026706, 0.320002937404137, 0, 0.933095433689795},
{0.800038509951648, 1.20274751778601, 1.55207513886163, 1.46600946033173, 0.830022143283238, 1.5416250309563, 1.53255698189437, 1.41208067821187, 1.47469999960758, 0.351200119909572, 0.570542199221932, 1.21378822764856, 0.609532859331199, 0.692733248746636, 1.40887880416009, 1.02015839286433, 0.807404666228614, 1.268589159299, 0.933095433689795, 0}
},
/*eigeninv*/
{
{-0.216311217101265, -0.215171653035930, -0.217000020881064, -0.232890860601250, -0.25403526530177, -0.211569372858927, -0.218073620637049, -0.240585637190076, -0.214507049619293, -0.228476323330312, -0.223235445346107, -0.216116483840334, -0.206903836810903, -0.223553828183343, -0.236937609127783, -0.217652789023588, -0.211982652566286, -0.245995223308316, -0.206187718714279, -0.227670670439422},
{-0.0843931919568687, -0.0342164464991033, 0.393702284928246, -0.166018266253027, 0.0500896782860136, -0.262731388032538, 0.030139964190519, -0.253997503551094, -0.0932603349591988, -0.32884667697173, 0.199966846276877, -0.117543453869516, 0.196248237055757, -0.456448703853250, 0.139286961076387, 0.241166801918811, -0.0783508285295053, 0.377438091416498, 0.109499076984234, 0.128581669647144},
{-0.0690428674271772, 0.0133858672878363, -0.208289917312908, 0.161232925220819, 0.0735806288007248, -0.316269599838174, -0.0640708424745702, -0.117078801507436, 0.360805085405857, 0.336899760384943, 0.0332447078185156, 0.132954055834276, 0.00595209121998118, -0.157755611190327, -0.199839273133436, 0.193688928807663, 0.0970290928040946, 0.374683975138541, -0.478110944870958, -0.243290196936098},
{0.117284581850481, 0.310399467781876, -0.143513477698805, 0.088808130300351, 0.105747812943691, -0.373871701179853, 0.189069306295134, 0.133258225034741, -0.213043549687694, 0.301303731259140, -0.182085224761849, -0.161971915020789, 0.229301173581378, -0.293586313243755, -0.0260480060747498, -0.0217953684540699, 0.0202675755458796, -0.160134624443657, 0.431950096999465, -0.329885160320501},
{0.256496969244703, 0.0907408349583135, 0.0135731083898029, 0.477557831930769, -0.0727379669280703, 0.101732675207959, -0.147293025369251, -0.348325291603251, -0.255678082078362, -0.187092643740172, -0.177164064346593, -0.225921480146133, 0.422318841046522, 0.319959853469398, -0.0623652546300045, 0.0824203908606883, -0.102057926881110, 0.120728407576411, -0.156845807891241, -0.123528163091204},
{-0.00906668858975576, -0.0814722888231236, -0.0762715085459023, 0.055819989938286, -0.0540516675257271, -0.0070589302769034, -0.315813159989213, -0.0103527463419808, -0.194634331372293, -0.0185860407566822, 0.50134169352609, 0.384531812730061, -0.0405008616742061, 0.0781033650669525, 0.069334900096687, 0.396455180448549, -0.204065801866462, -0.215272089630713, 0.171046818996465, -0.396393364716348},
{0.201971098571663, 0.489747667606921, 0.00226258734592836, 0.0969514005747054, 0.0853921636903791, 0.0862068740282345, -0.465412154271164, -0.130516676347786, 0.165513616974634, 0.0712238027886633, 0.140746943067963, -0.325919272273406, -0.421213488261598, -0.163508199065965, 0.269695802810568, -0.110296405171437, -0.106834099902202, 0.00509414588152415, 0.00909215239544615, 0.0500401865589727},
{0.515854176692456, -0.087468413428258, 0.102796468891449, -0.06046105990993, -0.212014383772414, -0.259853648383794, -0.0997372883043333, -0.109934574535736, 0.284891018406112, -0.250578342940183, 0.142174204994568, 0.210384918947619, 0.118803190788946, -0.0268434355996836, 0.0103721198836548, -0.355555176478458, 0.428042332431476, -0.150610175411631, 0.0464090887952940, -0.140238796382057},
{-0.239392215229762, -0.315483492656425, 0.100205194952396, 0.197830195325302, 0.40178804665223, 0.195809461460298, -0.407817115321684, 0.0226836686147386, -0.169780276210306, 0.0818161585952184, -0.172886230584939, 0.174982644851064, 0.0868786992159535, -0.198450519980824, 0.168581078329968, -0.361514336004068, 0.238668430084722, 0.165494019791904, 0.110437707249228, -0.169592003035203},
{-0.313151735678025, 0.10757884850664, -0.49249098807229, 0.0993472335619114, -0.148695715250836, 0.0573801136941699, -0.190040373500722, 0.254848437434773, 0.134147888304352, -0.352719341442756, 0.0839609323513986, -0.207904182300122, 0.253940523323376, -0.109832138553288, 0.0980084518687944, 0.209026594443723, 0.406236051871548, -0.0521120230935943, 0.0554108014592302, 0.134681046631955},
{-0.102905214421384, 0.235803606800009, 0.213414976431981, -0.253606415825635, 0.00945656859370683, 0.259551282655855, 0.159527348902192, 0.083218761193016, -0.286815935191867, 0.0135069477264877, 0.336758103107357, -0.271707359524149, -0.0400009875851839, 0.0871186292716414, -0.171506310409388, -0.0954276577211755, 0.393467571460712, 0.111732846649458, -0.239886066474217, -0.426474828195231},
{-0.0130795552324104, 0.0758967690968058, -0.165099404017689, -0.46035152559912, 0.409888158016031, -0.0235053940299396, 0.0699393201709723, -0.161320910316996, 0.226111732196825, -0.177811841258496, -0.219073917645916, -0.00703219376737286, 0.162831878334912, 0.271670554900684, 0.451033612762052, 0.0820942662443393, -0.0904983490498446, -0.0587000279313978, -0.0938852980928252, -0.306078621571843},
{0.345092040577428, -0.257721588971295, -0.301689123771848, -0.0875212184538126, 0.161012613069275, 0.385104899829821, 0.118355290985046, -0.241723794416731, 0.083201920119646, -0.0809095291508749, -0.0820275390511991, -0.115569770103317, -0.250105681098033, -0.164197583037664, -0.299481453795592, 0.255906951902366, 0.129042051416371, 0.203761730442746, 0.347550071284268, -0.109264854744020},
{0.056345924962239, 0.072536751679082, 0.303127492633681, -0.368877185781648, -0.343024497082421, 0.206879529669083, -0.413012709639426, 0.078538816203612, 0.103382383425097, 0.288319996147499, -0.392663258459423, 0.0319588502083897, 0.220316797792669, -0.0563686494606947, -0.0869286063283735, 0.323677017794391, 0.0984875197088935, -0.0303289828821742, 0.0450197853450979, -0.0261771221270139},
{-0.253701638374729, -0.148922815783583, 0.111794052194159, 0.157313977830326, -0.269846001260543, -0.222989872703583, 0.115441028189268, -0.350456582262355, -0.0409581422905941, 0.174078744248002, -0.130673397086811, -0.123963802708056, -0.351609207081548, 0.281548012920868, 0.340382662112428, 0.180262131025562, 0.3895263830793, 0.0121546812430960, 0.214830943227063, -0.0617782909660214},
{-0.025854479416026, 0.480654788977767, -0.138024550829229, -0.130191670810919, 0.107816875829919, -0.111243997319276, -0.0679814460571245, -0.183167991080677, -0.363355166018786, -0.183934891092050, -0.216097125080962, 0.520240628803255, -0.179616013606479, 0.0664131536100941, -0.178350708111064, 0.0352047611606709, 0.223857228692892, 0.128363679623513, -0.000403433628490731, 0.224972110977704},
{0.159207394033448, -0.0371517305736114, -0.294302634912281, -0.0866954375908417, -0.259998567870054, 0.284966673982689, 0.205356416771391, -0.257613708650298, -0.264820519037270, 0.293359248624603, 0.0997476397434102, 0.151390539497369, 0.165571346773648, -0.347569523551258, 0.43792310820533, -0.0723248163210163, 0.0379214984816955, -0.0542758730251438, -0.258020301801603, 0.128680501102363},
{0.316853842351797, -0.153950010941153, -0.13387065213508, -0.0702971390607613, -0.202558481846057, -0.172941438694837, -0.068882524588574, 0.524738203063889, -0.271670479920716, -0.112864756695310, -0.146831636946145, -0.0352336188578041, -0.211108490884767, 0.097857111349555, 0.276459740956662, 0.0231297536754823, -0.0773173324868396, 0.487208384389438, -0.0734191389266824, -0.113198765573319},
{-0.274285525741087, 0.227334266052039, -0.0973746625709059, -0.00965256583655389, -0.402438444750043, 0.198586229519026, 0.0958135064575833, -0.108934376958686, 0.253641732094319, -0.0551918478254021, 0.0243640218331436, 0.181936272247179, 0.090952738347629, 0.0603352483029044, -0.0043821671755761, -0.347720824658591, -0.267879988539971, 0.403804652116592, 0.337654323971186, -0.241509293972297},
{-0.0197089518344238, 0.139681034626696, 0.251980475788267, 0.341846624362846, -0.075141195125153, 0.2184951591319, 0.268870823491343, 0.150392399018138, 0.134592404015057, -0.337050200539163, -0.313109373497998, 0.201993318439135, -0.217140733851970, -0.337622749083808, 0.135253284365068, 0.181729249828045, -0.00627813335422765, -0.197218833324039, -0.194060005031698, -0.303055888528004}
},
/*eigenval*/
{
20.29131, 0.5045685, 0.2769945, 0.1551147, 0.03235484, -0.04127639, -0.3516426, -0.469973, -0.5835191, -0.6913107, -0.7207972, -0.7907875, -0.9524307, -1.095310, -1.402153, -1.424179, -1.936704, -2.037965, -3.273561, -5.488734
},
/*eigentot and codeFreq left out, these are initialized elsewhere*/
};
/* The JTT92 matrix, D. T. Jones, W. R. Taylor, & J. M. Thorton, CABIOS 8:275 (1992)
Derived from the PhyML source code (models.c) by filling in the other side of the symmetric matrix,
scaling the entries by the stationary rate (to give the rate of a->b not b|a), to set the diagonals
so the rows sum to 0, to rescale the matrix so that the implied rate of evolution is 1.
The resulting matrix is the transpose (I think).
*/
#if 0
{
int i,j;
for (i=0; i<20; i++) for (j=0; j<i; j++) daa[j*20+i] = daa[i*20+j];
for (i = 0; i < 20; i++) for (j = 0; j < 20; j++) daa[i*20+j] *= pi[j] / 100.0;
double mr = 0; /* mean rate */
for (i = 0; i < 20; i++) {
double sum = 0;
for (j = 0; j < 20; j++)
sum += daa[i*20+j];
daa[i*20+i] = -sum;
mr += pi[i] * sum;
}
for (i = 0; i < 20*20; i++)
daa[i] /= mr;
}
#endif
double statJTT92[MAXCODES] = {0.07674789,0.05169087,0.04264509,0.05154407,0.01980301,0.04075195,0.06182989,0.07315199,0.02294399,0.05376110,0.09190390,0.05867583,0.02382594,0.04012589,0.05090097,0.06876503,0.05856501,0.01426057,0.03210196,0.06600504};
double matrixJTT92[MAXCODES][MAXCODES] = {
{ -1.247831,0.044229,0.041179,0.061769,0.042704,0.043467,0.08007,0.136501,0.02059,0.027453,0.022877,0.02669,0.041179,0.011439,0.14794,0.288253,0.362223,0.006863,0.008388,0.227247 },
{ 0.029789,-1.025965,0.023112,0.008218,0.058038,0.159218,0.014895,0.070364,0.168463,0.011299,0.019517,0.33179,0.022599,0.002568,0.038007,0.051874,0.032871,0.064714,0.010272,0.008731 },
{ 0.022881,0.019068,-1.280568,0.223727,0.014407,0.03644,0.024576,0.034322,0.165676,0.019915,0.005085,0.11144,0.012712,0.004237,0.006356,0.213134,0.098304,0.00339,0.029661,0.00678 },
{ 0.041484,0.008194,0.270413,-1.044903,0.005121,0.025095,0.392816,0.066579,0.05736,0.005634,0.003585,0.013316,0.007682,0.002049,0.007682,0.030217,0.019462,0.002049,0.023559,0.015877 },
{ 0.011019,0.022234,0.00669,0.001968,-0.56571,0.001771,0.000984,0.011609,0.013577,0.003345,0.004526,0.001377,0.0061,0.015348,0.002755,0.043878,0.008264,0.022628,0.041124,0.012199 },
{ 0.02308,0.125524,0.034823,0.019841,0.003644,-1.04415,0.130788,0.010528,0.241735,0.003644,0.029154,0.118235,0.017411,0.00162,0.066406,0.021461,0.020651,0.007288,0.009718,0.008098 },
{ 0.064507,0.017816,0.035632,0.471205,0.003072,0.198435,-0.944343,0.073107,0.015973,0.007372,0.005529,0.111197,0.011058,0.003072,0.011058,0.01843,0.019659,0.006143,0.0043,0.027646 },
{ 0.130105,0.099578,0.058874,0.09449,0.042884,0.018898,0.086495,-0.647831,0.016717,0.004361,0.004361,0.019625,0.010176,0.003634,0.017444,0.146096,0.023986,0.039976,0.005815,0.034162 },
{ 0.006155,0.074775,0.089138,0.025533,0.01573,0.1361,0.005927,0.005243,-1.135695,0.003648,0.012767,0.010259,0.007523,0.009119,0.026217,0.016642,0.010487,0.001824,0.130629,0.002508 },
{ 0.01923,0.011752,0.025106,0.005876,0.009081,0.004808,0.00641,0.003205,0.008547,-1.273602,0.122326,0.011218,0.25587,0.047542,0.005342,0.021367,0.130873,0.004808,0.017094,0.513342 },
{ 0.027395,0.0347,0.010958,0.006392,0.021003,0.065748,0.008219,0.005479,0.051137,0.209115,-0.668139,0.012784,0.354309,0.226465,0.093143,0.053877,0.022829,0.047485,0.021916,0.16437 },
{ 0.020405,0.376625,0.153332,0.015158,0.004081,0.170239,0.105525,0.015741,0.026235,0.012243,0.008162,-0.900734,0.037896,0.002332,0.012243,0.027401,0.06005,0.00583,0.004664,0.008162 },
{ 0.012784,0.010416,0.007102,0.003551,0.007339,0.01018,0.004261,0.003314,0.007812,0.113397,0.091854,0.015388,-1.182051,0.01018,0.003788,0.006865,0.053503,0.005682,0.004261,0.076466 },
{ 0.00598,0.001993,0.003987,0.001595,0.031098,0.001595,0.001993,0.001993,0.015948,0.035484,0.098877,0.001595,0.017144,-0.637182,0.006778,0.03668,0.004784,0.021131,0.213701,0.024719 },
{ 0.098117,0.037426,0.007586,0.007586,0.007081,0.082944,0.009104,0.012138,0.058162,0.005058,0.051587,0.010621,0.008092,0.008598,-0.727675,0.144141,0.059679,0.003035,0.005058,0.011632 },
{ 0.258271,0.069009,0.343678,0.040312,0.152366,0.036213,0.020498,0.137334,0.049878,0.02733,0.040312,0.032113,0.019814,0.06286,0.194728,-1.447863,0.325913,0.023914,0.043045,0.025964 },
{ 0.276406,0.037242,0.135003,0.022112,0.02444,0.029677,0.018621,0.019203,0.026768,0.142567,0.014548,0.059936,0.131511,0.006983,0.068665,0.27757,-1.335389,0.006983,0.01222,0.065174 },
{ 0.001275,0.017854,0.001134,0.000567,0.016295,0.002551,0.001417,0.007793,0.001134,0.001275,0.007368,0.001417,0.003401,0.00751,0.00085,0.004959,0.0017,-0.312785,0.010061,0.003542 },
{ 0.003509,0.006379,0.022328,0.014673,0.066664,0.007655,0.002233,0.002552,0.182769,0.010207,0.007655,0.002552,0.005741,0.170967,0.00319,0.020095,0.006698,0.022647,-0.605978,0.005103 },
{ 0.195438,0.011149,0.010493,0.020331,0.040662,0.013117,0.029512,0.030824,0.007214,0.630254,0.11805,0.009182,0.211834,0.040662,0.015084,0.024922,0.073453,0.016396,0.010493,-1.241722 }
};
double statWAG01[MAXCODES] = {0.0866279,0.043972, 0.0390894,0.0570451,0.0193078,0.0367281,0.0580589,0.0832518,0.0244314,0.048466, 0.086209, 0.0620286,0.0195027,0.0384319,0.0457631,0.0695179,0.0610127,0.0143859,0.0352742,0.0708956};
double matrixWAG01[MAXCODES][MAXCODES] = {
{-1.117151, 0.050147, 0.046354, 0.067188, 0.093376, 0.082607, 0.143908, 0.128804, 0.028817, 0.017577, 0.036177, 0.082395, 0.081234, 0.019138, 0.130789, 0.306463, 0.192846, 0.010286, 0.021887, 0.182381},
{0.025455, -0.974318, 0.029321, 0.006798, 0.024376, 0.140086, 0.020267, 0.026982, 0.098628, 0.008629, 0.022967, 0.246964, 0.031527, 0.004740, 0.031358, 0.056495, 0.025586, 0.053714, 0.017607, 0.011623},
{0.020916, 0.026065, -1.452438, 0.222741, 0.010882, 0.063328, 0.038859, 0.046176, 0.162306, 0.022737, 0.005396, 0.123567, 0.008132, 0.003945, 0.008003, 0.163042, 0.083283, 0.002950, 0.044553, 0.008051},
{0.044244, 0.008819, 0.325058, -0.989665, 0.001814, 0.036927, 0.369645, 0.051822, 0.055719, 0.002361, 0.005077, 0.028729, 0.006212, 0.002798, 0.025384, 0.064166, 0.022443, 0.007769, 0.019500, 0.009120},
{0.020812, 0.010703, 0.005375, 0.000614, -0.487357, 0.002002, 0.000433, 0.006214, 0.005045, 0.003448, 0.007787, 0.001500, 0.007913, 0.008065, 0.002217, 0.028525, 0.010395, 0.014531, 0.011020, 0.020307},
{0.035023, 0.117008, 0.059502, 0.023775, 0.003809, -1.379785, 0.210830, 0.012722, 0.165524, 0.004391, 0.033516, 0.150135, 0.059565, 0.003852, 0.035978, 0.039660, 0.033070, 0.008316, 0.008777, 0.011613},
{0.096449, 0.026759, 0.057716, 0.376214, 0.001301, 0.333275, -1.236894, 0.034593, 0.034734, 0.007763, 0.009400, 0.157479, 0.019202, 0.004944, 0.041578, 0.042955, 0.050134, 0.009540, 0.011961, 0.035874},
{0.123784, 0.051085, 0.098345, 0.075630, 0.026795, 0.028838, 0.049604, -0.497615, 0.021792, 0.002661, 0.005356, 0.032639, 0.015212, 0.004363, 0.021282, 0.117240, 0.019732, 0.029444, 0.009052, 0.016361},
{0.008127, 0.054799, 0.101443, 0.023863, 0.006384, 0.110105, 0.014616, 0.006395, -0.992342, 0.003543, 0.012807, 0.022832, 0.010363, 0.017420, 0.017851, 0.018979, 0.012136, 0.006733, 0.099319, 0.003035},
{0.009834, 0.009511, 0.028192, 0.002006, 0.008654, 0.005794, 0.006480, 0.001549, 0.007029, -1.233162, 0.161294, 0.016472, 0.216559, 0.053891, 0.005083, 0.016249, 0.074170, 0.010808, 0.021372, 0.397837},
{0.036002, 0.045028, 0.011900, 0.007673, 0.034769, 0.078669, 0.013957, 0.005547, 0.045190, 0.286902, -0.726011, 0.023303, 0.439180, 0.191376, 0.037625, 0.031191, 0.029552, 0.060196, 0.036066, 0.162890},
{0.058998, 0.348377, 0.196082, 0.031239, 0.004820, 0.253558, 0.168246, 0.024319, 0.057967, 0.021081, 0.016767, -1.124580, 0.060821, 0.005783, 0.036254, 0.062960, 0.090292, 0.008952, 0.008675, 0.019884},
{0.018288, 0.013983, 0.004057, 0.002124, 0.007993, 0.031629, 0.006450, 0.003564, 0.008272, 0.087143, 0.099354, 0.019123, -1.322098, 0.024370, 0.003507, 0.010109, 0.031033, 0.010556, 0.008769, 0.042133},
{0.008490, 0.004143, 0.003879, 0.001885, 0.016054, 0.004030, 0.003273, 0.002014, 0.027402, 0.042734, 0.085315, 0.003583, 0.048024, -0.713669, 0.006512, 0.022020, 0.006934, 0.061698, 0.260332, 0.026213},
{0.069092, 0.032635, 0.009370, 0.020364, 0.005255, 0.044829, 0.032773, 0.011698, 0.033438, 0.004799, 0.019973, 0.026747, 0.008229, 0.007754, -0.605590, 0.077484, 0.038202, 0.006695, 0.010376, 0.015124},
{0.245933, 0.089317, 0.289960, 0.078196, 0.102703, 0.075066, 0.051432, 0.097899, 0.054003, 0.023306, 0.025152, 0.070562, 0.036035, 0.039831, 0.117705, -1.392239, 0.319421, 0.038212, 0.057419, 0.016981},
{0.135823, 0.035501, 0.129992, 0.024004, 0.032848, 0.054936, 0.052685, 0.014461, 0.030308, 0.093371, 0.020915, 0.088814, 0.097083, 0.011008, 0.050931, 0.280341, -1.154973, 0.007099, 0.018643, 0.088894},
{0.001708, 0.017573, 0.001086, 0.001959, 0.010826, 0.003257, 0.002364, 0.005088, 0.003964, 0.003208, 0.010045, 0.002076, 0.007786, 0.023095, 0.002105, 0.007908, 0.001674, -0.466694, 0.037525, 0.005516},
{0.008912, 0.014125, 0.040205, 0.012058, 0.020133, 0.008430, 0.007267, 0.003836, 0.143398, 0.015555, 0.014757, 0.004934, 0.015861, 0.238943, 0.007998, 0.029135, 0.010779, 0.092011, -0.726275, 0.011652},
{0.149259, 0.018739, 0.014602, 0.011335, 0.074565, 0.022417, 0.043805, 0.013932, 0.008807, 0.581952, 0.133956, 0.022726, 0.153161, 0.048356, 0.023429, 0.017317, 0.103293, 0.027186, 0.023418, -1.085487},
};
/* Le-Gascuel 2008 model data from Harry Yoo
https://github.com/hyoo/FastTree
*/
double statLG08[MAXCODES] = {0.079066, 0.055941, 0.041977, 0.053052, 0.012937, 0.040767, 0.071586, 0.057337, 0.022355, 0.062157, 0.099081, 0.0646, 0.022951, 0.042302, 0.04404, 0.061197, 0.053287, 0.012066, 0.034155, 0.069147};
double matrixLG08[MAXCODES][MAXCODES] = {
{-1.08959879,0.03361031,0.02188683,0.03124237,0.19680136,0.07668542,0.08211337,0.16335306,0.02837339,0.01184642,0.03125763,0.04242021,0.08887270,0.02005907,0.09311189,0.37375830,0.16916131,0.01428853,0.01731216,0.20144931},
{0.02378006,-0.88334349,0.04206069,0.00693409,0.02990323,0.15707674,0.02036079,0.02182767,0.13574610,0.00710398,0.01688563,0.35388551,0.02708281,0.00294931,0.01860218,0.04800569,0.03238902,0.03320688,0.01759004,0.00955956},
{0.01161996,0.03156149,-1.18705869,0.21308090,0.02219603,0.07118238,0.02273938,0.06034785,0.18928374,0.00803870,0.00287235,0.09004368,0.01557359,0.00375798,0.00679131,0.16825837,0.08398226,0.00190474,0.02569090,0.00351296},
{0.02096312,0.00657599,0.26929909,-0.86328733,0.00331871,0.02776660,0.27819699,0.04482489,0.04918511,0.00056712,0.00079981,0.01501150,0.00135537,0.00092395,0.02092662,0.06579888,0.02259266,0.00158572,0.00716768,0.00201422},
{0.03220119,0.00691547,0.00684065,0.00080928,-0.86781864,0.00109716,0.00004527,0.00736456,0.00828668,0.00414794,0.00768465,0.00017162,0.01156150,0.01429859,0.00097521,0.03602269,0.01479316,0.00866942,0.01507844,0.02534728},
{0.03953956,0.11446966,0.06913053,0.02133682,0.00345736,-1.24953177,0.16830979,0.01092385,0.19623161,0.00297003,0.02374496,0.13185209,0.06818543,0.00146170,0.02545052,0.04989165,0.04403378,0.00962910,0.01049079,0.00857458},
{0.07434507,0.02605508,0.03877888,0.37538659,0.00025048,0.29554848,-0.84254259,0.02497249,0.03034386,0.00316875,0.00498760,0.12936820,0.01243696,0.00134660,0.03002373,0.04380857,0.04327684,0.00557310,0.00859294,0.01754095},
{0.11846020,0.02237238,0.08243001,0.04844538,0.03263985,0.01536392,0.02000178,-0.50414422,0.01785951,0.00049912,0.00253779,0.01700817,0.00800067,0.00513658,0.01129312,0.09976552,0.00744439,0.01539442,0.00313512,0.00439779},
{0.00802225,0.05424651,0.10080372,0.02072557,0.01431930,0.10760560,0.00947583,0.00696321,-1.09324335,0.00243405,0.00818899,0.01558729,0.00989143,0.01524917,0.01137533,0.02213166,0.01306114,0.01334710,0.11863394,0.00266053},
{0.00931296,0.00789336,0.01190322,0.00066446,0.01992916,0.00452837,0.00275137,0.00054108,0.00676776,-1.41499789,0.25764421,0.00988722,0.26563382,0.06916358,0.00486570,0.00398456,0.06425393,0.00694043,0.01445289,0.66191466},
{0.03917027,0.02990732,0.00677980,0.00149374,0.05885464,0.05771026,0.00690325,0.00438541,0.03629495,0.41069624,-0.79375308,0.01362360,0.62543296,0.25688578,0.02467704,0.01806113,0.03001512,0.06139358,0.02968934,0.16870919},
{0.03465896,0.40866276,0.13857164,0.01827910,0.00085698,0.20893479,0.11674330,0.01916263,0.04504313,0.01027583,0.00888247,-0.97644156,0.04241650,0.00154510,0.02521473,0.04836478,0.07344114,0.00322392,0.00852278,0.01196402},
{0.02579765,0.01111131,0.00851489,0.00058635,0.02051079,0.03838702,0.00398738,0.00320253,0.01015515,0.09808327,0.14487451,0.01506968,-1.54195698,0.04128536,0.00229163,0.00796306,0.04636929,0.01597787,0.01104642,0.04357735},
{0.01073203,0.00223024,0.00378708,0.00073673,0.04675419,0.00151673,0.00079574,0.00378966,0.02885576,0.04707045,0.10967574,0.00101178,0.07609486,-0.81061579,0.00399600,0.01530562,0.00697985,0.10394083,0.33011973,0.02769432},
{0.05186360,0.01464471,0.00712508,0.01737179,0.00331981,0.02749383,0.01847072,0.00867414,0.02240973,0.00344749,0.01096857,0.01718973,0.00439734,0.00416018,-0.41664685,0.05893117,0.02516738,0.00418956,0.00394655,0.01305787},
{0.28928853,0.05251612,0.24529879,0.07590089,0.17040121,0.07489439,0.03745080,0.10648187,0.06058559,0.00392302,0.01115539,0.04581702,0.02123285,0.02214217,0.08188943,-1.42842431,0.39608294,0.01522956,0.02451220,0.00601987},
{0.11400727,0.03085239,0.10660988,0.02269274,0.06093244,0.05755704,0.03221430,0.00691855,0.03113348,0.05508469,0.01614250,0.06057985,0.10765893,0.00879238,0.03045173,0.34488735,-1.23444419,0.00750412,0.01310009,0.11660005},
{0.00218053,0.00716244,0.00054751,0.00036065,0.00808574,0.00284997,0.00093936,0.00323960,0.00720403,0.00134729,0.00747646,0.00060216,0.00840002,0.02964754,0.00114785,0.00300276,0.00169919,-0.44275283,0.03802969,0.00228662},
{0.00747852,0.01073967,0.02090366,0.00461457,0.03980863,0.00878929,0.00409985,0.00186756,0.18125441,0.00794180,0.01023445,0.00450612,0.01643896,0.26654152,0.00306072,0.01368064,0.00839668,0.10764993,-0.71435091,0.00851526},
{0.17617706,0.01181629,0.00578676,0.00262530,0.13547871,0.01454379,0.01694332,0.00530363,0.00822937,0.73635171,0.11773937,0.01280613,0.13129028,0.04526924,0.02050210,0.00680190,0.15130413,0.01310401,0.01723920,-1.33539639}
}; |
softmax_layer.c | #include "softmax_layer.h"
#include "blas.h"
#include "dark_cuda.h"
#include "utils.h"
#include "blas.h"
#include <float.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#define SECRET_NUM -1234
void softmax_tree(float *input, int batch, int inputs, float temp, tree *hierarchy, float *output)
{
int b;
for (b = 0; b < batch; ++b) {
int i;
int count = 0;
for (i = 0; i < hierarchy->groups; ++i) {
int group_size = hierarchy->group_size[i];
softmax(input + b*inputs + count, group_size, temp, output + b*inputs + count, 1);
count += group_size;
}
}
}
softmax_layer make_softmax_layer(int batch, int inputs, int groups)
{
assert(inputs%groups == 0);
fprintf(stderr, "softmax %4d\n", inputs);
softmax_layer l = { (LAYER_TYPE)0 };
l.type = SOFTMAX;
l.batch = batch;
l.groups = groups;
l.inputs = inputs;
l.outputs = inputs;
l.loss = (float*)xcalloc(inputs * batch, sizeof(float));
l.output = (float*)xcalloc(inputs * batch, sizeof(float));
l.delta = (float*)xcalloc(inputs * batch, sizeof(float));
l.cost = (float*)xcalloc(1, sizeof(float));
l.forward = forward_softmax_layer;
l.backward = backward_softmax_layer;
#ifdef GPU
l.forward_gpu = forward_softmax_layer_gpu;
l.backward_gpu = backward_softmax_layer_gpu;
l.output_gpu = cuda_make_array(l.output, inputs*batch);
l.loss_gpu = cuda_make_array(l.loss, inputs*batch);
l.delta_gpu = cuda_make_array(l.delta, inputs*batch);
#endif
return l;
}
void forward_softmax_layer(const softmax_layer l, network_state net)
{
if(l.softmax_tree){
int i;
int count = 0;
for (i = 0; i < l.softmax_tree->groups; ++i) {
int group_size = l.softmax_tree->group_size[i];
softmax_cpu(net.input + count, group_size, l.batch, l.inputs, 1, 0, 1, l.temperature, l.output + count);
count += group_size;
}
} else {
softmax_cpu(net.input, l.inputs/l.groups, l.batch, l.inputs, l.groups, l.inputs/l.groups, 1, l.temperature, l.output);
}
if(net.truth && !l.noloss){
softmax_x_ent_cpu(l.batch*l.inputs, l.output, net.truth, l.delta, l.loss);
l.cost[0] = sum_array(l.loss, l.batch*l.inputs);
}
}
void backward_softmax_layer(const softmax_layer l, network_state net)
{
axpy_cpu(l.inputs*l.batch, 1, l.delta, 1, net.delta, 1);
}
#ifdef GPU
void pull_softmax_layer_output(const softmax_layer layer)
{
cuda_pull_array(layer.output_gpu, layer.output, layer.inputs*layer.batch);
}
void forward_softmax_layer_gpu(const softmax_layer l, network_state net)
{
if(l.softmax_tree){
softmax_tree_gpu(net.input, 1, l.batch, l.inputs, l.temperature, l.output_gpu, *l.softmax_tree);
/*
int i;
int count = 0;
for (i = 0; i < l.softmax_tree->groups; ++i) {
int group_size = l.softmax_tree->group_size[i];
softmax_gpu(net.input_gpu + count, group_size, l.batch, l.inputs, 1, 0, 1, l.temperature, l.output_gpu + count);
count += group_size;
}
*/
} else {
if(l.spatial){
softmax_gpu_new_api(net.input, l.c, l.batch*l.c, l.inputs/l.c, l.w*l.h, 1, l.w*l.h, 1, l.output_gpu);
}else{
softmax_gpu_new_api(net.input, l.inputs/l.groups, l.batch, l.inputs, l.groups, l.inputs/l.groups, 1, l.temperature, l.output_gpu);
}
}
if(net.truth && !l.noloss){
softmax_x_ent_gpu(l.batch*l.inputs, l.output_gpu, net.truth, l.delta_gpu, l.loss_gpu);
if(l.softmax_tree){
mask_gpu_new_api(l.batch*l.inputs, l.delta_gpu, SECRET_NUM, net.truth, 0);
mask_gpu_new_api(l.batch*l.inputs, l.loss_gpu, SECRET_NUM, net.truth, 0);
}
cuda_pull_array(l.loss_gpu, l.loss, l.batch*l.inputs);
l.cost[0] = sum_array(l.loss, l.batch*l.inputs);
}
}
void backward_softmax_layer_gpu(const softmax_layer layer, network_state state)
{
axpy_ongpu(layer.batch*layer.inputs, state.net.loss_scale, layer.delta_gpu, 1, state.delta, 1);
}
#endif
// -------------------------------------
// Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf
contrastive_layer make_contrastive_layer(int batch, int w, int h, int c, int classes, int inputs, layer *yolo_layer)
{
contrastive_layer l = { (LAYER_TYPE)0 };
l.type = CONTRASTIVE;
l.batch = batch;
l.inputs = inputs;
l.w = w;
l.h = h;
l.c = c;
l.temperature = 1;
l.max_boxes = 0;
if (yolo_layer) {
l.detection = 1;
l.max_boxes = yolo_layer->max_boxes;
l.labels = yolo_layer->labels; // track id
l.n = yolo_layer->n; // num of embeddings per cell = num of anchors
l.classes = yolo_layer->classes;// num of classes
classes = l.classes;
l.embedding_size = l.inputs / (l.n*l.h*l.w);
l.truths = yolo_layer->truths;
if (l.embedding_size != yolo_layer->embedding_size) {
printf(" Error: [contrastive] embedding_size=%d isn't equal to [yolo] embedding_size=%d. They should use the same [convolutional] layer \n", l.embedding_size, yolo_layer->embedding_size);
getchar();
exit(0);
}
if (l.inputs % (l.n*l.h*l.w) != 0) {
printf(" Warning: filters= number in the previous (embedding) layer isn't divisable by number of anchors %d \n", l.n);
getchar();
}
}
else {
l.detection = 0;
l.labels = (int*)xcalloc(l.batch, sizeof(int)); // labels
l.n = 1; // num of embeddings per cell
l.classes = classes; // num of classes
l.embedding_size = l.c;
}
l.outputs = inputs;
l.loss = (float*)xcalloc(1, sizeof(float));
l.output = (float*)xcalloc(inputs * batch, sizeof(float));
l.delta = (float*)xcalloc(inputs * batch, sizeof(float));
l.cost = (float*)xcalloc(1, sizeof(float));
const size_t step = l.batch*l.n*l.h*l.w;
l.cos_sim = NULL;
l.exp_cos_sim = NULL;
l.p_constrastive = NULL;
if (!l.detection) {
l.cos_sim = (float*)xcalloc(step*step, sizeof(float));
l.exp_cos_sim = (float*)xcalloc(step*step, sizeof(float));
l.p_constrastive = (float*)xcalloc(step*step, sizeof(float));
}
//l.p_constrastive = (float*)xcalloc(step*step, sizeof(float));
//l.contrast_p_size = (int*)xcalloc(1, sizeof(int));
//*l.contrast_p_size = step;
//l.contrast_p = (contrastive_params*)xcalloc(*l.contrast_p_size, sizeof(contrastive_params));
l.forward = forward_contrastive_layer;
l.backward = backward_contrastive_layer;
#ifdef GPU
l.forward_gpu = forward_contrastive_layer_gpu;
l.backward_gpu = backward_contrastive_layer_gpu;
l.output_gpu = cuda_make_array(l.output, inputs*batch);
l.delta_gpu = cuda_make_array(l.delta, inputs*batch);
const int max_contr_size = (l.max_boxes*l.batch)*(l.max_boxes*l.batch) * sizeof(contrastive_params)/4;
printf(" max_contr_size = %d MB \n", max_contr_size / (1024*1024));
l.contrast_p_gpu = (contrastive_params *)cuda_make_array(NULL, max_contr_size);
#endif
fprintf(stderr, "contrastive %4d x%4d x%4d x emb_size %4d x batch: %4d classes = %4d, step = %4d \n", w, h, l.n, l.embedding_size, batch, l.classes, step);
if(l.detection) fprintf(stderr, "detection \n");
return l;
}
static inline float clip_value(float val, const float max_val)
{
if (val > max_val) {
//printf("\n val = %f > max_val = %f \n", val, max_val);
val = max_val;
}
else if (val < -max_val) {
//printf("\n val = %f < -max_val = %f \n", val, -max_val);
val = -max_val;
}
return val;
}
void forward_contrastive_layer(contrastive_layer l, network_state state)
{
if (!state.train) return;
const float truth_thresh = state.net.label_smooth_eps;
const int mini_batch = l.batch / l.steps;
int b, n, w, h;
fill_cpu(l.batch*l.inputs, 0, l.delta, 1);
if (!l.detection) {
for (b = 0; b < l.batch; ++b) {
if (state.net.adversarial) l.labels[b] = b % 2;
else l.labels[b] = b / 2;
}
// set labels
for (b = 0; b < l.batch; ++b) {
for (h = 0; h < l.h; ++h) {
for (w = 0; w < l.w; ++w)
{
// find truth with max prob (only 1 label even if mosaic is used)
float max_truth = 0;
int n;
for (n = 0; n < l.classes; ++n) {
const float truth_prob = state.truth[b*l.classes + n];
//printf(" truth_prob = %f, ", truth_prob);
//if (truth_prob > max_truth)
if (truth_prob > truth_thresh)
{
//printf(" truth_prob = %f, max_truth = %f, n = %d; ", truth_prob, max_truth, n);
max_truth = truth_prob;
l.labels[b] = n;
}
}
//printf(", l.labels[b] = %d ", l.labels[b]);
}
}
}
}
//printf("\n\n");
// set pointers to features
float **z = (float**)xcalloc(l.batch*l.n*l.h*l.w, sizeof(float*));
for (b = 0; b < l.batch; ++b) {
for (n = 0; n < l.n; ++n) {
for (h = 0; h < l.h; ++h) {
for (w = 0; w < l.w; ++w)
{
const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w;
if (l.labels[z_index] < 0) continue;
//const int input_index = b*l.inputs + n*l.embedding_size*l.h*l.w + h*l.w + w;
//float *ptr = state.input + input_index;
//z[z_index] = ptr;
z[z_index] = (float*)xcalloc(l.embedding_size, sizeof(float));
get_embedding(state.input, l.w, l.h, l.c, l.embedding_size, w, h, n, b, z[z_index]);
}
}
}
}
int b2, n2, h2, w2;
int contrast_p_index = 0;
const size_t step = l.batch*l.n*l.h*l.w;
size_t contrast_p_size = step;
if (!l.detection) contrast_p_size = l.batch*l.batch;
contrastive_params *contrast_p = (contrastive_params*)xcalloc(contrast_p_size, sizeof(contrastive_params));
float *max_sim_same = (float *)xcalloc(l.batch*l.inputs, sizeof(float));
float *max_sim_diff = (float *)xcalloc(l.batch*l.inputs, sizeof(float));
fill_cpu(l.batch*l.inputs, -10, max_sim_same, 1);
fill_cpu(l.batch*l.inputs, -10, max_sim_diff, 1);
// precalculate cosine similiraty
for (b = 0; b < l.batch; ++b) {
for (n = 0; n < l.n; ++n) {
for (h = 0; h < l.h; ++h) {
for (w = 0; w < l.w; ++w)
{
const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w;
if (l.labels[z_index] < 0) continue;
for (b2 = 0; b2 < l.batch; ++b2) {
for (n2 = 0; n2 < l.n; ++n2) {
for (h2 = 0; h2 < l.h; ++h2) {
for (w2 = 0; w2 < l.w; ++w2)
{
const int z_index2 = b2*l.n*l.h*l.w + n2*l.h*l.w + h2*l.w + w2;
if (l.labels[z_index2] < 0) continue;
if (z_index == z_index2) continue;
const int time_step_i = b / mini_batch;
const int time_step_j = b2 / mini_batch;
if (time_step_i != time_step_j) continue;
const size_t step = l.batch*l.n*l.h*l.w;
const float sim = cosine_similarity(z[z_index], z[z_index2], l.embedding_size);
const float exp_sim = expf(sim / l.temperature);
if (!l.detection) {
l.cos_sim[z_index*step + z_index2] = sim;
l.exp_cos_sim[z_index*step + z_index2] = exp_sim;
}
// calc good sim
if (l.labels[z_index] == l.labels[z_index2] && max_sim_same[z_index] < sim) max_sim_same[z_index] = sim;
if (l.labels[z_index] != l.labels[z_index2] && max_sim_diff[z_index] < sim) max_sim_diff[z_index] = sim;
//printf(" z_i = %d, z_i2 = %d, l = %d, l2 = %d, sim = %f \n", z_index, z_index2, l.labels[z_index], l.labels[z_index2], sim);
contrast_p[contrast_p_index].sim = sim;
contrast_p[contrast_p_index].exp_sim = exp_sim;
contrast_p[contrast_p_index].i = z_index;
contrast_p[contrast_p_index].j = z_index2;
contrast_p[contrast_p_index].time_step_i = time_step_i;
contrast_p[contrast_p_index].time_step_j = time_step_j;
contrast_p_index++;
//printf(" contrast_p_index = %d, contrast_p_size = %d \n", contrast_p_index, contrast_p_size);
if ((contrast_p_index+1) >= contrast_p_size) {
contrast_p_size = contrast_p_index + 1;
//printf(" contrast_p_size = %d, z_index = %d, z_index2 = %d \n", contrast_p_size, z_index, z_index2);
contrast_p = (contrastive_params*)xrealloc(contrast_p, contrast_p_size * sizeof(contrastive_params));
}
if (sim > 1.001 || sim < -1.001) {
printf(" sim = %f, ", sim); getchar();
}
}
}
}
}
}
}
}
}
// calc contrastive accuracy
int i;
int good_sims = 0, all_sims = 0, same_sim = 0, diff_sim = 0;
for (i = 0; i < l.batch*l.inputs; ++i) {
if (max_sim_same[i] >= -1 && max_sim_diff[i] >= -1) {
if (max_sim_same[i] >= -1) same_sim++;
if (max_sim_diff[i] >= -1) diff_sim++;
++all_sims;
//printf(" max_sim_diff[i] = %f, max_sim_same[i] = %f \n", max_sim_diff[i], max_sim_same[i]);
if (max_sim_diff[i] < max_sim_same[i]) good_sims++;
}
}
if (all_sims > 0) {
*l.loss = 100 * good_sims / all_sims;
}
else *l.loss = -1;
printf(" Contrast accuracy = %f %%, all = %d, good = %d, same = %d, diff = %d \n", *l.loss, all_sims, good_sims, same_sim, diff_sim);
free(max_sim_same);
free(max_sim_diff);
/*
// show near sim
float good_contrast = 0;
for (b = 0; b < l.batch; b += 2) {
float same = l.cos_sim[b*l.batch + b];
float aug = l.cos_sim[b*l.batch + b + 1];
float diff = l.cos_sim[b*l.batch + b + 2];
good_contrast += (aug > diff);
//printf(" l.labels[b] = %d, l.labels[b+1] = %d, l.labels[b+2] = %d, b = %d \n", l.labels[b], l.labels[b + 1], l.labels[b + 2], b);
//printf(" same = %f, aug = %f, diff = %f, (aug > diff) = %d \n", same, aug, diff, (aug > diff));
}
*l.loss = 100 * good_contrast / (l.batch / 2);
printf(" Contrast accuracy = %f %% \n", *l.loss);
*/
/*
// precalculate P_contrastive
for (b = 0; b < l.batch; ++b) {
int b2;
for (b2 = 0; b2 < l.batch; ++b2) {
if (b != b2) {
const float P = P_constrastive(b, b2, l.labels, l.batch, z, l.embedding_size, l.temperature, l.cos_sim);
l.p_constrastive[b*l.batch + b2] = P;
if (P > 1 || P < -1) {
printf(" p = %f, ", P); getchar();
}
}
}
}
*/
const size_t contr_size = contrast_p_index;
if (l.detection) {
#ifdef GPU
const int max_contr_size = (l.max_boxes*l.batch)*(l.max_boxes*l.batch);
if (max_contr_size < contr_size) {
printf(" Error: too large number of bboxes: contr_size = %d > max_contr_size = %d \n", contr_size, max_contr_size);
exit(0);
}
int *labels = NULL;
if (contr_size > 2) {
cuda_push_array((float *)l.contrast_p_gpu, (float *)contrast_p, contr_size * sizeof(contrastive_params) / 4);
P_constrastive_f_det_gpu(labels, l.embedding_size, l.temperature, l.contrast_p_gpu, contr_size);
cuda_pull_array((float *)l.contrast_p_gpu, (float *)contrast_p, contr_size * sizeof(contrastive_params) / 4);
}
#else // GPU
int k;
//#pragma omp parallel for
for (k = 0; k < contr_size; ++k) {
contrast_p[k].P = P_constrastive_f_det(k, l.labels, z, l.embedding_size, l.temperature, contrast_p, contr_size);
}
#endif // GPU
}
else {
// precalculate P-contrastive
for (b = 0; b < l.batch; ++b) {
for (n = 0; n < l.n; ++n) {
for (h = 0; h < l.h; ++h) {
for (w = 0; w < l.w; ++w)
{
const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w;
if (l.labels[z_index] < 0) continue;
for (b2 = 0; b2 < l.batch; ++b2) {
for (n2 = 0; n2 < l.n; ++n2) {
for (h2 = 0; h2 < l.h; ++h2) {
for (w2 = 0; w2 < l.w; ++w2)
{
const int z_index2 = b2*l.n*l.h*l.w + n2*l.h*l.w + h2*l.w + w2;
if (l.labels[z_index2] < 0) continue;
if (z_index == z_index2) continue;
const int time_step_i = b / mini_batch;
const int time_step_j = b2 / mini_batch;
if (time_step_i != time_step_j) continue;
const size_t step = l.batch*l.n*l.h*l.w;
float P = -10;
if (l.detection) {
P = P_constrastive_f(z_index, z_index2, l.labels, z, l.embedding_size, l.temperature, contrast_p, contr_size);
}
else {
P = P_constrastive(z_index, z_index2, l.labels, step, z, l.embedding_size, l.temperature, l.cos_sim, l.exp_cos_sim);
l.p_constrastive[z_index*step + z_index2] = P;
}
int q;
for (q = 0; q < contr_size; ++q)
if (contrast_p[q].i == z_index && contrast_p[q].j == z_index2) {
contrast_p[q].P = P;
break;
}
//if (q == contr_size) getchar();
//if (P > 1 || P < -1) {
// printf(" p = %f, z_index = %d, z_index2 = %d ", P, z_index, z_index2); getchar();
//}
}
}
}
}
}
}
}
}
}
// calc deltas
#pragma omp parallel for
for (b = 0; b < l.batch; ++b) {
for (n = 0; n < l.n; ++n) {
for (h = 0; h < l.h; ++h) {
for (w = 0; w < l.w; ++w)
{
const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w;
const size_t step = l.batch*l.n*l.h*l.w;
if (l.labels[z_index] < 0) continue;
const int delta_index = b*l.embedding_size*l.n*l.h*l.w + n*l.embedding_size*l.h*l.w + h*l.w + w;
const int wh = l.w*l.h;
if (l.detection) {
// detector
// positive
grad_contrastive_loss_positive_f(z_index, l.labels, step, z, l.embedding_size, l.temperature, l.delta + delta_index, wh, contrast_p, contr_size);
// negative
grad_contrastive_loss_negative_f(z_index, l.labels, step, z, l.embedding_size, l.temperature, l.delta + delta_index, wh, contrast_p, contr_size);
}
else {
// classifier
// positive
grad_contrastive_loss_positive(z_index, l.labels, step, z, l.embedding_size, l.temperature, l.cos_sim, l.p_constrastive, l.delta + delta_index, wh);
// negative
grad_contrastive_loss_negative(z_index, l.labels, step, z, l.embedding_size, l.temperature, l.cos_sim, l.p_constrastive, l.delta + delta_index, wh);
}
}
}
}
}
scal_cpu(l.inputs * l.batch, l.cls_normalizer, l.delta, 1);
for (i = 0; i < l.inputs * l.batch; ++i) {
l.delta[i] = clip_value(l.delta[i], l.max_delta);
}
*(l.cost) = pow(mag_array(l.delta, l.inputs * l.batch), 2);
if (state.net.adversarial) {
printf(" adversarial contrastive loss = %f \n\n", *(l.cost));
}
else {
printf(" contrastive loss = %f \n\n", *(l.cost));
}
for (b = 0; b < l.batch; ++b) {
for (n = 0; n < l.n; ++n) {
for (h = 0; h < l.h; ++h) {
for (w = 0; w < l.w; ++w)
{
const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w;
//if (l.labels[z_index] < 0) continue;
if (z[z_index]) free(z[z_index]);
}
}
}
}
free(contrast_p);
free(z);
}
void backward_contrastive_layer(contrastive_layer l, network_state state)
{
axpy_cpu(l.inputs*l.batch, 1, l.delta, 1, state.delta, 1);
}
#ifdef GPU
void pull_contrastive_layer_output(const contrastive_layer l)
{
cuda_pull_array(l.output_gpu, l.output, l.inputs*l.batch);
}
void push_contrastive_layer_output(const contrastive_layer l)
{
cuda_push_array(l.delta_gpu, l.delta, l.inputs*l.batch);
}
void forward_contrastive_layer_gpu(contrastive_layer l, network_state state)
{
simple_copy_ongpu(l.batch*l.inputs, state.input, l.output_gpu);
if (!state.train) return;
float *in_cpu = (float *)xcalloc(l.batch*l.inputs, sizeof(float));
cuda_pull_array(l.output_gpu, l.output, l.batch*l.outputs);
memcpy(in_cpu, l.output, l.batch*l.outputs * sizeof(float));
float *truth_cpu = 0;
if (state.truth) {
int num_truth = l.batch*l.classes;
if (l.detection) num_truth = l.batch*l.truths;
truth_cpu = (float *)xcalloc(num_truth, sizeof(float));
cuda_pull_array(state.truth, truth_cpu, num_truth);
}
network_state cpu_state = state;
cpu_state.net = state.net;
cpu_state.index = state.index;
cpu_state.train = state.train;
cpu_state.truth = truth_cpu;
cpu_state.input = in_cpu;
forward_contrastive_layer(l, cpu_state);
cuda_push_array(l.delta_gpu, l.delta, l.batch*l.outputs);
free(in_cpu);
if (cpu_state.truth) free(cpu_state.truth);
}
void backward_contrastive_layer_gpu(contrastive_layer layer, network_state state)
{
axpy_ongpu(layer.batch*layer.inputs, state.net.loss_scale, layer.delta_gpu, 1, state.delta, 1);
}
#endif |
Parallel_simplicial_ldl.h | //
// Created by kazem on 4/12/19.
//
#ifndef PROJECT_PARALLEL_SIMPLICIAL_LDL_H
#define PROJECT_PARALLEL_SIMPLICIAL_LDL_H
namespace nasoq{
#include "omp.h"
int ldl_parallel_left_simplicial_01 (int n, int* c, int* r, double* values,
int* cT, int* rT,
int* lC, int* lR, double* &lValues,
double *d,
#if 0
int *prunePtr, int *pruneSet,
#endif
int *eTree,
int nLevels, int *levelPtr,
int nPar, int *parPtr, int *partition) {
//ws n, ws_int size of 3*n
/*
* Performs a Cholesky decomposition on a given matrix (c, r, values), i.e.
* stored in compressed column format, and produces L, which are
* stored in column compressed format.
* (n, c, r, values) : IN : input matrix
* (lC, lR) : IN : The column and rwo sparsity patterns of L
* (lValues) : OUT : the nonzero values of the L factor
* (pruneSet, prunePtr) : IN : the row sparsity pattern of the factor L
*/
int top = 0;
double *f;
int *xi;
//omp_set_num_threads(1);
omp_set_nested(1);
for (int i1 = 0; i1 < nLevels; ++i1) {
#pragma omp parallel private(f, xi)
{
#pragma omp for schedule(static) private(f, xi)
for (int j1 = levelPtr[i1]; j1 < levelPtr[i1 + 1]; ++j1) {
f = new double[n]();
xi = new int[2 * n]();
//int pls = levelSet[j1];
for (int k1 = parPtr[j1]; k1 < parPtr[j1 + 1]; ++k1) {
int colNo = partition[k1];
int spCol = 0;
//Uncompress a col into a 1D array
for (int nzNo = c[colNo]; nzNo < c[colNo + 1]; ++nzNo) {
f[r[nzNo]] = values[nzNo];//Copying nonzero of the col
}
#if 0
for (int i = prunePtr[colNo]; i < prunePtr[colNo + 1]-1; ++i) {
spCol = pruneSet[i];
#endif
top = ereach(n, cT, rT, colNo, eTree, xi, xi + n);
//std::cout<<n-top<<";\n";
for (int i = top; i < n; ++i) {
spCol = xi[i];
bool sw = false;
double facing_val = 0, tmp = 0;
int facing_idx = -1;
for (int l = lC[spCol]; l < lC[spCol + 1]; ++l) {
if (lR[l] == colNo) {
facing_val = lValues[l];
tmp = facing_val * d[spCol];
facing_idx = l;
break;
}
}
assert(facing_idx >= 0);
for (int l = facing_idx + 1; l < lC[spCol + 1]; ++l) {
f[lR[l]] -= lValues[l] * tmp;
}
d[colNo] += facing_val * tmp;
}
d[colNo] = f[colNo] - d[colNo];
double diag = d[colNo];
//double tmpSqrt = sqrt(f[colNo]);
f[colNo] = 0;
lValues[lC[colNo]] = 1;
for (int j = lC[colNo] + 1; j < lC[colNo + 1]; ++j) {
lValues[j] = f[lR[j]] / diag;
f[lR[j]] = 0;
}
}
delete[]f;
delete[]xi;
}
}
}
return 1;
}
}
#endif //PROJECT_PARALLEL_SIMPLICIAL_LDL_H
|
multiplemodelmethod.h |
/*******************************************************************************
* Copyright 2019 AMADEUS. All rights reserved.
* Author: Paolo Iannino
*******************************************************************************/
#ifndef CPMML_MULTIPLEMODELMETHOD_H
#define CPMML_MULTIPLEMODELMETHOD_H
#include <string>
#include <unordered_map>
#include <vector>
#ifdef MULTITHREADING
#include <omp.h>
#endif
#include "core/internal_score.h"
#include "segment.h"
#include "utils/utils.h"
/**
* @class MultipleModelMethod
*
* Class reresenting <a
* href="http://dmg.org/pmml/v4-4/MultipleModels.html#xsdType_MULTIPLE-MODEL-METHOD">PMML
* MULTIPLE-MODEL-METHOD</a>.
*
* For instance:
* - majorityVote
* - weightedAverage
* - modelChain
*/
class MultipleModelMethod {
public:
enum class MultipleModelMethodType {
MAJORITY_VOTE,
WEIGHTED_MAJORITY_VOTE,
AVERAGE,
WEIGHTED_AVERAGE,
// MEDIAN,
// MAX,
SUM,
// SELECT_FIRST,
// SELECT_ALL,
MODEL_CHAIN
};
MultipleModelMethodType value;
std::function<std::unique_ptr<InternalScore>(const Sample &, const std::vector<Segment> &)> function;
MultipleModelMethod() = default;
explicit MultipleModelMethod(const std::string &multiplemodelmethod, const MiningFunction &mining_function)
: value(from_string(multiplemodelmethod)), function(to_function(multiplemodelmethod, mining_function)) {}
static MultipleModelMethodType from_string(const std::string &multiplemodelmethod) {
static const std::unordered_map<std::string, MultipleModelMethodType> multiplemodelmethod_converter = {
{"majorityvote", MultipleModelMethodType::MAJORITY_VOTE},
{"weightedmajorityvote", MultipleModelMethodType::WEIGHTED_MAJORITY_VOTE},
{"average", MultipleModelMethodType::AVERAGE},
{"weightedaverage", MultipleModelMethodType::WEIGHTED_AVERAGE},
// {"median", MultipleModelMethodType::MEDIAN},
// {"max", MultipleModelMethodType::MAX},
{"sum", MultipleModelMethodType::SUM},
// {"selectfirst", MultipleModelMethodType::SELECT_FIRST},
// {"selectall", MultipleModelMethodType::SELECT_ALL},
{"modelchain", MultipleModelMethodType::MODEL_CHAIN}};
try {
return multiplemodelmethod_converter.at(::to_lower(multiplemodelmethod));
} catch (const std::out_of_range &e) {
throw cpmml::ParsingException(multiplemodelmethod + " not supported");
}
}
static std::function<std::unique_ptr<InternalScore>(const Sample &, const std::vector<Segment> &)> to_function(
const std::string &multiplemodelmethod, const MiningFunction &mining_function) {
switch (from_string(multiplemodelmethod)) {
case MultipleModelMethodType::MAJORITY_VOTE:
return majority_vote;
case MultipleModelMethodType::WEIGHTED_MAJORITY_VOTE:
return weighted_majority_vote;
case MultipleModelMethodType::AVERAGE:
switch (mining_function.value) {
case MiningFunction::MiningFunctionType::CLASSIFICATION:
return classification_average;
case MiningFunction::MiningFunctionType::REGRESSION:
return regression_average;
}
case MultipleModelMethodType::WEIGHTED_AVERAGE:
return classification_weighted_average;
case MultipleModelMethodType::SUM:
return sum;
case MultipleModelMethodType::MODEL_CHAIN:
return model_chain;
}
throw cpmml::ParsingException(multiplemodelmethod + " not supported");
}
#ifndef MULTITHREADING
static std::unique_ptr<InternalScore> majority_vote(const Sample &sample, const std::vector<Segment> &ensemble) {
std::unordered_map<std::string, double> probabilities; // zero initialized
std::string score;
for (const auto &segment : ensemble)
if (segment.predicate(sample)) probabilities[segment.predict(sample)] += 1.0 / ensemble.size();
double max_prob = 0;
for (const auto &probability : probabilities) {
if (max_prob > 0.5) break;
if (probability.second > max_prob && probability.first != "") {
max_prob = probability.second;
score = probability.first;
}
}
return make_unique<InternalScore>(score, probabilities);
}
#else
inline static std::unique_ptr<InternalScore> majority_vote(const Sample &sample,
const std::vector<Segment> &ensemble) {
std::unordered_map<std::string, double> probabilities; // zero initialized
std::unordered_map<std::string, double> tmp_probabilities[NUM_THREADS];
std::string score;
#pragma omp parallel for if (ensemble.size() > 25) default(shared) num_threads(NUM_THREADS)
for (auto i = 0u; i < ensemble.size(); i++)
if (ensemble[i].predicate(sample))
tmp_probabilities[omp_get_thread_num()][ensemble[i].predict(sample)] += 1.0 / ensemble.size();
for (auto i = 0u; i < NUM_THREADS; i++)
for (const auto &pair : tmp_probabilities[i]) probabilities[pair.first] += pair.second;
double max_prob = 0;
for (const auto &probability : probabilities) {
if (max_prob > 0.5) break;
if (probability.second > max_prob && probability.first != "") {
max_prob = probability.second;
score = probability.first;
}
}
return make_unique<InternalScore>(score, probabilities);
}
#endif
inline static std::unique_ptr<InternalScore> weighted_majority_vote(const Sample &sample,
const std::vector<Segment> &ensemble) {
std::unordered_map<std::string, double> probabilities; // zero initialized
for (const auto &segment : ensemble)
if (segment.predicate(sample)) probabilities[segment.predict(sample)] += 1.0 * segment.weight / ensemble.size();
double max_prob = 0;
std::string score;
double winning_threshold = 1.0 / ensemble[0].model->target_field.n_values;
for (const auto &probability : probabilities) {
if (max_prob > winning_threshold) break;
if (probability.second > max_prob && probability.first != "") {
max_prob = probability.second;
score = probability.first;
}
}
return make_unique<InternalScore>(score, probabilities);
}
inline static std::unique_ptr<InternalScore> classification_average(const Sample &sample,
const std::vector<Segment> &ensemble) {
std::unique_ptr<InternalScore> first_score(ensemble[0].score(sample));
std::unordered_map<std::string, double> probabilities = first_score->probabilities;
for (auto i = 1u; i < ensemble.size(); i++)
if (ensemble[i].predicate(sample)) {
std::unique_ptr<InternalScore> tmp_score(ensemble[i].score(sample));
for (const auto &probability : tmp_score->probabilities) probabilities[probability.first] += probability.second;
}
for (const auto &probability : probabilities)
probabilities[probability.first] = probability.second / ensemble.size();
double max_prob = 0;
std::string score;
double winning_threshold = 1.0; // / ensemble[0].model->target_field.n_values;
for (const auto &probability : probabilities) {
if (max_prob >= winning_threshold) break;
if (probability.second > max_prob && probability.first != "") {
max_prob = probability.second;
score = probability.first;
}
}
return make_unique<InternalScore>(score, probabilities);
}
#ifndef MULTITHREADING
static std::unique_ptr<InternalScore> regression_average(const Sample &sample, const std::vector<Segment> &ensemble) {
double score = 0;
double count = 0;
for (const auto &segment : ensemble)
if (segment.predicate(sample)) {
count++;
score += to_double(segment.predict(sample));
}
score /= count;
return make_unique<InternalScore>(score);
}
#else
inline static std::unique_ptr<InternalScore> regression_average(const Sample &sample,
const std::vector<Segment> &ensemble) {
double score = 0;
double scores[NUM_THREADS];
double count = 0;
for (auto i = 0u; i < NUM_THREADS; i++) scores[i] = 0;
#pragma omp parallel for if (ensemble.size() > 25) default(shared) num_threads(NUM_THREADS)
for (auto i = 0u; i < ensemble.size(); i++)
if (ensemble[i].predicate(sample)) {
count++;
scores[omp_get_thread_num()] += to_double(ensemble[i].predict(sample));
}
for (auto i = 0u; i < NUM_THREADS; i++) score += scores[i];
score /= count;
return make_unique<InternalScore>(score);
}
#endif
inline static std::unique_ptr<InternalScore> classification_weighted_average(const Sample &sample,
const std::vector<Segment> &ensemble) {
std::unique_ptr<InternalScore> first_score(ensemble[0].score(sample));
std::unordered_map<std::string, double> probabilities = first_score->probabilities;
for (auto i = 1u; i < ensemble.size(); i++)
if (ensemble[i].predicate(sample)) {
std::unique_ptr<InternalScore> tmp_score(ensemble[i].score(sample));
for (const auto &probability : tmp_score->probabilities)
probabilities[probability.first] += probability.second * ensemble[i].weight;
}
for (const auto &probability : probabilities)
probabilities[probability.first] = probability.second / ensemble.size();
double max_prob = 0;
std::string score;
double winning_threshold = 1.0 / ensemble[0].model->target_field.n_values;
for (const auto &probability : probabilities) {
if (max_prob >= winning_threshold) break;
if (probability.second > max_prob && probability.first != "") {
max_prob = probability.second;
score = probability.first;
}
}
return make_unique<InternalScore>(score, probabilities);
}
#ifndef MULTITHREADING
inline static std::unique_ptr<InternalScore> sum(const Sample &sample, const std::vector<Segment> &ensemble) {
double score = 0;
for (const auto &segment : ensemble)
if (segment.predicate(sample)) score += std::unique_ptr<InternalScore>(segment.score(sample))->double_score;
return make_unique<InternalScore>(score);
}
#else
inline static std::unique_ptr<InternalScore> sum(const Sample &sample, const std::vector<Segment> &ensemble) {
double score = 0;
double scores[NUM_THREADS];
for (auto i = 0u; i < NUM_THREADS; i++) scores[i] = 0;
#pragma omp parallel for if (ensemble.size() > 25) default(shared) num_threads(NUM_THREADS)
for (auto i = 0u; i < ensemble.size(); i++)
if (ensemble[i].predicate(sample))
scores[omp_get_thread_num()] += std::unique_ptr<InternalScore>(ensemble[i].score(sample))->double_score;
for (auto i = 0u; i < NUM_THREADS; i++) score += scores[i];
return make_unique<InternalScore>(score);
}
#endif
inline static std::unique_ptr<InternalScore> model_chain(const Sample &sample, const std::vector<Segment> &ensemble) {
Sample tmp_sample = sample;
bool first = true;
for (auto i = 0u; i < ensemble.size() - 1; i++)
if (ensemble[i].predicate(tmp_sample)) {
if (first) {
ensemble[i].model->augment_first(tmp_sample);
first = false;
} else {
ensemble[i].model->augment(tmp_sample);
}
}
return ensemble.back().model->augment_last(tmp_sample);
}
};
#endif
|
convolution_quantize.h | // SenseNets is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2018 SenseNets Technology Ltd. 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.
#define M_Protect(a) ((a) > 127 ? (127) : ((a) < (-128) ? (-128) : (a)))
static void check_overflow(int sum, int &count, int &count_all)
{
if (sum > 32767 || sum < -32768)
{
count++;
}
count_all++;
}
static void conv1x1_quantize_int8_transform_kernel(const Mat &_kernel, Mat &kernel_tm, int inch, int outch, const stQuantizeParams &scale)
{
float ufKernelFactor = 0.f;
//initial quantized kernel Mat
kernel_tm.create(1 * inch * outch, 1);
const float *kernel = _kernel;
ufKernelFactor = scale.weightScale;
//quantize the kernel weight
signed char *kernel_s = (signed char *)kernel_tm.data;
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
int tmp = p * inch * 1 + q * 1;
float kernel_tmp;
for (int idx = 0; idx < 1; idx++)
{
if (kernel[tmp + idx] >= 0)
{
kernel_tmp = ufKernelFactor * kernel[tmp + idx] + 0.5;
}
else
{
kernel_tmp = ufKernelFactor * kernel[tmp + idx] - 0.5;
}
kernel_s[tmp + idx] = (signed char)(M_Protect(kernel_tmp));
}
}
}
}
static void conv3x3_quantize_int8_transform_kernel(const Mat &_kernel, Mat &kernel_tm, int inch, int outch, const stQuantizeParams &scale)
{
float ufKernelFactor = 0.f;
//initial quantized kernel Mat
kernel_tm.create(9 * inch * outch, 1);
const float *kernel = _kernel;
ufKernelFactor = scale.weightScale;
//quantize the kernel weight
signed char *kernel_s = (signed char *)kernel_tm.data;
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
int tmp = p * inch * 9 + q * 9;
float kernel_tmp;
for (int idx = 0; idx < 9; idx++)
{
if (kernel[tmp + idx] >= 0)
{
kernel_tmp = ufKernelFactor * kernel[tmp + idx] + 0.5;
}
else
{
kernel_tmp = ufKernelFactor * kernel[tmp + idx] - 0.5;
}
kernel_s[tmp + idx] = (signed char)(M_Protect(kernel_tmp));
}
}
}
}
static void convdw3x3_quantize_int8_transform_kernel(const Mat &_kernel, Mat &kernel_tm, int group, const stQuantizeParams &scale)
{
float ufKernelFactor = 0.f;
//initial quantized kernel Mat
kernel_tm.create(9 * group);
const float *kernel = _kernel;
ufKernelFactor = scale.weightScale;
//quantize the kernel weight
signed char *kernel_s = (signed char *)kernel_tm.data;
for (int g = 0; g < group; g++)
{
int tmp = g * 9;
float kernel_tmp;
for (int idx = 0; idx < 9; idx++)
{
if (kernel[tmp + idx] >= 0)
{
kernel_tmp = ufKernelFactor * kernel[tmp + idx] + 0.5;
}
else
{
kernel_tmp = ufKernelFactor * kernel[tmp + idx] - 0.5;
}
kernel_s[tmp + idx] = (signed char)(M_Protect(kernel_tmp));
}
}
}
static void conv_quantize(const Mat &bottom_blob, Mat &bottom_blob_s8, const float dataScale)
{
float ufDataFactor = dataScale;
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int size = w * h;
#if NCNN_INT8_INFO
fprintf(stderr, "scale %f\n", dataScale);
#endif
#pragma omp parallel for
for (int qidx = 0; qidx < inch; qidx++)
{
const float *img0 = bottom_blob.channel(qidx);
signed char *img0_s8 = bottom_blob_s8.channel(qidx);
for (int i = 0; i < size; i++)
{
signed int tmp;
if (img0[i] >= 0)
{
tmp = (int)(img0[i] * ufDataFactor + 0.5);
}
else
{
tmp = (int)(img0[i] * ufDataFactor - 0.5);
}
img0_s8[i] = (signed char)M_Protect(tmp);
}
}
}
static void conv_dequantize(Mat &top_blob, const Mat &_bias, const float dataScale, const float weightScale)
{
//float ufDataFactor = 0.f;
//float ufKernelFactor = 0.f;
float ufReverseFactor = 0.f;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
int size = outh * outw;
const float *bias = _bias;
if (0 != dataScale * weightScale)
{
ufReverseFactor = 1 / (dataScale * weightScale);
}
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
const float *img0 = top_blob.channel(p);
signed int *img0_s32 = (signed int *)img0;
float *img0_f32 = (float *)img0;
float bias0 = bias ? bias[p] : 0.f;
for (int i = 0; i < size; i++)
{
*img0_f32++ = ((float)(*img0_s32++)) * ufReverseFactor + bias0;
}
}
}
static void conv1x1s1_s8(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel)
{
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float *kernel = _kernel;
#if NCNN_INT8_INFO
int count_overflow = 0;
int count_result = 0;
#endif
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0.f);
int q = 0;
for (; q + 7 < inch; q += 8)
{
float *outptr0 = out0;
int *outptr0_s32 = (int *)outptr0;
const float *img0 = bottom_blob.channel(q);
const float *img1 = bottom_blob.channel(q + 1);
const float *img2 = bottom_blob.channel(q + 2);
const float *img3 = bottom_blob.channel(q + 3);
const float *img4 = bottom_blob.channel(q + 4);
const float *img5 = bottom_blob.channel(q + 5);
const float *img6 = bottom_blob.channel(q + 6);
const float *img7 = bottom_blob.channel(q + 7);
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
const signed char *r0 = (signed char *)img0;
const signed char *r1 = (signed char *)img1;
const signed char *r2 = (signed char *)img2;
const signed char *r3 = (signed char *)img3;
const signed char *r4 = (signed char *)img4;
const signed char *r5 = (signed char *)img5;
const signed char *r6 = (signed char *)img6;
const signed char *r7 = (signed char *)img7;
int size = outw * outh;
int remain = size;
for (; remain > 0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * (int)kernel0[0] + (int)*r1 * (int)kernel0[1] +
(int)*r2 * (int)kernel0[2] + (int)*r3 * (int)kernel0[3] +
(int)*r4 * (int)kernel0[4] + (int)*r5 * (int)kernel0[5] +
(int)*r6 * (int)kernel0[6] + (int)*r7 * (int)kernel0[7];
*outptr0_s32 += sum0;
#if NCNN_INT8_INFO
check_overflow(sum0, count_overflow, count_result);
#endif
r0++;
r1++;
r2++;
r3++;
r4++;
r5++;
r6++;
r7++;
outptr0_s32++;
}
}
for (; q < inch; q++)
{
float *outptr0 = out0;
int *outptr0_s32 = (int *)outptr0;
const float *img0 = bottom_blob.channel(q);
const signed char *img0_s8 = (signed char *)img0;
const signed char *r0 = img0_s8;
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
const signed char k0 = kernel0[0];
int size = outw * outh;
int remain = size;
for (; remain > 0; remain--)
{
int sum0 = (int)(*r0) * (int)k0;
*outptr0_s32 += sum0;
#if NCNN_INT8_INFO
check_overflow(sum0, count_overflow, count_result);
#endif
r0++;
outptr0_s32++;
}
}
}
#if NCNN_INT8_INFO
if (count_overflow)
printf("overflow : %d, all : %d, error rate : %.3f\n", count_overflow, count_result, (float)count_overflow / count_result * 100);
#endif
}
static void conv1x1s2_s8(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2*outw + w;
const signed char *kernel = _kernel;
#if NCNN_INT8_INFO
int count_overflow = 0;
int count_result = 0;
#endif
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0.f);
int q = 0;
for (; q + 7 < inch; q += 8)
{
float *outptr0 = out0;
int *outptr0_s32 = (int *)outptr0;
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
const signed char *r0 = bottom_blob.channel(q);
const signed char *r1 = bottom_blob.channel(q + 1);
const signed char *r2 = bottom_blob.channel(q + 2);
const signed char *r3 = bottom_blob.channel(q + 3);
const signed char *r4 = bottom_blob.channel(q + 4);
const signed char *r5 = bottom_blob.channel(q + 5);
const signed char *r6 = bottom_blob.channel(q + 6);
const signed char *r7 = bottom_blob.channel(q + 7);
for(int i = 0; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * (int)kernel0[0] + (int)*r1 * (int)kernel0[1] +
(int)*r2 * (int)kernel0[2] + (int)*r3 * (int)kernel0[3] +
(int)*r4 * (int)kernel0[4] + (int)*r5 * (int)kernel0[5] +
(int)*r6 * (int)kernel0[6] + (int)*r7 * (int)kernel0[7];
*outptr0_s32 += sum0;
#if NCNN_INT8_INFO
check_overflow(sum0, count_overflow, count_result);
#endif
r0 += 2;
r1 += 2;
r2 += 2;
r3 += 2;
r4 += 2;
r5 += 2;
r6 += 2;
r7 += 2;
outptr0_s32++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
r3 += tailstep;
r4 += tailstep;
r5 += tailstep;
r6 += tailstep;
r7 += tailstep;
}
}
for (; q < inch; q++)
{
float *outptr0 = out0;
int *outptr0_s32 = (int *)outptr0;
const signed char *r0 = bottom_blob.channel(q);
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
for(int i = 0; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * (int)kernel0[0];
*outptr0_s32 += sum0;
#if NCNN_INT8_INFO
check_overflow(sum0, count_overflow, count_result);
#endif
r0 += 2;
outptr0_s32++;
}
r0 += tailstep;
}
}
}
#if NCNN_INT8_INFO
if (count_overflow)
printf("overflow : %d, all : %d, error rate : %.3f\n", count_overflow, count_result, (float)count_overflow / count_result * 100);
#endif
}
static void conv3x3s1_s8(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel)
{
int w = bottom_blob.w;
//int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const signed char *kernel = _kernel;
#if NCNN_INT8_INFO
int count_overflow = 0;
int count_result = 0;
#endif
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
const signed char *kernel0 = (const signed char *)kernel + p * inch * 9;
for (int q = 0; q < inch; q++)
{
float *outptr0 = out0;
//float *outptr0n = outptr0 + outw;
int *outptr0_s32 = (int *)outptr0;
//int *outptr0n_s32 = (int *)outptr0n;
const float *img1 = bottom_blob.channel(q);
const signed char *img0 = (signed char *)img1;
const signed char *r0 = img0;
const signed char *r1 = img0 + w;
const signed char *r2 = img0 + w * 2;
//const signed char *r3 = img0 + w * 3;
//const signed char *k00 = kernel0;
//const signed char *k03 = kernel0 + 3;
//const signed char *k06 = kernel0 + 6;
for (int i = 0; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
int sum0 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
#if NCNN_INT8_INFO
check_overflow(sum0, count_overflow, count_result);
#endif
*outptr0_s32 += sum0;
r0++;
r1++;
r2++;
outptr0_s32++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
}
}
#if NCNN_INT8_INFO
if (count_overflow)
printf("overflow : %d, all : %d, error rate : %.3f\n", count_overflow, count_result, (float)count_overflow / count_result * 100);
#endif
}
static void conv3x3s2_s8(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel)
{
int w = bottom_blob.w;
//int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
const signed char *kernel = _kernel;
#if NCNN_INT8_INFO
int count_overflow = 0;
int count_result = 0;
#endif
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0.f);
const signed char *kernel0 = (const signed char *)kernel + p * inch * 9;
for (int q = 0; q < inch; q++)
{
float *outptr0 = out0;
int *outptr0_s32 = (int *)outptr0;
const float *img1 = bottom_blob.channel(q);
const signed char *img0 = (signed char *)img1;
const signed char *r0 = img0;
const signed char *r1 = img0 + w;
const signed char *r2 = img0 + w * 2;
//const signed char *k00 = kernel0;
//const signed char *k01 = kernel0 + 3;
//const signed char *k02 = kernel0 + 6;
for (int i = 0; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
int sum0 = 0;
sum0 += (int)r0[0] * (int)kernel0[0];
sum0 += (int)r0[1] * (int)kernel0[1];
sum0 += (int)r0[2] * (int)kernel0[2];
sum0 += (int)r1[0] * (int)kernel0[3];
sum0 += (int)r1[1] * (int)kernel0[4];
sum0 += (int)r1[2] * (int)kernel0[5];
sum0 += (int)r2[0] * (int)kernel0[6];
sum0 += (int)r2[1] * (int)kernel0[7];
sum0 += (int)r2[2] * (int)kernel0[8];
#if NCNN_INT8_INFO
check_overflow(sum0, count_overflow, count_result);
#endif
*outptr0_s32 += sum0;
r0 += 2;
r1 += 2;
r2 += 2;
outptr0_s32++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
}
}
#if NCNN_INT8_INFO
if (count_overflow)
printf("overflow : %d, all : %d, error rate : %.3f\n", count_overflow, count_result, (float)count_overflow / count_result * 100.0);
#endif
}
static void convdw3x3s1_s8(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel)
{
int w = bottom_blob.w;
//int h = bottom_blob.h;
//int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const signed char *kernel = _kernel;
#if NCNN_INT8_INFO
int count_overflow = 0;
int count_result = 0;
#endif
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
Mat out = top_blob.channel(p);
out.fill(0.f);
const signed char *kernel0 = (const signed char *)kernel + p * 9;
float *outptr = out;
int *outptr_s32 = (int *)outptr;
const float *img1 = bottom_blob.channel(p);
const signed char *img0 = (signed char *)img1;
const signed char *r0 = img0;
const signed char *r1 = img0 + w;
const signed char *r2 = img0 + w * 2;
//const signed char *k0 = kernel0;
//const signed char *k1 = kernel0 + 3;
//const signed char *k2 = kernel0 + 6;
int i = 0;
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
int sum = 0;
sum += (int)r0[0] * (int)kernel0[0];
sum += (int)r0[1] * (int)kernel0[1];
sum += (int)r0[2] * (int)kernel0[2];
sum += (int)r1[0] * (int)kernel0[3];
sum += (int)r1[1] * (int)kernel0[4];
sum += (int)r1[2] * (int)kernel0[5];
sum += (int)r2[0] * (int)kernel0[6];
sum += (int)r2[1] * (int)kernel0[7];
sum += (int)r2[2] * (int)kernel0[8];
*outptr_s32 += sum;
#if NCNN_INT8_INFO
check_overflow(sum, count_overflow, count_result);
#endif
r0++;
r1++;
r2++;
outptr_s32++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
}
#if NCNN_INT8_INFO
if (count_overflow)
printf("overflow : %d, all : %d, error rate : %.3f\n", count_overflow, count_result, (float)count_overflow / count_result * 100);
#endif
}
static void convdw3x3s2_s8(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel)
{
int w = bottom_blob.w;
//int h = bottom_blob.h;
//int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
const signed char *kernel = _kernel;
#if NCNN_INT8_INFO
int count_overflow = 0;
int count_result = 0;
#endif
#pragma omp parallel for
for (int p = 0; p < outch; p++)
{
Mat out = top_blob.channel(p);
out.fill(0.f);
const signed char *kernel0 = (const signed char *)kernel + p * 9;
float *outptr = out;
int *outptr_s32 = (int *)outptr;
const float *img1 = bottom_blob.channel(p);
const signed char *img0 = (signed char *)img1;
const signed char *r0 = img0;
const signed char *r1 = img0 + w;
const signed char *r2 = img0 + w * 2;
//const signed char *k0 = kernel0;
//const signed char *k1 = kernel0 + 3;
//const signed char *k2 = kernel0 + 6;
int i = 0;
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
int sum = 0;
sum += (int)r0[0] * (int)kernel0[0];
sum += (int)r0[1] * (int)kernel0[1];
sum += (int)r0[2] * (int)kernel0[2];
sum += (int)r1[0] * (int)kernel0[3];
sum += (int)r1[1] * (int)kernel0[4];
sum += (int)r1[2] * (int)kernel0[5];
sum += (int)r2[0] * (int)kernel0[6];
sum += (int)r2[1] * (int)kernel0[7];
sum += (int)r2[2] * (int)kernel0[8];
*outptr_s32 += sum;
#if NCNN_INT8_INFO
check_overflow(sum, count_overflow, count_result);
#endif
r0 += 2;
r1 += 2;
r2 += 2;
outptr_s32++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
}
#if NCNN_INT8_INFO
if (count_overflow)
printf("overflow : %d, all : %d, error rate : %.3f\n", count_overflow, count_result, (float)count_overflow / count_result * 100);
#endif
}
|
sobol.c | /******************************************************************
* Melissa *
*-----------------------------------------------------------------*
* COPYRIGHT (C) 2017 by INRIA and EDF. ALL RIGHTS RESERVED. *
* *
* This source is covered by the BSD 3-Clause License. *
* Refer to the LICENCE file for further information. *
* *
*-----------------------------------------------------------------*
* Original Contributors: *
* Theophile Terraz, *
* Bruno Raffin, *
* Alejandro Ribes, *
* Bertrand Iooss, *
******************************************************************/
/**
*
* @file sobol.c
* @brief Functions needed to compute sobol indices.
* @author Terraz Théophile
* @date 2016-29-02
*
**/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#ifdef BUILD_WITH_OPENMP
#include <omp.h>
#endif // BUILD_WITH_OPENMP
#include "mean.h"
#include "variance.h"
#include "covariance.h"
#include "sobol.h"
#include "melissa_utils.h"
static inline void increment_sobol_covariance (double *covariance,
double in_vect1[],
double in_vect2[],
double mean1[],
double mean2[],
const int vect_size,
const int increment)
{
int i;
double incr = 0;
incr = (double)increment;
if (increment > 1)
{
#pragma omp parallel for schedule(static) firstprivate(incr)
for (i=0; i<vect_size; i++)
{
covariance[i] *= (incr - 2);
covariance[i] += (in_vect1[i] - mean1[i]) * (in_vect2[i] - mean2[i]) * (incr/(incr-1));
covariance[i] /= (incr - 1);
}
}
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function initialise a Jansen Sobol indices structure
*
*******************************************************************************
*
* @param[in,out] *sobol_array
* input: reference or pointer to an uninitialised sobol indices structure,
* output: initialised structure, with values and variances set to 0
*
* @param[in] nb_parameters
* number of parameters of the study
*
* @param[in] vect_size
* size of the input vectors
*
*******************************************************************************/
void init_sobol_jansen (sobol_array_t *sobol_array,
int nb_parameters,
int vect_size)
{
int j;
sobol_array->sobol_jansen = melissa_malloc (nb_parameters * sizeof(sobol_martinez_t));
init_variance (&sobol_array->variance_a, vect_size);
for (j=0; j<nb_parameters; j++)
{
sobol_array->sobol_jansen[j].summ_a = melissa_calloc (vect_size, sizeof(double));
sobol_array->sobol_jansen[j].summ_b = melissa_calloc (vect_size, sizeof(double));
sobol_array->sobol_jansen[j].first_order_values = melissa_calloc (vect_size, sizeof(double));
sobol_array->sobol_jansen[j].total_order_values = melissa_calloc (vect_size, sizeof(double));
}
sobol_array->iteration = 0;
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function initialise a Martinez Sobol indices structure
*
*******************************************************************************
*
* @param[in,out] *sobol_array
* input: reference or pointer to an uninitialised sobol indices structure,
* output: initialised structure, with values and variances set to 0
*
* @param[in] nb_parameters
* number of parameters of the study
*
* @param[in] vect_size
* size of the input vectors
*
*******************************************************************************/
void init_sobol_martinez (sobol_array_t *sobol_array,
int nb_parameters,
int vect_size)
{
int j;
sobol_array->sobol_martinez = melissa_malloc (nb_parameters * sizeof(sobol_martinez_t));
init_variance (&sobol_array->variance_b, vect_size);
init_variance (&sobol_array->variance_a, vect_size);
for (j=0; j<nb_parameters; j++)
{
// init_covariance (&(sobol_array->sobol_martinez[j].first_order_covariance), vect_size);
// init_covariance (&(sobol_array->sobol_martinez[j].total_order_covariance), vect_size);
sobol_array->sobol_martinez[j].first_order_covariance= melissa_calloc (vect_size, sizeof(double));
sobol_array->sobol_martinez[j].total_order_covariance= melissa_calloc (vect_size, sizeof(double));
init_variance (&(sobol_array->sobol_martinez[j].variance_k), vect_size);
sobol_array->sobol_martinez[j].first_order_values = melissa_calloc (vect_size, sizeof(double));
sobol_array->sobol_martinez[j].total_order_values = melissa_calloc (vect_size, sizeof(double));
sobol_array->sobol_martinez[j].confidence_interval[0] = 1;
sobol_array->sobol_martinez[j].confidence_interval[1] = 1;
}
sobol_array->iteration = 0;
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function computes Sobol indices using Jansen formula
*
*******************************************************************************
*
* @param[out] *sobol_array
* computed sobol indices, using Jansen formula
*
* @param[in] nb_parameters
* size of sobol_array->sobol_jansen
*
* @param[in] **in_vect_tab
* array of input vectors
*
* @param[in] vect_size
* size of input vectors
*
*******************************************************************************/
void increment_sobol_jansen (sobol_array_t *sobol_array,
int nb_parameters,
double **in_vect_tab,
int vect_size)
{
int i, j;
double epsylon = 1e-12;
increment_variance (&(sobol_array->variance_a), in_vect_tab[0], vect_size);
sobol_array->iteration += 1;
for (i=0; i< nb_parameters; i++)
{
#pragma omp parallel
{
#pragma omp for nowait schedule(static)
for (j=0; j<vect_size; j++)
{
sobol_array->sobol_jansen[i].summ_a[j] += (in_vect_tab[0][j] + in_vect_tab[i+2][j])*(in_vect_tab[0][j] + in_vect_tab[i+2][j]);
}
#pragma omp for nowait schedule(static)
for (j=0; j<vect_size; j++)
{
sobol_array->sobol_jansen[i].summ_b[j] += (in_vect_tab[1][j] + in_vect_tab[i+2][j])*(in_vect_tab[1][j] + in_vect_tab[i+2][j]);
}
#pragma omp for nowait schedule(static)
for (j=0; j<vect_size; j++)
{
if (sobol_array->variance_a.variance[j] > epsylon)
{
sobol_array->sobol_jansen[i].first_order_values[j] = 1 - (sobol_array->sobol_jansen[i].summ_b[j]
/(2*sobol_array->iteration-1))
/sobol_array->variance_a.variance[j];
}
else
{
sobol_array->sobol_jansen[i].first_order_values[j] = 0;
}
}
#pragma omp for nowait schedule(static)
for (j=0; j<vect_size; j++)
{
if (sobol_array->variance_a.variance[j] > epsylon)
{
sobol_array->sobol_jansen[i].total_order_values[j] = (sobol_array->sobol_jansen[i].summ_a[j]
/(2*sobol_array->iteration-1))
/sobol_array->variance_a.variance[j];
}
else
{
sobol_array->sobol_jansen[i].total_order_values[j] = 0;
}
}
}
}
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function computes Sobol indices using Martinez formula
*
*******************************************************************************
*
* @param[out] *sobol_array
* computed sobol indices, using Martinez formula
*
* @param[in] nb_parameters
* size of sobol_array->sobol_martinez
*
* @param[in] **in_vect_tab
* array of input vectors
*
* @param[in] vect_size
* size of input vectors
*
*******************************************************************************/
void increment_sobol_martinez (sobol_array_t *sobol_array,
int nb_parameters,
double **in_vect_tab,
int vect_size)
{
int i, j;
double epsylon = 1e-12;
increment_variance (&(sobol_array->variance_a), in_vect_tab[0], vect_size);
increment_variance (&(sobol_array->variance_b), in_vect_tab[1], vect_size);
for (i=0; i< nb_parameters; i++)
{
increment_variance (&(sobol_array->sobol_martinez[i].variance_k), in_vect_tab[i+2], vect_size);
increment_sobol_covariance (sobol_array->sobol_martinez[i].first_order_covariance,
in_vect_tab[1],
in_vect_tab[i+2],
sobol_array->variance_b.mean_structure.mean,
sobol_array->sobol_martinez[i].variance_k.mean_structure.mean,
vect_size,
sobol_array->iteration);
increment_sobol_covariance (sobol_array->sobol_martinez[i].total_order_covariance,
in_vect_tab[0],
in_vect_tab[i+2],
sobol_array->variance_a.mean_structure.mean,
sobol_array->sobol_martinez[i].variance_k.mean_structure.mean,
vect_size,
sobol_array->iteration);
// increment_covariance (&(sobol_array->sobol_martinez[i].first_order_covariance), in_vect_tab[1], in_vect_tab[i+2], vect_size);
// increment_covariance (&(sobol_array->sobol_martinez[i].total_order_covariance), in_vect_tab[0], in_vect_tab[i+2], vect_size);
#pragma omp parallel
{
#pragma omp for nowait schedule(static)
for (j=0; j<vect_size; j++)
{
if (sobol_array->sobol_martinez[i].variance_k.variance[j] > epsylon && sobol_array->variance_b.variance[j] > epsylon)
{
sobol_array->sobol_martinez[i].first_order_values[j] = sobol_array->sobol_martinez[i].first_order_covariance[j]
/ ( sqrt(sobol_array->variance_b.variance[j])
* sqrt(sobol_array->sobol_martinez[i].variance_k.variance[j]) );
}
else
{
sobol_array->sobol_martinez[i].first_order_values[j] = 0;
}
}
#pragma omp for nowait schedule(static)
for (j=0; j<vect_size; j++)
{
if (sobol_array->sobol_martinez[i].variance_k.variance[j] > epsylon && sobol_array->variance_a.variance[j] > epsylon)
{
sobol_array->sobol_martinez[i].total_order_values[j] = 1.0 - sobol_array->sobol_martinez[i].total_order_covariance[j]
/ ( sqrt(sobol_array->variance_a.variance[j])
* sqrt(sobol_array->sobol_martinez[i].variance_k.variance[j]) );
}
else
{
sobol_array->sobol_martinez[i].total_order_values[j] = 0;
}
}
}
}
sobol_array->iteration += 1;
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function computes the confidence interval for Martinez Sobol indices
*
*******************************************************************************
*
* @param[out] *sobol_array
* Sobol indices
*
* @param[in] nb_parameters
* size of sobol_array->sobol_martinez
*
* @param[in] vect_size
* size of input vectors
*
*******************************************************************************/
void confidence_sobol_martinez(sobol_array_t *sobol_array,
int nb_parameters,
int vect_size)
{
int i, j;
double temp1, temp2, interval;
if (sobol_array->iteration < 4)
{
return;
}
temp2 = 1.96/(sqrt(sobol_array->iteration-3));
for (j=0; j< nb_parameters; j++)
{
interval = 0;
sobol_array->sobol_martinez[j].confidence_interval[0]=0;
sobol_array->sobol_martinez[j].confidence_interval[1]=0;
for (i=0; i<vect_size; i++)
{
temp1 = 0.5 * log((1.0+sobol_array->sobol_martinez[j].first_order_values[i])/(1.0-sobol_array->sobol_martinez[j].first_order_values[i]));
interval = tanh(temp1 + temp2) - tanh(temp1 - temp2);
if (sobol_array->sobol_martinez[j].confidence_interval[0] < interval)
{
sobol_array->sobol_martinez[j].confidence_interval[0] = interval;
}
}
interval = 0;
for (i=0; i<vect_size; i++)
{
temp1 = 0.5 * log((2.0-sobol_array->sobol_martinez[j].total_order_values[i])/sobol_array->sobol_martinez[j].total_order_values[i]);
interval = (1-tanh(temp1 - temp2)) - (1-tanh(temp1 + temp2));
if (sobol_array->sobol_martinez[j].confidence_interval[1] < interval)
{
sobol_array->sobol_martinez[j].confidence_interval[1] = interval;
}
}
}
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function computes the confidence interval for Martinez Sobol indices
* as if the worst value was 0
*
*******************************************************************************
*
* @param[out] *sobol_array
* Sobol indices
*
*******************************************************************************/
double simplified_confidence_sobol_martinez(int iteration)
{
double temp;
if (iteration < 4)
{
return 2.0;
}
temp = 1.96/(sqrt(iteration-3));
return tanh(temp) - tanh(0.0 - temp);
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function check if the Sobol indice convergence has been reached
*
*******************************************************************************
*
* @param[out] **sobol_array
* Sobol indices
*
* @param[in] confidence_value
* value to reach for the worst confidence interval
*
* @param[in] nb_time_steps
* number of time steps of the study
*
* @param[in] nb_parameters
* size of sobol_array->sobol_martinez
*
* @return[out] int
* 0 if convergence is not reached
* 1 if convergence is reached
*
*******************************************************************************/
int check_convergence_sobol_martinez(sobol_array_t **sobol_array,
double confidence_value,
int nb_time_steps,
int nb_parameters)
{
int i, j;
for (i=0; i<nb_time_steps; i++)
{
for (j=0; j<nb_parameters; j++)
{
if ((*sobol_array)[i].sobol_martinez[j].confidence_interval[0] > confidence_value)
{
return 0;
}
if ((*sobol_array)[i].sobol_martinez[j].confidence_interval[1] > confidence_value)
{
return 0;
}
}
}
return 1;
}
/**
*******************************************************************************
*
* @ingroup save_stats
*
* This function writes an array of sobol_jansen structures on disc
*
*******************************************************************************
*
* @param[in] *sobol_array
* sobol_array structures to save, size nb_time_steps
*
* @param[in] vect_size
* size of double vectors
*
* @param[in] nb_time_steps
* number of time_steps of the study
*
* @param[in] nb_parameters
* number of parameters of the study
*
* @param[in] f
* file descriptor
*
*******************************************************************************/
void save_sobol_jansen(sobol_array_t *sobol_array,
int vect_size,
int nb_time_steps,
int nb_parameters,
FILE* f)
{
int i, j;
for (i=0; i<nb_time_steps; i++)
{
for (j=0; j<nb_parameters; j++)
{
fwrite(sobol_array[i].sobol_jansen[j].summ_a, sizeof(double), vect_size,f);
fwrite(sobol_array[i].sobol_jansen[j].summ_b, sizeof(double), vect_size,f);
fwrite(sobol_array[i].sobol_jansen[j].first_order_values, sizeof(double), vect_size,f);
fwrite(sobol_array[i].sobol_jansen[j].total_order_values, sizeof(double), vect_size,f);
}
save_variance(&sobol_array[i].variance_a, vect_size, 1, f);
fwrite(&sobol_array[i].iteration, sizeof(int), 1, f);
}
}
/**
*******************************************************************************
*
* @ingroup save_stats
*
* This function writes an array of sobol_martinez structures on disc
*
*******************************************************************************
*
* @param[in] *sobol_array
* sobol_array structures to save, size nb_time_steps
*
* @param[in] vect_size
* size of double vectors
*
* @param[in] nb_time_steps
* number of time_steps of the study
*
* @param[in] nb_parameters
* number of parameters of the study
*
* @param[in] f
* file descriptor
*
*******************************************************************************/
void save_sobol_martinez(sobol_array_t *sobol_array,
int vect_size,
int nb_time_steps,
int nb_parameters,
FILE* f)
{
int i, j;
for (i=0; i<nb_time_steps; i++)
{
for (j=0; j<nb_parameters; j++)
{
fwrite(sobol_array[i].sobol_martinez[j].first_order_covariance, sizeof(double), vect_size,f);
fwrite(sobol_array[i].sobol_martinez[j].total_order_covariance, sizeof(double), vect_size,f);
save_variance (&sobol_array[i].sobol_martinez[j].variance_k, vect_size, 1, f);
fwrite(sobol_array[i].sobol_martinez[j].first_order_values, sizeof(double), vect_size,f);
fwrite(sobol_array[i].sobol_martinez[j].total_order_values, sizeof(double), vect_size,f);
fwrite(sobol_array[i].sobol_martinez[j].confidence_interval, sizeof(double), 2,f);
}
save_variance (&sobol_array[i].variance_a, vect_size, 1, f);
save_variance (&sobol_array[i].variance_b, vect_size, 1, f);
fwrite(&sobol_array[i].iteration, sizeof(int), 1, f);
}
}
/**
*******************************************************************************
*
* @ingroup save_stats
*
* This function reads an array of sobol_jansen structures on disc
*
*******************************************************************************
*
* @param[in] *sobol_array
* sobol_array structures to read, size nb_time_steps
*
* @param[in] vect_size
* size of double vectors
*
* @param[in] nb_time_steps
* number of time_steps of the study
*
* @param[in] nb_parameters
* number of parameters of the study
*
* @param[in] f
* file descriptor
*
*******************************************************************************/
void read_sobol_jansen(sobol_array_t *sobol_array,
int vect_size,
int nb_time_steps,
int nb_parameters,
FILE* f)
{
int i, j;
for (i=0; i<nb_time_steps; i++)
{
for (j=0; j<nb_parameters; j++)
{
fread(sobol_array[i].sobol_jansen[j].summ_a, sizeof(double), vect_size,f);
fread(sobol_array[i].sobol_jansen[j].summ_b, sizeof(double), vect_size,f);
fread(sobol_array[i].sobol_jansen[j].first_order_values, sizeof(double), vect_size,f);
fread(sobol_array[i].sobol_jansen[j].total_order_values, sizeof(double), vect_size,f);
}
read_variance(&sobol_array[i].variance_a, vect_size, 1, f);
fread(&sobol_array[i].iteration, sizeof(int), 1, f);
}
}
/**
*******************************************************************************
*
* @ingroup save_stats
*
* This function reads an array of sobol_martinez structures on disc
*
*******************************************************************************
*
* @param[in] *sobol_array
* sobol_array structures to read, size nb_time_steps
*
* @param[in] vect_size
* size of double vectors
*
* @param[in] nb_time_steps
* number of time_steps of the study
*
* @param[in] nb_parameters
* number of parameters of the study
*
* @param[in] f
* file descriptor
*
*******************************************************************************/
void read_sobol_martinez(sobol_array_t *sobol_array,
int vect_size,
int nb_time_steps,
int nb_parameters,
FILE* f)
{
int i, j;
for (i=0; i<nb_time_steps; i++)
{
for (j=0; j<nb_parameters; j++)
{
fread(sobol_array[i].sobol_martinez[j].first_order_covariance, sizeof(double), vect_size,f);
fread(sobol_array[i].sobol_martinez[j].total_order_covariance, sizeof(double), vect_size,f);
read_variance (&sobol_array[i].sobol_martinez[j].variance_k, vect_size, 1, f);
fread(sobol_array[i].sobol_martinez[j].first_order_values, sizeof(double), vect_size,f);
fread(sobol_array[i].sobol_martinez[j].total_order_values, sizeof(double), vect_size,f);
fread(sobol_array[i].sobol_martinez[j].confidence_interval, sizeof(double), 2,f);
}
read_variance (&sobol_array[i].variance_a, vect_size, 1, f);
read_variance (&sobol_array[i].variance_b, vect_size, 1, f);
fread(&sobol_array[i].iteration, sizeof(int), 1, f);
}
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function frees a Jansen Sobol array structure
*
*******************************************************************************
*
* @param[in] *sobol_array
* reference or pointer to a sobol index structure to free
*
* @param[in] nb_parameters
* number of parameters of the study
*
*******************************************************************************/
void free_sobol_jansen (sobol_array_t *sobol_array,
int nb_parameters)
{
int j;
free_variance (&sobol_array->variance_a);
for (j=0; j<nb_parameters; j++)
{
melissa_free (sobol_array->sobol_jansen->summ_a);
melissa_free (sobol_array->sobol_jansen->summ_b);
melissa_free (sobol_array->sobol_jansen->first_order_values);
melissa_free (sobol_array->sobol_jansen->total_order_values);
}
melissa_free (sobol_array->sobol_jansen);
}
/**
*******************************************************************************
*
* @ingroup sobol
*
* This function frees a Martinez Sobol indices structure
*
*******************************************************************************
*
* @param[in] *sobol_array
* reference or pointer to a sobol array structure to free
*
* @param[in] nb_parameters
* number of parameters of the study
*
*******************************************************************************/
void free_sobol_martinez (sobol_array_t *sobol_array,
int nb_parameters)
{
int j;
free_variance (&sobol_array->variance_a);
free_variance (&sobol_array->variance_b);
for (j=0; j<nb_parameters; j++)
{
// free_covariance (&sobol_array->sobol_martinez[j].first_order_covariance);
// free_covariance (&sobol_array->sobol_martinez[j].total_order_covariance);
free_variance (&sobol_array->sobol_martinez[j].variance_k);
melissa_free (sobol_array->sobol_martinez[j].first_order_covariance);
melissa_free (sobol_array->sobol_martinez[j].total_order_covariance);
melissa_free (sobol_array->sobol_martinez[j].first_order_values);
melissa_free (sobol_array->sobol_martinez[j].total_order_values);
}
melissa_free (sobol_array->sobol_martinez);
}
|
openmp_demo.c | //------------------------------------------------------------------------------
// GraphBLAS/Demo/Program/openmp_demo: example of user multithreading
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// This demo uses OpenMP, and illustrates how GraphBLAS can be called from
// a multi-threaded user program.
#include "GraphBLAS.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#if defined __INTEL_COMPILER
#pragma warning (disable: 58 167 144 177 181 186 188 589 593 869 981 1418 1419 1572 1599 2259 2282 2557 2547 3280 )
#elif defined __GNUC__
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#if !defined ( __cplusplus )
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
#endif
#endif
#define NTHREADS 8
#define NTRIALS 10
#define N 6
#define OK(method) \
{ \
GrB_Info info = method ; \
if (! (info == GrB_SUCCESS || info == GrB_NO_VALUE)) \
{ \
printf ("Failure (id: %d, info: %d):\n", id, info) ; \
/* return to caller (do not use inside critical section) */ \
return (0) ; \
} \
}
//------------------------------------------------------------------------------
// worker
//------------------------------------------------------------------------------
int worker (GrB_Matrix *Ahandle, int id)
{
printf ("\n================= worker %d starts:\n", id) ;
fprintf (stderr, "worker %d\n", id) ;
OK (GrB_Matrix_new (Ahandle, GrB_FP64, N, N)) ;
GrB_Matrix A = *Ahandle ;
// worker generates an intentional error message
GrB_Matrix_setElement_INT32 (A, 42, 1000+id, 1000+id) ;
// print the intentional error generated when the worker started
#pragma omp critical
{
// critical section
printf ("\n----------------- worker %d intentional error:\n", id) ;
const char *s ;
GrB_Matrix_error (&s, A) ;
printf ("%s\n", s) ;
}
for (int hammer_hard = 0 ; hammer_hard < NTRIALS ; hammer_hard++)
{
for (int i = 0 ; i < N ; i++)
{
for (int j = 0 ; j < N ; j++)
{
double x = (i+1)*100000 + (j+1)*1000 + id ;
OK (GrB_Matrix_setElement_FP64 (A, x, i, j)) ;
}
}
// force completion
OK (GrB_Matrix_wait (&A)) ;
}
// Printing is done in a critical section, just so it is not overly
// jumbled. Each matrix and error will print in a single body of text,
// but the order of the matrices and errors printed will be out of order
// because the critical section does not enforce the order that the
// threads enter.
GrB_Info info2 ;
#pragma omp critical
{
// critical section
printf ("\n----------------- worker %d is done:\n", id) ;
info2 = GxB_Matrix_fprint (A, "A", GxB_SHORT, stdout) ;
}
OK (info2) ;
// worker generates an intentional error message
GrB_Matrix_setElement_INT32 (A, 42, 1000+id, 1000+id) ;
// print the intentional error generated when the worker started
// It should be unchanged.
#pragma omp critical
{
// critical section
printf ("\n----------------- worker %d error should be same:\n", id) ;
const char *s ;
GrB_Matrix_error (&s, A) ;
printf ("%s\n", s) ;
}
return (0) ;
}
//------------------------------------------------------------------------------
// openmp_demo main program
//------------------------------------------------------------------------------
int main (int argc, char **argv)
{
fprintf (stderr, "Demo: %s:\n", argv [0]) ;
printf ("Demo: %s:\n", argv [0]) ;
// initialize the mutex
int id = -1 ;
// start GraphBLAS
OK (GrB_init (GrB_NONBLOCKING)) ;
int nthreads ;
OK (GxB_Global_Option_get (GxB_GLOBAL_NTHREADS, &nthreads)) ;
fprintf (stderr, "openmp demo, nthreads %d\n", nthreads) ;
// Determine which user-threading model is being used.
#ifdef _OPENMP
printf ("User threads in this program are OpenMP threads.\n") ;
#else
printf ("This user program is single threaded.\n") ;
#endif
GrB_Matrix Aarray [NTHREADS] ;
// create the threads
#pragma omp parallel for num_threads(NTHREADS)
for (id = 0 ; id < NTHREADS ; id++)
{
worker (&Aarray [id], id) ;
}
// the leader thread prints them again, and frees them
for (int id = 0 ; id < NTHREADS ; id++)
{
GrB_Matrix A = Aarray [id] ;
printf ("\n---- Leader prints matrix %d\n", id) ;
OK (GxB_Matrix_fprint (A, "A", GxB_SHORT, stdout)) ;
GrB_Matrix_free (&A) ;
}
// finish GraphBLAS
GrB_finalize ( ) ;
// finish OpenMP
exit (0) ;
}
|
libgomp-292348.c | /*
Test hipcc host compilation with -lgomp, from 292348.
*/
#include <stdio.h>
#include <omp.h>
void inc_subarray(int *array, int start, int end) {
for (int i = start; i <end; i++) {
array[i] += 1;
}
}
void inc_subarray_mt(int *array, int start, int end) {
#ifdef _OPENMP
#pragma omp parallel
{
int num_t = omp_get_num_threads();
int tid = omp_get_thread_num();
int q = (end - start) / num_t + 1;
int s = start + tid * q;
int e = s + q;
e = (e < end) ? e : end;
for (int i = s; i < e; i++) {
array[i] += 1;
}
//printf("tid: %d, num_t: %d\n", tid, num_t);
}
#endif
}
int main(int argc, char *argv[]) {
int num_threads = 0;
int errors = 0;
#pragma omp parallel
{
num_threads = omp_get_num_threads();
}
printf("omp threads: %d\n", num_threads);
int ary[1000] = {0};
int ary_mt[1000] = {0};
for (int i = 0; i < 1000; i++) {
ary[i] = 0;
ary_mt[i] = 0;
}
for (int i = 0; i < 10; i++) {
int start = (i *137) % 1000;
int end = ((i + 1) *279) % 1000;
if (start > end) {
int tmp = start;
start = end;
end = tmp;
}
printf("%d to %d\n", start, end);
inc_subarray_mt(ary_mt, start, end);
inc_subarray(ary, start, end);
}
for (int i = 0; i < 100; i++) {
if (ary_mt[i] != ary[i]) {
printf("ary[%d]: %d != %d\n", i, ary[i], ary_mt[i]);fflush(stdout);
errors++;
}
}
if (errors){
printf("FAIL\n");
return 1;
}
printf("PASS\n");
return 0;
}
|
FBGemmFPTest.h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <gtest/gtest.h>
#include <random>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "./TestUtils.h"
#include "bench/AlignedVec.h"
#include "bench/BenchUtils.h"
#include "fbgemm/FbgemmPackMatrixB.h"
#include "src/RefImplementations.h"
#ifdef USE_IACA
#include "iacaMarks.h"
#endif
namespace fbgemm {
/*
* @brief Abstract of the GEMM FP test
* The template parameter is transpose of A and B
*/
template <typename T>
class FBGemmFPTest : public testing::TestWithParam<
std::pair<fbgemm::matrix_op_t, fbgemm::matrix_op_t>> {
protected:
std::vector<std::vector<int>> GenShapes() const {
std::vector<std::vector<int>> shapes;
std::random_device r;
std::default_random_engine generator(r());
std::uniform_int_distribution<int> dm(1, 256);
std::uniform_int_distribution<int> dnk(1, 1024);
for (int i = 0; i < 10; i++) {
int m = dm(generator);
int n = dnk(generator);
int k = dnk(generator);
shapes.push_back({m, n, k});
}
return shapes;
}
void TestRun() {
auto shapes = GenShapes();
float alpha = 1.f, beta = 0.f;
matrix_op_t atrans, btrans;
std::tie(atrans, btrans) = GetParam();
for (auto s : shapes) {
int m = s[0];
int n = s[1];
int k = s[2];
std::cerr << "m = " << m << " n = " << n << " k = " << k;
if (atrans == matrix_op_t::Transpose) {
std::cerr << " A_transposed";
}
if (btrans == matrix_op_t::Transpose) {
std::cerr << " B_transposed";
}
std::cerr << std::endl;
// initialize with small numbers
aligned_vector<int> Aint(m * k);
aligned_vector<int> Bint(k * n);
randFill(Aint, 0, 4);
randFill(Bint, 0, 4);
aligned_vector<float> A(Aint.begin(), Aint.end());
aligned_vector<float> B(Bint.begin(), Bint.end());
aligned_vector<float> C(m * n, NAN);
aligned_vector<float> A_ref(A), B_ref(B), C_ref(C);
// Gold via reference sgemm
cblas_sgemm_ref(
atrans,
btrans,
m,
n,
k,
1.0f,
A_ref.data(),
atrans == matrix_op_t::Transpose ? m : k,
B_ref.data(),
btrans == matrix_op_t::Transpose ? k : n,
0.0f,
C_ref.data(),
n);
PackedGemmMatrixB<T> Bp(btrans, k, n, alpha, B.data());
#ifdef _OPENMP
#pragma omp parallel
#endif
{
int num_threads = fbgemm_get_num_threads();
int tid = fbgemm_get_thread_num();
cblas_gemm_compute(
atrans, m, A.data(), Bp, beta, C.data(), tid, num_threads);
}
// correctness check
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
float expected = C_ref[i * n + j];
float actual = C[i * n + j];
EXPECT_EQ(actual, expected)
<< "GEMM results differ at (" << i << ", " << j << "). ref "
<< expected << " FBGemm " << actual;
}
}
}
}
void UnpackTestRun() {
auto shapes = GenShapes();
float alpha = 1.f, beta = 0.f;
matrix_op_t atrans, btrans;
std::tie(atrans, btrans) = GetParam();
for (auto s : shapes) {
int m = s[0];
int n = s[1];
int k = s[2];
std::cerr << "m = " << m << " n = " << n << " k = " << k;
if (atrans == matrix_op_t::Transpose) {
std::cerr << " A_transposed";
}
if (btrans == matrix_op_t::Transpose) {
std::cerr << " B_transposed";
}
std::cerr << std::endl;
// initialize with small numbers
aligned_vector<int> Aint(m * k);
aligned_vector<int> Bint(k * n);
randFill(Aint, 0, 4);
randFill(Bint, 0, 4);
aligned_vector<float> A(Aint.begin(), Aint.end());
aligned_vector<float> B(Bint.begin(), Bint.end());
aligned_vector<float> C(m * n, NAN);
aligned_vector<float> A_ref(A), B_ref(B), C_ref(C);
// Gold via reference sgemm
cblas_sgemm_ref(
atrans,
btrans,
m,
n,
k,
1.0f,
A_ref.data(),
atrans == matrix_op_t::Transpose ? m : k,
B_ref.data(),
btrans == matrix_op_t::Transpose ? k : n,
0.0f,
C_ref.data(),
n);
// fbgemm fp16
PackedGemmMatrixB<T> Bp(btrans, k, n, alpha, B.data());
EXPECT_TRUE(Bp.packed());
// Test unpack
aligned_vector<T> tmp(Bp.matSize());
memcpy(tmp.data(), Bp.pmat(), Bp.matSize() * sizeof(T));
Bp.unpackFromSrc(btrans, tmp.data());
EXPECT_FALSE(Bp.packed());
memcpy(tmp.data(), Bp.pmat(), Bp.matSize() * sizeof(T));
for (int i = 0; i < k; ++i) {
for (int j = 0; j < n; ++j) {
EXPECT_EQ(
sizeof(T) == sizeof(float16) ? cpu_half2float(tmp[i * n + j])
: tmp[i * n + j],
B[i * n + j]);
}
}
// Pack it back
Bp.packFromSrc(btrans, tmp.data());
EXPECT_TRUE(Bp.packed());
#ifdef _OPENMP
#pragma omp parallel
#endif
{
int num_threads = fbgemm_get_num_threads();
int tid = fbgemm_get_thread_num();
cblas_gemm_compute(
atrans, m, A.data(), Bp, beta, C.data(), tid, num_threads);
}
// correctness check
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
float expected = C_ref[i * n + j];
float actual = C[i * n + j];
EXPECT_EQ(actual, expected)
<< "GEMM results differ at (" << i << ", " << j << "). ref "
<< expected << " FBGemm " << actual;
}
}
}
}
};
} // namespace fbgemm
|
test_zpotrf_nopack.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> s d c
*
**/
#include "test.h"
#include "flops.h"
#include "plasma.h"
#include <plasma_core_blas.h>
#include "core_lapack.h"
#include <assert.h>
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#define COMPLEX
#define A(i_, j_) A[(i_) + (size_t)lda*(j_)]
/***************************************************************************//**
*
* @brief Tests ZPOTRF.
*
* @param[in,out] param - array of parameters
* @param[in] run - whether to run test
*
* Sets flags in param indicating which parameters are used.
* If run is true, also runs test and stores output parameters.
******************************************************************************/
void test_zpotrf_nopack(param_value_t param[], bool run)
{
//================================================================
// Mark which parameters are used.
//================================================================
param[PARAM_UPLO ].used = true;
param[PARAM_DIM ].used = PARAM_USE_N;
param[PARAM_PADA ].used = true;
param[PARAM_NB ].used = true;
param[PARAM_ZEROCOL].used = true;
if (! run)
return;
//================================================================
// Set parameters.
//================================================================
plasma_enum_t uplo = plasma_uplo_const(param[PARAM_UPLO].c);
int n = param[PARAM_DIM].dim.n;
int lda = imax(1, n + param[PARAM_PADA].i);
int test = param[PARAM_TEST].c == 'y';
double tol = param[PARAM_TOL].d * LAPACKE_dlamch('E');
//================================================================
// Set tuning parameters.
//================================================================
plasma_set(PlasmaTuning, PlasmaDisabled);
plasma_set(PlasmaNb, param[PARAM_NB].i);
//================================================================
// Allocate and initialize arrays.
//================================================================
plasma_complex64_t *A =
(plasma_complex64_t*)malloc((size_t)lda*n*sizeof(plasma_complex64_t));
assert(A != NULL);
int seed[] = {0, 0, 0, 1};
lapack_int retval;
retval = LAPACKE_zlarnv(1, seed, (size_t)lda*n, A);
assert(retval == 0);
//================================================================
// Make the A matrix symmetric/Hermitian positive definite.
// It increases diagonal by n, and makes it real.
// It sets Aji = conj( Aij ) for j < i, that is, copy lower
// triangle to upper triangle.
//================================================================
for (int i = 0; i < n; i++) {
A(i, i) = creal(A(i, i)) + n;
for (int j = 0; j < i; j++) {
A(j, i) = conj(A(i, j));
}
}
int zerocol = param[PARAM_ZEROCOL].i;
if (zerocol >= 0 && zerocol < n)
memset(&A[zerocol*lda], 0, n*sizeof(plasma_complex64_t));
plasma_complex64_t *Aref = NULL;
if (test) {
Aref = (plasma_complex64_t*)malloc(
(size_t)lda*n*sizeof(plasma_complex64_t));
assert(Aref != NULL);
memcpy(Aref, A, (size_t)lda*n*sizeof(plasma_complex64_t));
}
//================================================================
// Run and time PLASMA.
//================================================================
//int plainfo = plasma_zpotrf(uplo, n, A, lda);
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if ((uplo != PlasmaUpper) &&
(uplo != PlasmaLower)) {
plasma_error("illegal value of uplo");
return -1;
}
if (n < 0) {
plasma_error("illegal value of n");
return -2;
}
if (lda < imax(1, n)) {
plasma_error("illegal value of lda");
return -4;
}
// quick return
if (imax(n, 0) == 0)
return PlasmaSuccess;
// Tune parameters.
if (plasma->tuning)
plasma_tune_potrf(plasma, PlasmaComplexDouble, n);
// Set tiling parameters.
int nb = plasma->nb;
// Create tile matrix.
plasma_desc_t AA;
int retval1;
retval1 = plasma_desc_triangular_create(PlasmaComplexDouble, uplo, nb, nb,
n, n, 0, 0, n, n, &AA);
if (retval1 != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
return retval1;
}
// Initialize sequence.
plasma_sequence_t sequence;
retval1 = plasma_sequence_init(&sequence);
// Initialize request.
plasma_request_t request;
retval1 = plasma_request_init(&request);
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate to tile layout.
plasma_omp_ztr2desc(A, lda, AA, &sequence, &request);
}
plasma_time_t start = omp_get_wtime();
#pragma omp parallel
#pragma omp master
{
// Call the tile async function.
plasma_omp_zpotrf(uplo, AA, &sequence, &request);
}
plasma_time_t stop = omp_get_wtime();
plasma_time_t time = stop-start;
param[PARAM_TIME].d = time;
param[PARAM_GFLOPS].d = flops_zpotrf(n) / time / 1e9;
#pragma omp parallel
#pragma omp master
{
// Translate back to LAPACK layout.
plasma_omp_zdesc2tr(AA, A, lda, &sequence, &request);
}
// implicit synchronization
// Free matrix A in tile layout.
plasma_desc_destroy(&AA);
int plainfo = sequence.status;
//================================================================
// Test results by comparing to a reference implementation.
//================================================================
if (test) {
int lapinfo = LAPACKE_zpotrf(LAPACK_COL_MAJOR,
lapack_const(uplo), n,
Aref, lda);
if (lapinfo == 0) {
plasma_complex64_t zmone = -1.0;
cblas_zaxpy((size_t)lda*n, CBLAS_SADDR(zmone), Aref, 1, A, 1);
double work[1];
double Anorm = LAPACKE_zlanhe_work(
LAPACK_COL_MAJOR, 'F', lapack_const(uplo), n, Aref, lda, work);
double error = LAPACKE_zlange_work(
LAPACK_COL_MAJOR, 'F', n, n, A, lda, work);
if (Anorm != 0)
error /= Anorm;
param[PARAM_ERROR].d = error;
param[PARAM_SUCCESS].i = error < tol;
}
else {
if (plainfo == lapinfo) {
param[PARAM_ERROR].d = 0.0;
param[PARAM_SUCCESS].i = 1;
}
else {
param[PARAM_ERROR].d = INFINITY;
param[PARAM_SUCCESS].i = 0;
}
}
}
//================================================================
// Free arrays.
//================================================================
free(A);
if (test)
free(Aref);
}
|
relic_cp_phpe.c | /*
* RELIC is an Efficient LIbrary for Cryptography
* Copyright (c) 2014 RELIC Authors
*
* This file is part of RELIC. RELIC is legal property of its developers,
* whose names are not listed here. Please refer to the COPYRIGHT file
* for contact information.
*
* RELIC is free software; you can redistribute it and/or modify it under the
* terms of the version 2.1 (or later) of the GNU Lesser General Public License
* as published by the Free Software Foundation; or version 2.0 of the Apache
* License as published by the Apache Software Foundation. See the LICENSE files
* for more details.
*
* RELIC 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 LICENSE files for more details.
*
* You should have received a copy of the GNU Lesser General Public or the
* Apache License along with RELIC. If not, see <https://www.gnu.org/licenses/>
* or <https://www.apache.org/licenses/>.
*/
/**
* @file
*
* Implementation of Paillier's Homomorphic Probabilistic Encryption.
*
* @ingroup cp
*/
#include "relic.h"
/*============================================================================*/
/* Public definitions */
/*============================================================================*/
int cp_phpe_gen(bn_t pub, phpe_t prv, int bits) {
int result = RLC_OK;
/* Generate primes p and q of equivalent length. */
do {
bn_gen_prime(prv->p, bits / 2);
bn_gen_prime(prv->q, bits / 2);
} while (bn_cmp(prv->p, prv->q) == RLC_EQ);
/* Compute n = pq and l = \phi(n). */
bn_mul(prv->n, prv->p, prv->q);
#ifdef CP_CRT
/* Fix g = n + 1. */
bn_add_dig(pub, prv->n, 1);
/* Precompute dp = 1/(pow(g, p-1, p^2)//p mod p. */
bn_sqr(prv->dp, prv->p);
bn_sub_dig(prv->p, prv->p, 1);
bn_mxp(prv->dp, pub, prv->p, prv->dp);
bn_sub_dig(prv->dp, prv->dp, 1);
bn_div(prv->dp, prv->dp, prv->p);
/* Precompute dq = 1/(pow(g, q-1, q^2)//q mod q. */
bn_sqr(prv->dq, prv->q);
bn_sub_dig(prv->q, prv->q, 1);
bn_mxp(prv->dq, pub, prv->q, prv->dq);
bn_sub_dig(prv->dq, prv->dq, 1);
bn_div(prv->dq, prv->dq, prv->q);
/* Restore p and q. */
bn_add_dig(prv->p, prv->p, 1);
bn_add_dig(prv->q, prv->q, 1);
bn_mod_inv(prv->dp, prv->dp, prv->p);
bn_mod_inv(prv->dq, prv->dq, prv->q);
/* qInv = q^(-1) mod p. */
bn_mod_inv(prv->qi, prv->q, prv->p);
#endif
bn_copy(pub, prv->n);
return result;
}
int cp_phpe_enc(bn_t c, bn_t m, bn_t pub) {
bn_t g, r, s;
int result = RLC_OK;
bn_null(g);
bn_null(r);
bn_null(s);
if (pub == NULL || bn_bits(m) > bn_bits(pub)) {
return RLC_ERR;
}
RLC_TRY {
bn_new(g);
bn_new(r);
bn_new(s);
/* Generate r in Z_n^*. */
bn_rand_mod(r, pub);
/* Compute c = (g^m)(r^n) mod n^2. */
bn_add_dig(g, pub, 1);
bn_sqr(s, pub);
bn_mxp(c, g, m, s);
bn_mxp(r, r, pub, s);
bn_mul(c, c, r);
bn_mod(c, c, s);
}
RLC_CATCH_ANY {
result = RLC_ERR;
}
RLC_FINALLY {
bn_free(g);
bn_free(r);
bn_free(s);
}
return result;
}
int cp_phpe_dec(bn_t m, bn_t c, phpe_t prv) {
bn_t s, t, u, v;
int result = RLC_OK;
if (prv == NULL || bn_bits(c) > 2 * bn_bits(prv->n)) {
return RLC_ERR;
}
bn_null(s);
bn_null(t);
bn_null(u);
bn_null(v);
RLC_TRY {
bn_new(s);
bn_new(t);
bn_new(u);
bn_new(v);
#if !defined(CP_CRT)
bn_sub_dig(s, prv->p, 1);
bn_sub_dig(t, prv->q, 1);
bn_mul(s, s, t);
/* Compute (c^l mod n^2) * u mod n. */
bn_sqr(t, prv->n);
bn_mxp(m, c, s, t);
bn_sub_dig(m, m, 1);
bn_div(m, m, prv->n);
bn_mod_inv(t, s, prv->n);
bn_mul(m, m, t);
bn_mod(m, m, prv->n);
#else
#if MULTI == OPENMP
omp_set_num_threads(CORES);
#pragma omp parallel copyin(core_ctx) firstprivate(c, prv)
{
#pragma omp sections
{
#pragma omp section
{
#endif
/* Compute m_p = (c^(p-1) mod p^2) * dp mod p. */
bn_sub_dig(t, prv->p, 1);
bn_sqr(s, prv->p);
bn_mxp(s, c, t, s);
bn_sub_dig(s, s, 1);
bn_div(s, s, prv->p);
bn_mul(s, s, prv->dp);
bn_mod(s, s, prv->p);
#if MULTI == OPENMP
}
#pragma omp section
{
#endif
/* Compute m_q = (c^(q-1) mod q^2) * dq mod q. */
bn_sub_dig(v, prv->q, 1);
bn_sqr(u, prv->q);
bn_mxp(u, c, v, u);
bn_sub_dig(u, u, 1);
bn_div(u, u, prv->q);
bn_mul(u, u, prv->dq);
bn_mod(u, u, prv->q);
#if MULTI == OPENMP
}
}
}
#endif
/* m = (m_p - m_q) mod p. */
bn_sub(m, s, u);
while (bn_sign(m) == RLC_NEG) {
bn_add(m, m, prv->p);
}
bn_mod(m, m, prv->p);
/* m1 = qInv(m_p - m_q) mod p. */
bn_mul(m, m, prv->qi);
bn_mod(m, m, prv->p);
/* m = m2 + m1 * q. */
bn_mul(m, m, prv->q);
bn_add(m, m, u);
bn_mod(m, m, prv->n);
#endif
} RLC_CATCH_ANY {
result = RLC_ERR;
}
RLC_FINALLY {
bn_free(s);
bn_free(t);
bn_free(u);
bn_free(v);
}
return result;
}
|
hmap_mk_tid.c | /*
* Copyright (c) 2019 Ramesh Subramonian <subramonian@gmail.com>
* All rights reserved.
*
* Use is subject to license terms, as specified in the LICENSE file.
*/
//------------------------------------------------------
//START_INCLUDES
#include "hmap_common.h"
//STOP_INCLUDES
#include "_hmap_mk_tid.h"
/* Ideally, we want to distribute the work to the threads so that
* 1) they never update the same cell
* 2) they (ideally) have large contiguous regions which they own i.e.,
* only they write in that region
Dividing based on hashes gives us 1)
Dividing based on locs gives us 2)
However, since 1) is more important than 2), we went with 1)
Note that locs doesn't give you the location of a key.
It only gives you a starting point for the hunt for the location of a key
*/
//START_FOR_CDEF
int
hmap_mk_tid(
uint32_t *hashes, // input [nkeys]
uint32_t nkeys, // input
uint32_t nT, // input , number of threads
uint8_t *tids // output [nkeys]
)
//STOP_FOR_CDEF
{
int status = 0;
int chunk_size = 1024;
uint64_t divinfo = fast_div32_init(nT);
#pragma omp parallel for schedule(static, chunk_size)
for ( uint32_t i = 0; i < nkeys; i++ ) {
tids[i] = fast_rem32(hashes[i], nT, divinfo);
}
return status;
}
|
pngquant.c | /* pngquant.c - quantize the colors in an alphamap down to a specified number
**
** © 2009-2019 by Kornel Lesiński.
** © 1989, 1991 by Jef Poskanzer.
** © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider.
**
** See COPYRIGHT file for license.
*/
char *PNGQUANT_USAGE = "\
usage: pngquant [options] [ncolors] -- pngfile [pngfile ...]\n\
pngquant [options] [ncolors] - >stdout <stdin\n\n\
options:\n\
--force overwrite existing output files (synonym: -f)\n\
--skip-if-larger only save converted files if they're smaller than original\n\
--output file destination file path to use instead of --ext (synonym: -o)\n\
--ext new.png set custom suffix/extension for output filenames\n\
--quality min-max don't save below min, use fewer colors below max (0-100)\n\
--speed N speed/quality trade-off. 1=slow, 4=default, 11=fast & rough\n\
--nofs disable Floyd-Steinberg dithering\n\
--posterize N output lower-precision color (e.g. for ARGB4444 output)\n\
--strip remove optional metadata (default on Mac)\n\
--verbose print status messages (synonym: -v)\n\
\n\
Quantizes one or more 32-bit RGBA PNGs to 8-bit (or smaller) RGBA-palette.\n\
The output filename is the same as the input name except that\n\
it ends in \"-fs8.png\", \"-or8.png\" or your custom extension (unless the\n\
input is stdin, in which case the quantized image will go to stdout).\n\
If you pass the special output path \"-\" and a single input file, that file\n\
will be processed and the quantized image will go to stdout.\n\
The default behavior if the output file exists is to skip the conversion;\n\
use --force to overwrite. See man page for full list of options.\n";
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
#include <math.h>
#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
#include <fcntl.h> /* O_BINARY */
#include <io.h> /* setmode() */
#include <locale.h> /* UTF-8 locale */
#else
#include <unistd.h>
#endif
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_max_threads() 1
#define omp_get_thread_num() 0
#endif
#include "rwpng.h" /* typedefs, common macros, public prototypes */
#include "libimagequant.h" /* if it fails here, run: git submodule update; ./configure; or add -Ilib to compiler flags */
#include "pngquant_opts.h"
char *PNGQUANT_VERSION = LIQ_VERSION_STRING " (September 2021)";
static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform tag, png8_image *output_image);
static void set_palette(liq_result *result, png8_image *output_image);
static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose);
static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options, liq_attr *liq);
static char *add_filename_extension(const char *filename, const char *newext);
static bool file_exists(const char *outname);
static void verbose_printf(liq_attr *liq, struct pngquant_options *context, const char *fmt, ...)
{
if (context->log_callback) {
va_list va;
va_start(va, fmt);
int required_space = vsnprintf(NULL, 0, fmt, va)+1; // +\0
va_end(va);
#if defined(_MSC_VER)
char *buf = malloc(required_space);
#else
char buf[required_space];
#endif
va_start(va, fmt);
vsnprintf(buf, required_space, fmt, va);
va_end(va);
context->log_callback(liq, buf, context->log_callback_user_info);
#if defined(_MSC_VER)
free(buf);
#endif
}
}
static void log_callback(const liq_attr *attr, const char *msg, void* user_info)
{
fprintf(stderr, "%s\n", msg);
}
#ifdef _OPENMP
#define LOG_BUFFER_SIZE 1300
struct buffered_log {
int buf_used;
char buf[LOG_BUFFER_SIZE];
};
static void log_callback_buferred_flush(const liq_attr *attr, void *context)
{
struct buffered_log *log = context;
if (log->buf_used) {
fwrite(log->buf, 1, log->buf_used, stderr);
fflush(stderr);
log->buf_used = 0;
}
}
static void log_callback_buferred(const liq_attr *attr, const char *msg, void* context)
{
struct buffered_log *log = context;
int len = strlen(msg);
if (len > LOG_BUFFER_SIZE-2) len = LOG_BUFFER_SIZE-2;
if (len > LOG_BUFFER_SIZE - log->buf_used - 2) log_callback_buferred_flush(attr, log);
memcpy(&log->buf[log->buf_used], msg, len);
log->buf_used += len+1;
log->buf[log->buf_used-1] = '\n';
log->buf[log->buf_used] = '\0';
}
#endif
void pngquant_internal_print_config(FILE *fd) {
fputs(""
#ifndef NDEBUG
" WARNING: this is a DEBUG (slow) version.\n" /* NDEBUG disables assert() */
#endif
#if !USE_SSE && (defined(__SSE__) || defined(__amd64__) || defined(__X86_64__) || defined(__i386__))
" SSE acceleration disabled.\n"
#endif
#if _OPENMP
" Compiled with OpenMP (multicore support).\n"
#endif
, fd);
fflush(fd);
}
FILE *pngquant_c_stderr() {
return stderr;
}
FILE *pngquant_c_stdout() {
return stdout;
}
static void print_full_version(FILE *fd)
{
fprintf(fd, "pngquant, %s, by Kornel Lesinski, Greg Roelofs.\n", PNGQUANT_VERSION);
pngquant_internal_print_config(fd);
rwpng_version_info(fd);
fputs("\n", fd);
}
static void print_usage(FILE *fd)
{
fputs(PNGQUANT_USAGE, fd);
}
/**
* N = automatic quality, uses limit unless force is set (N-N or 0-N)
* -N = no better than N (same as 0-N)
* N-M = no worse than N, no better than M
* N- = no worse than N, perfect if possible (same as N-100)
*
* where N,M are numbers between 0 (lousy) and 100 (perfect)
*/
static bool parse_quality(const char *quality, liq_attr *options, bool *min_quality_limit)
{
long limit, target;
const char *str = quality; char *end;
long t1 = strtol(str, &end, 10);
if (str == end) return false;
str = end;
if ('\0' == end[0] && t1 < 0) { // quality="-%d"
target = -t1;
limit = 0;
} else if ('\0' == end[0]) { // quality="%d"
target = t1;
limit = t1*9/10;
} else if ('-' == end[0] && '\0' == end[1]) { // quality="%d-"
target = 100;
limit = t1;
} else { // quality="%d-%d"
long t2 = strtol(str, &end, 10);
if (str == end || t2 > 0) return false;
target = -t2;
limit = t1;
}
*min_quality_limit = (limit > 0);
return LIQ_OK == liq_set_quality(options, limit, target);
}
pngquant_error pngquant_main_internal(struct pngquant_options *options, liq_attr *liq);
static pngquant_error pngquant_file_internal(const char *filename, const char *outname, struct pngquant_options *options, liq_attr *liq);
#ifndef PNGQUANT_NO_MAIN
int main(int argc, char *argv[])
{
struct pngquant_options options = {
.floyd = 1.f, // floyd-steinberg dithering
.strip = false,
};
pngquant_error retval = pngquant_parse_options(argc, argv, &options);
if (retval != SUCCESS) {
return retval;
}
if (options.print_version) {
puts(PNGQUANT_VERSION);
return SUCCESS;
}
if (options.missing_arguments) {
print_full_version(stderr);
print_usage(stderr);
return MISSING_ARGUMENT;
}
if (options.print_help) {
print_full_version(stdout);
print_usage(stdout);
return SUCCESS;
}
#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
setlocale(LC_ALL, ".65001"); // issue #376; set UTF-8 for Unicode filenames
#endif
liq_attr *liq = liq_attr_create();
if (!liq) {
fputs("SSE-capable CPU is required for this build.\n", stderr);
return WRONG_ARCHITECTURE;
}
if (options.quality && !parse_quality(options.quality, liq, &options.min_quality_limit)) {
fputs("Quality should be in format min-max where min and max are numbers in range 0-100.\n", stderr);
return INVALID_ARGUMENT;
}
if (options.iebug) {
// opacities above 238 will be rounded up to 255, because IE6 truncates <255 to 0.
liq_set_min_opacity(liq, 238);
fputs(" warning: the workaround for IE6 is deprecated\n", stderr);
}
if (options.verbose) {
liq_set_log_callback(liq, log_callback, NULL);
options.log_callback = log_callback;
}
if (options.last_index_transparent) {
liq_set_last_index_transparent(liq, true);
}
if (options.speed >= 10) {
options.fast_compression = true;
if (options.speed == 11) {
options.floyd = 0;
options.speed = 10;
}
}
if (options.speed && LIQ_OK != liq_set_speed(liq, options.speed)) {
fputs("Speed should be between 1 (slow) and 11 (fast).\n", stderr);
return INVALID_ARGUMENT;
}
if (options.colors && LIQ_OK != liq_set_max_colors(liq, options.colors)) {
fputs("Number of colors must be between 2 and 256.\n", stderr);
return INVALID_ARGUMENT;
}
if (options.posterize && LIQ_OK != liq_set_min_posterization(liq, options.posterize)) {
fputs("Posterization should be number of bits in range 0-4.\n", stderr);
return INVALID_ARGUMENT;
}
if (options.extension && options.output_file_path) {
fputs("--ext and --output options can't be used at the same time\n", stderr);
return INVALID_ARGUMENT;
}
// new filename extension depends on options used. Typically basename-fs8.png
if (options.extension == NULL) {
options.extension = options.floyd > 0 ? "-fs8.png" : "-or8.png";
}
if (options.output_file_path && options.num_files != 1) {
fputs(" error: Only one input file is allowed when --output is used. This error also happens when filenames with spaces are not in quotes.\n", stderr);
return INVALID_ARGUMENT;
}
if (options.using_stdout && !options.using_stdin && options.num_files != 1) {
fputs(" error: Only one input file is allowed when using the special output path \"-\" to write to stdout. This error also happens when filenames with spaces are not in quotes.\n", stderr);
return INVALID_ARGUMENT;
}
if (!options.num_files && !options.using_stdin) {
fputs("No input files specified.\n", stderr);
if (options.verbose) {
print_full_version(stderr);
}
print_usage(stderr);
return MISSING_ARGUMENT;
}
retval = pngquant_main_internal(&options, liq);
liq_attr_destroy(liq);
return retval;
}
#endif
// Don't use this. This is not a public API.
pngquant_error pngquant_main_internal(struct pngquant_options *options, liq_attr *liq)
{
#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
setlocale(LC_ALL, ".65001"); // issue #376; set UTF-8 for Unicode filenames
#endif
if (options->map_file) {
png24_image tmp = {.width=0};
if (SUCCESS != read_image(liq, options->map_file, false, &tmp, &options->fixed_palette_image, true, true, false)) {
fprintf(stderr, " error: unable to load %s", options->map_file);
return INVALID_ARGUMENT;
}
liq_result *tmp_quantize = liq_quantize_image(liq, options->fixed_palette_image);
const liq_palette *pal = liq_get_palette(tmp_quantize);
if (!pal) {
fprintf(stderr, " error: unable to read colors from %s", options->map_file);
return INVALID_ARGUMENT;
}
for(unsigned int i=0; i < pal->count; i++) {
liq_image_add_fixed_color(options->fixed_palette_image, pal->entries[i]);
}
liq_result_destroy(tmp_quantize);
}
#ifdef _OPENMP
// if there's a lot of files, coarse parallelism can be used
if (options->num_files > 2*omp_get_max_threads()) {
omp_set_nested(0);
omp_set_dynamic(1);
} else {
omp_set_nested(1);
}
#endif
unsigned int error_count=0, skipped_count=0, file_count=0;
pngquant_error latest_error=SUCCESS;
#pragma omp parallel for \
schedule(static, 1) reduction(+:skipped_count) reduction(+:error_count) reduction(+:file_count) shared(latest_error)
for(int i=0; i < options->num_files; i++) {
const char *filename = options->using_stdin ? "stdin" : options->files[i];
struct pngquant_options opts = *options;
liq_attr *local_liq = liq_attr_copy(liq);
#ifdef _OPENMP
struct buffered_log buf = {0};
if (opts.log_callback && omp_get_num_threads() > 1 && opts.num_files > 1) {
liq_set_log_callback(local_liq, log_callback_buferred, &buf);
liq_set_log_flush_callback(local_liq, log_callback_buferred_flush, &buf);
opts.log_callback = log_callback_buferred;
opts.log_callback_user_info = &buf;
}
#endif
pngquant_error retval = SUCCESS;
const char *outname = opts.output_file_path;
char *outname_free = NULL;
if (!opts.using_stdout) {
if (!outname) {
outname = outname_free = add_filename_extension(filename, opts.extension);
}
if (!opts.force && file_exists(outname)) {
fprintf(stderr, " error: '%s' exists; not overwriting\n", outname);
retval = NOT_OVERWRITING_ERROR;
}
}
if (SUCCESS == retval) {
retval = pngquant_file_internal(filename, outname, &opts, local_liq);
}
free(outname_free);
liq_attr_destroy(local_liq);
if (retval) {
#pragma omp critical
{
latest_error = retval;
}
if (retval == TOO_LOW_QUALITY || retval == TOO_LARGE_FILE) {
skipped_count++;
} else {
error_count++;
}
}
++file_count;
}
if (error_count) {
verbose_printf(liq, options, "There were errors quantizing %d file%s out of a total of %d file%s.",
error_count, (error_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s");
}
if (skipped_count) {
verbose_printf(liq, options, "Skipped %d file%s out of a total of %d file%s.",
skipped_count, (skipped_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s");
}
if (!skipped_count && !error_count) {
verbose_printf(liq, options, "Quantized %d image%s.",
file_count, (file_count == 1)? "" : "s");
}
if (options->fixed_palette_image) liq_image_destroy(options->fixed_palette_image);
return latest_error;
}
/// Don't hack this. Instead use https://github.com/ImageOptim/libimagequant/blob/f54d2f1a3e1cf728e17326f4db0d45811c63f063/example.c
static pngquant_error pngquant_file_internal(const char *filename, const char *outname, struct pngquant_options *options, liq_attr *liq)
{
pngquant_error retval = SUCCESS;
verbose_printf(liq, options, "%s:", filename);
liq_image *input_image = NULL;
png24_image input_image_rwpng = {.width=0};
bool keep_input_pixels = options->skip_if_larger || (options->using_stdout && options->min_quality_limit); // original may need to be output to stdout
if (SUCCESS == retval) {
retval = read_image(liq, filename, options->using_stdin, &input_image_rwpng, &input_image, keep_input_pixels, options->strip, options->verbose);
}
int quality_percent = 90; // quality on 0-100 scale, updated upon successful remap
png8_image output_image = {.width=0};
if (SUCCESS == retval) {
verbose_printf(liq, options, " read %luKB file", (input_image_rwpng.file_size+1023UL)/1024UL);
if (RWPNG_ICCP == input_image_rwpng.input_color) {
verbose_printf(liq, options, " used embedded ICC profile to transform image to sRGB colorspace");
} else if (RWPNG_GAMA_CHRM == input_image_rwpng.input_color) {
verbose_printf(liq, options, " used gAMA and cHRM chunks to transform image to sRGB colorspace");
} else if (RWPNG_ICCP_WARN_GRAY == input_image_rwpng.input_color) {
verbose_printf(liq, options, " warning: ignored ICC profile in GRAY colorspace");
} else if (RWPNG_COCOA == input_image_rwpng.input_color) {
// No comment
} else if (RWPNG_SRGB == input_image_rwpng.input_color) {
verbose_printf(liq, options, " passing sRGB tag from the input");
} else if (input_image_rwpng.gamma != 0.45455) {
verbose_printf(liq, options, " converted image from gamma %2.1f to gamma 2.2",
1.0/input_image_rwpng.gamma);
}
// when using image as source of a fixed palette the palette is extracted using regular quantization
liq_result *remap;
liq_error remap_error = liq_image_quantize(options->fixed_palette_image ? options->fixed_palette_image : input_image, liq, &remap);
if (LIQ_OK == remap_error) {
// fixed gamma ~2.2 for the web. PNG can't store exact 1/2.2
// NB: can't change gamma here, because output_color is allowed to be an sRGB tag
liq_set_output_gamma(remap, 0.45455);
liq_set_dithering_level(remap, options->floyd);
retval = prepare_output_image(remap, input_image, input_image_rwpng.output_color, &output_image);
if (SUCCESS == retval) {
if (LIQ_OK != liq_write_remapped_image_rows(remap, input_image, output_image.row_pointers)) {
retval = OUT_OF_MEMORY_ERROR;
}
set_palette(remap, &output_image);
double palette_error = liq_get_quantization_error(remap);
if (palette_error >= 0) {
quality_percent = liq_get_quantization_quality(remap);
verbose_printf(liq, options, " mapped image to new colors...MSE=%.3f (Q=%d)", palette_error, quality_percent);
}
}
liq_result_destroy(remap);
} else if (LIQ_QUALITY_TOO_LOW == remap_error) {
retval = TOO_LOW_QUALITY;
} else {
retval = INVALID_ARGUMENT; // dunno
}
}
if (SUCCESS == retval) {
if (options->skip_if_larger) {
// this is very rough approximation, but generally avoid losing more quality than is gained in file size.
// Quality is raised to 1.5, because even greater savings are needed to justify big quality loss.
// but >50% savings are considered always worthwhile in order to allow low quality conversions to work at all
const double quality = quality_percent/100.0;
const double expected_reduced_size = pow(quality, 1.5);
output_image.maximum_file_size = (input_image_rwpng.file_size-1) * (expected_reduced_size < 0.5 ? 0.5 : expected_reduced_size);
}
output_image.fast_compression = options->fast_compression;
output_image.chunks = input_image_rwpng.chunks; input_image_rwpng.chunks = NULL;
retval = write_image(&output_image, NULL, outname, options, liq);
if (TOO_LARGE_FILE == retval) {
verbose_printf(liq, options, " file exceeded expected size of %luKB", (unsigned long)output_image.maximum_file_size/1024UL);
}
if (SUCCESS == retval && output_image.metadata_size > 0) {
verbose_printf(liq, options, " copied %dKB of additional PNG metadata", (int)(output_image.metadata_size+999)/1000);
}
}
if (options->using_stdout && keep_input_pixels && (TOO_LARGE_FILE == retval || TOO_LOW_QUALITY == retval)) {
// when outputting to stdout it'd be nasty to create 0-byte file
// so if quality is too low, output 24-bit original
pngquant_error write_retval = write_image(NULL, &input_image_rwpng, outname, options, liq);
if (write_retval) {
retval = write_retval;
}
}
if (input_image) liq_image_destroy(input_image);
rwpng_free_image24(&input_image_rwpng);
rwpng_free_image8(&output_image);
return retval;
}
static void set_palette(liq_result *result, png8_image *output_image)
{
const liq_palette *palette = liq_get_palette(result);
output_image->num_palette = palette->count;
for(unsigned int i=0; i < palette->count; i++) {
const liq_color px = palette->entries[i];
output_image->palette[i] = (rwpng_rgba){.r=px.r, .g=px.g, .b=px.b, .a=px.a};
}
}
static bool file_exists(const char *outname)
{
FILE *outfile = fopen(outname, "rb");
if ((outfile ) != NULL) {
fclose(outfile);
return true;
}
return false;
}
/* build the output filename from the input name by inserting "-fs8" or
* "-or8" before the ".png" extension (or by appending that plus ".png" if
* there isn't any extension), then make sure it doesn't exist already */
static char *add_filename_extension(const char *filename, const char *newext)
{
size_t x = strlen(filename);
char* outname = malloc(x+4+strlen(newext)+1);
if (!outname) return NULL;
strcpy(outname, filename);
if (x > 4 && (strncmp(outname+x-4, ".png", 4) == 0 || strncmp(outname+x-4, ".PNG", 4) == 0)) {
strcpy(outname+x-4, newext);
} else {
strcpy(outname+x, newext);
}
return outname;
}
static char *temp_filename(const char *basename) {
size_t x = strlen(basename);
char *outname = malloc(x+1+4);
if (!outname) return NULL;
strcpy(outname, basename);
strcpy(outname+x, ".tmp");
return outname;
}
static void set_binary_mode(FILE *fp)
{
#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
setmode(fp == stdout ? 1 : 0, O_BINARY);
#endif
}
static const char *filename_part(const char *path)
{
const char *outfilename = strrchr(path, '/');
if (outfilename) {
return outfilename+1;
} else {
return path;
}
}
static bool replace_file(const char *from, const char *to, const bool force) {
#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
if (force) {
// On Windows rename doesn't replace
unlink(to);
}
#endif
return (0 == rename(from, to));
}
static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options, liq_attr *liq)
{
FILE *outfile;
char *tempname = NULL;
if (options->using_stdout) {
set_binary_mode(stdout);
outfile = stdout;
if (output_image) {
verbose_printf(liq, options, " writing %d-color image to stdout", output_image->num_palette);
} else {
verbose_printf(liq, options, " writing truecolor image to stdout");
}
} else {
tempname = temp_filename(outname);
if (!tempname) return OUT_OF_MEMORY_ERROR;
if ((outfile = fopen(tempname, "wb")) == NULL) {
fprintf(stderr, " error: cannot open '%s' for writing\n", tempname);
free(tempname);
return CANT_WRITE_ERROR;
}
if (output_image) {
verbose_printf(liq, options, " writing %d-color image as %s", output_image->num_palette, filename_part(outname));
} else {
verbose_printf(liq, options, " writing truecolor image as %s", filename_part(outname));
}
}
pngquant_error retval;
#pragma omp critical (libpng)
{
if (output_image) {
retval = rwpng_write_image8(outfile, output_image);
} else {
retval = rwpng_write_image24(outfile, output_image24);
}
}
if (!options->using_stdout) {
fclose(outfile);
if (SUCCESS == retval) {
// Image has been written to a temporary file and then moved over destination.
// This makes replacement atomic and avoids damaging destination file on write error.
if (!replace_file(tempname, outname, options->force)) {
retval = CANT_WRITE_ERROR;
}
}
if (retval) {
unlink(tempname);
}
}
free(tempname);
if (retval && retval != TOO_LARGE_FILE) {
fprintf(stderr, " error: failed writing image to %s (%d)\n", options->using_stdout ? "stdout" : outname, retval);
}
return retval;
}
static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose)
{
FILE *infile;
if (using_stdin) {
set_binary_mode(stdin);
infile = stdin;
} else if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, " error: cannot open %s for reading\n", filename);
return READ_ERROR;
}
pngquant_error retval;
#pragma omp critical (libpng)
{
retval = rwpng_read_image24(infile, input_image_p, strip, verbose);
}
if (!using_stdin) {
fclose(infile);
}
if (retval) {
fprintf(stderr, " error: cannot decode image %s\n", using_stdin ? "from stdin" : filename_part(filename));
return retval;
}
*liq_image_p = liq_image_create_rgba_rows(options, (void**)input_image_p->row_pointers, input_image_p->width, input_image_p->height, input_image_p->gamma);
if (!*liq_image_p) {
return OUT_OF_MEMORY_ERROR;
}
if (!keep_input_pixels) {
if (LIQ_OK != liq_image_set_memory_ownership(*liq_image_p, LIQ_OWN_ROWS | LIQ_OWN_PIXELS)) {
return OUT_OF_MEMORY_ERROR;
}
input_image_p->row_pointers = NULL;
input_image_p->rgba_data = NULL;
}
return SUCCESS;
}
static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform output_color, png8_image *output_image)
{
output_image->width = liq_image_get_width(input_image);
output_image->height = liq_image_get_height(input_image);
output_image->gamma = liq_get_output_gamma(result);
output_image->output_color = output_color;
/*
** Step 3.7 [GRR]: allocate memory for the entire indexed image
*/
output_image->indexed_data = malloc((size_t)output_image->height * (size_t)output_image->width);
output_image->row_pointers = malloc((size_t)output_image->height * sizeof(output_image->row_pointers[0]));
if (!output_image->indexed_data || !output_image->row_pointers) {
return OUT_OF_MEMORY_ERROR;
}
for(size_t row = 0; row < output_image->height; row++) {
output_image->row_pointers[row] = output_image->indexed_data + row * output_image->width;
}
const liq_palette *palette = liq_get_palette(result);
// tRNS, etc.
output_image->num_palette = palette->count;
return SUCCESS;
}
|
serialized.c | // RUN: %libomp-compile-and-run | FileCheck %s
// REQUIRES: ompt
// UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7
#include "callback.h"
int main()
{
// print_frame(0);
#pragma omp parallel num_threads(1)
{
// print_frame(1);
print_ids(0);
print_ids(1);
// print_frame(0);
#pragma omp parallel num_threads(1)
{
// print_frame(1);
print_ids(0);
print_ids(1);
print_ids(2);
// print_frame(0);
#pragma omp task
{
// print_frame(1);
print_ids(0);
print_ids(1);
print_ids(2);
print_ids(3);
}
}
print_fuzzy_address(1);
}
print_fuzzy_address(2);
// Check if libomp supports the callbacks for this test.
// 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_event_implicit_task_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_event_implicit_task_end'
// 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=1, codeptr_ra=[[OUTER_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]+]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame={{0x[0-f]+}}, reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: task level 1: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]], task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]], reenter_frame={{0x[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin: parent_task_id=[[IMPLICIT_TASK_ID]], parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]], requested_team_size=1, codeptr_ra=[[INNER_RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}}, invoker=[[PARALLEL_INVOKER]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: parallel_id=[[NESTED_PARALLEL_ID]], task_id=[[NESTED_IMPLICIT_TASK_ID:[0-9]+]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[NESTED_PARALLEL_ID]], task_id=[[NESTED_IMPLICIT_TASK_ID]], exit_frame={{0x[0-f]+}}, reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: task level 1: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame={{0x[0-f]+}}, reenter_frame={{0x[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: task level 2: parallel_id=[[IMPLICIT_PARALLEL_ID]], task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]], reenter_frame={{0x[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_create: parent_task_id=[[NESTED_IMPLICIT_TASK_ID]], parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id=[[EXPLICIT_TASK_ID:[0-9]+]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_schedule: first_task_id=[[NESTED_IMPLICIT_TASK_ID]], second_task_id=[[EXPLICIT_TASK_ID]], prior_task_status=ompt_task_switch=7
// CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[NESTED_PARALLEL_ID]], task_id=[[EXPLICIT_TASK_ID]], exit_frame={{0x[0-f]+}}, reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: task level 1: parallel_id=[[NESTED_PARALLEL_ID]], task_id=[[NESTED_IMPLICIT_TASK_ID]], exit_frame={{0x[0-f]+}}, reenter_frame={{0x[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: task level 2: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], exit_frame={{0x[0-f]+}}, reenter_frame={{0x[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_schedule: first_task_id=[[EXPLICIT_TASK_ID]], second_task_id=[[NESTED_IMPLICIT_TASK_ID]], prior_task_status=ompt_task_complete=1
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_end: task_id=[[EXPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: parallel_id=0, task_id=[[NESTED_IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_end: parallel_id=[[NESTED_PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]], invoker=[[PARALLEL_INVOKER]], codeptr_ra=[[INNER_RETURN_ADDRESS]]{{[0-f][0-f]}}
// CHECK: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[INNER_RETURN_ADDRESS]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_end: parallel_id=[[PARALLEL_ID]], task_id=[[PARENT_TASK_ID]], invoker=[[PARALLEL_INVOKER]], codeptr_ra=[[OUTER_RETURN_ADDRESS]]{{[0-f][0-f]}}
// CHECK: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[OUTER_RETURN_ADDRESS]]
return 0;
}
|
inputNomain.c | /*
test input
a file without the main entry
By C. Liao
*/
#include <stdio.h>
#ifdef _OPENMP
#include "omp.h"
#endif
int foo(void)
{
#ifdef _OPENMP
omp_set_nested(1);
#endif
#pragma omp parallel
printf("Hello,world!\n");
#pragma omp parallel
{
printf("1Hello,world!\n");
#pragma omp parallel
printf("2Hello,world!\n");
}
return 0;
}
|
GB_unop__frexpx_fp64_fp64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__frexpx_fp64_fp64)
// op(A') function: GB (_unop_tran__frexpx_fp64_fp64)
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = GB_frexpx (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_frexpx (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = GB_frexpx (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_FREXPX || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__frexpx_fp64_fp64)
(
double *Cx, // Cx and Ax may be aliased
const double *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = GB_frexpx (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = GB_frexpx (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__frexpx_fp64_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__pow_fp64.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef 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__pow_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__pow_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__pow_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__pow_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_fp64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__pow_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__pow_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_fp64)
// C=scalar+B GB (_bind1st__pow_fp64)
// C=scalar+B' GB (_bind1st_tran__pow_fp64)
// C=A+scalar GB (_bind2nd__pow_fp64)
// C=A'+scalar GB (_bind2nd_tran__pow_fp64)
// C type: double
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = GB_pow (aij, bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
double aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
double bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
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 = GB_pow (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_POW || GxB_NO_FP64 || GxB_NO_POW_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__pow_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__pow_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__pow_fp64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__pow_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__pow_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__pow_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__pow_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__pow_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__pow_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] = GB_pow (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__pow_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] = GB_pow (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_pow (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__pow_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] = GB_pow (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__pow_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
|
GB_unaryop__lnot_int8_int8.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int8_int8
// op(A') function: GB_tran__lnot_int8_int8
// C type: int8_t
// A type: int8_t
// cast: int8_t cij = (int8_t) aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 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)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int8_int8
(
int8_t *Cx, // Cx and Ax may be aliased
int8_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int8_int8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
cpl_io_fits.c | /*
* This file is part of the ESO Common Pipeline Library
* Copyright (C) 2001-2017 European Southern Observatory
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "cpl_io_fits.h"
#include <cpl_memory.h>
#include <cpl_error_impl.h>
#include <cxlist.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
/* The below doxygen has been inactivated by removing the '**' comment. */
/*----------------------------------------------------------------------------*/
/*
* @defgroup cpl_io_fits Optimize open and close of FITS files
*
* The CPL API for FITS I/O passes only the FITS file name, and per default
* opens and closes each file for each I/O operation. Since the FITS standard
* does not allow random access to a given extension, the open/close approach
* causes the writing of a file with N extensions to have complexity O(N^2).
* The same is true for reading all N extensions.
*
* The complexity of those operations can be reduced to the expected O(N) by
* keeping the FITS files open between operations. This is done with
* static (thread-shared) storage of the relevant data.
*
* In a multi-threaded environment it is assumed that if one thread enters
* a CPL FITS save function for a given file, then there are no concurrent
* threads inside a CPL FITS I/O function for the same file. Consequently, in a
* multi-threaded environment it is assumed that if one thread enters a CPL FITS
* load function for a given file, then there are no concurrent threads inside a
* CPL FITS save function.
*
* This means that it is safe to let different threads take turns using the
* same read/write handle (for reading and/or writing).
*
* A handle for read-only is only used by the creating thread, this allows
* different threads to read from different parts of the same file.
*
* The unit tests in cplcore/tests/cpl_io_fits-test.c provide examples of this.
*
* @par Synopsis:
* @code
* #include "cpl_io_fits.h"
* @endcode
*/
/*----------------------------------------------------------------------------*/
/**@{*/
/*-----------------------------------------------------------------------------
Private types
-----------------------------------------------------------------------------*/
typedef struct cpl_fitsfile_t {
char * name;
fitsfile * fptr;
int iomode; /* CFITSIO currently defines: READONLY, READWRITE */
cpl_boolean has_stat; /* Set to true iff stat() can be & was called OK. */
/* When false, the below members are undefined */
#ifdef CPL_HAVE_STAT
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
#endif
int tid; /* Thread id. It must be matched for read-reuse.
If must also be matched if a file must be closed
prematurely because there are too many open files.
If matched for write-reuse the thread id is therefore
modified to that of the reuser. */
cpl_boolean writing; /* CPL_TRUE iff a file is used for writing. If a
file opened for writing is reused for reading,
then this flag is set to false, indicating that
subsequent reuse for reading must match the
thread id. */
} cpl_fitsfile_t;
/*-----------------------------------------------------------------------------
Private variables
-----------------------------------------------------------------------------*/
/* The maximum number of open FITS-files */
static cpl_size cpl_io_max_open = (CPL_IO_FITS_MAX_OPEN);
static cpl_size cpl_nfitsfiles = 0; /* The number of open FITS-files */
static cx_list * cpl_fitslist = NULL; /* The list of open, cached FITS-files */
/*-----------------------------------------------------------------------------
Private functions
-----------------------------------------------------------------------------*/
#ifdef CPL_IO_FITS
static cpl_boolean cpl_io_fits_find_fptr(cx_list_iterator *, const char *,
const int *, const struct stat *)
#ifdef CPL_HAVE_ATTR_NONNULL
__attribute__((nonnull(1)))
#endif
;
#endif
static fitsfile * cpl_io_fits_unset_fptr(const char *, const int *);
static fitsfile * cpl_io_fits_reuse_fptr(const char *, int, cpl_boolean)
#ifdef CPL_HAVE_ATTR_NONNULL
__attribute__((nonnull(1)))
#endif
;
static const char * cpl_io_fits_find_name(const fitsfile *, int *)
CPL_ATTR_NONNULL;
static void cpl_io_fits_set(fitsfile *, const char *, int, cpl_boolean)
CPL_ATTR_NONNULL;
static cpl_fitsfile_t * cpl_io_fits_unset_tid(int);
static int cpl_io_fits_free(cpl_fitsfile_t *, cpl_boolean, int *)
#ifdef CPL_HAVE_ATTR_NONNULL
__attribute__((nonnull(3)))
#endif
;
/*-----------------------------------------------------------------------------
Function definitions
-----------------------------------------------------------------------------*/
/**
* @internal
* @brief Initialize the caching of FITS-files
* @return void
* @see cpl_io_fits_end()
* @note If the caching is already active, nothing happens
*/
void cpl_io_fits_init(void)
{
#if defined HAVE_SYSCONF && defined _SC_OPEN_MAX
const long open_max = sysconf(_SC_OPEN_MAX);
if (0 <= open_max && open_max/2 < (CPL_IO_FITS_MAX_OPEN))
cpl_io_max_open = (cpl_size)(open_max/2);
#endif
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, cpl_fitslist == NULL
? "Initializing, max file pointers: %" CPL_SIZE_FORMAT " <= "
CPL_STRINGIFY(CPL_IO_FITS_MAX_OPEN)
: "Already initialized, max file pointers: %"
CPL_SIZE_FORMAT " <= "
CPL_STRINGIFY(CPL_IO_FITS_MAX_OPEN), cpl_io_max_open);
#endif
#ifdef CPL_IO_FITS
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
{
if (cpl_fitslist == NULL) {
cpl_fitslist = cx_list_new();
}
}
#endif
}
/**
* @internal
* @brief Close all open FITS files
* @return CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error
* @see cpl_io_fits_init()
* @note Must be called before program termination, after it is called
* no other functions from this module may be called
*
*/
cpl_error_code cpl_io_fits_end(void)
{
const cpl_error_code error = cpl_io_fits_close_tid(CPL_IO_FITS_ALL);
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Finished: " CPL_STRINGIFY(CPL_IO_FITS_MAX_OPEN));
#endif
#ifdef CPL_IO_FITS
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
{
if (cpl_fitslist != NULL) {
cx_list_delete(cpl_fitslist);
cpl_fitslist = NULL;
}
}
#endif
return error ? cpl_error_set_where_() : CPL_ERROR_NONE;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Close all files in use by the specified thread(s) (current or all)
@param mode CPL_IO_FITS_ALL (all threads) or CPL_IO_FITS_ONE (current thread)
@return Zero on success or else the CFITSIO status
*/
/*----------------------------------------------------------------------------*/
cpl_error_code cpl_io_fits_close_tid(cpl_boolean mode)
{
int status = 0;
if (cpl_fitslist != NULL) {
const int tid = mode == CPL_IO_FITS_ONE ? omp_get_thread_num() : -1;
cpl_fitsfile_t * oldest;
do {
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
oldest = cpl_io_fits_unset_tid(tid);
/* If a matching file is found, close it */
} while (oldest != NULL &&
!cpl_io_fits_free(oldest, CPL_FALSE, &status));
}
return status ? cpl_error_set_where_() : CPL_ERROR_NONE;
}
/**
* @internal
* @brief Return true iff the I/O FITS optimized mode is enabled
* @return CPL_TRUE iff the I/O FITS optimized mode is enabled
* @see cpl_io_fits_init()
*
*/
cpl_boolean cpl_io_fits_is_enabled(void)
{
return cpl_fitslist != NULL ? CPL_TRUE : CPL_FALSE;
}
/**
* @internal
* @brief Open a fits file and destroy any preexisting file
* @param pfptr CFITSIO file pointer pointer to file
* @param filename Name of FITS file to open
* @param status Pointer to CFITSIO error status
* @return The CFITSIO error status
* @see fits_create_file()
* @note Since the underlying CFITSIO call supports meta-characters _all_
* currently open files are closed prior to opening this one.
*
*/
int cpl_io_fits_create_file(fitsfile **pfptr, const char *filename, int *status)
{
if (*status == 0) { /* Duplicate CFITSIO behaviour */
/* The caller comes from a cpl_*_save(), so we are free
to assume that no other thread is inside a cpl I/O function
concerning the same file. We can therefore unset and close all
file pointers open for that filename. */
while ((*pfptr = cpl_io_fits_unset_fptr(filename, NULL)) != NULL &&
!fits_close_file(*pfptr, status)) {
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--;
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Closed file: %s (%p) (%d)", filename,
(const void*)*pfptr, (int)cpl_nfitsfiles);
#endif
}
if (*pfptr == NULL) {
if (cpl_fitslist != NULL) {
const int tid = omp_get_thread_num();
cpl_fitsfile_t * oldest = NULL;
#ifdef _OPENMP
/* Comparison critical with cpl_nfitsfiles increment */
#pragma omp critical(cpl_io_fits)
#endif
{
/* Need to open a file. Incerement prior to actual open,
in order to avoid the case where a number of synchronized
threads first verify that the number of files is (just)
below the limit and then the all try to open, thus
exceeding the limit */
cpl_nfitsfiles++;
if (cpl_nfitsfiles > cpl_io_max_open) {
/* First need to close a file - find it first */
oldest = cpl_io_fits_unset_tid(tid);
}
}
if (cpl_io_fits_free(oldest, CPL_FALSE, status)) {
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--; /* The close failed, so no open */
return *status;
}
}
}
if (fits_create_file(pfptr, filename, status)) {
(void)cpl_error_set_fits(CPL_ERROR_FILE_NOT_CREATED, *status,
fits_create_file, "filename='%s'",
filename);
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--; /* The open failed */
} else {
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Opened file for writing: %s (%p) (%d)",
filename, (const void*)*pfptr,
(int)cpl_nfitsfiles);
#endif
/* FIXME: Assume READWRITE */
cpl_io_fits_set(*pfptr, filename, READWRITE, CPL_TRUE);
}
}
return *status;
}
/**
* @internal
* @brief Try to reuse an already existing CFITSIO file pointer or reopen
* @param pfptr CFITSIO file pointer pointer to file
* @param filename Name of FITS file to open
* @param iomode The CFITSIO iomode
* @param status Pointer to CFITSIO error status
* @return The CFITSIO error status
* @see fits_open_diskfile()
* @note Since this call may not actually open the file, the caller must
* use fits_movabs_hdu() and not fits_movrel_hdu().
*
*/
int cpl_io_fits_open_diskfile(fitsfile **pfptr, const char * filename,
int iomode, int *status)
{
if (*status == 0) { /* Duplicate CFITSIO behaviour */
const int rmiomode = iomode == READONLY ? READWRITE : READONLY;
if (iomode == READONLY) {
/* If the caller comes from a cpl_*_load() then we are free to
assume that no other thread is inside a cpl_*_save()
concerning the same file. If a writer file pointer exists
we can therefore unset and reuse it for reading. */
*pfptr = cpl_io_fits_reuse_fptr(filename, rmiomode, CPL_FALSE);
if (*pfptr != NULL) {
iomode = rmiomode; /* Reuse a READWRITE handle for reading */
/* A given file has at most one writer handle */
/* assert( cpl_io_fits_unset_fptr(filename, &rmiomode) ==
NULL); */
}
} else {
/* If the caller comes from a cpl_*_save() then we are free to
assume that no other thread is inside a CPL I/O function
concerning the same file. We can therefore unset and close all
reader file pointers open for that filename. A write file pointer
if present is not unset, since it can be reused. */
while ((*pfptr = cpl_io_fits_unset_fptr(filename, &rmiomode))
!= NULL && !fits_close_file(*pfptr, status)) {
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--;
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Closed file: %s (%p) (I/O-mode: %d != "
"%d) (%d)", filename, (const void*)*pfptr,
rmiomode, iomode, (int)cpl_nfitsfiles);
#endif
}
if (*status) {
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Could not close file: %s (%p) (I/O-"
"mode: %d) (%d)", filename, (const void*)*pfptr,
rmiomode, (int)cpl_nfitsfiles);
#endif
return *status;
}
}
if (*pfptr == NULL) {
/* Determine if an already open file can be reused */
/* If iomode is READONLY, then the tid must match */
/* If iomode is READWRITE, its tid will be set to the current one */
*pfptr = cpl_io_fits_reuse_fptr(filename, iomode,
iomode == READWRITE);
}
if (*pfptr != NULL) {
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Reusing handle (%p) for: %s (I/O-mode"
": %d%s) (%d)", (const void*)*pfptr, filename,
iomode, iomode == rmiomode ? " for reading" : "",
(int)cpl_nfitsfiles);
#endif
#ifdef CPL_IO_FITS_REWIND
/* A newly opened file points to the 1st HDU so do the same here */
if (fits_movabs_hdu(*pfptr, 1, NULL, status)) {
(void)cpl_error_fits(iomode == READWRITE
? CPL_ERROR_FILE_NOT_CREATED
: CPL_ERROR_FILE_NOT_FOUND, status,
fits_movabs_hdu, "filename='%s', mode=%d",
filename, iomode);
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Could not move to primary HDU: %s (%p) (I/O-"
"mode: %d) (%d)", filename, (const void*)*pfptr,
rmiomode, (int)cpl_nfitsfiles);
#endif
}
#endif
return *status;
}
if (cpl_fitslist != NULL) {
const int tid = omp_get_thread_num();
cpl_fitsfile_t * oldest = NULL;
#ifdef _OPENMP
/* Comparison critical with cpl_nfitsfiles increment */
#pragma omp critical(cpl_io_fits)
#endif
{
/* Need to open a file. Incerement prior to actual open,
in order to avoid the case where a number of synchronized
threads first verify that the number of files is (just)
below the limit and then the all try to open, thus
exceeding the limit */
cpl_nfitsfiles++;
if (cpl_nfitsfiles > cpl_io_max_open) {
/* First need to close a file - find it first */
oldest = cpl_io_fits_unset_tid(tid);
}
}
if (cpl_io_fits_free(oldest, CPL_FALSE, status)) {
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--; /* The close failed, so no open */
return *status;
}
}
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Opening file: %s (I/O-mode: %d) (%d)",
filename, iomode, (int)cpl_nfitsfiles);
#endif
if (fits_open_diskfile(pfptr, filename, iomode, status)) {
(void)cpl_error_set_fits(iomode == READWRITE
? CPL_ERROR_FILE_NOT_CREATED
: CPL_ERROR_FILE_NOT_FOUND, *status,
fits_open_diskfile,
"filename='%s', mode=%d", filename,
iomode);
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--; /* The open failed */
} else {
cpl_io_fits_set(*pfptr, filename, iomode, iomode == READWRITE);
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Set file: %s (%p) (I/O-mode: %d) (%d)",
filename, (const void*)*pfptr, iomode,
(int)cpl_nfitsfiles);
#endif
}
}
return *status;
}
/**
* @internal
* @brief Instead of closing the file, just flush any written data
* @param fptr CFITSIO file pointer to file
* @param status Pointer to CFITSIO error status
* @return The CFITSIO error status
* @see fits_flush_file()
From the 3.280 source code of fits_flush_file():
Flush all the data in the current FITS file to disk. This ensures that if
the program subsequently dies, the disk FITS file will be closed correctly.
*/
int cpl_io_fits_close_file(fitsfile *fptr, int *status)
{
if (*status == 0 && fptr != NULL) { /* Duplicate CFITSIO behaviour */
int iomode;
const char * name = cpl_io_fits_find_name(fptr, &iomode);
if (name == NULL) {
/* This branch is used when CPL_IO_MODE is inactive */
if (fits_close_file(fptr, status)) {
(void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, *status,
fits_close_file, ".");
}
} else if (iomode != READONLY) {
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Flushing handle (%p) for: %s (%d) (%d)",
(const void*)fptr, name, iomode, (int)cpl_nfitsfiles);
#endif
if (fits_flush_file(fptr, status)) {
(void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, *status,
fits_flush_file, "filename='%s', "
"mode=%d", name, iomode);
}
}
}
return *status;
}
/**
* @internal
* @brief Wrapper around fits_delete_file (used on error), with a close first
* @param fptr CFITSIO file pointer to file
* @param status Pointer to CFITSIO error status
* @return The CFITSIO error status
* @see fits_delete_file(), cpl_io_fits_close_file
* @note This wrapper is needed when CPL_IO_MODE is active
*/
int cpl_io_fits_delete_file(fitsfile *fptr, int *status)
{
if (fptr != NULL) { /* Duplicate CFITSIO behaviour (*status ignored) */
int iomode = 0; /* Initialize, in case the find fails */
const char * name = cpl_io_fits_find_name(fptr, &iomode);
cpl_fitsfile_t * cpl_fitsfile = NULL;
const char * filename = name != NULL && *name == '!' ? name+1 : name;
cx_list_iterator pos;
struct stat statbuf;
const cpl_boolean has_stat = filename ? !stat(filename, &statbuf)
: CPL_FALSE;
if (name != NULL) {
/* CPL_IO_MODE is active */
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
{
if (cpl_io_fits_find_fptr(&pos, filename, &iomode,
has_stat ? &statbuf : NULL)) {
/* Found it */
cpl_fitsfile = (cpl_fitsfile_t *)cx_list_extract(cpl_fitslist,
pos);
}
}
}
if (cpl_fitsfile != NULL) {
int status_ = 0;
cpl_io_fits_free(cpl_fitsfile, CPL_TRUE, &status_);
*status = status_;
} else {
int status_ = 0;
if (fits_delete_file(fptr, &status_)) {
(void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, status_,
fits_delete_file, "filename='%s', "
"I/O-mode: %d <=> %d/%d",
name, iomode, READONLY, READWRITE);
}
*status = status_;
}
}
return *status;
}
/**
* @internal
* @brief Select the 1st matching pointer structure unsetting it from the list
@param tid The thread ID in the pointer structure to match, or -1 for all
@return The pointer structure to deallocate, or NULL on no match
@note May not be called when fitslist is empty
*/
static cpl_fitsfile_t * cpl_io_fits_unset_tid(int tid)
{
#ifdef CPL_IO_FITS
cx_list_iterator pos = cx_list_begin(cpl_fitslist);
while (pos != cx_list_end(cpl_fitslist)) {
const cpl_fitsfile_t * cpl_fitsfile =
(const cpl_fitsfile_t *)cx_list_get(cpl_fitslist, pos);
if (tid < 0 || cpl_fitsfile->tid == tid) break;
pos = cx_list_next(cpl_fitslist, pos);
}
return pos != cx_list_end(cpl_fitslist)
? cx_list_extract(cpl_fitslist, pos) : NULL;
#else
return NULL;
#endif
}
/**
* @internal
* @brief Deallocate one pointer structure, closing or deleting the CFITS file
@param self The pointer structure to deallocate, or NULL
@param dodel Iff true then delete instead of just closing the file
@param status The CFITSIO status
@return Zero on success or else the CFITSIO status
*/
static
int cpl_io_fits_free(cpl_fitsfile_t * self, cpl_boolean dodel, int * status)
{
if (self != NULL) {
if (*status == 0) {
if (dodel) {
if (fits_delete_file(self->fptr, status)) {
(void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, *status,
fits_delete_file, "filename='%s', "
"I/O-mode: %d, Thread-ID: %d",
self->name, self->iomode,
self->tid);
}
} else if (fits_close_file(self->fptr, status)) {
(void)cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, *status,
fits_close_file, "filename='%s', "
"I/O-mode: %d, Thread-ID: %d",
self->name, self->iomode,
self->tid);
}
if (*status == 0) {
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--;
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Closed oldest file of thread %d: %s "
"(I/O-mode: %d. %p) (%d)", self->tid, self->name,
self->iomode, (const void*)self->fptr, *status);
#endif
}
}
cpl_free(self->name);
cpl_free(self);
}
return *status;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Close one named file, or all files
@param filename The file to be closed, NULL will close all
@param status The CFITSIO status
@return Zero on success or else the CFITSIO status
@note If no file handle exists for the file, nothing is done
*/
/*----------------------------------------------------------------------------*/
int cpl_io_fits_close(const char * filename, int * status)
{
if (*status == 0) { /* Duplicate CFITSIO behaviour */
fitsfile * fptr;
while ((fptr = cpl_io_fits_unset_fptr(filename, NULL))
!= NULL && !fits_close_file(fptr, status)) {
#ifdef _OPENMP
#pragma omp atomic
#endif
cpl_nfitsfiles--;
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "Closed CFITSIO-file: %p (%s) (%d)",
(const void*)fptr, filename, (int)cpl_nfitsfiles);
#endif
}
}
return *status;
}
/**@}*/
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Insert a CFITSIO triplet into the CPL I/O structure
@param fptr The CFITSIO pointer to insert
@param name The filename to insert
@param iomode The I/O mode to insert
@param writing CPL_TRUE iff the handle is used for writing
@void
@note Since this call is only done after a succesful opening of the named file
name (and fptr) can safely be assumed to be non-NULL.
*/
/*----------------------------------------------------------------------------*/
static void cpl_io_fits_set(fitsfile * fptr, const char * name, int iomode,
cpl_boolean writing)
{
#ifdef CPL_IO_FITS
if (cpl_fitslist != NULL) {
char * filename = cpl_strdup(*name == '!' ? name+1 : name);
struct stat statbuf;
const cpl_boolean has_stat = !stat(filename, &statbuf);
cpl_fitsfile_t * cpl_fitsfile = cpl_malloc(sizeof(*cpl_fitsfile));
/* assert(iomode != READONLY || !writing); */
cpl_fitsfile->fptr = fptr;
cpl_fitsfile->name = filename;
cpl_fitsfile->iomode = iomode;
cpl_fitsfile->tid = omp_get_thread_num();
cpl_fitsfile->writing = writing;
cpl_fitsfile->has_stat = has_stat;
if (has_stat) {
cpl_fitsfile->st_dev = statbuf.st_dev;
cpl_fitsfile->st_ino = statbuf.st_ino;
}
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
{
cx_list_push_back(cpl_fitslist, (cxcptr)cpl_fitsfile);
}
}
#endif
}
#ifdef CPL_IO_FITS
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Search by name for an already opened FITS file
@param pkey Iff found, *pkey is the location of the entry
@param filename The filename to look for, NULL will return first available
@param piomode Iff non-NULL, restrict search to *piomode
@param filestat Pointer to stat buffer of filename or NULL when unavailable
@return CPL_TRUE, iff found
@note Pointer pkey may not be NULL!
*/
/*----------------------------------------------------------------------------*/
static cpl_boolean cpl_io_fits_find_fptr(cx_list_iterator * pkey,
const char * filename,
const int * piomode,
const struct stat * filestat)
{
const int tid = omp_get_thread_num();
const cpl_fitsfile_t * cpl_fitsfile = NULL;
cpl_size i = 0;
cx_list_iterator pos = cx_list_begin(cpl_fitslist);
cpl_boolean found;
while ((found = pos != cx_list_end(cpl_fitslist))) {
cpl_fitsfile = (const cpl_fitsfile_t *)cx_list_get(cpl_fitslist, pos);
if (filename == NULL) break;/* Matches any entry */
if ((piomode == NULL || *piomode == cpl_fitsfile->iomode) &&
(((piomode == NULL || *piomode != READONLY)
&& cpl_fitsfile->writing) || cpl_fitsfile->tid == tid) &&
(filestat != NULL && cpl_fitsfile->has_stat
? cpl_fitsfile->st_dev == filestat->st_dev &&
cpl_fitsfile->st_ino == filestat->st_ino
: !strcmp(cpl_fitsfile->name, filename))) break;
pos = cx_list_next(cpl_fitslist, pos);
i++;
}
if (found) {
*pkey = pos;
#ifdef CPL_IO_FITS_DEBUG
cpl_msg_debug(cpl_func, "File %s found (%d < %d): %p (I/O-mode: "
"%d) (tid: %d <=> %d)", filename, (int)i,
(int)cpl_nfitsfiles, (const void*)cpl_fitsfile->fptr,
cpl_fitsfile->iomode, tid, cpl_fitsfile->tid);
} else if (piomode != NULL) {
cpl_msg_debug(cpl_func, "File %s not found (%d) (I/O-mode: %d, "
"tid=%d)", filename, (int)cpl_nfitsfiles, *piomode, tid);
} else {
cpl_msg_debug(cpl_func, "File %s not found (%d) (tid=%d)", filename,
(int)cpl_nfitsfiles, tid);
#endif
}
return found;
}
#endif
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Search by name for an already opened FITS file and unset it
@param name The filename to match, @em NULL will unset and return any
@param piomode Iff non-@em NULL, match *piomode, otherwise match any mode
@return When matched, the CFITSIO pointer structure otherwise NULL
@note The file is matched when the filename:
1) is NULL, or else
2) matches (using stat() if need be) and piomode is NULL, or else
3) matches (using stat() if need be) and piomode is non-NULL and
matches the mode of the entry and the mode is not READONLY, or else
4) matches (using stat() if need be) and piomode is non-NULL and
matches the mode of the entry and dounset is CPL_TRUE, or else
5) matches (using stat() if need be) and piomode is non-NULL
and matches the mode of the entry (which is READONLY) and the thread
id matches
*/
/*----------------------------------------------------------------------------*/
static fitsfile * cpl_io_fits_unset_fptr(const char * name, const int * piomode)
{
fitsfile * fptr = NULL;
#ifdef CPL_IO_FITS
if (cpl_fitslist != NULL) {
cpl_fitsfile_t * cpl_fitsfile = NULL;
const char * filename = name != NULL && *name == '!' ? name+1 : name;
cx_list_iterator pos;
struct stat statbuf;
const cpl_boolean has_stat = filename ? !stat(filename, &statbuf)
: CPL_FALSE;
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
{
if (cpl_io_fits_find_fptr(&pos, filename, piomode,
has_stat ? &statbuf : NULL)) {
/* Found it */
cpl_fitsfile = (cpl_fitsfile_t *)cx_list_extract(cpl_fitslist,
pos);
}
}
if (cpl_fitsfile != NULL) {
fptr = cpl_fitsfile->fptr;
cpl_free(cpl_fitsfile->name);
cpl_free(cpl_fitsfile);
}
}
#endif
return fptr;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Search by name for an already opened FITS file for reuse
@param name The filename to match
@param iomode The I/O mode to match
@param writing If the file is opened for read/write, its new writing flag
@return When matched, the CFITSIO pointer structure otherwise NULL
@see cpl_io_fits_unset_fptr()
@note Side-effect: If a write handle is matched for write-reuse (writing
is CPL_TRUE), then its thread id is set to that of the current thread,
so it can be unset if there are too many open files - and its writer
flag is set. If a write handle is matched for read-reuse (writing
is CPL_FALSE), then its thread id already matches - and its writer
flag is cleared.
*/
/*----------------------------------------------------------------------------*/
static fitsfile * cpl_io_fits_reuse_fptr(const char * name, int iomode,
cpl_boolean writing)
{
fitsfile * fptr = NULL;
#ifdef CPL_IO_FITS
if (cpl_fitslist != NULL) {
cpl_fitsfile_t * cpl_fitsfile = NULL;
const char * filename = *name == '!' ? name+1 : name;
cx_list_iterator pos;
struct stat statbuf;
const cpl_boolean has_stat = !stat(filename, &statbuf);
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
{
if (cpl_io_fits_find_fptr(&pos, filename, &iomode,
has_stat ? &statbuf : NULL)) {
/* Found it */
cpl_fitsfile = (cpl_fitsfile_t *)cx_list_get(cpl_fitslist, pos);
}
/* Extend critical section, since it is cheap and just to be sure */
if (cpl_fitsfile != NULL) {
/* If we are reading, the file pointer is used by no one else */
/* If we are writing (i.e. called from within a cpl_*save(),
we may assume that no one else is currently using the file */
fptr = cpl_fitsfile->fptr;
if (iomode != READONLY) {
/* assert( cpl_fitsfile->iomode == READWRITE ); */
cpl_fitsfile->tid = omp_get_thread_num();
cpl_fitsfile->writing = writing;
}
}
}
}
#endif
return fptr;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Try to find by CFITSIO pointer an already opened FITS file
@param fptr The CFITSIO pointer to look for
@param piomode When found, the I/O mode
@return When found, the name otherwise NULL
*/
/*----------------------------------------------------------------------------*/
static const char * cpl_io_fits_find_name(const fitsfile * fptr, int * piomode)
{
const char * name = NULL;
#ifdef CPL_IO_FITS
if (cpl_fitslist != NULL) {
#ifdef _OPENMP
#pragma omp critical(cpl_io_fits)
#endif
{
cx_list_const_iterator pos = cx_list_begin(cpl_fitslist);
while (pos != cx_list_end(cpl_fitslist)) {
const cpl_fitsfile_t * cpl_fitsfile = (const cpl_fitsfile_t *)
cx_list_get(cpl_fitslist, pos);
if (fptr == cpl_fitsfile->fptr) {
/* Found it */
name = cpl_fitsfile->name;
*piomode = cpl_fitsfile->iomode;
break;
}
pos = cx_list_next(cpl_fitslist, pos);
}
}
}
#endif
return name;
}
|
convolution_sgemm_pack8_fp16s.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_pack8_fp16sa_neon(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
// Mat bottom_im2col(size, maxk, inch, 16u, 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;
const __fp16* bias = _bias;
// permute
Mat tmp;
if (size >= 12)
tmp.create(12 * maxk, inch, size / 12 + (size % 12) / 8 + (size % 12 % 8) / 4 + (size % 12 % 4) / 2 + size % 12 % 2, 16u, 8, opt.workspace_allocator);
else if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 16u, 8, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 16u, 8, opt.workspace_allocator);
else if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 16u, 8, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 16u, 8, opt.workspace_allocator);
{
int nn_size = size / 12;
int remain_size_start = 0;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 12;
__fp16* tmpptr = tmp.channel(i / 12);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
// transpose 12x8
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n"
"ld4 {v4.8h, v5.8h, v6.8h, v7.8h}, [%0], #64 \n"
"ld4 {v16.8h, v17.8h, v18.8h, v19.8h}, [%0] \n"
"sub %0, %0, #128 \n"
"uzp1 v20.8h, v0.8h, v4.8h \n" // 0
"uzp1 v21.8h, v16.8h, v1.8h \n" // 1
"uzp1 v22.8h, v5.8h, v17.8h \n" // 2
"uzp1 v23.8h, v2.8h, v6.8h \n" // 3
"uzp1 v24.8h, v18.8h, v3.8h \n" // 4
"uzp1 v25.8h, v7.8h, v19.8h \n" // 5
"uzp2 v26.8h, v0.8h, v4.8h \n" // 6
"uzp2 v27.8h, v16.8h, v1.8h \n" // 7
"uzp2 v28.8h, v5.8h, v17.8h \n" // 8
"uzp2 v29.8h, v2.8h, v6.8h \n" // 9
"uzp2 v30.8h, v18.8h, v3.8h \n" // 10
"uzp2 v31.8h, v7.8h, v19.8h \n" // 11
"st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n"
"st1 {v24.8h, v25.8h, v26.8h, v27.8h}, [%1], #64 \n"
"st1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
img0 += size * 8;
}
}
}
remain_size_start += nn_size * 12;
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;
__fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
// transpose 8x8
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n"
"ld4 {v4.8h, v5.8h, v6.8h, v7.8h}, [%0] \n"
"sub %0, %0, #64 \n"
"uzp1 v16.8h, v0.8h, v4.8h \n"
"uzp2 v20.8h, v0.8h, v4.8h \n"
"uzp1 v17.8h, v1.8h, v5.8h \n"
"uzp2 v21.8h, v1.8h, v5.8h \n"
"uzp1 v18.8h, v2.8h, v6.8h \n"
"uzp2 v22.8h, v2.8h, v6.8h \n"
"uzp1 v19.8h, v3.8h, v7.8h \n"
"uzp2 v23.8h, v3.8h, v7.8h \n"
"st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n"
"st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
__fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n"
"st1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3");
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 2;
nn_size = (size - remain_size_start) >> 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 2;
__fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.8h, v1.8h}, [%0] \n"
"st1 {v0.8h, v1.8h}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
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++)
{
__fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
for (int q = 0; q < inch; q++)
{
const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.8h}, [%0] \n"
"st1 {v0.8h}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
img0 += size * 8;
}
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
__fp16* outptr0 = top_blob.channel(p);
const __fp16 zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const __fp16* biasptr = bias ? bias + p * 8 : zeros;
int i = 0;
for (; i + 11 < size; i += 12)
{
const __fp16* tmpptr = tmp.channel(i / 12);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v20.8h}, [%8] \n"
"mov v21.16b, v20.16b \n"
"mov v22.16b, v20.16b \n"
"mov v23.16b, v20.16b \n"
"mov v24.16b, v20.16b \n"
"mov v25.16b, v20.16b \n"
"mov v26.16b, v20.16b \n"
"mov v27.16b, v20.16b \n"
"mov v28.16b, v20.16b \n"
"mov v29.16b, v20.16b \n"
"mov v30.16b, v20.16b \n"
"mov v31.16b, v20.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%2], #64 \n" // r0123
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v12.8h, v13.8h, v14.8h, v15.8h}, [%3], #64 \n" // w0123
"fmla v20.8h, v12.8h, v0.h[0] \n"
"fmla v21.8h, v12.8h, v0.h[1] \n"
"fmla v22.8h, v12.8h, v0.h[2] \n"
"fmla v23.8h, v12.8h, v0.h[3] \n"
"fmla v24.8h, v12.8h, v0.h[4] \n"
"fmla v25.8h, v12.8h, v0.h[5] \n"
"fmla v26.8h, v12.8h, v0.h[6] \n"
"fmla v27.8h, v12.8h, v0.h[7] \n"
"fmla v28.8h, v12.8h, v1.h[0] \n"
"fmla v29.8h, v12.8h, v1.h[1] \n"
"fmla v30.8h, v12.8h, v1.h[2] \n"
"fmla v31.8h, v12.8h, v1.h[3] \n"
"fmla v20.8h, v13.8h, v1.h[4] \n"
"fmla v21.8h, v13.8h, v1.h[5] \n"
"fmla v22.8h, v13.8h, v1.h[6] \n"
"fmla v23.8h, v13.8h, v1.h[7] \n"
"fmla v24.8h, v13.8h, v2.h[0] \n"
"fmla v25.8h, v13.8h, v2.h[1] \n"
"fmla v26.8h, v13.8h, v2.h[2] \n"
"fmla v27.8h, v13.8h, v2.h[3] \n"
"fmla v28.8h, v13.8h, v2.h[4] \n"
"fmla v29.8h, v13.8h, v2.h[5] \n"
"fmla v30.8h, v13.8h, v2.h[6] \n"
"fmla v31.8h, v13.8h, v2.h[7] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%2], #64 \n" // r4567
"fmla v20.8h, v14.8h, v3.h[0] \n"
"fmla v21.8h, v14.8h, v3.h[1] \n"
"fmla v22.8h, v14.8h, v3.h[2] \n"
"fmla v23.8h, v14.8h, v3.h[3] \n"
"fmla v24.8h, v14.8h, v3.h[4] \n"
"fmla v25.8h, v14.8h, v3.h[5] \n"
"fmla v26.8h, v14.8h, v3.h[6] \n"
"fmla v27.8h, v14.8h, v3.h[7] \n"
"fmla v28.8h, v14.8h, v4.h[0] \n"
"fmla v29.8h, v14.8h, v4.h[1] \n"
"fmla v30.8h, v14.8h, v4.h[2] \n"
"fmla v31.8h, v14.8h, v4.h[3] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%3], #64 \n" // w4567
"fmla v20.8h, v15.8h, v4.h[4] \n"
"fmla v21.8h, v15.8h, v4.h[5] \n"
"fmla v22.8h, v15.8h, v4.h[6] \n"
"fmla v23.8h, v15.8h, v4.h[7] \n"
"fmla v24.8h, v15.8h, v5.h[0] \n"
"fmla v25.8h, v15.8h, v5.h[1] \n"
"fmla v26.8h, v15.8h, v5.h[2] \n"
"fmla v27.8h, v15.8h, v5.h[3] \n"
"fmla v28.8h, v15.8h, v5.h[4] \n"
"fmla v29.8h, v15.8h, v5.h[5] \n"
"fmla v30.8h, v15.8h, v5.h[6] \n"
"fmla v31.8h, v15.8h, v5.h[7] \n"
"fmla v20.8h, v16.8h, v6.h[0] \n"
"fmla v21.8h, v16.8h, v6.h[1] \n"
"fmla v22.8h, v16.8h, v6.h[2] \n"
"fmla v23.8h, v16.8h, v6.h[3] \n"
"fmla v24.8h, v16.8h, v6.h[4] \n"
"fmla v25.8h, v16.8h, v6.h[5] \n"
"fmla v26.8h, v16.8h, v6.h[6] \n"
"fmla v27.8h, v16.8h, v6.h[7] \n"
"fmla v28.8h, v16.8h, v7.h[0] \n"
"fmla v29.8h, v16.8h, v7.h[1] \n"
"fmla v30.8h, v16.8h, v7.h[2] \n"
"fmla v31.8h, v16.8h, v7.h[3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v8.8h, v9.8h, v10.8h, v11.8h}, [%2], #64 \n" // r891011
"fmla v20.8h, v17.8h, v7.h[4] \n"
"fmla v21.8h, v17.8h, v7.h[5] \n"
"fmla v22.8h, v17.8h, v7.h[6] \n"
"fmla v23.8h, v17.8h, v7.h[7] \n"
"fmla v24.8h, v17.8h, v8.h[0] \n"
"fmla v25.8h, v17.8h, v8.h[1] \n"
"fmla v26.8h, v17.8h, v8.h[2] \n"
"fmla v27.8h, v17.8h, v8.h[3] \n"
"fmla v28.8h, v17.8h, v8.h[4] \n"
"fmla v29.8h, v17.8h, v8.h[5] \n"
"fmla v30.8h, v17.8h, v8.h[6] \n"
"fmla v31.8h, v17.8h, v8.h[7] \n"
"fmla v20.8h, v18.8h, v9.h[0] \n"
"fmla v21.8h, v18.8h, v9.h[1] \n"
"fmla v22.8h, v18.8h, v9.h[2] \n"
"fmla v23.8h, v18.8h, v9.h[3] \n"
"fmla v24.8h, v18.8h, v9.h[4] \n"
"fmla v25.8h, v18.8h, v9.h[5] \n"
"fmla v26.8h, v18.8h, v9.h[6] \n"
"fmla v27.8h, v18.8h, v9.h[7] \n"
"fmla v28.8h, v18.8h, v10.h[0] \n"
"fmla v29.8h, v18.8h, v10.h[1] \n"
"fmla v30.8h, v18.8h, v10.h[2] \n"
"fmla v31.8h, v18.8h, v10.h[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v20.8h, v19.8h, v10.h[4] \n"
"fmla v21.8h, v19.8h, v10.h[5] \n"
"fmla v22.8h, v19.8h, v10.h[6] \n"
"fmla v23.8h, v19.8h, v10.h[7] \n"
"fmla v24.8h, v19.8h, v11.h[0] \n"
"fmla v25.8h, v19.8h, v11.h[1] \n"
"fmla v26.8h, v19.8h, v11.h[2] \n"
"fmla v27.8h, v19.8h, v11.h[3] \n"
"fmla v28.8h, v19.8h, v11.h[4] \n"
"fmla v29.8h, v19.8h, v11.h[5] \n"
"fmla v30.8h, v19.8h, v11.h[6] \n"
"fmla v31.8h, v19.8h, v11.h[7] \n"
"bne 0b \n"
"st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n"
"st1 {v24.8h, v25.8h, v26.8h, v27.8h}, [%1], #64 \n"
"st1 {v28.8h, v29.8h, v30.8h, v31.8h}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 7 < size; i += 8)
{
const __fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v16.8h}, [%8] \n"
"mov v17.16b, v16.16b \n"
"mov v18.16b, v16.16b \n"
"mov v19.16b, v16.16b \n"
"mov v20.16b, v16.16b \n"
"mov v21.16b, v16.16b \n"
"mov v22.16b, v16.16b \n"
"mov v23.16b, v16.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%2], #64 \n" // r0123
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.8h, v9.8h, v10.8h, v11.8h}, [%3], #64 \n" // w0123
"fmla v16.8h, v8.8h, v0.h[0] \n"
"fmla v17.8h, v8.8h, v0.h[1] \n"
"fmla v18.8h, v8.8h, v0.h[2] \n"
"fmla v19.8h, v8.8h, v0.h[3] \n"
"fmla v20.8h, v8.8h, v0.h[4] \n"
"fmla v21.8h, v8.8h, v0.h[5] \n"
"fmla v22.8h, v8.8h, v0.h[6] \n"
"fmla v23.8h, v8.8h, v0.h[7] \n"
"fmla v16.8h, v9.8h, v1.h[0] \n"
"fmla v17.8h, v9.8h, v1.h[1] \n"
"fmla v18.8h, v9.8h, v1.h[2] \n"
"fmla v19.8h, v9.8h, v1.h[3] \n"
"fmla v20.8h, v9.8h, v1.h[4] \n"
"fmla v21.8h, v9.8h, v1.h[5] \n"
"fmla v22.8h, v9.8h, v1.h[6] \n"
"fmla v23.8h, v9.8h, v1.h[7] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%2], #64 \n" // r4567
"fmla v16.8h, v10.8h, v2.h[0] \n"
"fmla v17.8h, v10.8h, v2.h[1] \n"
"fmla v18.8h, v10.8h, v2.h[2] \n"
"fmla v19.8h, v10.8h, v2.h[3] \n"
"fmla v20.8h, v10.8h, v2.h[4] \n"
"fmla v21.8h, v10.8h, v2.h[5] \n"
"fmla v22.8h, v10.8h, v2.h[6] \n"
"fmla v23.8h, v10.8h, v2.h[7] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v12.8h, v13.8h, v14.8h, v15.8h}, [%3], #64 \n" // w4567
"fmla v16.8h, v11.8h, v3.h[0] \n"
"fmla v17.8h, v11.8h, v3.h[1] \n"
"fmla v18.8h, v11.8h, v3.h[2] \n"
"fmla v19.8h, v11.8h, v3.h[3] \n"
"fmla v20.8h, v11.8h, v3.h[4] \n"
"fmla v21.8h, v11.8h, v3.h[5] \n"
"fmla v22.8h, v11.8h, v3.h[6] \n"
"fmla v23.8h, v11.8h, v3.h[7] \n"
"fmla v16.8h, v12.8h, v4.h[0] \n"
"fmla v17.8h, v12.8h, v4.h[1] \n"
"fmla v18.8h, v12.8h, v4.h[2] \n"
"fmla v19.8h, v12.8h, v4.h[3] \n"
"fmla v20.8h, v12.8h, v4.h[4] \n"
"fmla v21.8h, v12.8h, v4.h[5] \n"
"fmla v22.8h, v12.8h, v4.h[6] \n"
"fmla v23.8h, v12.8h, v4.h[7] \n"
"fmla v16.8h, v13.8h, v5.h[0] \n"
"fmla v17.8h, v13.8h, v5.h[1] \n"
"fmla v18.8h, v13.8h, v5.h[2] \n"
"fmla v19.8h, v13.8h, v5.h[3] \n"
"fmla v20.8h, v13.8h, v5.h[4] \n"
"fmla v21.8h, v13.8h, v5.h[5] \n"
"fmla v22.8h, v13.8h, v5.h[6] \n"
"fmla v23.8h, v13.8h, v5.h[7] \n"
"fmla v16.8h, v14.8h, v6.h[0] \n"
"fmla v17.8h, v14.8h, v6.h[1] \n"
"fmla v18.8h, v14.8h, v6.h[2] \n"
"fmla v19.8h, v14.8h, v6.h[3] \n"
"fmla v20.8h, v14.8h, v6.h[4] \n"
"fmla v21.8h, v14.8h, v6.h[5] \n"
"fmla v22.8h, v14.8h, v6.h[6] \n"
"fmla v23.8h, v14.8h, v6.h[7] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.8h, v15.8h, v7.h[0] \n"
"fmla v17.8h, v15.8h, v7.h[1] \n"
"fmla v18.8h, v15.8h, v7.h[2] \n"
"fmla v19.8h, v15.8h, v7.h[3] \n"
"fmla v20.8h, v15.8h, v7.h[4] \n"
"fmla v21.8h, v15.8h, v7.h[5] \n"
"fmla v22.8h, v15.8h, v7.h[6] \n"
"fmla v23.8h, v15.8h, v7.h[7] \n"
"bne 0b \n"
"st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n"
"st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
}
for (; i + 3 < size; i += 4)
{
const __fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v16.8h}, [%8] \n"
"mov v17.16b, v16.16b \n"
"mov v18.16b, v16.16b \n"
"mov v19.16b, v16.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%2], #64 \n" // r0123
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.8h, v9.8h, v10.8h, v11.8h}, [%3], #64 \n" // w0123
"fmla v16.8h, v8.8h, v0.h[0] \n"
"fmla v17.8h, v8.8h, v1.h[0] \n"
"fmla v18.8h, v8.8h, v2.h[0] \n"
"fmla v19.8h, v8.8h, v3.h[0] \n"
"fmla v16.8h, v9.8h, v0.h[1] \n"
"fmla v17.8h, v9.8h, v1.h[1] \n"
"fmla v18.8h, v9.8h, v2.h[1] \n"
"fmla v19.8h, v9.8h, v3.h[1] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v12.8h, v13.8h, v14.8h, v15.8h}, [%3], #64 \n" // w4567
"fmla v16.8h, v10.8h, v0.h[2] \n"
"fmla v17.8h, v10.8h, v1.h[2] \n"
"fmla v18.8h, v10.8h, v2.h[2] \n"
"fmla v19.8h, v10.8h, v3.h[2] \n"
"fmla v16.8h, v11.8h, v0.h[3] \n"
"fmla v17.8h, v11.8h, v1.h[3] \n"
"fmla v18.8h, v11.8h, v2.h[3] \n"
"fmla v19.8h, v11.8h, v3.h[3] \n"
"fmla v16.8h, v12.8h, v0.h[4] \n"
"fmla v17.8h, v12.8h, v1.h[4] \n"
"fmla v18.8h, v12.8h, v2.h[4] \n"
"fmla v19.8h, v12.8h, v3.h[4] \n"
"fmla v16.8h, v13.8h, v0.h[5] \n"
"fmla v17.8h, v13.8h, v1.h[5] \n"
"fmla v18.8h, v13.8h, v2.h[5] \n"
"fmla v19.8h, v13.8h, v3.h[5] \n"
"fmla v16.8h, v14.8h, v0.h[6] \n"
"fmla v17.8h, v14.8h, v1.h[6] \n"
"fmla v18.8h, v14.8h, v2.h[6] \n"
"fmla v19.8h, v14.8h, v3.h[6] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.8h, v15.8h, v0.h[7] \n"
"fmla v17.8h, v15.8h, v1.h[7] \n"
"fmla v18.8h, v15.8h, v2.h[7] \n"
"fmla v19.8h, v15.8h, v3.h[7] \n"
"bne 0b \n"
"st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
}
for (; i + 1 < size; i += 2)
{
const __fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v16.8h}, [%8] \n"
"mov v17.16b, v16.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v0.8h, v1.8h}, [%2], #32 \n" // r01
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.8h, v9.8h, v10.8h, v11.8h}, [%3], #64 \n" // w0123
"fmla v16.8h, v8.8h, v0.h[0] \n"
"fmla v17.8h, v8.8h, v1.h[0] \n"
"fmla v16.8h, v9.8h, v0.h[1] \n"
"fmla v17.8h, v9.8h, v1.h[1] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v12.8h, v13.8h, v14.8h, v15.8h}, [%3], #64 \n" // w4567
"fmla v16.8h, v10.8h, v0.h[2] \n"
"fmla v17.8h, v10.8h, v1.h[2] \n"
"fmla v16.8h, v11.8h, v0.h[3] \n"
"fmla v17.8h, v11.8h, v1.h[3] \n"
"fmla v16.8h, v12.8h, v0.h[4] \n"
"fmla v17.8h, v12.8h, v1.h[4] \n"
"fmla v16.8h, v13.8h, v0.h[5] \n"
"fmla v17.8h, v13.8h, v1.h[5] \n"
"fmla v16.8h, v14.8h, v0.h[6] \n"
"fmla v17.8h, v14.8h, v1.h[6] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.8h, v15.8h, v0.h[7] \n"
"fmla v17.8h, v15.8h, v1.h[7] \n"
"bne 0b \n"
"st1 {v16.8h, v17.8h}, [%1], #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17");
}
for (; i < size; i++)
{
const __fp16* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
const __fp16* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v16.8h}, [%8] \n"
"0: \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.8h}, [%2], #16 \n" // r0
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.8h, v9.8h, v10.8h, v11.8h}, [%3], #64 \n" // w0123
"fmla v16.8h, v8.8h, v0.h[0] \n"
"fmla v16.8h, v9.8h, v0.h[1] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v12.8h, v13.8h, v14.8h, v15.8h}, [%3], #64 \n" // w4567
"fmla v16.8h, v10.8h, v0.h[2] \n"
"fmla v16.8h, v11.8h, v0.h[3] \n"
"fmla v16.8h, v12.8h, v0.h[4] \n"
"fmla v16.8h, v13.8h, v0.h[5] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.8h, v14.8h, v0.h[6] \n"
"fmla v16.8h, v15.8h, v0.h[7] \n"
"bne 0b \n"
"st1 {v16.8h}, [%1], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16");
}
}
}
static void convolution_im2col_sgemm_transform_kernel_pack8_fp16sa_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 = 8b-8a-maxk-inch/8a-outch/8b
Mat kernel = _kernel.reshape(maxk, inch, outch);
kernel_tm.create(64 * maxk, inch / 8, outch / 8, 2u);
for (int q = 0; q + 7 < outch; q += 8)
{
Mat g0 = kernel_tm.channel(q / 8);
for (int p = 0; p + 7 < inch; p += 8)
{
__fp16* g00 = g0.row<__fp16>(p / 8);
for (int k = 0; k < maxk; k++)
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
const float* k00 = kernel.channel(q + j).row(p + i);
g00[0] = (__fp16)k00[k];
g00++;
}
}
}
}
}
}
static void convolution_im2col_sgemm_pack8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
const int size = outw * outh;
const int maxk = kernel_w * kernel_h;
// im2col
Mat bottom_im2col(size, maxk, inch, 16u, 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);
__fp16* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const __fp16* sptr = img.row<const __fp16>(dilation_h * u) + dilation_w * v * 8;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
float16x8_t _val0 = vld1q_f16(sptr);
float16x8_t _val1 = vld1q_f16(sptr + stride_w * 8);
float16x8_t _val2 = vld1q_f16(sptr + stride_w * 16);
float16x8_t _val3 = vld1q_f16(sptr + stride_w * 24);
vst1q_f16(ptr, _val0);
vst1q_f16(ptr + 8, _val1);
vst1q_f16(ptr + 16, _val2);
vst1q_f16(ptr + 24, _val3);
sptr += stride_w * 32;
ptr += 32;
}
for (; j + 1 < outw; j += 2)
{
float16x8_t _val0 = vld1q_f16(sptr);
float16x8_t _val1 = vld1q_f16(sptr + stride_w * 8);
vst1q_f16(ptr, _val0);
vst1q_f16(ptr + 8, _val1);
sptr += stride_w * 16;
ptr += 16;
}
for (; j < outw; j++)
{
float16x8_t _val = vld1q_f16(sptr);
vst1q_f16(ptr, _val);
sptr += stride_w * 8;
ptr += 8;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_pack8_fp16sa_neon(bottom_im2col, top_blob, kernel, _bias, opt);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.